Debian Codegraph @

ansible_collections/community/aws/plugins/modules/ecs_task.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_task
10 version_added: 1.0.0
11 short_description: Run, start or stop a task in ECS
12 description:
13 - Creates or deletes instances of task definitions.
14 author:
15 - Mark Chance (@Java1Guy)
16 options:
17 operation:
18 description:
19 - Which task operation to execute.
20 - When I(operation=run) I(task_definition) must be set.
21 - When I(operation=start) both I(task_definition) and I(container_instances) must be set.
22 - When I(operation=stop) both I(task_definition) and I(task) must be set.
23 required: True
24 choices: ['run', 'start', 'stop']
25 type: str
26 cluster:
27 description:
28 - The name of the cluster to run the task on.
29 - If not specified, the cluster name will be C(default).
30 required: False
31 type: str
32 default: 'default'
33 task_definition:
34 description:
35 - The task definition to start, run or stop.
36 required: False
37 type: str
38 overrides:
39 description:
40 - A dictionary of values to pass to the new instances.
41 required: False
42 type: dict
43 count:
44 description:
45 - How many new instances to start.
46 required: False
47 type: int
48 task:
49 description:
50 - The ARN of the task to stop.
51 required: False
52 type: str
53 container_instances:
54 description:
55 - The list of container instances on which to deploy the task.
56 required: False
57 type: list
58 elements: str
59 started_by:
60 description:
61 - A value showing who or what started the task (for informational purposes).
62 required: False
63 type: str
64 network_configuration:
65 description:
66 - Network configuration of the service. Only applicable for task definitions created with I(network_mode=awsvpc).
67 type: dict
68 suboptions:
69 assign_public_ip:
70 description: Whether the task's elastic network interface receives a public IP address.
71 type: bool
72 version_added: 1.5.0
73 subnets:
74 description: A list of subnet IDs to which the task is attached.
75 type: list
76 elements: str
77 security_groups:
78 description: A list of group names or group IDs for the task.
79 type: list
80 elements: str
81 launch_type:
82 description:
83 - The launch type on which to run your service.
84 required: false
85 choices: ["EC2", "FARGATE"]
86 type: str
87 tags:
88 type: dict
89 description:
90 - Tags that will be added to ecs tasks on start and run
91 required: false
92 aliases: ['resource_tags']
93 wait:
94 description:
95 - Whether or not to wait for the desired state.
96 type: bool
97 default: false
98 version_added: 4.1.0
99 extends_documentation_fragment:
100 - amazon.aws.common.modules
101 - amazon.aws.region.modules
102 - amazon.aws.boto3
103 """
104
105 EXAMPLES = r"""
106 # Simple example of run task
107 - name: Run task
108 community.aws.ecs_task:
109 operation: run
110 cluster: console-sample-app-static-cluster
111 task_definition: console-sample-app-static-taskdef
112 count: 1
113 started_by: ansible_user
114 register: task_output
115
116 # Simple example of start task
117
118 - name: Start a task
119 community.aws.ecs_task:
120 operation: start
121 cluster: console-sample-app-static-cluster
122 task_definition: console-sample-app-static-taskdef
123 task: "arn:aws:ecs:us-west-2:123456789012:task/3f8353d1-29a8-4689-bbf6-ad79937ffe8a"
124 tags:
125 resourceName: a_task_for_ansible_to_run
126 type: long_running_task
127 network: internal
128 version: 1.4
129 container_instances:
130 - arn:aws:ecs:us-west-2:123456789012:container-instance/79c23f22-876c-438a-bddf-55c98a3538a8
131 started_by: ansible_user
132 network_configuration:
133 subnets:
134 - subnet-abcd1234
135 security_groups:
136 - sg-aaaa1111
137 - my_security_group
138 register: task_output
139
140 - name: RUN a task on Fargate
141 community.aws.ecs_task:
142 operation: run
143 cluster: console-sample-app-static-cluster
144 task_definition: console-sample-app-static-taskdef
145 task: "arn:aws:ecs:us-west-2:123456789012:task/3f8353d1-29a8-4689-bbf6-ad79937ffe8a"
146 started_by: ansible_user
147 launch_type: FARGATE
148 network_configuration:
149 subnets:
150 - subnet-abcd1234
151 security_groups:
152 - sg-aaaa1111
153 - my_security_group
154 register: task_output
155
156 - name: RUN a task on Fargate with public ip assigned
157 community.aws.ecs_task:
158 operation: run
159 count: 2
160 cluster: console-sample-app-static-cluster
161 task_definition: console-sample-app-static-taskdef
162 task: "arn:aws:ecs:us-west-2:123456789012:task/3f8353d1-29a8-4689-bbf6-ad79937ffe8a"
163 started_by: ansible_user
164 launch_type: FARGATE
165 network_configuration:
166 assign_public_ip: true
167 subnets:
168 - subnet-abcd1234
169 register: task_output
170
171 - name: Stop a task
172 community.aws.ecs_task:
173 operation: stop
174 cluster: console-sample-app-static-cluster
175 task_definition: console-sample-app-static-taskdef
176 task: "arn:aws:ecs:us-west-2:123456789012:task/3f8353d1-29a8-4689-bbf6-ad79937ffe8a"
177 """
178
179 RETURN = r"""
180 task:
181 description: details about the task that was started
182 returned: success
183 type: complex
184 contains:
185 taskArn:
186 description: The Amazon Resource Name (ARN) that identifies the task.
187 returned: always
188 type: str
189 clusterArn:
190 description: The Amazon Resource Name (ARN) of the of the cluster that hosts the task.
191 returned: only when details is true
192 type: str
193 taskDefinitionArn:
194 description: The Amazon Resource Name (ARN) of the task definition.
195 returned: only when details is true
196 type: str
197 containerInstanceArn:
198 description: The Amazon Resource Name (ARN) of the container running the task.
199 returned: only when details is true
200 type: str
201 overrides:
202 description: The container overrides set for this task.
203 returned: only when details is true
204 type: list
205 elements: dict
206 lastStatus:
207 description: The last recorded status of the task.
208 returned: only when details is true
209 type: str
210 desiredStatus:
211 description: The desired status of the task.
212 returned: only when details is true
213 type: str
214 containers:
215 description: The container details.
216 returned: only when details is true
217 type: list
218 elements: dict
219 startedBy:
220 description: The used who started the task.
221 returned: only when details is true
222 type: str
223 stoppedReason:
224 description: The reason why the task was stopped.
225 returned: only when details is true
226 type: str
227 createdAt:
228 description: The timestamp of when the task was created.
229 returned: only when details is true
230 type: str
231 startedAt:
232 description: The timestamp of when the task was started.
233 returned: only when details is true
234 type: str
235 stoppedAt:
236 description: The timestamp of when the task was stopped.
237 returned: only when details is true
238 type: str
239 launchType:
240 description: The launch type on which to run your task.
241 returned: always
242 type: str
243 """
244
245 try:
246 import botocore
247 except ImportError:
248 pass # caught by AnsibleAWSModule
249
250 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import get_ec2_security_group_ids_from_names
251 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
252
253 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
254
255
256 class EcsExecManager:
257 """Handles ECS Tasks"""
258
259 def __init__(self, module):
260 self.module = module
261 self.ecs = module.client("ecs")
262 self.ec2 = module.client("ec2")
263
264 def format_network_configuration(self, network_config):
265 result = dict()
266 if "subnets" in network_config:
267 result["subnets"] = network_config["subnets"]
268 else:
269 self.module.fail_json(msg="Network configuration must include subnets")
270 if "security_groups" in network_config:
271 groups = network_config["security_groups"]
272 if any(not sg.startswith("sg-") for sg in groups):
273 try:
274 vpc_id = self.ec2.describe_subnets(SubnetIds=[result["subnets"][0]])["Subnets"][0]["VpcId"]
275 groups = get_ec2_security_group_ids_from_names(groups, self.ec2, vpc_id)
276 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
277 self.module.fail_json_aws(e, msg="Couldn't look up security groups")
278 result["securityGroups"] = groups
279 if "assign_public_ip" in network_config:
280 if network_config["assign_public_ip"] is True:
281 result["assignPublicIp"] = "ENABLED"
282 else:
283 result["assignPublicIp"] = "DISABLED"
284
285 return dict(awsvpcConfiguration=result)
286
287 def list_tasks(self, cluster_name, service_name, status):
288 response = self.ecs.list_tasks(
289 cluster=cluster_name,
290 family=service_name,
291 desiredStatus=status,
292 )
293 if len(response["taskArns"]) > 0:
294 for c in response["taskArns"]:
295 if c.endswith(service_name):
296 return c
297 return None
298
299 def run_task(self, cluster, task_definition, overrides, count, startedBy, launch_type, tags):
300 if overrides is None:
301 overrides = dict()
302 params = dict(
303 cluster=cluster, taskDefinition=task_definition, overrides=overrides, count=count, startedBy=startedBy
304 )
305 if self.module.params["network_configuration"]:
306 params["networkConfiguration"] = self.format_network_configuration(
307 self.module.params["network_configuration"]
308 )
309 if launch_type:
310 params["launchType"] = launch_type
311 if tags:
312 params["tags"] = ansible_dict_to_boto3_tag_list(tags, "key", "value")
313
314 # TODO: need to check if long arn format enabled.
315 try:
316 response = self.ecs.run_task(**params)
317 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
318 self.module.fail_json_aws(e, msg="Couldn't run task")
319 # include tasks and failures
320 return response["tasks"]
321
322 def start_task(self, cluster, task_definition, overrides, container_instances, startedBy, tags):
323 args = dict()
324 if cluster:
325 args["cluster"] = cluster
326 if task_definition:
327 args["taskDefinition"] = task_definition
328 if overrides:
329 args["overrides"] = overrides
330 if container_instances:
331 args["containerInstances"] = container_instances
332 if startedBy:
333 args["startedBy"] = startedBy
334 if self.module.params["network_configuration"]:
335 args["networkConfiguration"] = self.format_network_configuration(
336 self.module.params["network_configuration"]
337 )
338 if tags:
339 args["tags"] = ansible_dict_to_boto3_tag_list(tags, "key", "value")
340 try:
341 response = self.ecs.start_task(**args)
342 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
343 self.module.fail_json_aws(e, msg="Couldn't start task")
344 # include tasks and failures
345 return response["tasks"]
346
347 def stop_task(self, cluster, task):
348 response = self.ecs.stop_task(cluster=cluster, task=task)
349 return response["task"]
350
351 def ecs_task_long_format_enabled(self):
352 account_support = self.ecs.list_account_settings(name="taskLongArnFormat", effectiveSettings=True)
353 return account_support["settings"][0]["value"] == "enabled"
354
355
356 def main():
357 argument_spec = dict(
358 operation=dict(required=True, choices=["run", "start", "stop"]),
359 cluster=dict(required=False, type="str", default="default"), # R S P
360 task_definition=dict(required=False, type="str"), # R* S*
361 overrides=dict(required=False, type="dict"), # R S
362 count=dict(required=False, type="int"), # R
363 task=dict(required=False, type="str"), # P*
364 container_instances=dict(required=False, type="list", elements="str"), # S*
365 started_by=dict(required=False, type="str"), # R S
366 network_configuration=dict(required=False, type="dict"),
367 launch_type=dict(required=False, choices=["EC2", "FARGATE"]),
368 tags=dict(required=False, type="dict", aliases=["resource_tags"]),
369 wait=dict(required=False, default=False, type="bool"),
370 )
371
372 module = AnsibleAWSModule(
373 argument_spec=argument_spec,
374 supports_check_mode=True,
375 required_if=[
376 ("launch_type", "FARGATE", ["network_configuration"]),
377 ("operation", "run", ["task_definition"]),
378 ("operation", "start", ["task_definition", "container_instances"]),
379 ("operation", "stop", ["task_definition", "task"]),
380 ],
381 )
382
383 # Validate Inputs
384 if module.params["operation"] == "run":
385 task_to_list = module.params["task_definition"]
386 status_type = "RUNNING"
387
388 if module.params["operation"] == "start":
389 task_to_list = module.params["task"]
390 status_type = "RUNNING"
391
392 if module.params["operation"] == "stop":
393 task_to_list = module.params["task_definition"]
394 status_type = "STOPPED"
395
396 service_mgr = EcsExecManager(module)
397
398 if module.params["tags"]:
399 if not service_mgr.ecs_task_long_format_enabled():
400 module.fail_json(msg="Cannot set task tags: long format task arns are required to set tags")
401
402 existing = service_mgr.list_tasks(module.params["cluster"], task_to_list, status_type)
403
404 results = dict(changed=False)
405 if module.params["operation"] == "run":
406 if existing:
407 # TBD - validate the rest of the details
408 results["task"] = existing
409 else:
410 if not module.check_mode:
411 # run_task returns a list of tasks created
412 tasks = service_mgr.run_task(
413 module.params["cluster"],
414 module.params["task_definition"],
415 module.params["overrides"],
416 module.params["count"],
417 module.params["started_by"],
418 module.params["launch_type"],
419 module.params["tags"],
420 )
421
422 # Wait for task(s) to be running prior to exiting
423 if module.params["wait"]:
424 waiter = service_mgr.ecs.get_waiter("tasks_running")
425 try:
426 waiter.wait(
427 tasks=[task["taskArn"] for task in tasks],
428 cluster=module.params["cluster"],
429 )
430 except botocore.exceptions.WaiterError as e:
431 module.fail_json_aws(e, "Timeout waiting for tasks to run")
432
433 results["task"] = tasks
434
435 results["changed"] = True
436
437 elif module.params["operation"] == "start":
438 if existing:
439 # TBD - validate the rest of the details
440 results["task"] = existing
441 else:
442 if not module.check_mode:
443 results["task"] = service_mgr.start_task(
444 module.params["cluster"],
445 module.params["task_definition"],
446 module.params["overrides"],
447 module.params["container_instances"],
448 module.params["started_by"],
449 module.params["tags"],
450 )
451
452 results["changed"] = True
453
454 elif module.params["operation"] == "stop":
455 if existing:
456 results["task"] = existing
457 else:
458 if not module.check_mode:
459 # it exists, so we should delete it and mark changed.
460 # return info about the cluster deleted
461 results["task"] = service_mgr.stop_task(module.params["cluster"], module.params["task"])
462
463 # Wait for task to be stopped prior to exiting
464 if module.params["wait"]:
465 waiter = service_mgr.ecs.get_waiter("tasks_stopped")
466 try:
467 waiter.wait(
468 tasks=[module.params["task"]],
469 cluster=module.params["cluster"],
470 )
471 except botocore.exceptions.WaiterError as e:
472 module.fail_json_aws(e, "Timeout waiting for task to stop")
473
474 results["changed"] = True
475
476 module.exit_json(**results)
477
478
479 if __name__ == "__main__":
480 main()