Debian Codegraph @

ansible_collections/community/aws/plugins/modules/ecs_cluster.py

raw
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_cluster
10 version_added: 1.0.0
11 short_description: Create or terminate ECS clusters.
12 notes:
13 - When deleting a cluster, the information returned is the state of the cluster prior to deletion.
14 - It will also wait for a cluster to have instances registered to it.
15 description:
16 - Creates or terminates ecs clusters.
17 author:
18 - Mark Chance (@Java1Guy)
19 options:
20 state:
21 description:
22 - The desired state of the cluster.
23 required: true
24 choices: ['present', 'absent', 'has_instances']
25 type: str
26 name:
27 description:
28 - The cluster name.
29 required: true
30 type: str
31 delay:
32 description:
33 - Number of seconds to wait.
34 required: false
35 type: int
36 default: 10
37 repeat:
38 description:
39 - The number of times to wait for the cluster to have an instance.
40 required: false
41 type: int
42 default: 10
43 capacity_providers:
44 version_added: 5.2.0
45 description:
46 - List of capacity providers to use for the cluster.
47 required: false
48 type: list
49 elements: str
50 capacity_provider_strategy:
51 version_added: 5.2.0
52 description:
53 - List of capacity provider strategies to use for the cluster.
54 required: false
55 type: list
56 elements: dict
57 suboptions:
58 capacity_provider:
59 description:
60 - Name of capacity provider.
61 type: str
62 weight:
63 description:
64 - The relative percentage of the total number of launched tasks that should use the specified provider.
65 type: int
66 base:
67 description:
68 - How many tasks, at a minimum, should use the specified provider.
69 type: int
70 default: 0
71 purge_capacity_providers:
72 version_added: 5.2.0
73 description:
74 - Toggle overwriting of existing capacity providers or strategy. This is needed for backwards compatibility.
75 - By default I(purge_capacity_providers=true).
76 required: false
77 type: bool
78 default: true
79 extends_documentation_fragment:
80 - amazon.aws.common.modules
81 - amazon.aws.region.modules
82 - amazon.aws.boto3
83 """
84
85 EXAMPLES = r"""
86 # Note: These examples do not set authentication details, see the AWS Guide for details.
87
88 - name: Cluster creation
89 community.aws.ecs_cluster:
90 name: default
91 state: present
92
93 - name: Cluster creation with capacity providers and strategies.
94 community.aws.ecs_cluster:
95 name: default
96 state: present
97 capacity_providers:
98 - FARGATE
99 - FARGATE_SPOT
100 capacity_provider_strategy:
101 - capacity_provider: FARGATE
102 base: 1
103 weight: 1
104 - capacity_provider: FARGATE_SPOT
105 weight: 100
106 purge_capacity_providers: true
107
108 - name: Cluster deletion
109 community.aws.ecs_cluster:
110 name: default
111 state: absent
112
113 - name: Wait for register
114 community.aws.ecs_cluster:
115 name: "{{ new_cluster }}"
116 state: has_instances
117 delay: 10
118 repeat: 10
119 register: task_output
120 """
121
122 RETURN = r"""
123 activeServicesCount:
124 description: how many services are active in this cluster
125 returned: 0 if a new cluster
126 type: int
127 capacityProviders:
128 version_added: 5.2.0
129 description: list of capacity providers used in this cluster
130 returned: always
131 type: list
132 defaultCapacityProviderStrategy:
133 version_added: 5.2.0
134 description: list of capacity provider strategies used in this cluster
135 returned: always
136 type: list
137 clusterArn:
138 description: the ARN of the cluster just created
139 type: str
140 returned: 0 if a new cluster
141 sample: arn:aws:ecs:us-west-2:123456789012:cluster/test-cluster
142 clusterName:
143 description: name of the cluster just created (should match the input argument)
144 type: str
145 returned: always
146 sample: test-cluster
147 pendingTasksCount:
148 description: how many tasks are waiting to run in this cluster
149 returned: 0 if a new cluster
150 type: int
151 registeredContainerInstancesCount:
152 description: how many container instances are available in this cluster
153 returned: 0 if a new cluster
154 type: int
155 runningTasksCount:
156 description: how many tasks are running in this cluster
157 returned: 0 if a new cluster
158 type: int
159 status:
160 description: the status of the new cluster
161 returned: always
162 type: str
163 sample: ACTIVE
164 """
165
166 import time
167
168 try:
169 import botocore
170 except ImportError:
171 pass # Handled by AnsibleAWSModule
172
173 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
174 from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
175
176 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
177
178
179 class EcsClusterManager:
180 """Handles ECS Clusters"""
181
182 def __init__(self, module):
183 self.module = module
184 try:
185 self.ecs = module.client("ecs")
186 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
187 module.fail_json_aws(e, msg="Failed to connect to AWS")
188
189 def find_in_array(self, array_of_clusters, cluster_name, field_name="clusterArn"):
190 for c in array_of_clusters:
191 if c[field_name].endswith(cluster_name):
192 return c
193 return None
194
195 def describe_cluster(self, cluster_name):
196 response = self.ecs.describe_clusters(clusters=[cluster_name])
197 if len(response["failures"]) > 0:
198 c = self.find_in_array(response["failures"], cluster_name, "arn")
199 if c and c["reason"] == "MISSING":
200 return None
201 # fall thru and look through found ones
202 if len(response["clusters"]) > 0:
203 c = self.find_in_array(response["clusters"], cluster_name)
204 if c:
205 return c
206 raise Exception(f"Unknown problem describing cluster {cluster_name}.")
207
208 def create_cluster(self, cluster_name, capacity_providers, capacity_provider_strategy):
209 params = dict(clusterName=cluster_name)
210 if capacity_providers:
211 params["capacityProviders"] = snake_dict_to_camel_dict(capacity_providers)
212 if capacity_provider_strategy:
213 params["defaultCapacityProviderStrategy"] = snake_dict_to_camel_dict(capacity_provider_strategy)
214 response = self.ecs.create_cluster(**params)
215 return response["cluster"]
216
217 def update_cluster(self, cluster_name, capacity_providers, capacity_provider_strategy):
218 params = dict(cluster=cluster_name)
219 if capacity_providers:
220 params["capacityProviders"] = snake_dict_to_camel_dict(capacity_providers)
221 else:
222 params["capacityProviders"] = []
223 if capacity_provider_strategy:
224 params["defaultCapacityProviderStrategy"] = snake_dict_to_camel_dict(capacity_provider_strategy)
225 else:
226 params["defaultCapacityProviderStrategy"] = []
227 response = self.ecs.put_cluster_capacity_providers(**params)
228 return response["cluster"]
229
230 def delete_cluster(self, clusterName):
231 return self.ecs.delete_cluster(cluster=clusterName)
232
233
234 def main():
235 argument_spec = dict(
236 state=dict(required=True, choices=["present", "absent", "has_instances"]),
237 name=dict(required=True, type="str"),
238 delay=dict(required=False, type="int", default=10),
239 repeat=dict(required=False, type="int", default=10),
240 purge_capacity_providers=dict(required=False, type="bool", default=True),
241 capacity_providers=dict(required=False, type="list", elements="str"),
242 capacity_provider_strategy=dict(
243 required=False,
244 type="list",
245 elements="dict",
246 options=dict(
247 capacity_provider=dict(type="str"),
248 weight=dict(type="int"),
249 base=dict(type="int", default=0),
250 ),
251 ),
252 )
253 required_together = [["state", "name"]]
254
255 module = AnsibleAWSModule(
256 argument_spec=argument_spec,
257 supports_check_mode=True,
258 required_together=required_together,
259 )
260
261 cluster_mgr = EcsClusterManager(module)
262 try:
263 existing = cluster_mgr.describe_cluster(module.params["name"])
264 except Exception as e:
265 module.fail_json(msg="Exception describing cluster '" + module.params["name"] + "': " + str(e))
266
267 results = dict(changed=False)
268 if module.params["state"] == "present":
269 # Pull requested and existing capacity providers and strategies.
270 purge_capacity_providers = module.params["purge_capacity_providers"]
271 requested_cp = module.params["capacity_providers"]
272 requested_cps = module.params["capacity_provider_strategy"]
273 if existing and "status" in existing and existing["status"] == "ACTIVE":
274 existing_cp = existing["capacityProviders"]
275 existing_cps = existing["defaultCapacityProviderStrategy"]
276
277 if requested_cp is None:
278 requested_cp = []
279
280 # Check if capacity provider strategy needs to trigger an update.
281 cps_update_needed = False
282 if requested_cps is not None:
283 for strategy in requested_cps:
284 if snake_dict_to_camel_dict(strategy) not in existing_cps:
285 cps_update_needed = True
286 for strategy in existing_cps:
287 if camel_dict_to_snake_dict(strategy) not in requested_cps:
288 cps_update_needed = True
289 elif requested_cps is None and existing_cps != []:
290 cps_update_needed = True
291
292 # Unless purge_capacity_providers is true, we will not be updating the providers or strategy.
293 if not purge_capacity_providers:
294 cps_update_needed = False
295 requested_cp = existing_cp
296 requested_cps = existing_cps
297
298 # If either the providers or strategy differ, update the cluster.
299 if requested_cp != existing_cp or cps_update_needed:
300 if not module.check_mode:
301 results["cluster"] = cluster_mgr.update_cluster(
302 cluster_name=module.params["name"],
303 capacity_providers=requested_cp,
304 capacity_provider_strategy=requested_cps,
305 )
306 results["changed"] = True
307 else:
308 results["cluster"] = existing
309 else:
310 if not module.check_mode:
311 # doesn't exist. create it.
312 results["cluster"] = cluster_mgr.create_cluster(
313 cluster_name=module.params["name"],
314 capacity_providers=requested_cp,
315 capacity_provider_strategy=requested_cps,
316 )
317 results["changed"] = True
318
319 # delete the cluster
320 elif module.params["state"] == "absent":
321 if not existing:
322 pass
323 else:
324 # it exists, so we should delete it and mark changed.
325 # return info about the cluster deleted
326 results["cluster"] = existing
327 if "status" in existing and existing["status"] == "INACTIVE":
328 results["changed"] = False
329 else:
330 if not module.check_mode:
331 cluster_mgr.delete_cluster(module.params["name"])
332 results["changed"] = True
333 elif module.params["state"] == "has_instances":
334 if not existing:
335 module.fail_json(msg="Cluster '" + module.params["name"] + " not found.")
336
337 # it exists, so we should delete it and mark changed.
338 # return info about the cluster deleted
339 delay = module.params["delay"]
340 repeat = module.params["repeat"]
341 time.sleep(delay)
342 count = 0
343 for i in range(repeat):
344 existing = cluster_mgr.describe_cluster(module.params["name"])
345 count = existing["registeredContainerInstancesCount"]
346 if count > 0:
347 results["changed"] = True
348 break
349 time.sleep(delay)
350 if count == 0 and i is repeat - 1:
351 module.fail_json(
352 msg="Cluster instance count still zero after "
353 + str(repeat)
354 + " tries of "
355 + str(delay)
356 + " seconds each."
357 )
358
359 module.exit_json(**results)
360
361
362 if __name__ == "__main__":
363 main()