Debian Codegraph @

ansible_collections/community/aws/plugins/modules/ecs_service.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_service
10 version_added: 1.0.0
11 short_description: Create, terminate, start or stop a service in ECS
12 description:
13 - Creates or terminates ECS services.
14 notes:
15 - The service role specified must be assumable. (i.e. have a trust relationship for the ecs service, ecs.amazonaws.com)
16 - For details of the parameters and returns see U(https://boto3.readthedocs.io/en/latest/reference/services/ecs.html).
17 - An IAM role must have been previously created.
18 author:
19 - "Mark Chance (@Java1Guy)"
20 - "Darek Kaczynski (@kaczynskid)"
21 - "Stephane Maarek (@simplesteph)"
22 - "Zac Blazic (@zacblazic)"
23 options:
24 state:
25 description:
26 - The desired state of the service.
27 required: true
28 choices: ["present", "absent", "deleting"]
29 type: str
30 name:
31 description:
32 - The name of the service.
33 required: true
34 type: str
35 aliases: ['service']
36 cluster:
37 description:
38 - The name of the cluster in which the service exists.
39 - If not specified, the cluster name will be C(default).
40 required: false
41 type: str
42 default: 'default'
43 task_definition:
44 description:
45 - The task definition the service will run.
46 - This parameter is required when I(state=present) unless I(force_new_deployment=True).
47 - This parameter is ignored when updating a service with a C(CODE_DEPLOY) deployment controller in which case
48 the task definition is managed by Code Pipeline and cannot be updated.
49 required: false
50 type: str
51 load_balancers:
52 description:
53 - The list of ELBs defined for this service.
54 - Load balancers for an existing service cannot be updated, and it is an error to do so.
55 - When the deployment controller is CODE_DEPLOY changes to this value are simply ignored, and do not cause an error.
56 required: false
57 type: list
58 elements: dict
59 default: []
60 desired_count:
61 description:
62 - The count of how many instances of the service.
63 - This parameter is required when I(state=present).
64 required: false
65 type: int
66 client_token:
67 description:
68 - Unique, case-sensitive identifier you provide to ensure the idempotency of the request. Up to 32 ASCII characters are allowed.
69 required: false
70 type: str
71 default: ''
72 role:
73 description:
74 - The name or full Amazon Resource Name (ARN) of the IAM role that allows your Amazon ECS container agent to make calls to your load balancer
75 on your behalf.
76 - This parameter is only required if you are using a load balancer with your service in a network mode other than C(awsvpc).
77 required: false
78 type: str
79 default: ''
80 delay:
81 description:
82 - The time to wait before checking that the service is available.
83 required: false
84 default: 10
85 type: int
86 repeat:
87 description:
88 - The number of times to check that the service is available.
89 required: false
90 default: 10
91 type: int
92 force_new_deployment:
93 description:
94 - Force deployment of service even if there are no changes.
95 required: false
96 type: bool
97 default: false
98 deployment_controller:
99 description:
100 - The deployment controller to use for the service. If no deploymenet controller is specified, the ECS controller is used.
101 required: false
102 version_added: 4.1.0
103 type: dict
104 default: {}
105 suboptions:
106 type:
107 type: str
108 choices: ["ECS", "CODE_DEPLOY", "EXTERNAL"]
109 description: The deployment controller type to use.
110 deployment_configuration:
111 description:
112 - Optional parameters that control the deployment_configuration.
113 - Format is '{"maximum_percent":<integer>, "minimum_healthy_percent":<integer>}
114 required: false
115 type: dict
116 default: {}
117 suboptions:
118 maximum_percent:
119 type: int
120 description: Upper limit on the number of tasks in a service that are allowed in the RUNNING or PENDING state during a deployment.
121 minimum_healthy_percent:
122 type: int
123 description: A lower limit on the number of tasks in a service that must remain in the RUNNING state during a deployment.
124 deployment_circuit_breaker:
125 type: dict
126 description: The deployment circuit breaker determines whether a service deployment will fail if the service can't reach a steady state.
127 suboptions:
128 enable:
129 type: bool
130 description: If enabled, a service deployment will transition to a failed state and stop launching new tasks.
131 rollback:
132 type: bool
133 description: If enabled, ECS will roll back your service to the last completed deployment after a failure.
134 enable_execute_command:
135 description:
136 - Whether or not to enable the execute command functionality for the containers in the ECS task.
137 - If I(enable_execute_command=true) execute command functionality is enabled on all containers in the ECS task.
138 required: false
139 type: bool
140 version_added: 5.4.0
141 placement_constraints:
142 description:
143 - The placement constraints for the tasks in the service.
144 - See U(https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_PlacementConstraint.html) for more details.
145 required: false
146 type: list
147 elements: dict
148 default: []
149 suboptions:
150 type:
151 description: The type of constraint.
152 type: str
153 expression:
154 description: A cluster query language expression to apply to the constraint.
155 required: false
156 type: str
157 purge_placement_constraints:
158 version_added: 5.3.0
159 description:
160 - Toggle overwriting of existing placement constraints. This is needed for backwards compatibility.
161 - By default I(purge_placement_constraints=false). In release 9.0.0 this will be changed to I(purge_placement_constraints=true).
162 required: false
163 type: bool
164 default: false
165 placement_strategy:
166 description:
167 - The placement strategy objects to use for tasks in your service. You can specify a maximum of 5 strategy rules per service.
168 required: false
169 type: list
170 elements: dict
171 default: []
172 suboptions:
173 type:
174 description: The type of placement strategy.
175 type: str
176 field:
177 description: The field to apply the placement strategy against.
178 type: str
179 purge_placement_strategy:
180 version_added: 5.3.0
181 description:
182 - Toggle overwriting of existing placement strategy. This is needed for backwards compatibility.
183 - By default I(purge_placement_strategy=false). In release 9.0.0 this will be changed to I(purge_placement_strategy=true).
184 required: false
185 type: bool
186 default: false
187 force_deletion:
188 description:
189 - Forcibly delete the service. Required when deleting a service with >0 scale, or no target group.
190 default: False
191 type: bool
192 version_added: 2.1.0
193 network_configuration:
194 description:
195 - Network configuration of the service. Only applicable for task definitions created with I(network_mode=awsvpc).
196 type: dict
197 suboptions:
198 subnets:
199 description:
200 - A list of subnet IDs to associate with the task.
201 type: list
202 elements: str
203 security_groups:
204 description:
205 - A list of security group names or group IDs to associate with the task.
206 type: list
207 elements: str
208 assign_public_ip:
209 description:
210 - Whether the task's elastic network interface receives a public IP address.
211 type: bool
212 launch_type:
213 description:
214 - The launch type on which to run your service.
215 required: false
216 choices: ["EC2", "FARGATE"]
217 type: str
218 capacity_provider_strategy:
219 version_added: 4.0.0
220 description:
221 - The capacity provider strategy to use with your service. You can specify a maximum of 6 providers per strategy.
222 required: false
223 type: list
224 elements: dict
225 default: []
226 suboptions:
227 capacity_provider:
228 description:
229 - Name of capacity provider.
230 type: str
231 weight:
232 description:
233 - The relative percentage of the total number of launched tasks that should use the specified provider.
234 type: int
235 base:
236 description:
237 - How many tasks, at a minimum, should use the specified provider.
238 type: int
239 platform_version:
240 type: str
241 description:
242 - Numeric part of platform version or LATEST
243 - See U(https://docs.aws.amazon.com/AmazonECS/latest/developerguide/platform_versions.html) for more details.
244 required: false
245 version_added: 1.5.0
246 health_check_grace_period_seconds:
247 description:
248 - Seconds to wait before health checking the freshly added/updated services.
249 required: false
250 type: int
251 service_registries:
252 description:
253 - Describes service discovery registries this service will register with.
254 type: list
255 elements: dict
256 default: []
257 required: false
258 suboptions:
259 container_name:
260 description:
261 - Container name for service discovery registration.
262 type: str
263 container_port:
264 description:
265 - Container port for service discovery registration.
266 type: int
267 arn:
268 description:
269 - Service discovery registry ARN.
270 type: str
271 scheduling_strategy:
272 description:
273 - The scheduling strategy.
274 - Defaults to C(REPLICA) if not given to preserve previous behavior.
275 required: false
276 choices: ["DAEMON", "REPLICA"]
277 type: str
278 wait:
279 description:
280 - Whether or not to wait for the service to be inactive.
281 - Waits only when I(state) is C(absent).
282 type: bool
283 default: false
284 version_added: 4.1.0
285 propagate_tags:
286 description:
287 - Propagate tags from ECS task defintition or ECS service to ECS task.
288 required: false
289 choices: ["TASK_DEFINITION", "SERVICE"]
290 type: str
291 version_added: 4.1.0
292 tags:
293 description:
294 - A dictionary of tags to add or remove from the resource.
295 type: dict
296 required: false
297 version_added: 4.1.0
298 extends_documentation_fragment:
299 - amazon.aws.common.modules
300 - amazon.aws.region.modules
301 - amazon.aws.boto3
302 """
303
304 EXAMPLES = r"""
305 # Note: These examples do not set authentication details, see the AWS Guide for details.
306 # Basic provisioning example
307 - community.aws.ecs_service:
308 state: present
309 name: console-test-service
310 cluster: new_cluster
311 task_definition: 'new_cluster-task:1'
312 desired_count: 0
313
314 - name: create ECS service on VPC network
315 community.aws.ecs_service:
316 state: present
317 name: console-test-service
318 cluster: new_cluster
319 task_definition: 'new_cluster-task:1'
320 desired_count: 0
321 network_configuration:
322 subnets:
323 - subnet-abcd1234
324 security_groups:
325 - sg-aaaa1111
326 - my_security_group
327
328 # Simple example to delete
329 - community.aws.ecs_service:
330 name: default
331 state: absent
332 cluster: new_cluster
333
334 # With custom deployment configuration (added in version 2.3), placement constraints and strategy (added in version 2.4)
335 - community.aws.ecs_service:
336 state: present
337 name: test-service
338 cluster: test-cluster
339 task_definition: test-task-definition
340 desired_count: 3
341 deployment_configuration:
342 minimum_healthy_percent: 75
343 maximum_percent: 150
344 placement_constraints:
345 - type: memberOf
346 expression: 'attribute:flavor==test'
347 placement_strategy:
348 - type: binpack
349 field: memory
350
351 # With deployment circuit breaker (added in version 4.0)
352 - community.aws.ecs_service:
353 state: present
354 name: test-service
355 cluster: test-cluster
356 task_definition: test-task-definition
357 desired_count: 3
358 deployment_configuration:
359 deployment_circuit_breaker:
360 enable: true
361 rollback: true
362
363 # With capacity_provider_strategy (added in version 4.0)
364 - community.aws.ecs_service:
365 state: present
366 name: test-service
367 cluster: test-cluster
368 task_definition: test-task-definition
369 desired_count: 1
370 capacity_provider_strategy:
371 - capacity_provider: test-capacity-provider-1
372 weight: 1
373 base: 0
374
375 # With tags and tag propagation
376 - community.aws.ecs_service:
377 state: present
378 name: tags-test-service
379 cluster: new_cluster
380 task_definition: 'new_cluster-task:1'
381 desired_count: 1
382 tags:
383 Firstname: jane
384 lastName: doe
385 propagate_tags: SERVICE
386 """
387
388 RETURN = r"""
389 service:
390 description: Details of created service.
391 returned: when creating a service
392 type: complex
393 contains:
394 capacityProviderStrategy:
395 version_added: 4.0.0
396 description: The capacity provider strategy to use with your service.
397 returned: always
398 type: complex
399 contains:
400 base:
401 description: How many tasks, at a minimum, should use the specified provider.
402 returned: always
403 type: int
404 capacityProvider:
405 description: Name of capacity provider.
406 returned: always
407 type: str
408 weight:
409 description: The relative percentage of the total number of launched tasks that should use the specified provider.
410 returned: always
411 type: int
412 clusterArn:
413 description: The Amazon Resource Name (ARN) of the of the cluster that hosts the service.
414 returned: always
415 type: str
416 desiredCount:
417 description: The desired number of instantiations of the task definition to keep running on the service.
418 returned: always
419 type: int
420 loadBalancers:
421 description:
422 - A list of load balancer objects
423 returned: always
424 type: complex
425 contains:
426 loadBalancerName:
427 description: the name
428 returned: always
429 type: str
430 containerName:
431 description: The name of the container to associate with the load balancer.
432 returned: always
433 type: str
434 containerPort:
435 description: The port on the container to associate with the load balancer.
436 returned: always
437 type: int
438 pendingCount:
439 description: The number of tasks in the cluster that are in the PENDING state.
440 returned: always
441 type: int
442 runningCount:
443 description: The number of tasks in the cluster that are in the RUNNING state.
444 returned: always
445 type: int
446 serviceArn:
447 description:
448 - The Amazon Resource Name (ARN) that identifies the service. The ARN contains the C(arn:aws:ecs) namespace, followed by
449 the region of the service, the AWS account ID of the service owner, the service namespace, and then the service name.
450 sample: 'arn:aws:ecs:us-east-1:123456789012:service/my-service'
451 returned: always
452 type: str
453 serviceName:
454 description: A user-generated string used to identify the service
455 returned: always
456 type: str
457 status:
458 description: The valid values are ACTIVE, DRAINING, or INACTIVE.
459 returned: always
460 type: str
461 tags:
462 description: The tags applied to this resource.
463 returned: success
464 type: dict
465 taskDefinition:
466 description: The ARN of a task definition to use for tasks in the service.
467 returned: always
468 type: str
469 deployments:
470 description: list of service deployments
471 returned: always
472 type: list
473 elements: dict
474 deploymentConfiguration:
475 description: dictionary of deploymentConfiguration
476 returned: always
477 type: complex
478 contains:
479 maximumPercent:
480 description: maximumPercent param
481 returned: always
482 type: int
483 minimumHealthyPercent:
484 description: minimumHealthyPercent param
485 returned: always
486 type: int
487 deploymentCircuitBreaker:
488 description: dictionary of deploymentCircuitBreaker
489 returned: always
490 type: complex
491 contains:
492 enable:
493 description: The state of the circuit breaker feature.
494 returned: always
495 type: bool
496 rollback:
497 description: The state of the rollback feature of the circuit breaker.
498 returned: always
499 type: bool
500 events:
501 description: list of service events
502 returned: always
503 type: list
504 elements: dict
505 placementConstraints:
506 description: List of placement constraints objects
507 returned: always
508 type: list
509 elements: dict
510 contains:
511 type:
512 description: The type of constraint. Valid values are distinctInstance and memberOf.
513 returned: always
514 type: str
515 expression:
516 description: A cluster query language expression to apply to the constraint. Note you cannot specify an expression if the constraint type is
517 distinctInstance.
518 returned: always
519 type: str
520 placementStrategy:
521 description: List of placement strategy objects
522 returned: always
523 type: list
524 elements: dict
525 contains:
526 type:
527 description: The type of placement strategy. Valid values are random, spread and binpack.
528 returned: always
529 type: str
530 field:
531 description: The field to apply the placement strategy against. For the spread placement strategy, valid values are instanceId
532 (or host, which has the same effect), or any platform or custom attribute that is applied to a container instance,
533 such as attribute:ecs.availability-zone. For the binpack placement strategy, valid values are CPU and MEMORY.
534 returned: always
535 type: str
536 propagateTags:
537 description: The type of tag propagation applied to the resource.
538 returned: always
539 type: str
540 ansible_facts:
541 description: Facts about deleted service.
542 returned: when deleting a service
543 type: complex
544 contains:
545 service:
546 description: Details of deleted service.
547 returned: when service existed and was deleted
548 type: complex
549 contains:
550 clusterArn:
551 description: The Amazon Resource Name (ARN) of the of the cluster that hosts the service.
552 returned: always
553 type: str
554 desiredCount:
555 description: The desired number of instantiations of the task definition to keep running on the service.
556 returned: always
557 type: int
558 loadBalancers:
559 description: A list of load balancer objects
560 returned: always
561 type: complex
562 contains:
563 loadBalancerName:
564 description: the name
565 returned: always
566 type: str
567 containerName:
568 description: The name of the container to associate with the load balancer.
569 returned: always
570 type: str
571 containerPort:
572 description: The port on the container to associate with the load balancer.
573 returned: always
574 type: int
575 pendingCount:
576 description: The number of tasks in the cluster that are in the PENDING state.
577 returned: always
578 type: int
579 runningCount:
580 description: The number of tasks in the cluster that are in the RUNNING state.
581 returned: always
582 type: int
583 serviceArn:
584 description:
585 - The Amazon Resource Name (ARN) that identifies the service. The ARN contains the arn:aws:ecs namespace, followed by the region
586 of the service, the AWS account ID of the service owner, the service namespace, and then the service name.
587 sample: 'arn:aws:ecs:us-east-1:123456789012:service/my-service'
588 returned: always
589 type: str
590 serviceName:
591 description: A user-generated string used to identify the service
592 returned: always
593 type: str
594 status:
595 description: The valid values are ACTIVE, DRAINING, or INACTIVE.
596 returned: always
597 type: str
598 tags:
599 description: The tags applied to this resource.
600 returned: when tags found
601 type: list
602 elements: dict
603 taskDefinition:
604 description: The ARN of a task definition to use for tasks in the service.
605 returned: always
606 type: str
607 deployments:
608 description: list of service deployments
609 returned: always
610 type: list
611 elements: dict
612 deploymentConfiguration:
613 description: dictionary of deploymentConfiguration
614 returned: always
615 type: complex
616 contains:
617 maximumPercent:
618 description: maximumPercent param
619 returned: always
620 type: int
621 minimumHealthyPercent:
622 description: minimumHealthyPercent param
623 returned: always
624 type: int
625 deploymentCircuitBreaker:
626 description: dictionary of deploymentCircuitBreaker
627 returned: always
628 type: complex
629 contains:
630 enable:
631 description: The state of the circuit breaker feature.
632 returned: always
633 type: bool
634 rollback:
635 description: The state of the rollback feature of the circuit breaker.
636 returned: always
637 type: bool
638 events:
639 description: list of service events
640 returned: always
641 type: list
642 elements: dict
643 placementConstraints:
644 description: List of placement constraints objects
645 returned: always
646 type: list
647 elements: dict
648 contains:
649 type:
650 description: The type of constraint. Valid values are distinctInstance and memberOf.
651 returned: always
652 type: str
653 expression:
654 description: A cluster query language expression to apply to the constraint. Note you cannot specify an expression if
655 the constraint type is distinctInstance.
656 returned: always
657 type: str
658 placementStrategy:
659 description: List of placement strategy objects
660 returned: always
661 type: list
662 elements: dict
663 contains:
664 type:
665 description: The type of placement strategy. Valid values are random, spread and binpack.
666 returned: always
667 type: str
668 field:
669 description: The field to apply the placement strategy against. For the spread placement strategy, valid values are instanceId
670 (or host, which has the same effect), or any platform or custom attribute that is applied to a container instance,
671 such as attribute:ecs.availability-zone. For the binpack placement strategy, valid values are CPU and MEMORY.
672 returned: always
673 type: str
674 propagateTags:
675 description: The type of tag propagation applied to the resource
676 returned: always
677 type: str
678
679 """
680
681 import time
682
683 try:
684 import botocore
685 except ImportError:
686 pass # caught by AnsibleAWSModule
687
688 from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
689
690 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import get_ec2_security_group_ids_from_names
691 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
692 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
693 from ansible_collections.amazon.aws.plugins.module_utils.transformation import map_complex_type
694
695 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
696
697 DEPLOYMENT_CONTROLLER_TYPE_MAP = {
698 "type": "str",
699 }
700
701 DEPLOYMENT_CONFIGURATION_TYPE_MAP = {
702 "maximum_percent": "int",
703 "minimum_healthy_percent": "int",
704 "deployment_circuit_breaker": "dict",
705 }
706
707
708 class EcsServiceManager:
709 """Handles ECS Services"""
710
711 def __init__(self, module):
712 self.module = module
713 self.ecs = module.client("ecs")
714 self.ec2 = module.client("ec2")
715
716 def format_network_configuration(self, network_config):
717 result = dict()
718 if network_config["subnets"] is not None:
719 result["subnets"] = network_config["subnets"]
720 else:
721 self.module.fail_json(msg="Network configuration must include subnets")
722 if network_config["security_groups"] is not None:
723 groups = network_config["security_groups"]
724 if any(not sg.startswith("sg-") for sg in groups):
725 try:
726 vpc_id = self.ec2.describe_subnets(SubnetIds=[result["subnets"][0]])["Subnets"][0]["VpcId"]
727 groups = get_ec2_security_group_ids_from_names(groups, self.ec2, vpc_id)
728 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
729 self.module.fail_json_aws(e, msg="Couldn't look up security groups")
730 result["securityGroups"] = groups
731 if network_config["assign_public_ip"] is not None:
732 if network_config["assign_public_ip"] is True:
733 result["assignPublicIp"] = "ENABLED"
734 else:
735 result["assignPublicIp"] = "DISABLED"
736 return dict(awsvpcConfiguration=result)
737
738 def find_in_array(self, array_of_services, service_name, field_name="serviceArn"):
739 for c in array_of_services:
740 if c[field_name].endswith(service_name):
741 return c
742 return None
743
744 def describe_service(self, cluster_name, service_name):
745 response = self.ecs.describe_services(
746 cluster=cluster_name,
747 services=[service_name],
748 include=["TAGS"],
749 )
750 msg = ""
751
752 if len(response["failures"]) > 0:
753 c = self.find_in_array(response["failures"], service_name, "arn")
754 msg += ", failure reason is " + c["reason"]
755 if c and c["reason"] == "MISSING":
756 return None
757 # fall thru and look through found ones
758 if len(response["services"]) > 0:
759 c = self.find_in_array(response["services"], service_name)
760 if c:
761 return c
762 raise Exception(f"Unknown problem describing service {service_name}.")
763
764 def is_matching_service(self, expected, existing):
765 # aws returns the arn of the task definition
766 # arn:aws:ecs:eu-central-1:123456789:task-definition/ansible-fargate-nginx:3
767 # but the user is just entering
768 # ansible-fargate-nginx:3
769 if expected["task_definition"] != existing["taskDefinition"].split("/")[-1]:
770 if existing.get("deploymentController", {}).get("type", None) != "CODE_DEPLOY":
771 return False
772
773 if expected.get("health_check_grace_period_seconds"):
774 if expected.get("health_check_grace_period_seconds") != existing.get("healthCheckGracePeriodSeconds"):
775 return False
776
777 if (expected["load_balancers"] or []) != existing["loadBalancers"]:
778 return False
779
780 if (expected["propagate_tags"] or "NONE") != existing["propagateTags"]:
781 return False
782
783 if boto3_tag_list_to_ansible_dict(existing.get("tags", [])) != (expected["tags"] or {}):
784 return False
785
786 if (expected["enable_execute_command"] or False) != existing.get("enableExecuteCommand", False):
787 return False
788
789 # expected is params. DAEMON scheduling strategy returns desired count equal to
790 # number of instances running; don't check desired count if scheduling strat is daemon
791 if expected["scheduling_strategy"] != "DAEMON":
792 if (expected["desired_count"] or 0) != existing["desiredCount"]:
793 return False
794
795 return True
796
797 def create_service(
798 self,
799 service_name,
800 cluster_name,
801 task_definition,
802 load_balancers,
803 desired_count,
804 client_token,
805 role,
806 deployment_controller,
807 deployment_configuration,
808 placement_constraints,
809 placement_strategy,
810 health_check_grace_period_seconds,
811 network_configuration,
812 service_registries,
813 launch_type,
814 platform_version,
815 scheduling_strategy,
816 capacity_provider_strategy,
817 tags,
818 propagate_tags,
819 enable_execute_command,
820 ):
821 params = dict(
822 cluster=cluster_name,
823 serviceName=service_name,
824 taskDefinition=task_definition,
825 loadBalancers=load_balancers,
826 clientToken=client_token,
827 role=role,
828 deploymentConfiguration=deployment_configuration,
829 placementStrategy=placement_strategy,
830 )
831 if network_configuration:
832 params["networkConfiguration"] = network_configuration
833 if deployment_controller:
834 params["deploymentController"] = deployment_controller
835 if launch_type:
836 params["launchType"] = launch_type
837 if platform_version:
838 params["platformVersion"] = platform_version
839 if self.health_check_setable(params) and health_check_grace_period_seconds is not None:
840 params["healthCheckGracePeriodSeconds"] = health_check_grace_period_seconds
841 if service_registries:
842 params["serviceRegistries"] = service_registries
843
844 # filter placement_constraint and left only those where value is not None
845 # use-case: `distinctInstance` type should never contain `expression`, but None will fail `str` type validation
846 if placement_constraints:
847 params["placementConstraints"] = [
848 {key: value for key, value in constraint.items() if value is not None}
849 for constraint in placement_constraints
850 ]
851
852 # desired count is not required if scheduling strategy is daemon
853 if desired_count is not None:
854 params["desiredCount"] = desired_count
855 if capacity_provider_strategy:
856 params["capacityProviderStrategy"] = capacity_provider_strategy
857 if propagate_tags:
858 params["propagateTags"] = propagate_tags
859 # desired count is not required if scheduling strategy is daemon
860 if desired_count is not None:
861 params["desiredCount"] = desired_count
862 if tags:
863 params["tags"] = ansible_dict_to_boto3_tag_list(tags, "key", "value")
864
865 if scheduling_strategy:
866 params["schedulingStrategy"] = scheduling_strategy
867 if enable_execute_command:
868 params["enableExecuteCommand"] = enable_execute_command
869
870 response = self.ecs.create_service(**params)
871 return self.jsonize(response["service"])
872
873 def update_service(
874 self,
875 service_name,
876 cluster_name,
877 task_definition,
878 desired_count,
879 deployment_configuration,
880 placement_constraints,
881 placement_strategy,
882 network_configuration,
883 health_check_grace_period_seconds,
884 force_new_deployment,
885 capacity_provider_strategy,
886 load_balancers,
887 purge_placement_constraints,
888 purge_placement_strategy,
889 enable_execute_command,
890 ):
891 params = dict(
892 cluster=cluster_name,
893 service=service_name,
894 taskDefinition=task_definition,
895 deploymentConfiguration=deployment_configuration,
896 )
897 # filter placement_constraint and left only those where value is not None
898 # use-case: `distinctInstance` type should never contain `expression`, but None will fail `str` type validation
899 if placement_constraints:
900 params["placementConstraints"] = [
901 {key: value for key, value in constraint.items() if value is not None}
902 for constraint in placement_constraints
903 ]
904
905 if purge_placement_constraints and not placement_constraints:
906 params["placementConstraints"] = []
907
908 if placement_strategy:
909 params["placementStrategy"] = placement_strategy
910
911 if purge_placement_strategy and not placement_strategy:
912 params["placementStrategy"] = []
913
914 if network_configuration:
915 params["networkConfiguration"] = network_configuration
916 if force_new_deployment:
917 params["forceNewDeployment"] = force_new_deployment
918 if capacity_provider_strategy:
919 params["capacityProviderStrategy"] = capacity_provider_strategy
920 if health_check_grace_period_seconds is not None:
921 params["healthCheckGracePeriodSeconds"] = health_check_grace_period_seconds
922 # desired count is not required if scheduling strategy is daemon
923 if desired_count is not None:
924 params["desiredCount"] = desired_count
925 if enable_execute_command is not None:
926 params["enableExecuteCommand"] = enable_execute_command
927
928 if load_balancers:
929 params["loadBalancers"] = load_balancers
930
931 response = self.ecs.update_service(**params)
932
933 return self.jsonize(response["service"])
934
935 def jsonize(self, service):
936 # some fields are datetime which is not JSON serializable
937 # make them strings
938 if "createdAt" in service:
939 service["createdAt"] = str(service["createdAt"])
940 if "deployments" in service:
941 for d in service["deployments"]:
942 if "createdAt" in d:
943 d["createdAt"] = str(d["createdAt"])
944 if "updatedAt" in d:
945 d["updatedAt"] = str(d["updatedAt"])
946 if "events" in service:
947 for e in service["events"]:
948 if "createdAt" in e:
949 e["createdAt"] = str(e["createdAt"])
950 return service
951
952 def delete_service(self, service, cluster=None, force=False):
953 return self.ecs.delete_service(cluster=cluster, service=service, force=force)
954
955 def health_check_setable(self, params):
956 load_balancers = params.get("loadBalancers", [])
957 return len(load_balancers) > 0
958
959
960 def main():
961 argument_spec = dict(
962 state=dict(required=True, choices=["present", "absent", "deleting"]),
963 name=dict(required=True, type="str", aliases=["service"]),
964 cluster=dict(required=False, type="str", default="default"),
965 task_definition=dict(required=False, type="str"),
966 load_balancers=dict(required=False, default=[], type="list", elements="dict"),
967 desired_count=dict(required=False, type="int"),
968 client_token=dict(required=False, default="", type="str", no_log=False),
969 role=dict(required=False, default="", type="str"),
970 delay=dict(required=False, type="int", default=10),
971 repeat=dict(required=False, type="int", default=10),
972 force_new_deployment=dict(required=False, default=False, type="bool"),
973 force_deletion=dict(required=False, default=False, type="bool"),
974 deployment_controller=dict(required=False, default={}, type="dict"),
975 deployment_configuration=dict(required=False, default={}, type="dict"),
976 wait=dict(required=False, default=False, type="bool"),
977 placement_constraints=dict(
978 required=False,
979 default=[],
980 type="list",
981 elements="dict",
982 options=dict(type=dict(type="str"), expression=dict(required=False, type="str")),
983 ),
984 purge_placement_constraints=dict(required=False, default=False, type="bool"),
985 placement_strategy=dict(
986 required=False,
987 default=[],
988 type="list",
989 elements="dict",
990 options=dict(
991 type=dict(type="str"),
992 field=dict(type="str"),
993 ),
994 ),
995 purge_placement_strategy=dict(required=False, default=False, type="bool"),
996 health_check_grace_period_seconds=dict(required=False, type="int"),
997 network_configuration=dict(
998 required=False,
999 type="dict",
1000 options=dict(
1001 subnets=dict(type="list", elements="str"),
1002 security_groups=dict(type="list", elements="str"),
1003 assign_public_ip=dict(type="bool"),
1004 ),
1005 ),
1006 launch_type=dict(required=False, choices=["EC2", "FARGATE"]),
1007 platform_version=dict(required=False, type="str"),
1008 service_registries=dict(required=False, type="list", default=[], elements="dict"),
1009 scheduling_strategy=dict(required=False, choices=["DAEMON", "REPLICA"]),
1010 capacity_provider_strategy=dict(
1011 required=False,
1012 type="list",
1013 default=[],
1014 elements="dict",
1015 options=dict(
1016 capacity_provider=dict(type="str"),
1017 weight=dict(type="int"),
1018 base=dict(type="int"),
1019 ),
1020 ),
1021 propagate_tags=dict(required=False, choices=["TASK_DEFINITION", "SERVICE"]),
1022 tags=dict(required=False, type="dict"),
1023 enable_execute_command=dict(required=False, type="bool"),
1024 )
1025
1026 module = AnsibleAWSModule(
1027 argument_spec=argument_spec,
1028 supports_check_mode=True,
1029 required_if=[("launch_type", "FARGATE", ["network_configuration"])],
1030 required_together=[["load_balancers", "role"]],
1031 mutually_exclusive=[["launch_type", "capacity_provider_strategy"]],
1032 )
1033
1034 if module.params["state"] == "present":
1035 if module.params["scheduling_strategy"] == "REPLICA" and module.params["desired_count"] is None:
1036 module.fail_json(msg="state is present, scheduling_strategy is REPLICA; missing desired_count")
1037 if module.params["task_definition"] is None and not module.params["force_new_deployment"]:
1038 module.fail_json(msg="Either task_definition or force_new_deployment is required when status is present.")
1039
1040 if len(module.params["capacity_provider_strategy"]) > 6:
1041 module.fail_json(msg="AWS allows a maximum of six capacity providers in the strategy.")
1042
1043 service_mgr = EcsServiceManager(module)
1044 if module.params["network_configuration"]:
1045 network_configuration = service_mgr.format_network_configuration(module.params["network_configuration"])
1046 else:
1047 network_configuration = None
1048
1049 deployment_controller = map_complex_type(module.params["deployment_controller"], DEPLOYMENT_CONTROLLER_TYPE_MAP)
1050
1051 deploymentController = snake_dict_to_camel_dict(deployment_controller)
1052
1053 deployment_configuration = map_complex_type(
1054 module.params["deployment_configuration"], DEPLOYMENT_CONFIGURATION_TYPE_MAP
1055 )
1056
1057 deploymentConfiguration = snake_dict_to_camel_dict(deployment_configuration)
1058 serviceRegistries = list(map(snake_dict_to_camel_dict, module.params["service_registries"]))
1059 capacityProviders = list(map(snake_dict_to_camel_dict, module.params["capacity_provider_strategy"]))
1060
1061 try:
1062 existing = service_mgr.describe_service(module.params["cluster"], module.params["name"])
1063 except Exception as e:
1064 module.fail_json_aws(
1065 e,
1066 msg=f"Exception describing service '{module.params['name']}' in cluster '{module.params['cluster']}'",
1067 )
1068
1069 results = dict(changed=False)
1070
1071 if module.params["state"] == "present":
1072 matching = False
1073 update = False
1074
1075 if existing and "status" in existing and existing["status"] == "ACTIVE":
1076 if module.params["force_new_deployment"]:
1077 update = True
1078 elif service_mgr.is_matching_service(module.params, existing):
1079 matching = True
1080 results["service"] = existing
1081 else:
1082 update = True
1083
1084 if not matching:
1085 if not module.check_mode:
1086 role = module.params["role"]
1087 clientToken = module.params["client_token"]
1088
1089 loadBalancers = []
1090 for loadBalancer in module.params["load_balancers"]:
1091 if "containerPort" in loadBalancer:
1092 loadBalancer["containerPort"] = int(loadBalancer["containerPort"])
1093 loadBalancers.append(loadBalancer)
1094
1095 for loadBalancer in loadBalancers:
1096 if "containerPort" in loadBalancer:
1097 loadBalancer["containerPort"] = int(loadBalancer["containerPort"])
1098
1099 if update:
1100 # check various parameters and AWS SDK versions and give a helpful error if the SDK is not new enough for feature
1101
1102 if module.params["scheduling_strategy"]:
1103 if (existing["schedulingStrategy"]) != module.params["scheduling_strategy"]:
1104 module.fail_json(
1105 msg="It is not possible to update the scheduling strategy of an existing service"
1106 )
1107
1108 if module.params["service_registries"]:
1109 if (existing["serviceRegistries"] or []) != serviceRegistries:
1110 module.fail_json(
1111 msg="It is not possible to update the service registries of an existing service"
1112 )
1113 if module.params["capacity_provider_strategy"]:
1114 if "launchType" in existing.keys():
1115 module.fail_json(
1116 msg="It is not possible to change an existing service from launch_type to capacity_provider_strategy."
1117 )
1118 if module.params["launch_type"]:
1119 if "capacityProviderStrategy" in existing.keys():
1120 module.fail_json(
1121 msg="It is not possible to change an existing service from capacity_provider_strategy to launch_type."
1122 )
1123 if (existing["loadBalancers"] or []) != loadBalancers:
1124 # fails if deployment type is not CODE_DEPLOY or ECS
1125 if existing["deploymentController"]["type"] not in ["CODE_DEPLOY", "ECS"]:
1126 module.fail_json(
1127 msg="It is not possible to update the load balancers of an existing service"
1128 )
1129
1130 if existing.get("deploymentController", {}).get("type", None) == "CODE_DEPLOY":
1131 task_definition = ""
1132 network_configuration = []
1133 else:
1134 task_definition = module.params["task_definition"]
1135
1136 if module.params["propagate_tags"] and module.params["propagate_tags"] != existing["propagateTags"]:
1137 module.fail_json(
1138 msg="It is not currently supported to enable propagation tags of an existing service"
1139 )
1140
1141 if (
1142 module.params["tags"]
1143 and boto3_tag_list_to_ansible_dict(existing["tags"]) != module.params["tags"]
1144 ):
1145 module.fail_json(msg="It is not currently supported to change tags of an existing service")
1146
1147 updatedLoadBalancers = loadBalancers if existing["deploymentController"]["type"] == "ECS" else []
1148
1149 if task_definition is None and module.params["force_new_deployment"]:
1150 task_definition = existing["taskDefinition"]
1151
1152 try:
1153 # update required
1154 response = service_mgr.update_service(
1155 module.params["name"],
1156 module.params["cluster"],
1157 task_definition,
1158 module.params["desired_count"],
1159 deploymentConfiguration,
1160 module.params["placement_constraints"],
1161 module.params["placement_strategy"],
1162 network_configuration,
1163 module.params["health_check_grace_period_seconds"],
1164 module.params["force_new_deployment"],
1165 capacityProviders,
1166 updatedLoadBalancers,
1167 module.params["purge_placement_constraints"],
1168 module.params["purge_placement_strategy"],
1169 module.params["enable_execute_command"],
1170 )
1171 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
1172 module.fail_json_aws(e, msg="Couldn't create service")
1173
1174 else:
1175 try:
1176 response = service_mgr.create_service(
1177 module.params["name"],
1178 module.params["cluster"],
1179 module.params["task_definition"],
1180 loadBalancers,
1181 module.params["desired_count"],
1182 clientToken,
1183 role,
1184 deploymentController,
1185 deploymentConfiguration,
1186 module.params["placement_constraints"],
1187 module.params["placement_strategy"],
1188 module.params["health_check_grace_period_seconds"],
1189 network_configuration,
1190 serviceRegistries,
1191 module.params["launch_type"],
1192 module.params["platform_version"],
1193 module.params["scheduling_strategy"],
1194 capacityProviders,
1195 module.params["tags"],
1196 module.params["propagate_tags"],
1197 module.params["enable_execute_command"],
1198 )
1199 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
1200 module.fail_json_aws(e, msg="Couldn't create service")
1201
1202 if response.get("tags", None):
1203 response["tags"] = boto3_tag_list_to_ansible_dict(response["tags"])
1204 results["service"] = response
1205
1206 results["changed"] = True
1207
1208 elif module.params["state"] == "absent":
1209 if not existing:
1210 pass
1211 else:
1212 # it exists, so we should delete it and mark changed.
1213 # return info about the cluster deleted
1214 del existing["deployments"]
1215 del existing["events"]
1216 results["ansible_facts"] = existing
1217 if "status" in existing and existing["status"] == "INACTIVE":
1218 results["changed"] = False
1219 else:
1220 if not module.check_mode:
1221 try:
1222 service_mgr.delete_service(
1223 module.params["name"],
1224 module.params["cluster"],
1225 module.params["force_deletion"],
1226 )
1227
1228 # Wait for service to be INACTIVE prior to exiting
1229 if module.params["wait"]:
1230 waiter = service_mgr.ecs.get_waiter("services_inactive")
1231 try:
1232 waiter.wait(
1233 services=[module.params["name"]],
1234 cluster=module.params["cluster"],
1235 WaiterConfig={
1236 "Delay": module.params["delay"],
1237 "MaxAttempts": module.params["repeat"],
1238 },
1239 )
1240 except botocore.exceptions.WaiterError as e:
1241 module.fail_json_aws(e, "Timeout waiting for service removal")
1242 except botocore.exceptions.ClientError as e:
1243 module.fail_json_aws(e, msg="Couldn't delete service")
1244
1245 results["changed"] = True
1246
1247 elif module.params["state"] == "deleting":
1248 if not existing:
1249 module.fail_json(msg="Service '" + module.params["name"] + " not found.")
1250
1251 # it exists, so we should delete it and mark changed.
1252 # return info about the cluster deleted
1253 delay = module.params["delay"]
1254 repeat = module.params["repeat"]
1255 time.sleep(delay)
1256 for i in range(repeat):
1257 existing = service_mgr.describe_service(module.params["cluster"], module.params["name"])
1258 status = existing["status"]
1259 if status == "INACTIVE":
1260 results["changed"] = True
1261 break
1262 time.sleep(delay)
1263 if i is repeat - 1:
1264 module.fail_json(msg=f"Service still not deleted after {repeat} tries of {delay} seconds each.")
1265
1266 module.exit_json(**results)
1267
1268
1269 if __name__ == "__main__":
1270 main()