Debian Codegraph @

ansible_collections/cisco/mso/plugins/modules/ndo_dhcp_option_policy.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2024, Akini Ross (@akinross) <[email protected]>
5
6 # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 from __future__ import absolute_import, division, print_function
9
10 __metaclass__ = type
11
12 ANSIBLE_METADATA = {"metadata_version": "1.1", "status": ["preview"], "supported_by": "community"}
13
14 DOCUMENTATION = r"""
15 ---
16 module: ndo_dhcp_option_policy
17 short_description: Manage DHCP Option Policies on Cisco Nexus Dashboard Orchestrator (NDO).
18 description:
19 - Manage DHCP Option Policies on Cisco Nexus Dashboard Orchestrator (NDO).
20 - This module is only supported on ND v3.1 (NDO v4.3) and later.
21 author:
22 - Akini Ross (@akinross)
23 options:
24 template:
25 description:
26 - The name of the template.
27 - The template must be a tenant template.
28 type: str
29 required: true
30 option_policy:
31 description:
32 - The name of the DHCP Option Policy.
33 type: str
34 aliases: [ name ]
35 option_policy_uuid:
36 description:
37 - The uuid of the DHCP Option Policy.
38 - This parameter is required when the O(option_policy) needs to be updated.
39 type: str
40 aliases: [ uuid ]
41 description:
42 description:
43 - The description of the DHCP Option Policy.
44 type: str
45 options:
46 description:
47 - A list of options attached to the DHCP Option Policy.
48 - The list of configured options must contain at least one option.
49 - When the list of options is null the update will not change existing option configuration.
50 type: list
51 elements: dict
52 suboptions:
53 name:
54 description:
55 - The name of the option.
56 type: str
57 required: true
58 id:
59 description:
60 - The id of the option.
61 type: int
62 data:
63 description:
64 - The data of the option.
65 type: str
66 state:
67 description:
68 - Use C(absent) for removing.
69 - Use C(query) for listing an object or multiple objects.
70 - Use C(present) for creating or updating.
71 type: str
72 choices: [ absent, query, present ]
73 default: query
74 extends_documentation_fragment: cisco.mso.modules
75 """
76
77 EXAMPLES = r"""
78 - name: Create a new dhcp option policy
79 cisco.mso.ndo_dhcp_option_policy:
80 host: mso_host
81 username: admin
82 password: SomeSecretPassword
83 template: ansible_tenant_template
84 option_policy: ansible_test_option_policy
85 options:
86 - name: option_1
87 id: 1
88 data: data_1
89 state: present
90 register: create
91
92 - name: Query a dhcp option policy with name
93 cisco.mso.ndo_dhcp_option_policy:
94 host: mso_host
95 username: admin
96 password: SomeSecretPassword
97 template: ansible_tenant_template
98 option_policy: ansible_test_option_policy
99 state: query
100 register: query_one
101
102 - name: Query a dhcp option policy with UUID
103 cisco.mso.ndo_dhcp_option_policy:
104 host: mso_host
105 username: admin
106 password: SomeSecretPassword
107 template: ansible_tenant_template
108 option_policy_uuid: '{{ create.current.uuid }}'
109 state: query
110 register: query_uuid
111
112 - name: Query all dhcp option policy in the template
113 cisco.mso.ndo_dhcp_option_policy:
114 host: mso_host
115 username: admin
116 password: SomeSecretPassword
117 template: ansible_tenant_template
118 state: query
119 register: query_all
120
121 - name: Delete a dhcp option policy
122 cisco.mso.ndo_dhcp_option_policy:
123 host: mso_host
124 username: admin
125 password: SomeSecretPassword
126 template: ansible_tenant_template
127 option_policy: ansible_test_option_policy
128 state: absent
129 """
130
131 RETURN = r"""
132 """
133
134
135 import copy
136 from ansible.module_utils.basic import AnsibleModule
137 from ansible_collections.cisco.mso.plugins.module_utils.mso import MSOModule, mso_argument_spec
138 from ansible_collections.cisco.mso.plugins.module_utils.template import MSOTemplate, KVPair
139
140
141 def main():
142 argument_spec = mso_argument_spec()
143 argument_spec.update(
144 template=dict(type="str", required=True),
145 option_policy=dict(type="str", aliases=["name"]),
146 option_policy_uuid=dict(type="str", aliases=["uuid"]),
147 description=dict(type="str"),
148 options=dict(
149 type="list",
150 elements="dict",
151 options=dict(
152 name=dict(type="str", required=True),
153 id=dict(type="int"),
154 data=dict(type="str"),
155 ),
156 ),
157 state=dict(type="str", default="query", choices=["absent", "query", "present"]),
158 )
159
160 module = AnsibleModule(
161 argument_spec=argument_spec,
162 supports_check_mode=True,
163 required_if=[
164 ["state", "absent", ["option_policy"]],
165 ["state", "present", ["option_policy"]],
166 ],
167 )
168
169 mso = MSOModule(module)
170
171 template = module.params.get("template")
172 option_policy = module.params.get("option_policy")
173 option_policy_uuid = module.params.get("option_policy_uuid")
174 options = get_options_payload(module.params.get("options")) if module.params.get("options") else []
175 description = module.params.get("description")
176 state = module.params.get("state")
177
178 ops = []
179 match = None
180 err_message_min_options = "At least one option is required when state is present."
181
182 mso_template = MSOTemplate(mso, "tenant", template)
183 mso_template.validate_template("tenantPolicy")
184
185 path = "/tenantPolicyTemplate/template/dhcpOptionPolicies"
186
187 match = get_dhcp_option_policy(mso_template, option_policy_uuid, option_policy)
188
189 if option_policy_uuid or option_policy:
190 if match:
191 mso.existing = mso.previous = copy.deepcopy(match.details) # Query a specific object
192 elif match:
193 mso.existing = match # Query all objects
194
195 if state == "present":
196 if match:
197 if module.params.get("options") is not None and len(options) == 0:
198 mso.fail_json(msg=err_message_min_options)
199
200 if option_policy and match.details.get("name") != option_policy:
201 ops.append(dict(op="replace", path="{0}/{1}/name".format(path, match.index), value=option_policy))
202 match.details["name"] = option_policy
203
204 if description is not None and match.details.get("description") != description:
205 ops.append(dict(op="replace", path="{0}/{1}/description".format(path, match.index), value=description))
206 match.details["description"] = description
207
208 if module.params.get("options") is not None and match.details.get("options") != options:
209 ops.append(dict(op="replace", path="{0}/{1}/options".format(path, match.index), value=options))
210 match.details["options"] = options
211
212 mso.sanitize(match.details)
213
214 else:
215 if not options:
216 mso.fail_json(msg=err_message_min_options)
217
218 payload = {"name": option_policy, "options": options}
219 if description:
220 payload["description"] = description
221
222 ops.append(dict(op="add", path="{0}/-".format(path), value=payload))
223
224 mso.sanitize(payload)
225
226 mso.existing = mso.proposed
227
228 elif state == "absent":
229 if match:
230 ops.append(dict(op="remove", path="{0}/{1}".format(path, match.index)))
231 mso.existing = {}
232
233 if not module.check_mode and ops:
234 mso_template.template = mso.request(mso_template.template_path, method="PATCH", data=ops)
235 match = get_dhcp_option_policy(mso_template, option_policy_uuid, option_policy)
236 if match:
237 mso.existing = match.details # When the state is present
238 else:
239 mso.existing = {} # When the state is absent
240 elif module.check_mode and state != "query": # When the state is present/absent with check mode
241 mso.existing = mso.proposed if state == "present" else {}
242
243 mso.exit_json()
244
245
246 def get_dhcp_option_policy(mso_template, uuid=None, name=None, fail_module=False):
247 existing_dhcp_option_policies = mso_template.template.get("tenantPolicyTemplate", {}).get("template", {}).get("dhcpOptionPolicies", [])
248 if uuid or name: # Query a specific object
249 return mso_template.get_object_by_key_value_pairs(
250 "DHCP Option Policy", existing_dhcp_option_policies, [KVPair("uuid", uuid) if uuid else KVPair("name", name)], fail_module
251 )
252 return existing_dhcp_option_policies # Query all objects
253
254
255 def get_options_payload(options):
256 payload = []
257 for option in options:
258 option_payload = {"name": option.get("name")}
259 if option.get("id") and id != 0:
260 option_payload["id"] = option.get("id")
261 if option.get("data"):
262 option_payload["data"] = option.get("data")
263 payload.append(option_payload)
264 return payload
265
266
267 if __name__ == "__main__":
268 main()