Debian Codegraph @

ansible_collections/community/general/plugins/modules/sl_vm.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2017, Ansible Project
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: sl_vm
11 short_description: Create or cancel a virtual instance in SoftLayer
12 description:
13 - Creates or cancels SoftLayer instances.
14 - When created, optionally waits for it to be 'running'.
15 extends_documentation_fragment:
16 - community.general._attributes
17 attributes:
18 check_mode:
19 support: none
20 diff_mode:
21 support: none
22 options:
23 instance_id:
24 description:
25 - Instance ID of the virtual instance to perform action option.
26 type: str
27 hostname:
28 description:
29 - Hostname to be provided to a virtual instance.
30 type: str
31 domain:
32 description:
33 - Domain name to be provided to a virtual instance.
34 type: str
35 datacenter:
36 description:
37 - Datacenter for the virtual instance to be deployed.
38 type: str
39 choices:
40 - ams01
41 - ams03
42 - che01
43 - dal01
44 - dal05
45 - dal06
46 - dal09
47 - dal10
48 - dal12
49 - dal13
50 - fra02
51 - fra04
52 - fra05
53 - hkg02
54 - hou02
55 - lon02
56 - lon04
57 - lon06
58 - mel01
59 - mex01
60 - mil01
61 - mon01
62 - osl01
63 - par01
64 - sao01
65 - sea01
66 - seo01
67 - sjc01
68 - sjc03
69 - sjc04
70 - sng01
71 - syd01
72 - syd04
73 - tok02
74 - tor01
75 - wdc01
76 - wdc04
77 - wdc06
78 - wdc07
79 tags:
80 description:
81 - Tag or list of tags to be provided to a virtual instance.
82 type: str
83 hourly:
84 description:
85 - Flag to determine if the instance should be hourly billed.
86 type: bool
87 default: true
88 private:
89 description:
90 - Flag to determine if the instance should be private only.
91 type: bool
92 default: false
93 dedicated:
94 description:
95 - Flag to determine if the instance should be deployed in dedicated space.
96 type: bool
97 default: false
98 local_disk:
99 description:
100 - Flag to determine if local disk should be used for the new instance.
101 type: bool
102 default: true
103 cpus:
104 description:
105 - Count of cpus to be assigned to new virtual instance.
106 type: int
107 choices: [1, 2, 4, 8, 16, 32, 56]
108 memory:
109 description:
110 - Amount of memory to be assigned to new virtual instance.
111 type: int
112 choices: [1024, 2048, 4096, 6144, 8192, 12288, 16384, 32768, 49152, 65536, 131072, 247808]
113 flavor:
114 description:
115 - Specify which SoftLayer flavor template to use instead of cpus and memory.
116 version_added: '0.2.0'
117 type: str
118 disks:
119 description:
120 - List of disk sizes to be assigned to new virtual instance.
121 default: [25]
122 type: list
123 elements: int
124 os_code:
125 description:
126 - OS Code to be used for new virtual instance.
127 type: str
128 image_id:
129 description:
130 - Image Template to be used for new virtual instance.
131 type: str
132 nic_speed:
133 description:
134 - NIC Speed to be assigned to new virtual instance.
135 choices: [10, 100, 1000]
136 type: int
137 public_vlan:
138 description:
139 - VLAN by its ID to be assigned to the public NIC.
140 type: str
141 private_vlan:
142 description:
143 - VLAN by its ID to be assigned to the private NIC.
144 type: str
145 ssh_keys:
146 description:
147 - List of ssh keys by their ID to be assigned to a virtual instance.
148 type: list
149 elements: str
150 default: []
151 post_uri:
152 description:
153 - URL of a post provisioning script to be loaded and executed on virtual instance.
154 type: str
155 state:
156 description:
157 - Create, or cancel a virtual instance.
158 - Specify V(present) for create, V(absent) to cancel.
159 choices: [absent, present]
160 default: present
161 type: str
162 wait:
163 description:
164 - Flag used to wait for active status before returning.
165 type: bool
166 default: true
167 wait_time:
168 description:
169 - Time in seconds before wait returns.
170 default: 600
171 type: int
172 requirements:
173 - softlayer >= 4.1.1
174 notes:
175 - The C(softlayer-python) library, at version 6.2.6 (from Jan 2025), only supports Python version 3.8, 3.9 and 3.10.
176 author:
177 - Matt Colton (@mcltn)
178 seealso:
179 - name: SoftLayer API Python Client
180 description: The SoftLayer API Python Client is required for this module.
181 link: https://github.com/SoftLayer/softlayer-python
182 """
183
184 EXAMPLES = r"""
185 - name: Build instance
186 hosts: localhost
187 gather_facts: false
188 tasks:
189 - name: Build instance request
190 community.general.sl_vm:
191 hostname: instance-1
192 domain: anydomain.com
193 datacenter: dal09
194 tags: ansible-module-test
195 hourly: true
196 private: false
197 dedicated: false
198 local_disk: true
199 cpus: 1
200 memory: 1024
201 disks: [25]
202 os_code: UBUNTU_LATEST
203 wait: false
204
205 - name: Build additional instances
206 hosts: localhost
207 gather_facts: false
208 tasks:
209 - name: Build instances request
210 community.general.sl_vm:
211 hostname: "{{ item.hostname }}"
212 domain: "{{ item.domain }}"
213 datacenter: "{{ item.datacenter }}"
214 tags: "{{ item.tags }}"
215 hourly: "{{ item.hourly }}"
216 private: "{{ item.private }}"
217 dedicated: "{{ item.dedicated }}"
218 local_disk: "{{ item.local_disk }}"
219 cpus: "{{ item.cpus }}"
220 memory: "{{ item.memory }}"
221 disks: "{{ item.disks }}"
222 os_code: "{{ item.os_code }}"
223 ssh_keys: "{{ item.ssh_keys }}"
224 wait: "{{ item.wait }}"
225 with_items:
226 - hostname: instance-2
227 domain: anydomain.com
228 datacenter: dal09
229 tags:
230 - ansible-module-test
231 - ansible-module-test-replicas
232 hourly: true
233 private: false
234 dedicated: false
235 local_disk: true
236 cpus: 1
237 memory: 1024
238 disks:
239 - 25
240 - 100
241 os_code: UBUNTU_LATEST
242 ssh_keys: []
243 wait: true
244 - hostname: instance-3
245 domain: anydomain.com
246 datacenter: dal09
247 tags:
248 - ansible-module-test
249 - ansible-module-test-replicas
250 hourly: true
251 private: false
252 dedicated: false
253 local_disk: true
254 cpus: 1
255 memory: 1024
256 disks:
257 - 25
258 - 100
259 os_code: UBUNTU_LATEST
260 ssh_keys: []
261 wait: true
262
263 - name: Cancel instances
264 hosts: localhost
265 gather_facts: false
266 tasks:
267 - name: Cancel by tag
268 community.general.sl_vm:
269 state: absent
270 tags: ansible-module-test
271 """
272
273 # TODO: Disabled RETURN as it is breaking the build for docs. Needs to be fixed.
274 RETURN = """#"""
275
276 import json
277 import time
278
279 try:
280 import SoftLayer
281 from SoftLayer import VSManager
282
283 HAS_SL = True
284 vsManager = VSManager(SoftLayer.create_client_from_env())
285 except ImportError:
286 HAS_SL = False
287
288 from ansible.module_utils.basic import AnsibleModule
289
290 # TODO: get this info from API
291 STATES = ["present", "absent"]
292 DATACENTERS = [
293 "ams01",
294 "ams03",
295 "che01",
296 "dal01",
297 "dal05",
298 "dal06",
299 "dal09",
300 "dal10",
301 "dal12",
302 "dal13",
303 "fra02",
304 "fra04",
305 "fra05",
306 "hkg02",
307 "hou02",
308 "lon02",
309 "lon04",
310 "lon06",
311 "mel01",
312 "mex01",
313 "mil01",
314 "mon01",
315 "osl01",
316 "par01",
317 "sao01",
318 "sea01",
319 "seo01",
320 "sjc01",
321 "sjc03",
322 "sjc04",
323 "sng01",
324 "syd01",
325 "syd04",
326 "tok02",
327 "tor01",
328 "wdc01",
329 "wdc04",
330 "wdc06",
331 "wdc07",
332 ]
333 CPU_SIZES = [1, 2, 4, 8, 16, 32, 56]
334 MEMORY_SIZES = [1024, 2048, 4096, 6144, 8192, 12288, 16384, 32768, 49152, 65536, 131072, 247808]
335 INITIALDISK_SIZES = [25, 100]
336 LOCALDISK_SIZES = [25, 100, 150, 200, 300]
337 SANDISK_SIZES = [10, 20, 25, 30, 40, 50, 75, 100, 125, 150, 175, 200, 250, 300, 350, 400, 500, 750, 1000, 1500, 2000]
338 NIC_SPEEDS = [10, 100, 1000]
339
340
341 def create_virtual_instance(module):
342 instances = vsManager.list_instances(
343 hostname=module.params.get("hostname"),
344 domain=module.params.get("domain"),
345 datacenter=module.params.get("datacenter"),
346 )
347
348 if instances:
349 return False, None
350
351 # Check if OS or Image Template is provided (Can't be both, defaults to OS)
352 if module.params.get("os_code") is not None and module.params.get("os_code") != "":
353 module.params["image_id"] = ""
354 elif module.params.get("image_id") is not None and module.params.get("image_id") != "":
355 module.params["os_code"] = ""
356 module.params["disks"] = [] # Blank out disks since it will use the template
357 else:
358 return False, None
359
360 tags = module.params.get("tags")
361 if isinstance(tags, list):
362 tags = ",".join(map(str, module.params.get("tags")))
363
364 instance = vsManager.create_instance(
365 hostname=module.params.get("hostname"),
366 domain=module.params.get("domain"),
367 cpus=module.params.get("cpus"),
368 memory=module.params.get("memory"),
369 flavor=module.params.get("flavor"),
370 hourly=module.params.get("hourly"),
371 datacenter=module.params.get("datacenter"),
372 os_code=module.params.get("os_code"),
373 image_id=module.params.get("image_id"),
374 local_disk=module.params.get("local_disk"),
375 disks=module.params.get("disks"),
376 ssh_keys=module.params.get("ssh_keys"),
377 nic_speed=module.params.get("nic_speed"),
378 private=module.params.get("private"),
379 public_vlan=module.params.get("public_vlan"),
380 private_vlan=module.params.get("private_vlan"),
381 dedicated=module.params.get("dedicated"),
382 post_uri=module.params.get("post_uri"),
383 tags=tags,
384 )
385
386 if instance is not None and instance["id"] > 0:
387 return True, instance
388 else:
389 return False, None
390
391
392 def wait_for_instance(module, id):
393 instance = None
394 completed = False
395 wait_timeout = time.time() + module.params.get("wait_time")
396 while not completed and wait_timeout > time.time():
397 try:
398 completed = vsManager.wait_for_ready(id, 10, 2)
399 if completed:
400 instance = vsManager.get_instance(id)
401 except Exception:
402 completed = False
403
404 return completed, instance
405
406
407 def cancel_instance(module):
408 canceled = True
409 if module.params.get("instance_id") is None and (
410 module.params.get("tags") or module.params.get("hostname") or module.params.get("domain")
411 ):
412 tags = module.params.get("tags")
413 if isinstance(tags, str):
414 tags = [module.params.get("tags")]
415 instances = vsManager.list_instances(
416 tags=tags, hostname=module.params.get("hostname"), domain=module.params.get("domain")
417 )
418 for instance in instances:
419 try:
420 vsManager.cancel_instance(instance["id"])
421 except Exception:
422 canceled = False
423 elif module.params.get("instance_id") and module.params.get("instance_id") != 0:
424 try:
425 vsManager.cancel_instance(instance["id"])
426 except Exception:
427 canceled = False
428 else:
429 return False, None
430
431 return canceled, None
432
433
434 def main():
435 module = AnsibleModule(
436 argument_spec=dict(
437 instance_id=dict(type="str"),
438 hostname=dict(type="str"),
439 domain=dict(type="str"),
440 datacenter=dict(type="str", choices=DATACENTERS),
441 tags=dict(type="str"),
442 hourly=dict(type="bool", default=True),
443 private=dict(type="bool", default=False),
444 dedicated=dict(type="bool", default=False),
445 local_disk=dict(type="bool", default=True),
446 cpus=dict(type="int", choices=CPU_SIZES),
447 memory=dict(type="int", choices=MEMORY_SIZES),
448 flavor=dict(type="str"),
449 disks=dict(type="list", elements="int", default=[25]),
450 os_code=dict(type="str"),
451 image_id=dict(type="str"),
452 nic_speed=dict(type="int", choices=NIC_SPEEDS),
453 public_vlan=dict(type="str"),
454 private_vlan=dict(type="str"),
455 ssh_keys=dict(type="list", elements="str", default=[], no_log=False),
456 post_uri=dict(type="str"),
457 state=dict(type="str", default="present", choices=STATES),
458 wait=dict(type="bool", default=True),
459 wait_time=dict(type="int", default=600),
460 )
461 )
462
463 if not HAS_SL:
464 module.fail_json(msg="softlayer python library required for this module")
465
466 if module.params.get("state") == "absent":
467 (changed, instance) = cancel_instance(module)
468
469 elif module.params.get("state") == "present":
470 (changed, instance) = create_virtual_instance(module)
471 if module.params.get("wait") is True and instance:
472 (changed, instance) = wait_for_instance(module, instance["id"])
473
474 module.exit_json(changed=changed, instance=json.loads(json.dumps(instance, default=lambda o: o.__dict__)))
475
476
477 if __name__ == "__main__":
478 main()