summaryrefslogtreecommitdiff
path: root/lib/ansible/modules/cloud/amazon/ecs_attribute.py
blob: 3d5ec3646b0b8174e5b99a7de15d266cb358c77c (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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
#!/usr/bin/python
# Copyright: Ansible Project
# 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: ecs_attribute
short_description: manage ecs attributes
description:
    - Create, update or delete ECS container instance attributes.
version_added: "2.4"
author: Andrej Svenke (@anryko)
requirements: [ botocore, boto3 ]
options:
    cluster:
        description:
            - The short name or full Amazon Resource Name (ARN) of the cluster
              that contains the resource to apply attributes.
        required: true
        type: str
    state:
        description:
            - The desired state of the attributes.
        required: false
        default: present
        choices: ['present', 'absent']
        type: str
    attributes:
        description:
            - List of attributes.
        required: true
        type: list
        elements: dict
        suboptions:
            name:
                description:
                    - The name of the attribute. Up to 128 letters (uppercase and lowercase),
                      numbers, hyphens, underscores, and periods are allowed.
                required: true
                type: str
            value:
                description:
                    - The value of the attribute. Up to 128 letters (uppercase and lowercase),
                      numbers, hyphens, underscores, periods, at signs (@), forward slashes, colons,
                      and spaces are allowed.
                required: false
                type: str
    ec2_instance_id:
        description:
            - EC2 instance ID of ECS cluster container instance.
        required: true
        type: str
extends_documentation_fragment:
    - aws
    - ec2
'''

EXAMPLES = '''
# Note: These examples do not set authentication details, see the AWS Guide for details.

# Set attributes
- ecs_attribute:
    state: present
    cluster: test-cluster
    ec2_instance_id: "{{ ec2_id }}"
    attributes:
      - flavor: test
      - migrated
  delegate_to: localhost

# Delete attributes
- ecs_attribute:
    state: absent
    cluster: test-cluster
    ec2_instance_id: "{{ ec2_id }}"
    attributes:
      - flavor: test
      - migrated
  delegate_to: localhost
'''

RETURN = '''
attributes:
    description: attributes
    type: complex
    returned: always
    contains:
        cluster:
            description: cluster name
            type: str
        ec2_instance_id:
            description: ec2 instance id of ecs container instance
            type: str
        attributes:
            description: list of attributes
            type: list
            elements: dict
            contains:
                name:
                    description: name of the attribute
                    type: str
                value:
                    description: value of the attribute
                    returned: if present
                    type: str
'''

try:
    import boto3
    from botocore.exceptions import ClientError, EndpointConnectionError
    HAS_BOTO3 = True
except ImportError:
    HAS_BOTO3 = False

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import boto3_conn, ec2_argument_spec, get_aws_connection_info


class EcsAttributes(object):
    """Handles ECS Cluster Attribute"""

    def __init__(self, module, attributes):
        self.module = module
        self.attributes = attributes if self._validate_attrs(attributes) else self._parse_attrs(attributes)

    def __bool__(self):
        return bool(self.attributes)

    __nonzero__ = __bool__

    def __iter__(self):
        return iter(self.attributes)

    @staticmethod
    def _validate_attrs(attrs):
        return all(tuple(attr.keys()) in (('name', 'value'), ('value', 'name')) for attr in attrs)

    def _parse_attrs(self, attrs):
        attrs_parsed = []
        for attr in attrs:
            if isinstance(attr, dict):
                if len(attr) != 1:
                    self.module.fail_json(msg="Incorrect attribute format - %s" % str(attr))
                name, value = list(attr.items())[0]
                attrs_parsed.append({'name': name, 'value': value})
            elif isinstance(attr, str):
                attrs_parsed.append({'name': attr, 'value': None})
            else:
                self.module.fail_json(msg="Incorrect attributes format - %s" % str(attrs))

        return attrs_parsed

    def _setup_attr_obj(self, ecs_arn, name, value=None, skip_value=False):
        attr_obj = {'targetType': 'container-instance',
                    'targetId': ecs_arn,
                    'name': name}
        if not skip_value and value is not None:
            attr_obj['value'] = value

        return attr_obj

    def get_for_ecs_arn(self, ecs_arn, skip_value=False):
        """
        Returns list of attribute dicts ready to be passed to boto3
        attributes put/delete methods.
        """
        return [self._setup_attr_obj(ecs_arn, skip_value=skip_value, **attr) for attr in self.attributes]

    def diff(self, attrs):
        """
        Returns EcsAttributes Object containing attributes which are present
        in self but are absent in passed attrs (EcsAttributes Object).
        """
        attrs_diff = [attr for attr in self.attributes if attr not in attrs]
        return EcsAttributes(self.module, attrs_diff)


class Ec2EcsInstance(object):
    """Handle ECS Cluster Remote Operations"""

    def __init__(self, module, cluster, ec2_id):
        self.module = module
        self.cluster = cluster
        self.ec2_id = ec2_id

        region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)
        if not region:
            module.fail_json(msg=("Region must be specified as a parameter,"
                                  " in EC2_REGION or AWS_REGION environment"
                                  " variables or in boto configuration file"))
        self.ecs = boto3_conn(module, conn_type='client', resource='ecs',
                              region=region, endpoint=ec2_url, **aws_connect_kwargs)

        self.ecs_arn = self._get_ecs_arn()

    def _get_ecs_arn(self):
        try:
            ecs_instances_arns = self.ecs.list_container_instances(cluster=self.cluster)['containerInstanceArns']
            ec2_instances = self.ecs.describe_container_instances(cluster=self.cluster,
                                                                  containerInstances=ecs_instances_arns)['containerInstances']
        except (ClientError, EndpointConnectionError) as e:
            self.module.fail_json(msg="Can't connect to the cluster - %s" % str(e))

        try:
            ecs_arn = next(inst for inst in ec2_instances
                           if inst['ec2InstanceId'] == self.ec2_id)['containerInstanceArn']
        except StopIteration:
            self.module.fail_json(msg="EC2 instance Id not found in ECS cluster - %s" % str(self.cluster))

        return ecs_arn

    def attrs_put(self, attrs):
        """Puts attributes on ECS container instance"""
        try:
            self.ecs.put_attributes(cluster=self.cluster,
                                    attributes=attrs.get_for_ecs_arn(self.ecs_arn))
        except ClientError as e:
            self.module.fail_json(msg=str(e))

    def attrs_delete(self, attrs):
        """Deletes attributes from ECS container instance."""
        try:
            self.ecs.delete_attributes(cluster=self.cluster,
                                       attributes=attrs.get_for_ecs_arn(self.ecs_arn, skip_value=True))
        except ClientError as e:
            self.module.fail_json(msg=str(e))

    def attrs_get_by_name(self, attrs):
        """
        Returns EcsAttributes object containing attributes from ECS container instance with names
        matching to attrs.attributes (EcsAttributes Object).
        """
        attr_objs = [{'targetType': 'container-instance', 'attributeName': attr['name']}
                     for attr in attrs]

        try:
            matched_ecs_targets = [attr_found for attr_obj in attr_objs
                                   for attr_found in self.ecs.list_attributes(cluster=self.cluster, **attr_obj)['attributes']]
        except ClientError as e:
            self.module.fail_json(msg="Can't connect to the cluster - %s" % str(e))

        matched_objs = [target for target in matched_ecs_targets
                        if target['targetId'] == self.ecs_arn]

        results = [{'name': match['name'], 'value': match.get('value', None)}
                   for match in matched_objs]

        return EcsAttributes(self.module, results)


def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(dict(
        state=dict(required=False, default='present', choices=['present', 'absent']),
        cluster=dict(required=True, type='str'),
        ec2_instance_id=dict(required=True, type='str'),
        attributes=dict(required=True, type='list'),
    ))

    required_together = [['cluster', 'ec2_instance_id', 'attributes']]

    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True,
                           required_together=required_together)

    if not HAS_BOTO3:
        module.fail_json(msg='boto3 is required.')

    cluster = module.params['cluster']
    ec2_instance_id = module.params['ec2_instance_id']
    attributes = module.params['attributes']

    conti = Ec2EcsInstance(module, cluster, ec2_instance_id)
    attrs = EcsAttributes(module, attributes)

    results = {'changed': False,
               'attributes': [
                   {'cluster': cluster,
                    'ec2_instance_id': ec2_instance_id,
                    'attributes': attributes}
               ]}

    attrs_present = conti.attrs_get_by_name(attrs)

    if module.params['state'] == 'present':
        attrs_diff = attrs.diff(attrs_present)
        if not attrs_diff:
            module.exit_json(**results)

        conti.attrs_put(attrs_diff)
        results['changed'] = True

    elif module.params['state'] == 'absent':
        if not attrs_present:
            module.exit_json(**results)

        conti.attrs_delete(attrs_present)
        results['changed'] = True

    module.exit_json(**results)


if __name__ == '__main__':
    main()