Debian Codegraph @

ansible_collections/community/general/plugins/modules/linode_v4.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: linode_v4
11 short_description: Manage instances on the Linode cloud
12 description: Manage instances on the Linode cloud.
13 requirements:
14 - linode_api4 >= 2.0.0
15 author:
16 - Luke Murphy (@decentral1se)
17 notes:
18 - No Linode resizing is currently implemented. This module aims to replace the current Linode module which uses deprecated
19 API bindings on the Linode side.
20 extends_documentation_fragment:
21 - community.general._attributes
22 attributes:
23 check_mode:
24 support: none
25 diff_mode:
26 support: none
27 options:
28 region:
29 description:
30 - The region of the instance. This is a required parameter only when creating Linode instances. See U(https://www.linode.com/docs/api/regions/).
31 type: str
32 image:
33 description:
34 - The image of the instance. This is a required parameter only when creating Linode instances.
35 - See U(https://www.linode.com/docs/api/images/).
36 type: str
37 type:
38 description:
39 - The type of the instance. This is a required parameter only when creating Linode instances.
40 - See U(https://www.linode.com/docs/api/linode-types/).
41 type: str
42 label:
43 description:
44 - The instance label. This label is used as the main determiner for idempotency for the module and is therefore mandatory.
45 type: str
46 required: true
47 group:
48 description:
49 - The group that the instance should be marked under. Please note, that group labelling is deprecated but still supported.
50 The encouraged method for marking instances is to use tags.
51 type: str
52 private_ip:
53 description:
54 - If V(true), the created Linode instance has private networking enabled and assigned a private IPv4 address.
55 type: bool
56 default: false
57 version_added: 3.0.0
58 tags:
59 description:
60 - The tags that the instance should be marked under.
61 - See U(https://www.linode.com/docs/api/tags/).
62 type: list
63 elements: str
64 root_pass:
65 description:
66 - The password for the root user. If not specified, it generates a new one. This generated password is available in
67 the task success JSON.
68 type: str
69 authorized_keys:
70 description:
71 - A list of SSH public key parts to deploy for the root user.
72 type: list
73 elements: str
74 state:
75 description:
76 - The desired instance state.
77 type: str
78 choices:
79 - present
80 - absent
81 required: true
82 access_token:
83 description:
84 - The Linode API v4 access token. It may also be specified by exposing the E(LINODE_ACCESS_TOKEN) environment variable.
85 - See U(https://www.linode.com/docs/api#access-and-authentication).
86 required: true
87 type: str
88 stackscript_id:
89 description:
90 - The numeric ID of the StackScript to use when creating the instance.
91 - See U(https://www.linode.com/docs/api/stackscripts/).
92 type: int
93 version_added: 1.3.0
94 stackscript_data:
95 description:
96 - An object containing arguments to any User Defined Fields present in the StackScript used when creating the instance.
97 Only valid when a O(stackscript_id) is provided.
98 - See U(https://www.linode.com/docs/api/stackscripts/).
99 type: dict
100 version_added: 1.3.0
101 """
102
103 EXAMPLES = r"""
104 - name: Create a new Linode.
105 community.general.linode_v4:
106 label: new-linode
107 type: g6-nanode-1
108 region: eu-west
109 image: linode/debian9
110 root_pass: passw0rd
111 authorized_keys:
112 - "ssh-rsa ..."
113 stackscript_id: 1337
114 stackscript_data:
115 variable: value
116 state: present
117
118 - name: Delete that new Linode.
119 community.general.linode_v4:
120 label: new-linode
121 state: absent
122 """
123
124 RETURN = r"""
125 instance:
126 description: The instance description in JSON serialized form.
127 returned: Always.
128 type: dict
129 sample:
130 {
131 "root_pass": "foobar", # if auto-generated
132 "alerts": {
133 "cpu": 90,
134 "io": 10000,
135 "network_in": 10,
136 "network_out": 10,
137 "transfer_quota": 80
138 },
139 "backups": {
140 "enabled": false,
141 "schedule": {
142 "day": null,
143 "window": null
144 }
145 },
146 "created": "2018-09-26T08:12:33",
147 "group": "Foobar Group",
148 "hypervisor": "kvm",
149 "id": 10480444,
150 "image": "linode/centos7",
151 "ipv4": [
152 "130.132.285.233"
153 ],
154 "ipv6": "2a82:7e00::h03c:46ff:fe04:5cd2/64",
155 "label": "lin-foo",
156 "region": "eu-west",
157 "specs": {
158 "disk": 25600,
159 "memory": 1024,
160 "transfer": 1000,
161 "vcpus": 1
162 },
163 "status": "running",
164 "tags": [],
165 "type": "g6-nanode-1",
166 "updated": "2018-09-26T10:10:14",
167 "watchdog_enabled": true
168 }
169 """
170
171 import traceback
172
173 from ansible.module_utils.basic import AnsibleModule, env_fallback, missing_required_lib
174
175 from ansible_collections.community.general.plugins.module_utils._linode import get_user_agent
176
177 LINODE_IMP_ERR = None
178 try:
179 from linode_api4 import Instance, LinodeClient
180
181 HAS_LINODE_DEPENDENCY = True
182 except ImportError:
183 LINODE_IMP_ERR = traceback.format_exc()
184 HAS_LINODE_DEPENDENCY = False
185
186
187 def create_linode(module, client, **kwargs):
188 """Creates a Linode instance and handles return format."""
189 if kwargs["root_pass"] is None:
190 kwargs.pop("root_pass")
191
192 try:
193 response = client.linode.instance_create(**kwargs)
194 except Exception as exception:
195 module.fail_json(msg=f"Unable to query the Linode API. Saw: {exception}")
196
197 try:
198 if isinstance(response, tuple):
199 instance, root_pass = response
200 instance_json = instance._raw_json
201 instance_json.update({"root_pass": root_pass})
202 return instance_json
203 else:
204 return response._raw_json
205 except TypeError:
206 module.fail_json(
207 msg="Unable to parse Linode instance creation response. Please raise a bug against this"
208 " module on https://github.com/ansible-collections/community.general/issues"
209 )
210
211
212 def maybe_instance_from_label(module, client):
213 """Try to retrieve an instance based on a label."""
214 try:
215 label = module.params["label"]
216 result = client.linode.instances(Instance.label == label)
217 return result[0]
218 except IndexError:
219 return None
220 except Exception as exception:
221 module.fail_json(msg=f"Unable to query the Linode API. Saw: {exception}")
222
223
224 def initialise_module():
225 """Initialise the module parameter specification."""
226 return AnsibleModule(
227 argument_spec=dict(
228 label=dict(type="str", required=True),
229 state=dict(type="str", required=True, choices=["present", "absent"]),
230 access_token=dict(
231 type="str",
232 required=True,
233 no_log=True,
234 fallback=(env_fallback, ["LINODE_ACCESS_TOKEN"]),
235 ),
236 authorized_keys=dict(type="list", elements="str", no_log=False),
237 group=dict(type="str"),
238 image=dict(type="str"),
239 private_ip=dict(type="bool", default=False),
240 region=dict(type="str"),
241 root_pass=dict(type="str", no_log=True),
242 tags=dict(type="list", elements="str"),
243 type=dict(type="str"),
244 stackscript_id=dict(type="int"),
245 stackscript_data=dict(type="dict"),
246 ),
247 supports_check_mode=False,
248 required_one_of=(["state", "label"],),
249 required_together=(["region", "image", "type"],),
250 )
251
252
253 def build_client(module):
254 """Build a LinodeClient."""
255 return LinodeClient(module.params["access_token"], user_agent=get_user_agent("linode_v4_module"))
256
257
258 def main():
259 """Module entrypoint."""
260 module = initialise_module()
261
262 if not HAS_LINODE_DEPENDENCY:
263 module.fail_json(msg=missing_required_lib("linode-api4"), exception=LINODE_IMP_ERR)
264
265 client = build_client(module)
266 instance = maybe_instance_from_label(module, client)
267
268 if module.params["state"] == "present" and instance is not None:
269 module.exit_json(changed=False, instance=instance._raw_json)
270
271 elif module.params["state"] == "present" and instance is None:
272 instance_json = create_linode(
273 module,
274 client,
275 authorized_keys=module.params["authorized_keys"],
276 group=module.params["group"],
277 image=module.params["image"],
278 label=module.params["label"],
279 private_ip=module.params["private_ip"],
280 region=module.params["region"],
281 root_pass=module.params["root_pass"],
282 tags=module.params["tags"],
283 ltype=module.params["type"],
284 stackscript=module.params["stackscript_id"],
285 stackscript_data=module.params["stackscript_data"],
286 )
287 module.exit_json(changed=True, instance=instance_json)
288
289 elif module.params["state"] == "absent" and instance is not None:
290 instance.delete()
291 module.exit_json(changed=True, instance=instance._raw_json)
292
293 elif module.params["state"] == "absent" and instance is None:
294 module.exit_json(changed=False, instance={})
295
296
297 if __name__ == "__main__":
298 main()