| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: Ansible Project |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
DOCUMENTATION = r""" |
| 8 |
--- |
| 9 |
module: ecs_attribute |
| 10 |
version_added: 1.0.0 |
| 11 |
short_description: manage ecs attributes |
| 12 |
description: |
| 13 |
- Create, update or delete ECS container instance attributes. |
| 14 |
author: |
| 15 |
- Andrej Svenke (@anryko) |
| 16 |
options: |
| 17 |
cluster: |
| 18 |
description: |
| 19 |
- The short name or full Amazon Resource Name (ARN) of the cluster |
| 20 |
that contains the resource to apply attributes. |
| 21 |
required: true |
| 22 |
type: str |
| 23 |
state: |
| 24 |
description: |
| 25 |
- The desired state of the attributes. |
| 26 |
required: false |
| 27 |
default: present |
| 28 |
choices: ['present', 'absent'] |
| 29 |
type: str |
| 30 |
attributes: |
| 31 |
description: |
| 32 |
- List of attributes. |
| 33 |
required: true |
| 34 |
type: list |
| 35 |
elements: dict |
| 36 |
suboptions: |
| 37 |
name: |
| 38 |
description: |
| 39 |
- The name of the attribute. Up to 128 letters (uppercase and lowercase), |
| 40 |
numbers, hyphens, underscores, and periods are allowed. |
| 41 |
required: true |
| 42 |
type: str |
| 43 |
value: |
| 44 |
description: |
| 45 |
- The value of the attribute. Up to 128 letters (uppercase and lowercase), |
| 46 |
numbers, hyphens, underscores, periods, at signs (@), forward slashes, colons, |
| 47 |
and spaces are allowed. |
| 48 |
required: false |
| 49 |
type: str |
| 50 |
ec2_instance_id: |
| 51 |
description: |
| 52 |
- EC2 instance ID of ECS cluster container instance. |
| 53 |
required: true |
| 54 |
type: str |
| 55 |
extends_documentation_fragment: |
| 56 |
- amazon.aws.common.modules |
| 57 |
- amazon.aws.region.modules |
| 58 |
- amazon.aws.boto3 |
| 59 |
""" |
| 60 |
|
| 61 |
EXAMPLES = r""" |
| 62 |
# Note: These examples do not set authentication details, see the AWS Guide for details. |
| 63 |
|
| 64 |
- name: Set attributes |
| 65 |
community.aws.ecs_attribute: |
| 66 |
state: present |
| 67 |
cluster: test-cluster |
| 68 |
ec2_instance_id: "{{ ec2_id }}" |
| 69 |
attributes: |
| 70 |
- flavor: test |
| 71 |
- migrated |
| 72 |
delegate_to: localhost |
| 73 |
|
| 74 |
- name: Delete attributes |
| 75 |
community.aws.ecs_attribute: |
| 76 |
state: absent |
| 77 |
cluster: test-cluster |
| 78 |
ec2_instance_id: "{{ ec2_id }}" |
| 79 |
attributes: |
| 80 |
- flavor: test |
| 81 |
- migrated |
| 82 |
delegate_to: localhost |
| 83 |
""" |
| 84 |
|
| 85 |
RETURN = r""" |
| 86 |
attributes: |
| 87 |
description: attributes |
| 88 |
type: complex |
| 89 |
returned: always |
| 90 |
contains: |
| 91 |
cluster: |
| 92 |
description: cluster name |
| 93 |
type: str |
| 94 |
ec2_instance_id: |
| 95 |
description: ec2 instance id of ecs container instance |
| 96 |
type: str |
| 97 |
attributes: |
| 98 |
description: list of attributes |
| 99 |
type: list |
| 100 |
elements: dict |
| 101 |
contains: |
| 102 |
name: |
| 103 |
description: name of the attribute |
| 104 |
type: str |
| 105 |
value: |
| 106 |
description: value of the attribute |
| 107 |
returned: if present |
| 108 |
type: str |
| 109 |
""" |
| 110 |
|
| 111 |
try: |
| 112 |
import botocore |
| 113 |
from botocore.exceptions import ClientError |
| 114 |
from botocore.exceptions import EndpointConnectionError |
| 115 |
except ImportError: |
| 116 |
pass # Handled by AnsibleAWSModule |
| 117 |
|
| 118 |
from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule |
| 119 |
|
| 120 |
|
| 121 |
class EcsAttributes(object): |
| 122 |
"""Handles ECS Cluster Attribute""" |
| 123 |
|
| 124 |
def __init__(self, module, attributes): |
| 125 |
self.module = module |
| 126 |
self.attributes = attributes if self._validate_attrs(attributes) else self._parse_attrs(attributes) |
| 127 |
|
| 128 |
def __bool__(self): |
| 129 |
return bool(self.attributes) |
| 130 |
|
| 131 |
__nonzero__ = __bool__ |
| 132 |
|
| 133 |
def __iter__(self): |
| 134 |
return iter(self.attributes) |
| 135 |
|
| 136 |
@staticmethod |
| 137 |
def _validate_attrs(attrs): |
| 138 |
return all(tuple(attr.keys()) in (("name", "value"), ("value", "name")) for attr in attrs) |
| 139 |
|
| 140 |
def _parse_attrs(self, attrs): |
| 141 |
attrs_parsed = [] |
| 142 |
for attr in attrs: |
| 143 |
if isinstance(attr, dict): |
| 144 |
if len(attr) != 1: |
| 145 |
self.module.fail_json(msg=f"Incorrect attribute format - {str(attr)}") |
| 146 |
name, value = list(attr.items())[0] |
| 147 |
attrs_parsed.append({"name": name, "value": value}) |
| 148 |
elif isinstance(attr, str): |
| 149 |
attrs_parsed.append({"name": attr, "value": None}) |
| 150 |
else: |
| 151 |
self.module.fail_json(msg=f"Incorrect attributes format - {str(attrs)}") |
| 152 |
|
| 153 |
return attrs_parsed |
| 154 |
|
| 155 |
def _setup_attr_obj(self, ecs_arn, name, value=None, skip_value=False): |
| 156 |
attr_obj = {"targetType": "container-instance", "targetId": ecs_arn, "name": name} |
| 157 |
if not skip_value and value is not None: |
| 158 |
attr_obj["value"] = value |
| 159 |
|
| 160 |
return attr_obj |
| 161 |
|
| 162 |
def get_for_ecs_arn(self, ecs_arn, skip_value=False): |
| 163 |
""" |
| 164 |
Returns list of attribute dicts ready to be passed to boto3 |
| 165 |
attributes put/delete methods. |
| 166 |
""" |
| 167 |
return [self._setup_attr_obj(ecs_arn, skip_value=skip_value, **attr) for attr in self.attributes] |
| 168 |
|
| 169 |
def diff(self, attrs): |
| 170 |
""" |
| 171 |
Returns EcsAttributes Object containing attributes which are present |
| 172 |
in self but are absent in passed attrs (EcsAttributes Object). |
| 173 |
""" |
| 174 |
attrs_diff = [attr for attr in self.attributes if attr not in attrs] |
| 175 |
return EcsAttributes(self.module, attrs_diff) |
| 176 |
|
| 177 |
|
| 178 |
class Ec2EcsInstance(object): |
| 179 |
"""Handle ECS Cluster Remote Operations""" |
| 180 |
|
| 181 |
def __init__(self, module, cluster, ec2_id): |
| 182 |
self.module = module |
| 183 |
self.cluster = cluster |
| 184 |
self.ec2_id = ec2_id |
| 185 |
|
| 186 |
try: |
| 187 |
self.ecs = module.client("ecs") |
| 188 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 189 |
module.fail_json_aws(e, msg="Failed to connect to AWS") |
| 190 |
|
| 191 |
self.ecs_arn = self._get_ecs_arn() |
| 192 |
|
| 193 |
def _get_ecs_arn(self): |
| 194 |
try: |
| 195 |
ecs_instances_arns = self.ecs.list_container_instances(cluster=self.cluster)["containerInstanceArns"] |
| 196 |
ec2_instances = self.ecs.describe_container_instances( |
| 197 |
cluster=self.cluster, containerInstances=ecs_instances_arns |
| 198 |
)["containerInstances"] |
| 199 |
except (ClientError, EndpointConnectionError) as e: |
| 200 |
self.module.fail_json(msg=f"Can't connect to the cluster - {str(e)}") |
| 201 |
|
| 202 |
try: |
| 203 |
ecs_arn = next(inst for inst in ec2_instances if inst["ec2InstanceId"] == self.ec2_id)[ |
| 204 |
"containerInstanceArn" |
| 205 |
] |
| 206 |
except StopIteration: |
| 207 |
self.module.fail_json(msg=f"EC2 instance Id not found in ECS cluster - {str(self.cluster)}") |
| 208 |
|
| 209 |
return ecs_arn |
| 210 |
|
| 211 |
def attrs_put(self, attrs): |
| 212 |
"""Puts attributes on ECS container instance""" |
| 213 |
try: |
| 214 |
self.ecs.put_attributes(cluster=self.cluster, attributes=attrs.get_for_ecs_arn(self.ecs_arn)) |
| 215 |
except ClientError as e: |
| 216 |
self.module.fail_json(msg=str(e)) |
| 217 |
|
| 218 |
def attrs_delete(self, attrs): |
| 219 |
"""Deletes attributes from ECS container instance.""" |
| 220 |
try: |
| 221 |
self.ecs.delete_attributes( |
| 222 |
cluster=self.cluster, attributes=attrs.get_for_ecs_arn(self.ecs_arn, skip_value=True) |
| 223 |
) |
| 224 |
except ClientError as e: |
| 225 |
self.module.fail_json(msg=str(e)) |
| 226 |
|
| 227 |
def attrs_get_by_name(self, attrs): |
| 228 |
""" |
| 229 |
Returns EcsAttributes object containing attributes from ECS container instance with names |
| 230 |
matching to attrs.attributes (EcsAttributes Object). |
| 231 |
""" |
| 232 |
attr_objs = [{"targetType": "container-instance", "attributeName": attr["name"]} for attr in attrs] |
| 233 |
|
| 234 |
try: |
| 235 |
matched_ecs_targets = [ |
| 236 |
attr_found |
| 237 |
for attr_obj in attr_objs |
| 238 |
for attr_found in self.ecs.list_attributes(cluster=self.cluster, **attr_obj)["attributes"] |
| 239 |
] |
| 240 |
except ClientError as e: |
| 241 |
self.module.fail_json(msg=f"Can't connect to the cluster - {str(e)}") |
| 242 |
|
| 243 |
matched_objs = [target for target in matched_ecs_targets if target["targetId"] == self.ecs_arn] |
| 244 |
|
| 245 |
results = [{"name": match["name"], "value": match.get("value", None)} for match in matched_objs] |
| 246 |
|
| 247 |
return EcsAttributes(self.module, results) |
| 248 |
|
| 249 |
|
| 250 |
def main(): |
| 251 |
argument_spec = dict( |
| 252 |
state=dict(required=False, default="present", choices=["present", "absent"]), |
| 253 |
cluster=dict(required=True, type="str"), |
| 254 |
ec2_instance_id=dict(required=True, type="str"), |
| 255 |
attributes=dict(required=True, type="list", elements="dict"), |
| 256 |
) |
| 257 |
|
| 258 |
required_together = [["cluster", "ec2_instance_id", "attributes"]] |
| 259 |
|
| 260 |
module = AnsibleAWSModule( |
| 261 |
argument_spec=argument_spec, |
| 262 |
supports_check_mode=True, |
| 263 |
required_together=required_together, |
| 264 |
) |
| 265 |
|
| 266 |
cluster = module.params["cluster"] |
| 267 |
ec2_instance_id = module.params["ec2_instance_id"] |
| 268 |
attributes = module.params["attributes"] |
| 269 |
|
| 270 |
conti = Ec2EcsInstance(module, cluster, ec2_instance_id) |
| 271 |
attrs = EcsAttributes(module, attributes) |
| 272 |
|
| 273 |
results = { |
| 274 |
"changed": False, |
| 275 |
"attributes": [ |
| 276 |
{ |
| 277 |
"cluster": cluster, |
| 278 |
"ec2_instance_id": ec2_instance_id, |
| 279 |
"attributes": attributes, |
| 280 |
} |
| 281 |
], |
| 282 |
} |
| 283 |
|
| 284 |
attrs_present = conti.attrs_get_by_name(attrs) |
| 285 |
|
| 286 |
if module.params["state"] == "present": |
| 287 |
attrs_diff = attrs.diff(attrs_present) |
| 288 |
if not attrs_diff: |
| 289 |
module.exit_json(**results) |
| 290 |
|
| 291 |
conti.attrs_put(attrs_diff) |
| 292 |
results["changed"] = True |
| 293 |
|
| 294 |
elif module.params["state"] == "absent": |
| 295 |
if not attrs_present: |
| 296 |
module.exit_json(**results) |
| 297 |
|
| 298 |
conti.attrs_delete(attrs_present) |
| 299 |
results["changed"] = True |
| 300 |
|
| 301 |
module.exit_json(**results) |
| 302 |
|
| 303 |
|
| 304 |
if __name__ == "__main__": |
| 305 |
main() |