
    VhD                         d Z dZdZ	 ddlZddlmZ ddlmZ ddl	m
Z  G d d	      Zd
 Zedk(  r e        yy# e$ r Y 4w xY w)a  
---
module: ecs_task
version_added: 1.0.0
short_description: Run, start or stop a task in ECS
description:
    - Creates or deletes instances of task definitions.
author:
    - Mark Chance (@Java1Guy)
options:
    operation:
        description:
            - Which task operation to execute.
            - When I(operation=run) I(task_definition) must be set.
            - When I(operation=start) both I(task_definition) and I(container_instances) must be set.
            - When I(operation=stop) both I(task_definition) and I(task) must be set.
        required: True
        choices: ['run', 'start', 'stop']
        type: str
    cluster:
        description:
            - The name of the cluster to run the task on.
            - If not specified, the cluster name will be C(default).
        required: False
        type: str
        default: 'default'
    task_definition:
        description:
            - The task definition to start, run or stop.
        required: False
        type: str
    overrides:
        description:
            - A dictionary of values to pass to the new instances.
        required: False
        type: dict
    count:
        description:
            - How many new instances to start.
        required: False
        type: int
    task:
        description:
            - The ARN of the task to stop.
        required: False
        type: str
    container_instances:
        description:
            - The list of container instances on which to deploy the task.
        required: False
        type: list
        elements: str
    started_by:
        description:
            - A value showing who or what started the task (for informational purposes).
        required: False
        type: str
    network_configuration:
        description:
          - Network configuration of the service. Only applicable for task definitions created with I(network_mode=awsvpc).
        type: dict
        suboptions:
            assign_public_ip:
                description: Whether the task's elastic network interface receives a public IP address.
                type: bool
                version_added: 1.5.0
            subnets:
                description: A list of subnet IDs to which the task is attached.
                type: list
                elements: str
            security_groups:
                description: A list of group names or group IDs for the task.
                type: list
                elements: str
    launch_type:
        description:
          - The launch type on which to run your service.
        required: false
        choices: ["EC2", "FARGATE"]
        type: str
    tags:
        type: dict
        description:
          - Tags that will be added to ecs tasks on start and run
        required: false
        aliases: ['resource_tags']
    wait:
        description:
          - Whether or not to wait for the desired state.
        type: bool
        default: false
        version_added: 4.1.0
extends_documentation_fragment:
    - amazon.aws.common.modules
    - amazon.aws.region.modules
    - amazon.aws.boto3
a  
# Simple example of run task
- name: Run task
  community.aws.ecs_task:
    operation: run
    cluster: console-sample-app-static-cluster
    task_definition: console-sample-app-static-taskdef
    count: 1
    started_by: ansible_user
  register: task_output

# Simple example of start task

- name: Start a task
  community.aws.ecs_task:
    operation: start
    cluster: console-sample-app-static-cluster
    task_definition: console-sample-app-static-taskdef
    task: "arn:aws:ecs:us-west-2:123456789012:task/3f8353d1-29a8-4689-bbf6-ad79937ffe8a"
    tags:
      resourceName: a_task_for_ansible_to_run
      type: long_running_task
      network: internal
      version: 1.4
    container_instances:
      - arn:aws:ecs:us-west-2:123456789012:container-instance/79c23f22-876c-438a-bddf-55c98a3538a8
    started_by: ansible_user
    network_configuration:
      subnets:
        - subnet-abcd1234
      security_groups:
        - sg-aaaa1111
        - my_security_group
  register: task_output

- name: RUN a task on Fargate
  community.aws.ecs_task:
    operation: run
    cluster: console-sample-app-static-cluster
    task_definition: console-sample-app-static-taskdef
    task: "arn:aws:ecs:us-west-2:123456789012:task/3f8353d1-29a8-4689-bbf6-ad79937ffe8a"
    started_by: ansible_user
    launch_type: FARGATE
    network_configuration:
      subnets:
        - subnet-abcd1234
      security_groups:
        - sg-aaaa1111
        - my_security_group
  register: task_output

- name: RUN a task on Fargate with public ip assigned
  community.aws.ecs_task:
    operation: run
    count: 2
    cluster: console-sample-app-static-cluster
    task_definition: console-sample-app-static-taskdef
    task: "arn:aws:ecs:us-west-2:123456789012:task/3f8353d1-29a8-4689-bbf6-ad79937ffe8a"
    started_by: ansible_user
    launch_type: FARGATE
    network_configuration:
      assign_public_ip: true
      subnets:
        - subnet-abcd1234
  register: task_output

- name: Stop a task
  community.aws.ecs_task:
    operation: stop
    cluster: console-sample-app-static-cluster
    task_definition: console-sample-app-static-taskdef
    task: "arn:aws:ecs:us-west-2:123456789012:task/3f8353d1-29a8-4689-bbf6-ad79937ffe8a"
aX	  
task:
    description: details about the task that was started
    returned: success
    type: complex
    contains:
        taskArn:
            description: The Amazon Resource Name (ARN) that identifies the task.
            returned: always
            type: str
        clusterArn:
            description: The Amazon Resource Name (ARN) of the of the cluster that hosts the task.
            returned: only when details is true
            type: str
        taskDefinitionArn:
            description: The Amazon Resource Name (ARN) of the task definition.
            returned: only when details is true
            type: str
        containerInstanceArn:
            description: The Amazon Resource Name (ARN) of the container running the task.
            returned: only when details is true
            type: str
        overrides:
            description: The container overrides set for this task.
            returned: only when details is true
            type: list
            elements: dict
        lastStatus:
            description: The last recorded status of the task.
            returned: only when details is true
            type: str
        desiredStatus:
            description: The desired status of the task.
            returned: only when details is true
            type: str
        containers:
            description: The container details.
            returned: only when details is true
            type: list
            elements: dict
        startedBy:
            description: The used who started the task.
            returned: only when details is true
            type: str
        stoppedReason:
            description: The reason why the task was stopped.
            returned: only when details is true
            type: str
        createdAt:
            description: The timestamp of when the task was created.
            returned: only when details is true
            type: str
        startedAt:
            description: The timestamp of when the task was started.
            returned: only when details is true
            type: str
        stoppedAt:
            description: The timestamp of when the task was stopped.
            returned: only when details is true
            type: str
        launchType:
            description: The launch type on which to run your task.
            returned: always
            type: str
    N)%get_ec2_security_group_ids_from_names)ansible_dict_to_boto3_tag_list)AnsibleCommunityAWSModulec                   :    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
