Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 DOCUMENTATION = r"""
8 ---
9 module: lightsail
10 version_added: 1.0.0
11 short_description: Manage instances in AWS Lightsail
12 description:
13 - Manage instances in AWS Lightsail.
14 - Instance tagging is not yet supported in this module.
15 author:
16 - "Nick Ball (@nickball)"
17 - "Prasad Katti (@prasadkatti)"
18 options:
19 state:
20 description:
21 - Indicate desired state of the target.
22 - I(rebooted) and I(restarted) are aliases.
23 default: present
24 choices: ['present', 'absent', 'running', 'restarted', 'rebooted', 'stopped']
25 type: str
26 name:
27 description: Name of the instance.
28 required: true
29 type: str
30 zone:
31 description:
32 - AWS availability zone in which to launch the instance.
33 - Required when I(state=present)
34 type: str
35 blueprint_id:
36 description:
37 - ID of the instance blueprint image.
38 - Required when I(state=present)
39 type: str
40 bundle_id:
41 description:
42 - Bundle of specification info for the instance.
43 - Required when I(state=present).
44 type: str
45 user_data:
46 description:
47 - Launch script that can configure the instance with additional data.
48 type: str
49 default: ''
50 public_ports:
51 description:
52 - A list of dictionaries to describe the ports to open for the specified instance.
53 type: list
54 elements: dict
55 suboptions:
56 from_port:
57 description: The first port in a range of open ports on the instance.
58 type: int
59 required: true
60 to_port:
61 description: The last port in a range of open ports on the instance.
62 type: int
63 required: true
64 protocol:
65 description: The IP protocol name accepted for the defined range of open ports.
66 type: str
67 choices: ['tcp', 'all', 'udp', 'icmp']
68 required: true
69 cidrs:
70 description:
71 - The IPv4 address, or range of IPv4 addresses (in CIDR notation) that are allowed to connect to the instance through the ports, and the protocol.
72 - One of I(cidrs) or I(ipv6_cidrs) must be specified.
73 type: list
74 elements: str
75 ipv6_cidrs:
76 description:
77 - The IPv6 address, or range of IPv6 addresses (in CIDR notation) that are allowed to connect to the instance through the ports, and the protocol.
78 - One of I(cidrs) or I(ipv6_cidrs) must be specified.
79 type: list
80 elements: str
81 version_added: 6.0.0
82 key_pair_name:
83 description:
84 - Name of the key pair to use with the instance.
85 - If I(state=present) and a key_pair_name is not provided, the default keypair from the region will be used.
86 type: str
87 wait:
88 description:
89 - Wait for the instance to be in state 'running' before returning.
90 - If I(wait=false) an ip_address may not be returned.
91 - Has no effect when I(state=rebooted) or I(state=absent).
92 type: bool
93 default: true
94 wait_timeout:
95 description:
96 - How long before I(wait) gives up, in seconds.
97 default: 300
98 type: int
99
100 extends_documentation_fragment:
101 - amazon.aws.common.modules
102 - amazon.aws.region.modules
103 - amazon.aws.boto3
104 """
105
106
107 EXAMPLES = r"""
108 - name: Create a new Lightsail instance
109 community.aws.lightsail:
110 state: present
111 name: my_instance
112 region: us-east-1
113 zone: us-east-1a
114 blueprint_id: ubuntu_16_04
115 bundle_id: nano_1_0
116 key_pair_name: id_rsa
117 user_data: " echo 'hello world' > /home/ubuntu/test.txt"
118 public_ports:
119 - from_port: 22
120 to_port: 22
121 protocol: "tcp"
122 cidrs: ["0.0.0.0/0"]
123 ipv6_cidrs: ["::/0"]
124 register: my_instance
125
126 - name: Delete an instance
127 community.aws.lightsail:
128 state: absent
129 region: us-east-1
130 name: my_instance
131 """
132
133 RETURN = r"""
134 changed:
135 description: if a snapshot has been modified/created
136 returned: always
137 type: bool
138 sample:
139 changed: true
140 instance:
141 description: instance data
142 returned: always
143 type: dict
144 sample:
145 arn: "arn:aws:lightsail:us-east-1:123456789012:Instance/1fef0175-d6c8-480e-84fa-214f969cda87"
146 blueprint_id: "ubuntu_16_04"
147 blueprint_name: "Ubuntu"
148 bundle_id: "nano_1_0"
149 created_at: "2017-03-27T08:38:59.714000-04:00"
150 hardware:
151 cpu_count: 1
152 ram_size_in_gb: 0.5
153 is_static_ip: false
154 location:
155 availability_zone: "us-east-1a"
156 region_name: "us-east-1"
157 name: "my_instance"
158 networking:
159 monthly_transfer:
160 gb_per_month_allocated: 1024
161 ports:
162 - access_direction: "inbound"
163 access_from: "Anywhere (0.0.0.0/0)"
164 access_type: "public"
165 common_name: ""
166 from_port: 80
167 protocol: tcp
168 to_port: 80
169 - access_direction: "inbound"
170 access_from: "Anywhere (0.0.0.0/0)"
171 access_type: "public"
172 common_name: ""
173 from_port: 22
174 protocol: tcp
175 to_port: 22
176 private_ip_address: "172.26.8.14"
177 public_ip_address: "34.207.152.202"
178 resource_type: "Instance"
179 ssh_key_name: "keypair"
180 state:
181 code: 16
182 name: running
183 support_code: "123456789012/i-0997c97831ee21e33"
184 username: "ubuntu"
185 """
186
187 import time
188
189 try:
190 import botocore
191 except ImportError:
192 # will be caught by AnsibleAWSModule
193 pass
194
195 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
196 from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
197
198 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
199
200 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
201
202
203 def find_instance_info(module, client, instance_name, fail_if_not_found=False):
204 try:
205 res = client.get_instance(instanceName=instance_name)
206 except is_boto3_error_code("NotFoundException") as e:
207 if fail_if_not_found:
208 module.fail_json_aws(e)
209 return None
210 except botocore.exceptions.ClientError as e: # pylint: disable=duplicate-except
211 module.fail_json_aws(e)
212 return res["instance"]
213
214
215 def wait_for_instance_state(module, client, instance_name, states):
216 """
217 `states` is a list of instance states that we are waiting for.
218 """
219
220 wait_timeout = module.params.get("wait_timeout")
221 wait_max = time.time() + wait_timeout
222 while wait_max > time.time():
223 try:
224 instance = find_instance_info(module, client, instance_name)
225 if instance["state"]["name"] in states:
226 break
227 time.sleep(5)
228 except botocore.exceptions.ClientError as e:
229 module.fail_json_aws(e)
230 else:
231 module.fail_json(
232 msg=f'Timed out waiting for instance "{instance_name}" to get to one of the following states - {states}'
233 )
234
235
236 def update_public_ports(module, client, instance_name):
237 try:
238 client.put_instance_public_ports(
239 portInfos=snake_dict_to_camel_dict(module.params.get("public_ports")),
240 instanceName=instance_name,
241 )
242 except botocore.exceptions.ClientError as e:
243 module.fail_json_aws(e)
244
245
246 def create_or_update_instance(module, client, instance_name):
247 inst = find_instance_info(module, client, instance_name)
248
249 if not inst:
250 create_params = {
251 "instanceNames": [instance_name],
252 "availabilityZone": module.params.get("zone"),
253 "blueprintId": module.params.get("blueprint_id"),
254 "bundleId": module.params.get("bundle_id"),
255 "userData": module.params.get("user_data"),
256 }
257
258 key_pair_name = module.params.get("key_pair_name")
259 if key_pair_name:
260 create_params["keyPairName"] = key_pair_name
261
262 try:
263 client.create_instances(**create_params)
264 except botocore.exceptions.ClientError as e:
265 module.fail_json_aws(e)
266
267 wait = module.params.get("wait")
268 if wait:
269 desired_states = ["running"]
270 wait_for_instance_state(module, client, instance_name, desired_states)
271
272 if module.params.get("public_ports") is not None:
273 update_public_ports(module, client, instance_name)
274 after_update_inst = find_instance_info(module, client, instance_name, fail_if_not_found=True)
275
276 module.exit_json(
277 changed=after_update_inst != inst,
278 instance=camel_dict_to_snake_dict(after_update_inst),
279 )
280
281
282 def delete_instance(module, client, instance_name):
283 changed = False
284
285 inst = find_instance_info(module, client, instance_name)
286 if inst is None:
287 module.exit_json(changed=changed, instance={})
288
289 # Wait for instance to exit transition state before deleting
290 desired_states = ["running", "stopped"]
291 wait_for_instance_state(module, client, instance_name, desired_states)
292
293 try:
294 client.delete_instance(instanceName=instance_name)
295 changed = True
296 except botocore.exceptions.ClientError as e:
297 module.fail_json_aws(e)
298
299 module.exit_json(changed=changed, instance=camel_dict_to_snake_dict(inst))
300
301
302 def restart_instance(module, client, instance_name):
303 """
304 Reboot an existing instance
305 Wait will not apply here as this is an OS-level operation
306 """
307
308 changed = False
309
310 inst = find_instance_info(module, client, instance_name, fail_if_not_found=True)
311
312 try:
313 client.reboot_instance(instanceName=instance_name)
314 changed = True
315 except botocore.exceptions.ClientError as e:
316 module.fail_json_aws(e)
317
318 module.exit_json(changed=changed, instance=camel_dict_to_snake_dict(inst))
319
320
321 def start_or_stop_instance(module, client, instance_name, state):
322 """
323 Start or stop an existing instance
324 """
325
326 changed = False
327
328 inst = find_instance_info(module, client, instance_name, fail_if_not_found=True)
329
330 # Wait for instance to exit transition state before state change
331 desired_states = ["running", "stopped"]
332 wait_for_instance_state(module, client, instance_name, desired_states)
333
334 # Try state change
335 if inst and inst["state"]["name"] != state:
336 try:
337 if state == "running":
338 client.start_instance(instanceName=instance_name)
339 else:
340 client.stop_instance(instanceName=instance_name)
341 except botocore.exceptions.ClientError as e:
342 module.fail_json_aws(e)
343 changed = True
344 # Grab current instance info
345 inst = find_instance_info(module, client, instance_name)
346
347 wait = module.params.get("wait")
348 if wait:
349 desired_states = [state]
350 wait_for_instance_state(module, client, instance_name, desired_states)
351 inst = find_instance_info(module, client, instance_name, fail_if_not_found=True)
352
353 module.exit_json(changed=changed, instance=camel_dict_to_snake_dict(inst))
354
355
356 def main():
357 argument_spec = dict(
358 name=dict(type="str", required=True),
359 state=dict(
360 type="str", default="present", choices=["present", "absent", "stopped", "running", "restarted", "rebooted"]
361 ),
362 zone=dict(type="str"),
363 blueprint_id=dict(type="str"),
364 bundle_id=dict(type="str"),
365 key_pair_name=dict(type="str"),
366 user_data=dict(type="str", default=""),
367 wait=dict(type="bool", default=True),
368 wait_timeout=dict(default=300, type="int"),
369 public_ports=dict(
370 type="list",
371 elements="dict",
372 options=dict(
373 from_port=dict(type="int", required=True),
374 to_port=dict(type="int", required=True),
375 protocol=dict(type="str", choices=["tcp", "all", "udp", "icmp"], required=True),
376 cidrs=dict(type="list", elements="str"),
377 ipv6_cidrs=dict(type="list", elements="str"),
378 ),
379 required_one_of=[("cidrs", "ipv6_cidrs")],
380 ),
381 )
382
383 module = AnsibleAWSModule(
384 argument_spec=argument_spec, required_if=[["state", "present", ("zone", "blueprint_id", "bundle_id")]]
385 )
386
387 client = module.client("lightsail")
388
389 name = module.params.get("name")
390 state = module.params.get("state")
391
392 if state == "present":
393 create_or_update_instance(module, client, name)
394 elif state == "absent":
395 delete_instance(module, client, name)
396 elif state in ("running", "stopped"):
397 start_or_stop_instance(module, client, name, state)
398 elif state in ("restarted", "rebooted"):
399 restart_instance(module, client, name)
400
401
402 if __name__ == "__main__":
403 main()