Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # This file is part of Ansible
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: ec2_ami_copy
10 version_added: 1.0.0
11 short_description: copies AMI between AWS regions, return new image id
12 description:
13 - Copies AMI from a source region to a destination region. B(Since version 2.3 this module depends on boto3.)
14 options:
15 source_region:
16 description:
17 - The source region the AMI should be copied from.
18 required: true
19 type: str
20 source_image_id:
21 description:
22 - The ID of the AMI in source region that should be copied.
23 required: true
24 type: str
25 name:
26 description:
27 - The name of the new AMI to copy. (As of 2.3 the default is C(default), in prior versions it was C(null).)
28 default: "default"
29 type: str
30 description:
31 description:
32 - An optional human-readable string describing the contents and purpose of the new AMI.
33 type: str
34 default: ''
35 encrypted:
36 description:
37 - Whether or not the destination snapshots of the copied AMI should be encrypted.
38 type: bool
39 default: false
40 kms_key_id:
41 description:
42 - KMS key id used to encrypt the image. If not specified, uses default EBS Customer Master Key (CMK) for your account.
43 type: str
44 wait:
45 description:
46 - Wait for the copied AMI to be in state C(available) before returning.
47 type: bool
48 default: false
49 wait_timeout:
50 description:
51 - How long before wait gives up, in seconds.
52 - Prior to 2.3 the default was C(1200).
53 - From 2.3-2.5 this option was deprecated in favor of boto3 waiter defaults.
54 - This was reenabled in 2.6 to allow timeouts greater than 10 minutes.
55 default: 600
56 type: int
57 tags:
58 description:
59 - 'A hash/dictionary of tags to add to the new copied AMI: C({"key":"value"}) and C({"key":"value","key":"value"})'
60 type: dict
61 aliases: ['resource_tags']
62 tag_equality:
63 description:
64 - Whether to use tags if the source AMI already exists in the target region. If this is set, and all tags match
65 in an existing AMI, the AMI will not be copied again.
66 default: false
67 type: bool
68 author:
69 - Amir Moulavi (@amir343) <[email protected]>
70 - Tim C (@defunctio) <[email protected]>
71 extends_documentation_fragment:
72 - amazon.aws.common.modules
73 - amazon.aws.region.modules
74 - amazon.aws.boto3
75 """
76
77 EXAMPLES = r"""
78 - name: Basic AMI Copy
79 community.aws.ec2_ami_copy:
80 source_region: us-east-1
81 region: eu-west-1
82 source_image_id: ami-xxxxxxx
83
84 - name: AMI copy wait until available
85 community.aws.ec2_ami_copy:
86 source_region: us-east-1
87 region: eu-west-1
88 source_image_id: ami-xxxxxxx
89 wait: true
90 wait_timeout: 1200 # Default timeout is 600
91 register: image_id
92
93 - name: Named AMI copy
94 community.aws.ec2_ami_copy:
95 source_region: us-east-1
96 region: eu-west-1
97 source_image_id: ami-xxxxxxx
98 name: My-Awesome-AMI
99 description: latest patch
100
101 - name: Tagged AMI copy (will not copy the same AMI twice)
102 community.aws.ec2_ami_copy:
103 source_region: us-east-1
104 region: eu-west-1
105 source_image_id: ami-xxxxxxx
106 tags:
107 Name: My-Super-AMI
108 Patch: 1.2.3
109 tag_equality: true
110
111 - name: Encrypted AMI copy
112 community.aws.ec2_ami_copy:
113 source_region: us-east-1
114 region: eu-west-1
115 source_image_id: ami-xxxxxxx
116 encrypted: true
117
118 - name: Encrypted AMI copy with specified key
119 community.aws.ec2_ami_copy:
120 source_region: us-east-1
121 region: eu-west-1
122 source_image_id: ami-xxxxxxx
123 encrypted: true
124 kms_key_id: arn:aws:kms:us-east-1:XXXXXXXXXXXX:key/746de6ea-50a4-4bcb-8fbc-e3b29f2d367b
125 """
126
127 RETURN = r"""
128 image_id:
129 description: AMI ID of the copied AMI
130 returned: always
131 type: str
132 sample: ami-e689729e
133 """
134
135 try:
136 from botocore.exceptions import BotoCoreError
137 from botocore.exceptions import ClientError
138 from botocore.exceptions import WaiterError
139 except ImportError:
140 pass # caught by AnsibleAWSModule
141
142 from ansible.module_utils._text import to_native
143 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
144
145 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
146
147 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
148
149
150 def copy_image(module, ec2):
151 """
152 Copies an AMI
153
154 module : AnsibleAWSModule object
155 ec2: ec2 connection object
156 """
157
158 image = None
159 changed = False
160 tags = module.params.get("tags")
161
162 params = {
163 "SourceRegion": module.params.get("source_region"),
164 "SourceImageId": module.params.get("source_image_id"),
165 "Name": module.params.get("name"),
166 "Description": module.params.get("description"),
167 "Encrypted": module.params.get("encrypted"),
168 }
169 if module.params.get("kms_key_id"):
170 params["KmsKeyId"] = module.params.get("kms_key_id")
171
172 try:
173 if module.params.get("tag_equality"):
174 filters = [{"Name": f"tag:{k}", "Values": [v]} for (k, v) in module.params.get("tags").items()]
175 filters.append(dict(Name="state", Values=["available", "pending"]))
176 images = ec2.describe_images(Filters=filters)
177 if len(images["Images"]) > 0:
178 image = images["Images"][0]
179 if not image:
180 image = ec2.copy_image(**params)
181 image_id = image["ImageId"]
182 if tags:
183 ec2.create_tags(Resources=[image_id], Tags=ansible_dict_to_boto3_tag_list(tags))
184 changed = True
185
186 if module.params.get("wait"):
187 delay = 15
188 max_attempts = module.params.get("wait_timeout") // delay
189 image_id = image.get("ImageId")
190 ec2.get_waiter("image_available").wait(
191 ImageIds=[image_id], WaiterConfig={"Delay": delay, "MaxAttempts": max_attempts}
192 )
193
194 module.exit_json(changed=changed, **camel_dict_to_snake_dict(image))
195 except WaiterError as e:
196 module.fail_json_aws(e, msg="An error occurred waiting for the image to become available")
197 except (ClientError, BotoCoreError) as e:
198 module.fail_json_aws(e, msg="Could not copy AMI")
199 except Exception as e:
200 module.fail_json(msg=f"Unhandled exception. ({to_native(e)})")
201
202
203 def main():
204 argument_spec = dict(
205 source_region=dict(required=True),
206 source_image_id=dict(required=True),
207 name=dict(default="default"),
208 description=dict(default=""),
209 encrypted=dict(type="bool", default=False, required=False),
210 kms_key_id=dict(type="str", required=False),
211 wait=dict(type="bool", default=False),
212 wait_timeout=dict(type="int", default=600),
213 tags=dict(type="dict", aliases=["resource_tags"]),
214 tag_equality=dict(type="bool", default=False),
215 )
216
217 module = AnsibleAWSModule(argument_spec=argument_spec)
218 ec2 = module.client("ec2")
219 copy_image(module, ec2)
220
221
222 if __name__ == "__main__":
223 main()