y	)
EcsExecManagerzHandles ECS Tasksc                 j    || _         |j                  d      | _        |j                  d      | _        y )Necsec2)moduleclientr	   r
   )selfr   s     j/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/aws/plugins/modules/ecs_task.py__init__zEcsExecManager.__init__  s)    =='=='    c                 6   t               }d|v r	|d   |d<   n| j                  j                  d       d|v r`|d   }t        d |D              rD	 | j                  j                  |d   d   g      d   d   d	   }t        || j                  |      }||d<   d|v r|d   du rd|d<   nd|d<   t        |      S # t        j                  j                  t        j                  j                  f$ r'}| j                  j                  |d
       Y d }~d }~ww xY w)Nsubnetsz*Network configuration must include subnetsmsgsecurity_groupsc              3   @   K   | ]  }|j                  d          yw)zsg-N)
startswith).0sgs     r   	<genexpr>z>EcsExecManager.format_network_configuration.<locals>.<genexpr>  s     =r}}U++=s   r   )	SubnetIdsSubnetsVpcIdz Couldn't look up security groupssecurityGroupsassign_public_ipTENABLEDassignPublicIpDISABLED)awsvpcConfiguration)dictr   	fail_jsonanyr
   describe_subnetsr   botocore
exceptionsClientErrorBotoCoreErrorfail_json_aws)r   network_configresultgroupsvpc_ides         r   format_network_configurationz+EcsExecManager.format_network_configuration  s7   & .y 9F9KK!!&R!S.#$56F=f==Y!XX66&BSTUBVAW6XYbcdefgnoFB6488U[\F (.F#$/01T9+4'(+5'(// !++779L9L9Z9Z[ YKK--a5W-XXYs   AB: :7D1DDc                     | j                   j                  |||      }t        |d         dkD  r|d   D ]  }|j                  |      s|c S  y )N)clusterfamilydesiredStatustaskArnsr   )r	   
list_taskslenendswith)r   cluster_nameservice_namestatusresponsecs         r   r8   zEcsExecManager.list_tasks  sb    88&&   ' 

 x
#$q(j) ::l+H r   c                    |
t               }t        |||||      }| j                  j                  d   r+| j                  | j                  j                  d         |d<   |r||d<   |rt	        |dd      |d<   	  | j
                  j                  di |}	|	d
   S # t        j                  j                  t        j                  j                  f$ r+}
| j                  j                  |
d	       Y d }
~
	d
   S d }
~
ww xY w)N)r4   taskDefinition	overridescount	startedBynetwork_configurationnetworkConfiguration
launchTypekeyvaluetagszCouldn't run taskr   tasks )r$   r   paramsr2   r   r	   run_taskr(   r)   r*   r+   r,   )r   r4   task_definitionrB   rC   rD   launch_typerJ   rM   r>   r1   s              r   rN   zEcsExecManager.run_task+  s   IOyX]ir
 ;;56-1-N-N""#:;.F)* #.F< ;D%QF6N	B(txx((262H    ##//1D1D1R1RS 	BKK%%a-@%AA  	Bs   ;B 7C>C99C>c                    t               }|r||d<   |r||d<   |r||d<   |r||d<   |r||d<   | j                  j                  d   r+| j                  | j                  j                  d         |d<   |rt	        |dd	      |d
<   	  | j
                  j                  di |}|d   S # t        j                  j                  t        j                  j                  f$ r+}	| j                  j                  |	d       Y d }	~	d   S d }	~	ww xY w)Nr4   rA   rB   containerInstancesrD   rE   rF   rH   rI   rJ   zCouldn't start taskr   rK   rL   )r$   r   rM   r2   r   r	   
start_taskr(   r)   r*   r+   r,   )
r   r4   rO   rB   container_instancesrD   rJ   argsr>   r1   s
             r   rS   zEcsExecManager.start_taskB  s!   v%DO%4D!" )D)<D%& )D;;56+/+L+L""#:;,D'( 9$wODL	D*txx**2T2H    ##//1D1D1R1RS 	DKK%%a-B%CC  	Ds   B& &7DDDc                 F    | j                   j                  ||      }|d   S )N)r4   taskrW   )r	   	stop_task)r   r4   rW   r>   s       r   rX   zEcsExecManager.stop_task[  s&    88%%gD%Ar   c                 X    | j                   j                  dd      }|d   d   d   dk(  S )NtaskLongArnFormatT)nameeffectiveSettingssettingsr   rI   enabled)r	   list_account_settings)r   account_supports     r   ecs_task_long_format_enabledz+EcsExecManager.ecs_task_long_format_enabled_  s7    ((88>Qei8jz*1-g6)CCr   N)__name__
__module____qualname____doc__r   r2   r8   rN   rS   rX   ra   rL   r   r   r   r      s)    (
0.
!.!2 Dr   r   c                     t        t        dg d      t        ddd      t        dd      t        dd	      t        dd
      t        dd      t        ddd      t        dd      t        dd	      t        dddg      t        dd	dg      t        ddd            } t        | ddddgfdddgfddddgfddddgfg      }|j                  d   dk(  r|j                  d   }d}|j                  d   dk(  r|j                  d   }d}|j                  d   dk(  r|j                  d   }d}t        |      }|j                  d    r"|j	                         s|j                  d!"       |j                  |j                  d#         }t        d$      }|j                  d   dk(  r|r||d<   n-|j                  s|j                  |j                  d#   |j                  d   |j                  d%   |j                  d&   |j                  d'   |j                  d   |j                  d          }|j                  d(   rM|j                  j                  d)      }	 |j                  |D 	cg c]  }	|	d*   	 c}	|j                  d#   +       ||d<   d|d-<   nG|j                  d   dk(  r|r||d<   n,|j                  sg|j!                  |j                  d#   |j                  d   |j                  d%   |j                  d   |j                  d'   |j                  d          |d<   d|d-<   n|j                  d   dk(  r|r||d<   n|j                  s|j#                  |j                  d#   |j                  d         |d<   |j                  d(   rJ|j                  j                  d.      }	 |j                  |j                  d   g|j                  d#   +       d|d-<    |j$                  d0i | y c c}	w # t        j                  j                  $ r}
|j                  |
d,       Y d }
~
d }
~
ww xY w# t        j                  j                  $ r}
|j                  |
d/       Y d }
~
d }
~
ww xY w)1NT)runstartstop)requiredchoicesFstrdefault)rj   typerm   )rj   rn   r$   intlist)rj   rn   elementsEC2FARGATEresource_tags)rj   rn   aliasesbool)rj   rm   rn   )	operationr4   rO   rB   rC   rW   rT   
started_byrE   rP   rJ   waitrP   rE   rw   rg   rO   rh   rT   ri   rW   )argument_specsupports_check_moderequired_ifRUNNINGSTOPPEDrJ   zDCannot set task tags: long format task arns are required to set tagsr   r4   )changedrB   rC   rx   ry   tasks_runningtaskArn)rK   r4   z Timeout waiting for tasks to runr   tasks_stoppedz Timeout waiting for task to stoprL   )r$   AnsibleAWSModulerM   r   ra   r%   r8   
check_moderN   r	   
get_waiterry   r(   r)   WaiterErrorr,   rS   rX   	exit_json)rz   r   task_to_liststatus_typeservice_mgrexistingresultsrK   waiterrW   r1   s              r   mainr   d  sq   .FGe%Ce%8F3E.5u- %fuMU3"E?%%1CD5v7HI5%f=M # I(?'@A%"3!45'$57L#MN&#4f"=>	
	F }}[!U*}}%67}}[!W,}}V,}}[!V+}}%67 (K}}V779!gh%%fmmI&>kZH5!G}}[!U*&GFO$$#,,MM),MM"34MM+.MM'*MM,/MM-0MM&) ==((__77HFT?D"Et4	?"E$*MM)$< $  #(!%GI	{	#w	.&GFO$$"-"8"8MM),MM"34MM+.MM"78MM,/MM&)# "&GI	{	#v	-&GFO$$ #."7"7i8PRXR_R_`fRg"h ==((__77HFT#)==#8"9$*MM)$< $  "&GIFwc #F $..:: T,,Q0RSSTR $..:: T,,Q0RSSTsB   O: -O59O: /.P7 5O: :P4P//P47Q0Q++Q0__main__)DOCUMENTATIONEXAMPLESRETURNr(   ImportError7ansible_collections.amazon.aws.plugins.module_utils.ec2r   ;ansible_collections.amazon.aws.plugins.module_utils.taggingr   >ansible_collections.community.aws.plugins.module_utils.modulesr   r   r   r   rb   rL   r   r   <module>r      ss   `DHT@
D	 j f xaD aDHx v zF Q  		s   9 A A