Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2019, Nurfet Becirevic <[email protected]>
4 # Copyright (c) 2019, Tomas Karasek <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import annotations
9
10 DOCUMENTATION = r"""
11 module: packet_project
12
13 short_description: Create/delete a project in Packet host
14
15 description:
16 - Create/delete a project in Packet host.
17 - API is documented at U(https://www.packet.com/developers/api/#projects).
18 version_added: '0.2.0'
19
20 author:
21 - Tomas Karasek (@t0mk) <[email protected]>
22 - Nurfet Becirevic (@nurfet-becirevic) <[email protected]>
23
24 extends_documentation_fragment:
25 - community.general._attributes
26
27 attributes:
28 check_mode:
29 support: full
30 diff_mode:
31 support: none
32
33 options:
34 state:
35 description:
36 - Indicate desired state of the target.
37 default: present
38 choices: ['present', 'absent']
39 type: str
40
41 payment_method:
42 description:
43 - Payment method is name of one of the payment methods available to your user.
44 - When blank, the API assumes the default payment method.
45 type: str
46
47 auth_token:
48 description:
49 - Packet API token. You can also supply it in environment variable E(PACKET_API_TOKEN).
50 type: str
51
52 name:
53 description:
54 - Name for/of the project.
55 type: str
56
57 org_id:
58 description:
59 - UUID of the organization to create a project for.
60 - When blank, the API assumes the default organization.
61 type: str
62
63 id:
64 description:
65 - UUID of the project which you want to remove.
66 type: str
67
68 custom_data:
69 description:
70 - Custom data about the project to create.
71 type: str
72
73 requirements:
74 - "packet-python >= 1.40"
75 """
76
77 EXAMPLES = r"""
78 # All the examples assume that you have your Packet API token in env var PACKET_API_TOKEN.
79 # You can also pass the api token in module param auth_token.
80
81 - name: Create new project
82 hosts: localhost
83 tasks:
84 - community.general.packet_project:
85 name: "new project"
86
87 - name: Create new project within non-default organization
88 hosts: localhost
89 tasks:
90 - community.general.packet_project:
91 name: "my org project"
92 org_id: a4cc87f9-e00f-48c2-9460-74aa60beb6b0
93
94 - name: Remove project by id
95 hosts: localhost
96 tasks:
97 - community.general.packet_project:
98 state: absent
99 id: eef49903-7a09-4ca1-af67-4087c29ab5b6
100
101 - name: Create new project with non-default billing method
102 hosts: localhost
103 tasks:
104 - community.general.packet_project:
105 name: "newer project"
106 payment_method: "the other visa"
107 """
108
109 RETURN = r"""
110 name:
111 description: Name of addressed project.
112 type: str
113 returned: success
114
115 id:
116 description: UUID of addressed project.
117 type: str
118 returned: success
119 """
120
121 from ansible.module_utils.basic import AnsibleModule, env_fallback
122
123 HAS_PACKET_SDK = True
124
125 try:
126 import packet
127 except ImportError:
128 HAS_PACKET_SDK = False
129
130 PACKET_API_TOKEN_ENV_VAR = "PACKET_API_TOKEN"
131
132
133 def act_on_project(target_state, module, packet_conn):
134 result_dict = {"changed": False}
135 given_id = module.params.get("id")
136 given_name = module.params.get("name")
137 if given_id:
138 matching_projects = [p for p in packet_conn.list_projects() if given_id == p.id]
139 else:
140 matching_projects = [p for p in packet_conn.list_projects() if given_name == p.name]
141
142 if target_state == "present":
143 if len(matching_projects) == 0:
144 org_id = module.params.get("org_id")
145 custom_data = module.params.get("custom_data")
146 payment_method = module.params.get("payment_method")
147
148 if not org_id:
149 params = {"name": given_name, "payment_method_id": payment_method, "customdata": custom_data}
150 new_project_data = packet_conn.call_api("projects", "POST", params)
151 new_project = packet.Project(new_project_data, packet_conn)
152 else:
153 new_project = packet_conn.create_organization_project(
154 org_id=org_id, name=given_name, payment_method_id=payment_method, customdata=custom_data
155 )
156
157 result_dict["changed"] = True
158 matching_projects.append(new_project)
159
160 result_dict["name"] = matching_projects[0].name
161 result_dict["id"] = matching_projects[0].id
162 else:
163 if len(matching_projects) > 1:
164 _msg = f"More than projects matched for module call with state = absent: {matching_projects}"
165 module.fail_json(msg=_msg)
166
167 if len(matching_projects) == 1:
168 p = matching_projects[0]
169 result_dict["name"] = p.name
170 result_dict["id"] = p.id
171 result_dict["changed"] = True
172 try:
173 p.delete()
174 except Exception as e:
175 _msg = f"while trying to remove project {p.name}, id {p.id}, got error: {e}"
176 module.fail_json(msg=_msg)
177 return result_dict
178
179
180 def main():
181 module = AnsibleModule(
182 argument_spec=dict(
183 state=dict(choices=["present", "absent"], default="present"),
184 auth_token=dict(type="str", fallback=(env_fallback, [PACKET_API_TOKEN_ENV_VAR]), no_log=True),
185 name=dict(type="str"),
186 id=dict(type="str"),
187 org_id=dict(type="str"),
188 payment_method=dict(type="str"),
189 custom_data=dict(type="str"),
190 ),
191 supports_check_mode=True,
192 required_one_of=[
193 (
194 "name",
195 "id",
196 )
197 ],
198 mutually_exclusive=[
199 ("name", "id"),
200 ],
201 )
202 if not HAS_PACKET_SDK:
203 module.fail_json(msg="packet required for this module")
204
205 if not module.params.get("auth_token"):
206 _fail_msg = f"if Packet API token is not in environment variable {PACKET_API_TOKEN_ENV_VAR}, the auth_token parameter is required"
207 module.fail_json(msg=_fail_msg)
208
209 auth_token = module.params.get("auth_token")
210
211 packet_conn = packet.Manager(auth_token=auth_token)
212
213 state = module.params.get("state")
214
215 if state in ["present", "absent"]:
216 if module.check_mode:
217 module.exit_json(changed=False)
218
219 try:
220 module.exit_json(**act_on_project(state, module, packet_conn))
221 except Exception as e:
222 module.fail_json(msg=f"failed to set project state {state}: {e}")
223 else:
224 module.fail_json(msg=f"{state} is not a valid state for this module")
225
226
227 if __name__ == "__main__":
228 main()