Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 #
3 # Scaleway IP management module
4 #
5 # Copyright (c) Ansible project
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 from __future__ import annotations
10
11 DOCUMENTATION = r"""
12 module: scaleway_ip
13 short_description: Scaleway IP management module
14 author: Remy Leone (@remyleone)
15 description:
16 - This module manages IP on Scaleway account U(https://developer.scaleway.com).
17 extends_documentation_fragment:
18 - community.general._scaleway
19 - community.general._attributes
20 - community.general._scaleway.actiongroup_scaleway
21
22 attributes:
23 check_mode:
24 support: full
25 diff_mode:
26 support: none
27 action_group:
28 version_added: 11.3.0
29
30 options:
31 state:
32 type: str
33 description:
34 - Indicate desired state of the IP.
35 default: present
36 choices:
37 - present
38 - absent
39
40 organization:
41 type: str
42 description:
43 - Scaleway organization identifier.
44 - Exactly one of O(project) and O(organization) must be specified.
45
46 project:
47 type: str
48 description:
49 - Project identifier.
50 - Exactly one of O(project) and O(organization) must be specified.
51 version_added: 12.3.0
52
53 region:
54 type: str
55 description:
56 - Scaleway region to use (for example par1).
57 required: true
58 choices:
59 - ams1
60 - EMEA-NL-EVS
61 - ams2
62 - ams3
63 - par1
64 - EMEA-FR-PAR1
65 - par2
66 - EMEA-FR-PAR2
67 - par3
68 - waw1
69 - EMEA-PL-WAW1
70 - waw2
71 - waw3
72
73 id:
74 type: str
75 description:
76 - ID of the Scaleway IP (UUID).
77 server:
78 type: str
79 description:
80 - ID of the server you want to attach an IP to.
81 - To unattach an IP do not specify this option.
82 reverse:
83 type: str
84 description:
85 - Reverse to assign to the IP.
86 """
87
88 EXAMPLES = r"""
89 - name: Create an IP with a project ID
90 community.general.scaleway_ip:
91 project: '{{ project_id }}'
92 state: present
93 region: par1
94 register: ip_creation_task
95
96 - name: Make sure IP deleted
97 community.general.scaleway_ip:
98 id: '{{ ip_creation_task.scaleway_ip.id }}'
99 state: absent
100 region: par1
101
102 - name: Create an IP in the default project with an organization ID (deprecated)
103 community.general.scaleway_ip:
104 organization: '{{ scw_org }}'
105 state: present
106 region: par1
107 register: ip_creation_task
108 """
109
110 RETURN = r"""
111 data:
112 description: This is only present when O(state=present).
113 returned: when O(state=present)
114 type: dict
115 sample:
116 {
117 "ips": [
118 {
119 "organization": "951df375-e094-4d26-97c1-ba548eeb9c42",
120 "reverse": null,
121 "id": "dd9e8df6-6775-4863-b517-e0b0ee3d7477",
122 "server": {
123 "id": "3f1568ca-b1a2-4e98-b6f7-31a0588157f1",
124 "name": "ansible_tuto-1"
125 },
126 "address": "212.47.232.136"
127 }
128 ]
129 }
130 """
131
132 from ansible.module_utils.basic import AnsibleModule
133
134 from ansible_collections.community.general.plugins.module_utils._scaleway import (
135 SCALEWAY_LOCATION,
136 Scaleway,
137 scaleway_argument_spec,
138 )
139
140
141 def ip_attributes_should_be_changed(api, target_ip, wished_ip):
142 patch_payload = {}
143
144 if target_ip["reverse"] != wished_ip["reverse"]:
145 patch_payload["reverse"] = wished_ip["reverse"]
146
147 # IP is assigned to a server
148 if target_ip["server"] is None and wished_ip["server"]:
149 patch_payload["server"] = wished_ip["server"]
150
151 # IP is unassigned to a server
152 try:
153 if target_ip["server"]["id"] and wished_ip["server"] is None:
154 patch_payload["server"] = wished_ip["server"]
155 except (TypeError, KeyError):
156 pass
157
158 # IP is migrated between 2 different servers
159 try:
160 if target_ip["server"]["id"] != wished_ip["server"]:
161 patch_payload["server"] = wished_ip["server"]
162 except (TypeError, KeyError):
163 pass
164
165 return patch_payload
166
167
168 def payload_from_wished_ip(wished_ip):
169 return {k: v for k, v in wished_ip.items() if k != "id" and v is not None}
170
171
172 def present_strategy(api, wished_ip):
173 changed = False
174
175 response = api.get("ips")
176 if not response.ok:
177 api.module.fail_json(msg=f"Error getting IPs [{response.status_code}: {response.json['message']}]")
178
179 ips_list = response.json["ips"]
180 ip_lookup = {ip["id"]: ip for ip in ips_list}
181
182 if wished_ip["id"] not in ip_lookup.keys():
183 changed = True
184 if api.module.check_mode:
185 return changed, {"status": "An IP would be created."}
186
187 # Create IP
188 creation_response = api.post("/ips", data=payload_from_wished_ip(wished_ip))
189
190 if not creation_response.ok:
191 msg = f"Error during ip creation: {creation_response.info['msg']}: '{creation_response.json['message']}' ({creation_response.json})"
192 api.module.fail_json(msg=msg)
193 return changed, creation_response.json["ip"]
194
195 target_ip = ip_lookup[wished_ip["id"]]
196 patch_payload = ip_attributes_should_be_changed(api=api, target_ip=target_ip, wished_ip=wished_ip)
197
198 if not patch_payload:
199 return changed, target_ip
200
201 changed = True
202 if api.module.check_mode:
203 return changed, {"status": "IP attributes would be changed."}
204
205 ip_patch_response = api.patch(path=f"ips/{target_ip['id']}", data=patch_payload)
206
207 if not ip_patch_response.ok:
208 api.module.fail_json(
209 msg=f"Error during IP attributes update: [{ip_patch_response.status_code}: {ip_patch_response.json['message']}]"
210 )
211
212 return changed, ip_patch_response.json["ip"]
213
214
215 def absent_strategy(api, wished_ip):
216 response = api.get("ips")
217 changed = False
218
219 status_code = response.status_code
220 ips_json = response.json
221 ips_list = ips_json["ips"]
222
223 if not response.ok:
224 api.module.fail_json(msg=f"Error getting IPs [{status_code}: {response.json['message']}]")
225
226 ip_lookup = {ip["id"]: ip for ip in ips_list}
227 if wished_ip["id"] not in ip_lookup.keys():
228 return changed, {}
229
230 changed = True
231 if api.module.check_mode:
232 return changed, {"status": "IP would be destroyed"}
233
234 response = api.delete(f"/ips/{wished_ip['id']}")
235 if not response.ok:
236 api.module.fail_json(msg=f"Error deleting IP [{response.status_code}: {response.json}]")
237
238 return changed, response.json
239
240
241 def core(module):
242 wished_ip = {
243 "organization": module.params["organization"],
244 "project": module.params["project"],
245 "reverse": module.params["reverse"],
246 "id": module.params["id"],
247 "server": module.params["server"],
248 }
249
250 region = module.params["region"]
251 module.params["api_url"] = SCALEWAY_LOCATION[region]["api_endpoint"]
252
253 api = Scaleway(module=module)
254 if module.params["state"] == "absent":
255 changed, summary = absent_strategy(api=api, wished_ip=wished_ip)
256 else:
257 changed, summary = present_strategy(api=api, wished_ip=wished_ip)
258 module.exit_json(changed=changed, scaleway_ip=summary)
259
260
261 def main():
262 argument_spec = scaleway_argument_spec()
263 argument_spec.update(
264 dict(
265 state=dict(default="present", choices=["absent", "present"]),
266 organization=dict(),
267 project=dict(),
268 server=dict(),
269 reverse=dict(),
270 region=dict(required=True, choices=list(SCALEWAY_LOCATION.keys())),
271 id=dict(),
272 )
273 )
274 module = AnsibleModule(
275 argument_spec=argument_spec,
276 supports_check_mode=True,
277 mutually_exclusive=[
278 ("organization", "project"),
279 ],
280 required_one_of=[
281 ("organization", "project"),
282 ],
283 )
284
285 core(module)
286
287
288 if __name__ == "__main__":
289 main()