summaryrefslogtreecommitdiff
path: root/lib/ansible/modules/remote_management/manageiq/manageiq_tags.py
blob: b459c03cfc4fa614a5ed261c267984dc561e13e9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Daniel Korn <korndaniel1@gmail.com>
# (c) 2017, Yaacov Zamir <yzamir@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function
__metaclass__ = type


ANSIBLE_METADATA = {
    'metadata_version': '1.1',
    'status': ['preview'],
    'supported_by': 'community'
}


DOCUMENTATION = '''

module: manageiq_tags

short_description: Management of resource tags in ManageIQ.
extends_documentation_fragment: manageiq
version_added: '2.5'
author: Daniel Korn (@dkorn)
description:
  - The manageiq_tags module supports adding, updating and deleting tags in ManageIQ.

options:
  state:
    description:
      - absent - tags should not exist, present - tags should be.
    required: False
    choices: ['absent', 'present']
    default: 'present'
  tags:
    description:
      - tags - list of dictionaries, each includes 'name' and 'category' keys.
      - categories - tag categories.
    required: true
    default: null
  resource_type:
    description:
      - the relevant resource type in manageiq
    required: true
    choices: ['provider', 'host', 'vm', 'blueprint', 'category', 'cluster',
        'data store', 'group', 'resource pool', 'service', 'service template',
        'template', 'tenant', 'user']
    default: null
  resource_name:
    description:
      - the relevant resource name in manageiq
    required: true
    default: null
'''

EXAMPLES = '''
- name: Create new tags for a provider in ManageIQ
  manageiq_tags:
    resource_name: 'EngLab'
    resource_type: 'provider'
    tags:
    - category: environment
      name: prod
    - category: owner
      name: prod_ops
    manageiq_connection:
      url: 'http://127.0.0.1:3000'
      username: 'admin'
      password: 'smartvm'
      verify_ssl: False

- name: Remove tags for a provider in ManageIQ
  manageiq_tags:
    state: absent
    resource_name: 'EngLab'
    resource_type: 'provider'
    tags:
    - category: environment
      name: prod
    - category: owner
      name: prod_ops
    manageiq_connection:
      url: 'http://127.0.0.1:3000'
      username: 'admin'
      password: 'smartvm'
      verify_ssl: False
'''

RETURN = '''
'''

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.manageiq import ManageIQ, manageiq_argument_spec, manageiq_entities


def query_resource_id(manageiq, resource_type, resource_name):
    """ Query the resource name in ManageIQ.

    Returns:
        the resource id if it exists in manageiq, Fail otherwise.
    """
    resource = manageiq.find_collection_resource_by(resource_type, name=resource_name)
    if resource:
        return resource["id"]
    else:
        msg = "{resource_name} {resource_type} does not exist in manageiq".format(
            resource_name=resource_name, resource_type=resource_type)
        manageiq.module.fail_json(msg=msg)


class ManageIQTags(object):
    """
        Object to execute tags management operations of manageiq resources.
    """

    def __init__(self, manageiq, resource_type, resource_id):
        self.manageiq = manageiq

        self.module = self.manageiq.module
        self.api_url = self.manageiq.api_url
        self.client = self.manageiq.client

        self.resource_type = resource_type
        self.resource_id = resource_id
        self.resource_url = '{api_url}/{resource_type}/{resource_id}'.format(
            api_url=self.api_url,
            resource_type=resource_type,
            resource_id=resource_id)

    def full_tag_name(self, tag):
        """ Returns the full tag name in manageiq
        """
        return '/managed/{tag_category}/{tag_name}'.format(
            tag_category=tag['category'],
            tag_name=tag['name'])

    def query_resource_tags(self):
        """ Returns a set of the full tag names assigned to the resource
        """
        url = '{resource_url}/tags?expand=resources'.format(resource_url=self.resource_url)
        try:
            response = self.client.get(url)
        except Exception as e:
            msg = "Failed to query {resource_type} tags: {error}".format(
                resource_type=self.resource_type,
                error=e)
            self.module.fail_json(msg=msg)

        tags = response.get('resources', [])
        tags_set = set([tag['name'] for tag in tags])
        return tags_set

    def tags_to_update(self, tags, action):
        """ Create a list of tags we need to update in ManageIQ.

        Returns:
            Whether or not a change took place and a message describing the
            operation executed.
        """
        tags_to_post = []
        assigned_tags = self.query_resource_tags()
        for tag in tags:
            assigned = self.full_tag_name(tag) in assigned_tags

            if assigned and action == 'unassign':
                tags_to_post.append(tag)
            elif (not assigned) and action == 'assign':
                tags_to_post.append(tag)

        return tags_to_post

    def assign_or_unassign_tags(self, tags, action):
        """ Perform assign/unassign action
        """
        # get a list of tags needed to be changed
        tags_to_post = self.tags_to_update(tags, action)
        if not tags_to_post:
            return dict(
                changed=False,
                msg="Tags already {action}ed, nothing to do".format(action=action))

        # try to assign or unassign tags to resource
        url = '{resource_url}/tags'.format(resource_url=self.resource_url)
        try:
            response = self.client.post(url, action=action, resources=tags)
        except Exception as e:
            msg = "Failed to {action} tag: {error}".format(
                action=action,
                error=e)
            self.module.fail_json(msg=msg)

        # check all entities in result to be successfull
        for result in response['results']:
            if not result['success']:
                msg = "Failed to {action}: {message}".format(
                    action=action,
                    message=result['message'])
                self.module.fail_json(msg=msg)

        # successfully changed all needed tags
        return dict(
            changed=True,
            msg="Successfully {action}ed tags".format(action=action))


def main():
    actions = {'present': 'assign', 'absent': 'unassign'}

    module = AnsibleModule(
        argument_spec=dict(
            manageiq_connection=dict(required=True, type='dict',
                                     options=manageiq_argument_spec()),
            tags=dict(required=True, type='list'),
            resource_name=dict(required=True, type='str'),
            resource_type=dict(required=True, type='str',
                               choices=manageiq_entities().keys()),
            state=dict(required=False, type='str',
                       choices=['present', 'absent'], default='present'),
        )
    )

    tags = module.params['tags']
    resource_type_key = module.params['resource_type']
    resource_name = module.params['resource_name']
    state = module.params['state']

    # get the action and resource type
    action = actions[state]
    resource_type = manageiq_entities()[resource_type_key]

    manageiq = ManageIQ(module)

    # query resource id, fail if resource does not exist
    resource_id = query_resource_id(manageiq, resource_type, resource_name)

    manageiq_tags = ManageIQTags(manageiq, resource_type, resource_id)

    # assign or unassign the tags
    res_args = manageiq_tags.assign_or_unassign_tags(tags, action)

    module.exit_json(**res_args)


if __name__ == "__main__":
    main()