Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Contributors to the 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_taskdefinition
10 version_added: 1.0.0
11 short_description: register a task definition in ecs
12 description:
13 - Registers or deregisters task definitions in the Amazon Web Services (AWS) EC2 Container Service (ECS).
14 author:
15 - Mark Chance (@Java1Guy)
16 - Alina Buzachis (@alinabuzachis)
17 options:
18 state:
19 description:
20 - State whether the task definition should exist or be deleted.
21 required: true
22 choices: ['present', 'absent']
23 type: str
24 arn:
25 description:
26 - The ARN of the task description to delete.
27 required: false
28 type: str
29 family:
30 description:
31 - A Name that would be given to the task definition.
32 required: false
33 type: str
34 revision:
35 description:
36 - A revision number for the task definition.
37 required: False
38 type: int
39 force_create:
40 description:
41 - Always create new task definition.
42 required: False
43 type: bool
44 default: false
45 containers:
46 description:
47 - A list of containers definitions.
48 - See U(https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ecs.html) for a complete list of parameters.
49 required: True
50 type: list
51 elements: dict
52 suboptions:
53 name:
54 description: The name of a container.
55 required: False
56 type: str
57 image:
58 description: The image used to start a container.
59 required: False
60 type: str
61 repositoryCredentials:
62 description: The private repository authentication credentials to use.
63 required: False
64 type: dict
65 suboptions:
66 credentialsParameter:
67 description:
68 - The Amazon Resource Name (ARN) of the secret containing the private repository credentials.
69 required: True
70 type: str
71 cpu:
72 description: The number of cpu units reserved for the container.
73 required: False
74 type: int
75 memory:
76 description: The amount (in MiB) of memory to present to the container.
77 required: False
78 type: int
79 memoryReservation:
80 description: The soft limit (in MiB) of memory to reserve for the container.
81 required: False
82 type: int
83 links:
84 description:
85 - Allows containers to communicate with each other without the need for port mappings.
86 - This parameter is only supported if I(network_mode=bridge).
87 required: False
88 type: list
89 elements: str
90 portMappings:
91 description: The list of port mappings for the container.
92 required: False
93 type: list
94 elements: dict
95 suboptions:
96 containerPort:
97 description: The port number on the container that is bound to the user-specified or automatically assigned host port.
98 required: False
99 type: int
100 hostPort:
101 description: The port number on the container instance to reserve for your container.
102 required: False
103 type: int
104 protocol:
105 description: The protocol used for the port mapping.
106 required: False
107 type: str
108 default: tcp
109 choices: ['tcp', 'udp']
110 essential:
111 description:
112 - If I(essential=True), and the container fails or stops for any reason, all other containers that are part of the task are stopped.
113 required: False
114 type: bool
115 entryPoint:
116 description: The entry point that is passed to the container.
117 required: False
118 type: str
119 command:
120 description: The command that is passed to the container. If there are multiple arguments, each argument is a separated string in the array.
121 required: False
122 type: list
123 elements: str
124 environment:
125 description: The environment variables to pass to a container.
126 required: False
127 type: list
128 elements: dict
129 suboptions:
130 name:
131 description: The name of the key-value pair.
132 required: False
133 type: str
134 value:
135 description: The value of the key-value pair.
136 required: False
137 type: str
138 environmentFiles:
139 description: A list of files containing the environment variables to pass to a container.
140 required: False
141 type: list
142 elements: dict
143 suboptions:
144 value:
145 description: The Amazon Resource Name (ARN) of the Amazon S3 object containing the environment variable file.
146 required: False
147 type: str
148 type:
149 description: The file type to use. The only supported value is C(s3).
150 required: False
151 type: str
152 mountPoints:
153 description: The mount points for data volumes in your container.
154 required: False
155 type: list
156 elements: dict
157 suboptions:
158 sourceVolume:
159 description: The name of the volume to mount.
160 required: False
161 type: str
162 containerPath:
163 description: The path on the container to mount the host volume at.
164 required: False
165 type: str
166 readOnly:
167 description:
168 - If this value is C(True), the container has read-only access to the volume.
169 - If this value is C(False), then the container can write to the volume.
170 required: False
171 default: False
172 type: bool
173 volumesFrom:
174 description: Data volumes to mount from another container.
175 required: False
176 type: list
177 elements: dict
178 suboptions:
179 sourceContainer:
180 description:
181 - The name of another container within the same task definition from which to mount volumes.
182 required: False
183 type: str
184 readOnly:
185 description:
186 - If this value is C(True), the container has read-only access to the volume.
187 - If this value is C(False), then the container can write to the volume.
188 required: False
189 default: False
190 type: bool
191 linuxParameters:
192 description: Linux-specific modifications that are applied to the container, such as Linux kernel capabilities.
193 required: False
194 type: dict
195 suboptions:
196 capabilities:
197 description:
198 - The Linux capabilities for the container that are added to or dropped from the default configuration provided by Docker.
199 required: False
200 type: dict
201 suboptions:
202 add:
203 description:
204 - The Linux capabilities for the container that have been added to the default configuration provided by Docker.
205 - If I(launch_type=FARGATE), this parameter is not supported.
206 required: False
207 type: list
208 choices: ["ALL", "AUDIT_CONTROL", "AUDIT_WRITE", "BLOCK_SUSPEND", "CHOWN", "DAC_OVERRIDE", "DAC_READ_SEARCH", "FOWNER",
209 "FSETID", "IPC_LOCK", "IPC_OWNER", "KILL", "LEASE", "LINUX_IMMUTABLE", "MAC_ADMIN", "MAC_OVERRIDE", "MKNOD",
210 "NET_ADMIN", "NET_BIND_SERVICE", "NET_BROADCAST", "NET_RAW", "SETFCAP", "SETGID", "SETPCAP", "SETUID",
211 "SYS_ADMIN", "SYS_BOOT", "SYS_CHROOT", "SYS_MODULE", "SYS_NICE", "SYS_PACCT", "SYS_PTRACE", "SYS_RAWIO",
212 "SYS_RESOURCE", "SYS_TIME", "SYS_TTY_CONFIG", "SYSLOG", "WAKE_ALARM"]
213 elements: str
214 drop:
215 description:
216 - The Linux capabilities for the container that have been removed from the default configuration provided by Docker.
217 required: False
218 type: list
219 choices: ["ALL", "AUDIT_CONTROL", "AUDIT_WRITE", "BLOCK_SUSPEND", "CHOWN", "DAC_OVERRIDE", "DAC_READ_SEARCH", "FOWNER",
220 "FSETID", "IPC_LOCK", "IPC_OWNER", "KILL", "LEASE", "LINUX_IMMUTABLE", "MAC_ADMIN", "MAC_OVERRIDE", "MKNOD",
221 "NET_ADMIN", "NET_BIND_SERVICE", "NET_BROADCAST", "NET_RAW", "SETFCAP", "SETGID", "SETPCAP", "SETUID",
222 "SYS_ADMIN", "SYS_BOOT", "SYS_CHROOT", "SYS_MODULE", "SYS_NICE", "SYS_PACCT", "SYS_PTRACE", "SYS_RAWIO",
223 "SYS_RESOURCE", "SYS_TIME", "SYS_TTY_CONFIG", "SYSLOG", "WAKE_ALARM"]
224 elements: str
225 devices:
226 description:
227 - Any host devices to expose to the container.
228 - If I(launch_type=FARGATE), this parameter is not supported.
229 required: False
230 type: list
231 elements: dict
232 suboptions:
233 hostPath:
234 description: The path for the device on the host container instance.
235 required: True
236 type: str
237 containerPath:
238 description: The path inside the container at which to expose the host device.
239 required: False
240 type: str
241 permissions:
242 description: The explicit permissions to provide to the container for the device.
243 required: False
244 type: list
245 elements: str
246 initProcessEnabled:
247 description: Run an init process inside the container that forwards signals and reaps processes.
248 required: False
249 type: bool
250 sharedMemorySize:
251 description:
252 - The value for the size (in MiB) of the /dev/shm volume.
253 - If I(launch_type=FARGATE), this parameter is not supported.
254 required: False
255 type: int
256 tmpfs:
257 description:
258 - The container path, mount options, and size (in MiB) of the tmpfs mount.
259 - If I(launch_type=FARGATE), this parameter is not supported.
260 required: False
261 type: list
262 elements: dict
263 suboptions:
264 containerPath:
265 description: The absolute file path where the tmpfs volume is to be mounted.
266 required: True
267 type: str
268 size:
269 description: The size (in MiB) of the tmpfs volume.
270 required: True
271 type: int
272 mountOptions:
273 description: The list of tmpfs volume mount options.
274 required: False
275 type: list
276 choices: ["defaults", "ro", "rw", "suid", "nosuid", "dev", "nodev", "exec", "noexec", "sync", "async", "dirsync",
277 "remount", "mand", "nomand", "atime", "noatime", "diratime", "nodiratime", "bind", "rbind", "unbindable",
278 "runbindable", "private", "rprivate", "shared", "rshared", "slave", "rslave", "relatime", "norelatime",
279 "strictatime", "nostrictatime", "mode", "uid", "gid", "nr_inodes", "nr_blocks", "mpol"]
280 elements: str
281 maxSwap:
282 description:
283 - The total amount of swap memory (in MiB) a container can use.
284 - If I(launch_type=FARGATE), this parameter is not supported.
285 required: False
286 type: int
287 swappiness:
288 description:
289 - This allows you to tune a container's memory swappiness behavior.
290 - If I(launch_type=FARGATE), this parameter is not supported.
291 required: False
292 type: int
293 secrets:
294 description: The secrets to pass to the container.
295 required: False
296 type: list
297 elements: dict
298 suboptions:
299 name:
300 description: The value to set as the environment variable on the container.
301 required: True
302 type: str
303 size:
304 description: The secret to expose to the container.
305 required: True
306 type: str
307 dependsOn:
308 description:
309 - The dependencies defined for container startup and shutdown.
310 - When a dependency is defined for container startup, for container shutdown it is reversed.
311 required: False
312 type: list
313 elements: dict
314 suboptions:
315 containerName:
316 description: The name of a container.
317 type: str
318 required: True
319 condition:
320 description: The dependency condition of the container.
321 type: str
322 required: True
323 choices: ["start", "complete", "success", "healthy"]
324 startTimeout:
325 description: Time duration (in seconds) to wait before giving up on resolving dependencies for a container.
326 required: False
327 type: int
328 stopTimeout:
329 description: Time duration (in seconds) to wait before the container is forcefully killed if it doesn't exit normally on its own.
330 required: False
331 type: int
332 hostname:
333 description:
334 - The hostname to use for your container.
335 - This parameter is not supported if I(network_mode=awsvpc).
336 required: False
337 type: str
338 user:
339 description:
340 - The user to use inside the container.
341 - This parameter is not supported for Windows containers.
342 required: False
343 type: str
344 workingDirectory:
345 description: The working directory in which to run commands inside the container.
346 required: False
347 type: str
348 disableNetworking:
349 description: When this parameter is C(True), networking is disabled within the container.
350 required: False
351 type: bool
352 privileged:
353 description: When this parameter is C(True), the container is given elevated privileges on the host container instance.
354 required: False
355 type: bool
356 readonlyRootFilesystem:
357 description: When this parameter is C(True), the container is given read-only access to its root file system.
358 required: false
359 type: bool
360 dnsServers:
361 description:
362 - A list of DNS servers that are presented to the container.
363 - This parameter is not supported for Windows containers.
364 required: False
365 type: list
366 elements: str
367 dnsSearchDomains:
368 description:
369 - A list of DNS search domains that are presented to the container.
370 - This parameter is not supported for Windows containers.
371 required: False
372 type: list
373 elements: str
374 extraHosts:
375 description:
376 - A list of hostnames and IP address mappings to append to the /etc/hosts file on the container.
377 - This parameter is not supported for Windows containers or tasks that use I(network_mode=awsvpc).
378 required: False
379 type: list
380 elements: dict
381 suboptions:
382 hostname:
383 description: The hostname to use in the /etc/hosts entry.
384 type: str
385 required: False
386 ipAddress:
387 description: The IP address to use in the /etc/hosts entry.
388 type: str
389 required: False
390 dockerSecurityOptions:
391 description:
392 - A list of strings to provide custom labels for SELinux and AppArmor multi-level security systems.
393 - This parameter is not supported for Windows containers.
394 required: False
395 type: list
396 elements: str
397 interactive:
398 description:
399 - When I(interactive=True), it allows to deploy containerized applications that require stdin or a tty to be allocated.
400 required: False
401 type: bool
402 pseudoTerminal:
403 description: When this parameter is C(True), a TTY is allocated.
404 required: False
405 type: bool
406 dockerLabels:
407 description: A key/value map of labels to add to the container.
408 required: False
409 type: dict
410 ulimits:
411 description:
412 - A list of ulimits to set in the container.
413 - This parameter is not supported for Windows containers.
414 required: False
415 type: list
416 elements: dict
417 suboptions:
418 name:
419 description: The type of the ulimit.
420 type: str
421 required: False
422 choices: ['core', 'cpu', 'data', 'fsize', 'locks', 'memlock', 'msgqueue', 'nice', 'nofile', 'nproc', 'rss',
423 'rtprio', 'rttime', 'sigpending', 'stack']
424 softLimit:
425 description: The soft limit for the ulimit type.
426 type: int
427 required: False
428 hardLimit:
429 description: The hard limit for the ulimit type.
430 type: int
431 required: False
432 logConfiguration:
433 description: The log configuration specification for the container.
434 required: False
435 type: dict
436 suboptions:
437 logDriver:
438 description:
439 - The log driver to use for the container.
440 - For tasks on AWS Fargate, the supported log drivers are C(awslogs), C(splunk), and C(awsfirelens).
441 - For tasks hosted on Amazon EC2 instances, the supported log drivers are C(awslogs), C(fluentd),
442 C(gelf), C(json-file), C(journald), C(logentries), C(syslog), C(splunk), and C(awsfirelens).
443 type: str
444 required: False
445 options:
446 description: The configuration options to send to the log driver.
447 required: False
448 type: str
449 secretOptions:
450 description: The secrets to pass to the log configuration.
451 required: False
452 type: list
453 elements: dict
454 suboptions:
455 name:
456 description: The name of the secret.
457 type: str
458 required: False
459 valueFrom:
460 description: The secret to expose to the container.
461 type: str
462 required: False
463 healthCheck:
464 description: The health check command and associated configuration parameters for the container.
465 required: False
466 type: dict
467 suboptions:
468 command:
469 description:
470 - A string array representing the command that the container runs to determine if it is healthy.
471 - >
472 The string array must start with CMD to run the command arguments directly,
473 or CMD-SHELL to run the command with the container's default shell.
474 - An exit code of 0 indicates success, and non-zero exit code indicates failure.
475 required: False
476 type: list
477 elements: str
478 interval:
479 description:
480 - The time period in seconds between each health check execution.
481 - You may specify between 5 and 300 seconds. The default value is 30 seconds.
482 required: False
483 type: int
484 default: 30
485 retries:
486 description:
487 - The number of times to retry a failed health check before the container is considered unhealthy.
488 - You may specify between 1 and 10 retries. The default value is 3.
489 required: False
490 type: int
491 default: 3
492 startPeriod:
493 description:
494 - >
495 The optional grace period to provide containers time to bootstrap
496 before failed health checks count towards the maximum number of retries.
497 - You can specify between 0 and 300 seconds. By default, the startPeriod is disabled.
498 - >
499 Note: If a health check succeeds within the startPeriod,
500 then the container is considered healthy and any subsequent failures count toward the maximum number of retries.
501 required: False
502 type: int
503 timeout:
504 description:
505 - The time period in seconds to wait for a health check to succeed before it is considered a failure.
506 - You may specify between 2 and 60 seconds. The default value is 5.
507 required: False
508 type: int
509 default: 5
510 systemControls:
511 description: A list of namespaced kernel parameters to set in the container.
512 required: False
513 type: list
514 elements: dict
515 suboptions:
516 namespace:
517 description: The namespaced kernel parameter to set a C(value) for.
518 type: str
519 value:
520 description: The value for the namespaced kernel parameter that's specified in C(namespace).
521 type: str
522 resourceRequirements:
523 description:
524 - The type and amount of a resource to assign to a container.
525 - The only supported resources are C(GPU) and C(InferenceAccelerator).
526 required: False
527 type: list
528 elements: dict
529 suboptions:
530 value:
531 description: The value for the specified resource type.
532 type: str
533 type:
534 description: The type of resource to assign to a container.
535 type: str
536 choices: ['GPU', 'InferenceAccelerator']
537 firelensConfiguration:
538 description:
539 - The FireLens configuration for the container.
540 - This is used to specify and configure a log router for container logs.
541 required: False
542 type: dict
543 suboptions:
544 type:
545 description:
546 - The log router to use. The valid values are C(fluentd) or C(fluentbit).
547 required: False
548 type: str
549 choices:
550 - fluentd
551 - fluentbit
552 options:
553 description:
554 - The options to use when configuring the log router.
555 - This field is optional and can be used to specify a custom configuration
556 file or to add additional metadata, such as the task, task definition, cluster,
557 and container instance details to the log event.
558 - If specified, the syntax to use is
559 C({"enable-ecs-log-metadata":"true|false","config-file-type:"s3|file","config-file-value":"arn:aws:s3:::mybucket/fluent.conf|filepath"}).
560 - For more information, see U(https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html#firelens-taskdef).
561 required: False
562 type: dict
563 network_mode:
564 description:
565 - The Docker networking mode to use for the containers in the task.
566 - Windows containers must use I(network_mode=default), which will utilize docker NAT networking.
567 - Setting I(network_mode=default) for a Linux container will use C(bridge) mode.
568 required: false
569 default: bridge
570 choices: [ 'default', 'bridge', 'host', 'none', 'awsvpc' ]
571 type: str
572 task_role_arn:
573 description:
574 - The Amazon Resource Name (ARN) of the IAM role that containers in this task can assume. All containers in this task are granted
575 the permissions that are specified in this role.
576 required: false
577 type: str
578 default: ''
579 execution_role_arn:
580 description:
581 - The Amazon Resource Name (ARN) of the task execution role that the Amazon ECS container agent and the Docker daemon can assume.
582 required: false
583 type: str
584 default: ''
585 volumes:
586 description:
587 - A list of names of volumes to be attached.
588 required: False
589 type: list
590 elements: dict
591 suboptions:
592 name:
593 type: str
594 description: The name of the volume.
595 required: true
596 launch_type:
597 description:
598 - The launch type on which to run your task.
599 required: false
600 type: str
601 choices: ["EC2", "FARGATE"]
602 cpu:
603 description:
604 - The number of cpu units used by the task. If I(launch_type=EC2), this field is optional and any value can be used.
605 - If I(launch_type=FARGATE), this field is required and you must use one of C(256), C(512), C(1024), C(2048), C(4096).
606 required: false
607 type: str
608 memory:
609 description:
610 - The amount (in MiB) of memory used by the task. If I(launch_type=EC2), this field is optional and any value can be used.
611 - If I(launch_type=FARGATE), this field is required and is limited by the CPU.
612 required: false
613 type: str
614 placement_constraints:
615 version_added: 2.1.0
616 description:
617 - Placement constraint objects to use for the task.
618 - You can specify a maximum of 10 constraints per task.
619 - Task placement constraints are not supported for tasks run on Fargate.
620 required: false
621 type: list
622 elements: dict
623 suboptions:
624 type:
625 description: The type of constraint.
626 type: str
627 expression:
628 description: A cluster query language expression to apply to the constraint.
629 type: str
630 runtime_platform:
631 version_added: 6.4.0
632 description:
633 - runtime platform configuration for the task
634 required: false
635 type: dict
636 default: {
637 "operatingSystemFamily": "LINUX",
638 "cpuArchitecture": "X86_64"
639 }
640 suboptions:
641 cpuArchitecture:
642 description: The CPU Architecture type to be used by the task
643 type: str
644 required: false
645 choices: ['X86_64', 'ARM64']
646 operatingSystemFamily:
647 description: OS type to be used by the task
648 type: str
649 required: false
650 choices: ['LINUX', 'WINDOWS_SERVER_2019_FULL', 'WINDOWS_SERVER_2019_CORE', 'WINDOWS_SERVER_2022_FULL', 'WINDOWS_SERVER_2022_CORE']
651 extends_documentation_fragment:
652 - amazon.aws.common.modules
653 - amazon.aws.region.modules
654 - amazon.aws.boto3
655 """
656
657 EXAMPLES = r"""
658 - name: Create task definition
659 community.aws.ecs_taskdefinition:
660 containers:
661 - name: simple-app
662 cpu: 10
663 essential: true
664 image: "httpd:2.4"
665 memory: 300
666 mountPoints:
667 - containerPath: /usr/local/apache2/htdocs
668 sourceVolume: my-vol
669 portMappings:
670 - containerPort: 80
671 hostPort: 80
672 logConfiguration:
673 logDriver: awslogs
674 options:
675 awslogs-group: /ecs/test-cluster-taskdef
676 awslogs-region: us-west-2
677 awslogs-stream-prefix: ecs
678 - name: busybox
679 command:
680 - >
681 /bin/sh -c "while true; do echo '<html><head><title>Amazon ECS Sample App</title></head><body><div><h1>Amazon ECS Sample App</h1>
682 <h2>Congratulations!</h2>
683 <p>Your application is now running on a container in Amazon ECS.</p>' > top; /bin/date > date ; echo '</div></body></html>' > bottom;
684 cat top date bottom > /usr/local/apache2/htdocs/index.html ; sleep 1; done"
685 cpu: 10
686 entryPoint:
687 - sh
688 - "-c"
689 essential: false
690 image: busybox
691 memory: 200
692 volumesFrom:
693 - sourceContainer: simple-app
694 volumes:
695 - name: my-vol
696 family: test-cluster-taskdef
697 state: present
698 register: task_output
699
700 - name: Create task definition
701 community.aws.ecs_taskdefinition:
702 family: nginx
703 containers:
704 - name: nginx
705 essential: true
706 image: "nginx"
707 portMappings:
708 - containerPort: 8080
709 hostPort: 8080
710 cpu: 512
711 memory: 1024
712 state: present
713
714 - name: Create task definition
715 community.aws.ecs_taskdefinition:
716 family: nginx
717 containers:
718 - name: nginx
719 essential: true
720 image: "nginx"
721 portMappings:
722 - containerPort: 8080
723 hostPort: 8080
724 launch_type: FARGATE
725 cpu: 512
726 memory: 1024
727 state: present
728 network_mode: awsvpc
729
730 - name: Create task definition
731 community.aws.ecs_taskdefinition:
732 family: nginx
733 containers:
734 - name: nginx
735 essential: true
736 image: "nginx"
737 portMappings:
738 - containerPort: 8080
739 hostPort: 8080
740 cpu: 512
741 memory: 1024
742 dependsOn:
743 - containerName: "simple-app"
744 condition: "start"
745
746 # Create Task Definition with Environment Variables and Secrets
747 - name: Create task definition
748 community.aws.ecs_taskdefinition:
749 family: nginx
750 containers:
751 - name: nginx
752 essential: true
753 image: "nginx"
754 environment:
755 - name: "PORT"
756 value: "8080"
757 secrets:
758 # For variables stored in Secrets Manager
759 - name: "NGINX_HOST"
760 valueFrom: "arn:aws:secretsmanager:us-west-2:123456789012:secret:nginx/NGINX_HOST"
761 # For variables stored in Parameter Store
762 - name: "API_KEY"
763 valueFrom: "arn:aws:ssm:us-west-2:123456789012:parameter/nginx/API_KEY"
764 launch_type: FARGATE
765 cpu: 512
766 memory: 1GB
767 state: present
768 network_mode: awsvpc
769
770 # Create Task Definition with health check
771 - name: Create task definition
772 community.aws.ecs_taskdefinition:
773 family: nginx
774 containers:
775 - name: nginx
776 essential: true
777 image: "nginx"
778 portMappings:
779 - containerPort: 8080
780 hostPort: 8080
781 cpu: 512
782 memory: 1024
783 healthCheck:
784 command:
785 - CMD-SHELL
786 - /app/healthcheck.py
787 interval: 60
788 retries: 3
789 startPeriod: 15
790 timeout: 15
791 state: present
792 """
793
794 RETURN = r"""
795 taskdefinition:
796 description: a reflection of the input parameters
797 type: dict
798 returned: always
799 """
800
801 try:
802 import botocore
803 except ImportError:
804 pass # caught by AnsibleAWSModule
805
806 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
807
808 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
809
810
811 class EcsTaskManager:
812 """Handles ECS Tasks"""
813
814 def __init__(self, module):
815 self.module = module
816
817 self.ecs = module.client("ecs", AWSRetry.jittered_backoff())
818
819 def describe_task(self, task_name):
820 try:
821 response = self.ecs.describe_task_definition(aws_retry=True, taskDefinition=task_name)
822 return response["taskDefinition"]
823 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError):
824 return None
825
826 def register_task(
827 self,
828 family,
829 task_role_arn,
830 execution_role_arn,
831 network_mode,
832 container_definitions,
833 volumes,
834 launch_type,
835 cpu,
836 memory,
837 placement_constraints,
838 runtime_platform,
839 ):
840 validated_containers = []
841
842 # Ensures the number parameters are int as required by the AWS SDK
843 for container in container_definitions:
844 for param in ("memory", "cpu", "memoryReservation", "startTimeout", "stopTimeout"):
845 if param in container:
846 container[param] = int(container[param])
847
848 if "portMappings" in container:
849 for port_mapping in container["portMappings"]:
850 for port in ("hostPort", "containerPort"):
851 if port in port_mapping:
852 port_mapping[port] = int(port_mapping[port])
853 if network_mode == "awsvpc" and "hostPort" in port_mapping:
854 if port_mapping["hostPort"] != port_mapping.get("containerPort"):
855 self.module.fail_json(
856 msg=(
857 "In awsvpc network mode, host port must be set to the same as "
858 "container port or not be set"
859 )
860 )
861
862 if "linuxParameters" in container:
863 for linux_param in container.get("linuxParameters"):
864 if linux_param == "tmpfs":
865 for tmpfs_param in container["linuxParameters"]["tmpfs"]:
866 if "size" in tmpfs_param:
867 tmpfs_param["size"] = int(tmpfs_param["size"])
868
869 for param in ("maxSwap", "swappiness", "sharedMemorySize"):
870 if param in linux_param:
871 container["linuxParameters"][param] = int(container["linuxParameters"][param])
872
873 if "ulimits" in container:
874 for limits_mapping in container["ulimits"]:
875 for limit in ("softLimit", "hardLimit"):
876 if limit in limits_mapping:
877 limits_mapping[limit] = int(limits_mapping[limit])
878
879 validated_containers.append(container)
880
881 params = dict(
882 family=family,
883 taskRoleArn=task_role_arn,
884 containerDefinitions=container_definitions,
885 volumes=volumes,
886 )
887 if network_mode != "default":
888 params["networkMode"] = network_mode
889 if cpu:
890 params["cpu"] = cpu
891 if memory:
892 params["memory"] = memory
893 if launch_type:
894 params["requiresCompatibilities"] = [launch_type]
895 if execution_role_arn:
896 params["executionRoleArn"] = execution_role_arn
897 if placement_constraints:
898 params["placementConstraints"] = placement_constraints
899 if runtime_platform:
900 params["runtimePlatform"] = runtime_platform
901
902 try:
903 response = self.ecs.register_task_definition(aws_retry=True, **params)
904 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
905 self.module.fail_json_aws(e, msg="Failed to register task")
906
907 return response["taskDefinition"]
908
909 def describe_task_definitions(self, family):
910 data = {"taskDefinitionArns": [], "nextToken": None}
911
912 def fetch():
913 # Boto3 is weird about params passed, so only pass nextToken if we have a value
914 params = {"familyPrefix": family}
915
916 if data["nextToken"]:
917 params["nextToken"] = data["nextToken"]
918
919 result = self.ecs.list_task_definitions(aws_retry=True, **params)
920 data["taskDefinitionArns"] += result["taskDefinitionArns"]
921 data["nextToken"] = result.get("nextToken", None)
922 return data["nextToken"] is not None
923
924 # Fetch all the arns, possibly across multiple pages
925 while fetch():
926 pass
927
928 # Return the full descriptions of the task definitions, sorted ascending by revision
929 return list(
930 sorted(
931 [
932 self.ecs.describe_task_definition(aws_retry=True, taskDefinition=arn)["taskDefinition"]
933 for arn in data["taskDefinitionArns"]
934 ],
935 key=lambda td: td["revision"],
936 )
937 )
938
939 def deregister_task(self, taskArn):
940 response = self.ecs.deregister_task_definition(aws_retry=True, taskDefinition=taskArn)
941 return response["taskDefinition"]
942
943
944 def main():
945 argument_spec = dict(
946 state=dict(required=True, choices=["present", "absent"]),
947 arn=dict(required=False, type="str"),
948 family=dict(required=False, type="str"),
949 revision=dict(required=False, type="int"),
950 force_create=dict(required=False, default=False, type="bool"),
951 containers=dict(required=True, type="list", elements="dict"),
952 network_mode=dict(
953 required=False, default="bridge", choices=["default", "bridge", "host", "none", "awsvpc"], type="str"
954 ),
955 task_role_arn=dict(required=False, default="", type="str"),
956 execution_role_arn=dict(required=False, default="", type="str"),
957 volumes=dict(required=False, type="list", elements="dict"),
958 launch_type=dict(required=False, choices=["EC2", "FARGATE"]),
959 cpu=dict(),
960 memory=dict(required=False, type="str"),
961 placement_constraints=dict(
962 required=False,
963 type="list",
964 elements="dict",
965 options=dict(type=dict(type="str"), expression=dict(type="str")),
966 ),
967 runtime_platform=dict(
968 required=False,
969 default={"operatingSystemFamily": "LINUX", "cpuArchitecture": "X86_64"},
970 type="dict",
971 options=dict(
972 cpuArchitecture=dict(required=False, choices=["X86_64", "ARM64"]),
973 operatingSystemFamily=dict(
974 required=False,
975 choices=[
976 "LINUX",
977 "WINDOWS_SERVER_2019_FULL",
978 "WINDOWS_SERVER_2019_CORE",
979 "WINDOWS_SERVER_2022_FULL",
980 "WINDOWS_SERVER_2022_CORE",
981 ],
982 ),
983 ),
984 ),
985 )
986
987 module = AnsibleAWSModule(
988 argument_spec=argument_spec,
989 supports_check_mode=True,
990 required_if=[("launch_type", "FARGATE", ["cpu", "memory"])],
991 )
992
993 task_to_describe = None
994 task_mgr = EcsTaskManager(module)
995 results = dict(changed=False)
996
997 if module.params["state"] == "present":
998 if "containers" not in module.params or not module.params["containers"]:
999 module.fail_json(msg="To use task definitions, a list of containers must be specified")
1000
1001 if "family" not in module.params or not module.params["family"]:
1002 module.fail_json(msg="To use task definitions, a family must be specified")
1003
1004 network_mode = module.params["network_mode"]
1005 launch_type = module.params["launch_type"]
1006 placement_constraints = module.params["placement_constraints"]
1007 if launch_type == "FARGATE":
1008 if network_mode != "awsvpc":
1009 module.fail_json(msg="To use FARGATE launch type, network_mode must be awsvpc")
1010 if placement_constraints:
1011 module.fail_json(msg="Task placement constraints are not supported for tasks run on Fargate")
1012
1013 for container in module.params["containers"]:
1014 if container.get("links") and network_mode == "awsvpc":
1015 module.fail_json(msg="links parameter is not supported if network mode is awsvpc.")
1016
1017 for environment in container.get("environment", []):
1018 environment["value"] = environment["value"]
1019
1020 for environment_file in container.get("environmentFiles", []):
1021 if environment_file["type"] != "s3":
1022 module.fail_json(msg="The only supported value for environmentFiles is s3.")
1023
1024 for linux_param in container.get("linuxParameters", {}):
1025 if linux_param == "maxSwap" and launch_type == "FARGATE":
1026 module.fail_json(msg="devices parameter is not supported with the FARGATE launch type.")
1027
1028 if linux_param == "maxSwap" and launch_type == "FARGATE":
1029 module.fail_json(msg="maxSwap parameter is not supported with the FARGATE launch type.")
1030 elif linux_param == "maxSwap" and int(container["linuxParameters"]["maxSwap"]) < 0:
1031 module.fail_json(msg="Accepted values for maxSwap are 0 or any positive integer.")
1032
1033 if linux_param == "swappiness" and (
1034 int(container["linuxParameters"]["swappiness"]) < 0
1035 or int(container["linuxParameters"]["swappiness"]) > 100
1036 ):
1037 module.fail_json(msg="Accepted values for swappiness are whole numbers between 0 and 100.")
1038
1039 if linux_param == "sharedMemorySize" and launch_type == "FARGATE":
1040 module.fail_json(msg="sharedMemorySize parameter is not supported with the FARGATE launch type.")
1041
1042 if linux_param == "tmpfs" and launch_type == "FARGATE":
1043 module.fail_json(msg="tmpfs parameter is not supported with the FARGATE launch type.")
1044
1045 if container.get("hostname") and network_mode == "awsvpc":
1046 module.fail_json(msg="hostname parameter is not supported when the awsvpc network mode is used.")
1047
1048 if container.get("extraHosts") and network_mode == "awsvpc":
1049 module.fail_json(msg="extraHosts parameter is not supported when the awsvpc network mode is used.")
1050
1051 family = module.params["family"]
1052 existing_definitions_in_family = task_mgr.describe_task_definitions(module.params["family"])
1053
1054 if "revision" in module.params and module.params["revision"]:
1055 # The definition specifies revision. We must guarantee that an active revision of that number will result from this.
1056 revision = int(module.params["revision"])
1057
1058 # A revision has been explicitly specified. Attempt to locate a matching revision
1059 tasks_defs_for_revision = [td for td in existing_definitions_in_family if td["revision"] == revision]
1060 existing = tasks_defs_for_revision[0] if len(tasks_defs_for_revision) > 0 else None
1061
1062 if existing and existing["status"] != "ACTIVE":
1063 # We cannot reactivate an inactive revision
1064 module.fail_json(
1065 msg=f"A task in family '{family}' already exists for revision {int(revision)}, but it is inactive"
1066 )
1067 elif not existing:
1068 if not existing_definitions_in_family and revision != 1:
1069 module.fail_json(
1070 msg=f"You have specified a revision of {int(revision)} but a created revision would be 1"
1071 )
1072 elif existing_definitions_in_family and existing_definitions_in_family[-1]["revision"] + 1 != revision:
1073 module.fail_json(
1074 msg=(
1075 f"You have specified a revision of {int(revision)} but a created revision would be"
1076 f" {int(existing_definitions_in_family[-1]['revision'] + 1)}"
1077 )
1078 )
1079 else:
1080 existing = None
1081
1082 def _right_has_values_of_left(left, right):
1083 # Make sure the values are equivalent for everything left has
1084 for k, v in left.items():
1085 if not ((not v and (k not in right or not right[k])) or (k in right and v == right[k])):
1086 # We don't care about list ordering because ECS can change things
1087 if isinstance(v, list) and k in right:
1088 left_list = v
1089 right_list = right[k] or []
1090
1091 if len(left_list) != len(right_list):
1092 return False
1093
1094 for list_val in left_list:
1095 if list_val not in right_list:
1096 # if list_val is the port mapping, the key 'protocol' may be absent (but defaults to 'tcp')
1097 # fill in that default if absent and see if it is in right_list then
1098 if isinstance(list_val, dict) and not list_val.get("protocol"):
1099 modified_list_val = dict(list_val)
1100 modified_list_val.update(protocol="tcp")
1101 if modified_list_val in right_list:
1102 continue
1103 else:
1104 return False
1105
1106 # Make sure right doesn't have anything that left doesn't
1107 for k, v in right.items():
1108 if v and k not in left:
1109 # 'essential' defaults to True when not specified
1110 if k == "essential" and v is True:
1111 pass
1112 else:
1113 return False
1114
1115 return True
1116
1117 def _task_definition_matches(
1118 requested_volumes,
1119 requested_containers,
1120 requested_task_role_arn,
1121 requested_launch_type,
1122 existing_task_definition,
1123 ):
1124 if td["status"] != "ACTIVE":
1125 return None
1126
1127 if requested_task_role_arn != td.get("taskRoleArn", ""):
1128 return None
1129
1130 if requested_launch_type is not None and requested_launch_type not in td.get(
1131 "requiresCompatibilities", []
1132 ):
1133 return None
1134
1135 existing_volumes = td.get("volumes", []) or []
1136
1137 if len(requested_volumes) != len(existing_volumes):
1138 # Nope.
1139 return None
1140
1141 if len(requested_volumes) > 0:
1142 for requested_vol in requested_volumes:
1143 found = False
1144
1145 for actual_vol in existing_volumes:
1146 if _right_has_values_of_left(requested_vol, actual_vol):
1147 found = True
1148 break
1149
1150 if not found:
1151 return None
1152
1153 existing_containers = td.get("containerDefinitions", []) or []
1154
1155 if len(requested_containers) != len(existing_containers):
1156 # Nope.
1157 return None
1158
1159 for requested_container in requested_containers:
1160 found = False
1161
1162 for actual_container in existing_containers:
1163 if _right_has_values_of_left(requested_container, actual_container):
1164 found = True
1165 break
1166
1167 if not found:
1168 return None
1169
1170 return existing_task_definition
1171
1172 # No revision explicitly specified. Attempt to find an active, matching revision that has all the properties requested
1173 for td in existing_definitions_in_family:
1174 requested_volumes = module.params["volumes"] or []
1175 requested_containers = module.params["containers"] or []
1176 requested_task_role_arn = module.params["task_role_arn"]
1177 requested_launch_type = module.params["launch_type"]
1178 existing = _task_definition_matches(
1179 requested_volumes, requested_containers, requested_task_role_arn, requested_launch_type, td
1180 )
1181
1182 if existing:
1183 break
1184
1185 if existing and not module.params.get("force_create"):
1186 # Awesome. Have an existing one. Nothing to do.
1187 results["taskdefinition"] = existing
1188 else:
1189 if not module.check_mode:
1190 # Doesn't exist. create it.
1191 volumes = module.params.get("volumes", []) or []
1192 results["taskdefinition"] = task_mgr.register_task(
1193 module.params["family"],
1194 module.params["task_role_arn"],
1195 module.params["execution_role_arn"],
1196 module.params["network_mode"],
1197 module.params["containers"],
1198 volumes,
1199 module.params["launch_type"],
1200 module.params["cpu"],
1201 module.params["memory"],
1202 module.params["placement_constraints"],
1203 module.params["runtime_platform"],
1204 )
1205 results["changed"] = True
1206
1207 elif module.params["state"] == "absent":
1208 # When de-registering a task definition, we can specify the ARN OR the family and revision.
1209 if module.params["state"] == "absent":
1210 if "arn" in module.params and module.params["arn"] is not None:
1211 task_to_describe = module.params["arn"]
1212 elif (
1213 "family" in module.params
1214 and module.params["family"] is not None
1215 and "revision" in module.params
1216 and module.params["revision"] is not None
1217 ):
1218 task_to_describe = module.params["family"] + ":" + str(module.params["revision"])
1219 else:
1220 module.fail_json(msg="To use task definitions, an arn or family and revision must be specified")
1221
1222 existing = task_mgr.describe_task(task_to_describe)
1223
1224 if not existing:
1225 pass
1226 else:
1227 # It exists, so we should delete it and mark changed. Return info about the task definition deleted
1228 results["taskdefinition"] = existing
1229 if "status" in existing and existing["status"] == "INACTIVE":
1230 results["changed"] = False
1231 else:
1232 if not module.check_mode:
1233 task_mgr.deregister_task(task_to_describe)
1234 results["changed"] = True
1235
1236 module.exit_json(**results)
1237
1238
1239 if __name__ == "__main__":
1240 main()