Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, Dag Wieers (@dagwieers) <[email protected]>
5 # Copyright: (c) 2024, Akini Ross (@akinross) <[email protected]>
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: mso_schema_template_anp_epg_contract
17 short_description: Manage EPG contracts in schema templates
18 description:
19 - Manage EPG contracts in schema templates on Cisco ACI Multi-Site.
20 author:
21 - Dag Wieers (@dagwieers)
22 - Akini Ross (@akinross)
23 options:
24 schema:
25 description:
26 - The name of the Schema.
27 type: str
28 required: true
29 template:
30 description:
31 - The name of the Template.
32 type: str
33 required: true
34 anp:
35 description:
36 - The name of the ANP.
37 type: str
38 required: true
39 epg:
40 description:
41 - The name of the EPG.
42 type: str
43 required: true
44 force_replace:
45 description:
46 - Replaces all the configured contract(s) with the provided contract(s).
47 - This option can only be used in combination with the O(contracts) option.
48 - In combination with the O(state=absent) and without any contract configuration all configured static port(s) will be removed.
49 type: bool
50 contract:
51 description:
52 - The Contract associated to this EPG.
53 - This option can not be used in combination with the I(contracts) option.
54 type: dict
55 suboptions:
56 name:
57 description:
58 - The name of the Contract.
59 required: true
60 type: str
61 schema:
62 description:
63 - The name of the Schema that defines the referenced Contract.
64 - If this parameter is unspecified, it defaults to the current schema.
65 type: str
66 template:
67 description:
68 - The name of the Template that defines the referenced Contract.
69 - If this parameter is unspecified, it defaults to the current schema.
70 type: str
71 type:
72 description:
73 - The type of the Contract.
74 type: str
75 required: true
76 choices: [ consumer, provider ]
77 contracts:
78 description:
79 - A list of Contracts associated to this EPG.
80 - This option can not be used in combination with the O(contract) option.
81 - All configured contract(s) will be replaced with the provided contract(s) when used with O(force_replace=true).
82 - Only the provided contract(s) will be added, updated or removed when used with O(force_replace=false).
83 - In combination with the O(state=query) all provided contract(s) must be found else the task will fail.
84 type: list
85 elements: dict
86 suboptions:
87 name:
88 description:
89 - The name of the Contract.
90 required: true
91 type: str
92 schema:
93 description:
94 - The name of the Schema that defines the referenced Contract.
95 - If this parameter is unspecified, it defaults to the current schema.
96 type: str
97 template:
98 description:
99 - The name of the Template that defines the referenced Contract.
100 - If this parameter is unspecified, it defaults to the current schema.
101 type: str
102 type:
103 description:
104 - The type of the Contract.
105 type: str
106 required: true
107 choices: [ consumer, provider ]
108 state:
109 description:
110 - Use C(present) or C(absent) for adding or removing.
111 - Use C(query) for listing an object or multiple objects.
112 type: str
113 choices: [ absent, present, query ]
114 default: present
115 seealso:
116 - module: cisco.mso.mso_schema_template_anp_epg
117 - module: cisco.mso.mso_schema_template_contract_filter
118 extends_documentation_fragment: cisco.mso.modules
119 """
120
121 EXAMPLES = r"""
122 - name: Add a contract to an EPG
123 cisco.mso.mso_schema_template_anp_epg_contract:
124 host: mso_host
125 username: admin
126 password: SomeSecretPassword
127 schema: Schema 1
128 template: Template 1
129 anp: ANP 1
130 epg: EPG 1
131 contract:
132 name: Contract 1
133 type: consumer
134 state: present
135
136 - name: Add 2 contracts to an EPG
137 cisco.mso.mso_schema_template_anp_epg_contract:
138 host: mso_host
139 username: admin
140 password: SomeSecretPassword
141 schema: Schema 1
142 template: Template 1
143 anp: ANP 1
144 epg: EPG 1
145 contracts:
146 - name: Contract 1
147 type: provider
148 - name: Contract 1
149 type: consumer
150 state: present
151
152 - name: Replace all existing contracts on an EPG with 2 new contracts
153 cisco.mso.mso_schema_template_anp_epg_contract:
154 host: mso_host
155 username: admin
156 password: SomeSecretPassword
157 schema: Schema 1
158 template: Template 1
159 anp: ANP 1
160 epg: EPG 1
161 force_replace: true
162 contracts:
163 - name: Contract 2
164 type: provider
165 - name: Contract 2
166 type: consumer
167 state: present
168
169 - name: Query a specific Contract
170 cisco.mso.mso_schema_template_anp_epg_contract:
171 host: mso_host
172 username: admin
173 password: SomeSecretPassword
174 schema: Schema 1
175 template: Template 1
176 anp: ANP 1
177 epg: EPG 1
178 contract:
179 name: Contract 1
180 type: consumer
181 state: query
182 register: query_result
183
184 - name: Query a list of Contracts
185 cisco.mso.mso_schema_template_anp_epg_contract:
186 host: mso_host
187 username: admin
188 password: SomeSecretPassword
189 schema: Schema 1
190 template: Template 1
191 anp: ANP 1
192 epg: EPG 1
193 contracts:
194 - name: Contract 2
195 type: provider
196 - name: Contract 2
197 type: consumer
198 state: query
199 register: query_result
200
201 - name: Query all Contracts
202 cisco.mso.mso_schema_template_anp_epg_contract:
203 host: mso_host
204 username: admin
205 password: SomeSecretPassword
206 schema: Schema 1
207 template: Template 1
208 anp: ANP 1
209 state: query
210 register: query_result
211
212 - name: Remove a Contract
213 cisco.mso.mso_schema_template_anp_epg_contract:
214 host: mso_host
215 username: admin
216 password: SomeSecretPassword
217 schema: Schema 1
218 template: Template 1
219 anp: ANP 1
220 epg: EPG 1
221 contract:
222 name: Contract 1
223 state: absent
224
225 - name: Remove 2 contracts to an EPG
226 cisco.mso.mso_schema_template_anp_epg_contract:
227 host: mso_host
228 username: admin
229 password: SomeSecretPassword
230 schema: Schema 1
231 template: Template 1
232 anp: ANP 1
233 epg: EPG 1
234 contracts:
235 - name: Contract 1
236 type: provider
237 - name: Contract 1
238 type: consumer
239 state: absent
240
241 - name: Remove all existing contracts from an EPG
242 cisco.mso.mso_schema_template_anp_epg_contract:
243 host: mso_host
244 username: admin
245 password: SomeSecretPassword
246 schema: Schema 1
247 template: Template 1
248 anp: ANP 1
249 epg: EPG 1
250 force_replace: true
251 state: absent
252 """
253
254 RETURN = r"""
255 """
256
257 from ansible.module_utils.basic import AnsibleModule
258 from ansible_collections.cisco.mso.plugins.module_utils.mso import MSOModule, mso_argument_spec, mso_contractref_spec
259 from ansible_collections.cisco.mso.plugins.module_utils.schema import MSOSchema
260
261
262 def main():
263 argument_spec = mso_argument_spec()
264 argument_spec.update(
265 schema=dict(type="str", required=True),
266 template=dict(type="str", required=True),
267 anp=dict(type="str", required=True),
268 epg=dict(type="str", required=True),
269 force_replace=dict(type="bool"),
270 contract=dict(type="dict", options=mso_contractref_spec()),
271 contracts=dict(type="list", elements="dict", options=mso_contractref_spec()),
272 state=dict(type="str", default="present", choices=["absent", "present", "query"]),
273 )
274
275 module = AnsibleModule(
276 argument_spec=argument_spec,
277 supports_check_mode=True,
278 required_if=[
279 ["state", "absent", ["contract", "contracts", "force_replace"], True],
280 ["state", "present", ["contract", "contracts"], True],
281 ],
282 mutually_exclusive=[
283 ["contract", "contracts"],
284 ["contract", "force_replace"],
285 ],
286 )
287
288 schema = module.params.get("schema")
289 template = module.params.get("template").replace(" ", "")
290 anp = module.params.get("anp")
291 epg = module.params.get("epg")
292 force_replace = module.params.get("force_replace")
293 contract = module.params.get("contract")
294 contracts = module.params.get("contracts")
295 state = module.params.get("state")
296
297 mso = MSOModule(module)
298
299 mso_schema = MSOSchema(mso, schema, template)
300 mso_schema.set_template(template)
301 mso_schema.set_template_anp(anp)
302 mso_schema.set_template_anp_epg(epg)
303
304 # Schema dict is used as a cache store for schema id lookups
305 # This is done to limit the amount of schema id lookups when schema is not specified for multiple contracts
306 schema_cache = {mso_schema.schema_name: mso_schema.id}
307 if contract:
308 overwrite_contract_schema_and_template(mso, contract, schema, schema_cache, template)
309 elif contracts:
310 for contract_dict in contracts:
311 overwrite_contract_schema_and_template(mso, contract_dict, schema, schema_cache, template)
312
313 contracts_path = "/templates/{0}/anps/{1}/epgs/{2}/contractRelationships".format(template, anp, epg)
314 contract_path = "{0}/-".format(contracts_path)
315 ops = []
316
317 if contract:
318 contract_ref = mso.contract_ref(**contract)
319 mso_schema.set_template_anp_epg_contract(contract_ref, contract.get("type"), False)
320 if mso_schema.schema_objects.get("template_anp_epg_contract") is not None:
321 mso.existing = get_contract_payload_from_schema(mso, mso_schema)
322 contract_path = "{0}/{1}".format(contracts_path, mso_schema.schema_objects["template_anp_epg_contract"].index)
323 else:
324 found_contracts = []
325 set_existing_contracts(mso, mso_schema)
326 if contracts:
327 for contract_details in contracts:
328 contract_ref = mso.contract_ref(**contract_details)
329 mso_schema.set_template_anp_epg_contract(contract_ref, contract_details.get("type"), False)
330 if mso_schema.schema_objects.get("template_anp_epg_contract") is not None:
331 found_contracts.append(get_contract_payload_from_schema(mso, mso_schema))
332
333 if state == "query":
334 if contracts:
335 if len(found_contracts) == len(contracts):
336 mso.existing = found_contracts
337 else:
338 not_found_contracts = [
339 "Contract with Reference '{0}' and type '{1}' not found".format(mso.contract_ref(**contract), contract.get("type"))
340 for contract in contracts
341 if contract not in found_contracts
342 ]
343 mso.fail_json(msg=not_found_contracts)
344 elif contract and not mso.existing:
345 mso.fail_json(msg="Contract with Reference '{0}' and type '{1}' not found".format(contract_ref, contract.get("type")))
346 mso.exit_json()
347
348 mso.previous = mso.existing
349
350 if state == "absent" and mso.existing:
351 if contract:
352 mso.sent = mso.proposed = {}
353 ops.append(dict(op="remove", path=contract_path))
354 elif force_replace:
355 mso.sent = mso.proposed = []
356 ops.append(dict(op="remove", path=contracts_path))
357 else:
358 mso.proposed = mso.existing.copy()
359 remove_index = []
360 for contract in contracts:
361 payload = get_contract_payload(contract)
362 if any(True if payload == found_contract else False for found_contract in found_contracts):
363 mso.proposed.remove(payload)
364 remove_index.append(mso.existing.index(payload))
365 # The list index should not shift when removing contracts from the list
366 # By sorting the indexes found in reverse order, we assure that the highest index is removed first by the NDO backend
367 # This logic is to avoid removing the wrong contract
368 for index in reversed(sorted(remove_index)):
369 ops.append(dict(op="remove", path="{0}/{1}".format(contracts_path, index)))
370 mso.sent = mso.proposed
371
372 elif state == "present":
373 if contract:
374 mso.sanitize(get_contract_payload(contract), collate=True)
375 if not mso.existing:
376 ops.append(dict(op="add", path=contract_path, value=mso.sent))
377 elif force_replace:
378 mso.sent = mso.proposed = [get_contract_payload(contract) for contract in contracts]
379 if mso.existing:
380 ops.append(dict(op="replace", path=contracts_path, value=mso.sent))
381 else:
382 ops.append(dict(op="add", path=contracts_path, value=mso.sent))
383 else:
384 mso.sent = []
385 mso.proposed = mso.existing.copy()
386 for contract in contracts:
387 payload = get_contract_payload(contract)
388 if payload not in mso.existing:
389 mso.proposed.append(payload)
390 # Only add the operation list if the contract is not already present
391 # This is to avoid adding the same contract multiple times
392 # Replace operation is not required because there are no attributes that can be changed except the contract itself
393 if not force_replace and not any(True if payload == found_contract else False for found_contract in found_contracts):
394 ops.append(dict(op="add", path=contract_path, value=payload))
395 mso.sent.append(payload)
396
397 mso.existing = mso.proposed
398
399 if not module.check_mode and mso.proposed != mso.previous:
400 mso.request(mso_schema.path, method="PATCH", data=ops)
401
402 mso.exit_json()
403
404
405 def set_existing_contracts(mso, mso_schema):
406 mso.existing = []
407 for existing_contract in mso_schema.schema_objects["template_anp_epg"].details.get("contractRelationships"):
408 mso.existing.append(
409 dict(
410 relationshipType=existing_contract.get("relationshipType"),
411 contractRef=mso.dict_from_ref(existing_contract.get("contractRef")),
412 )
413 )
414
415
416 def get_contract_payload_from_schema(mso, mso_schema):
417 return dict(
418 relationshipType=mso_schema.schema_objects["template_anp_epg_contract"].details.get("relationshipType"),
419 contractRef=mso.dict_from_ref(mso_schema.schema_objects["template_anp_epg_contract"].details.get("contractRef")),
420 )
421
422
423 def get_contract_payload(contract):
424 return dict(
425 relationshipType=contract.get("type"),
426 contractRef=dict(
427 contractName=contract.get("name"),
428 templateName=contract.get("template"),
429 schemaId=contract.get("schema_id"),
430 ),
431 )
432
433
434 def overwrite_contract_schema_and_template(mso, contract, epg_schema_name, schema_cache, epg_template_name):
435 if contract.get("schema") is None:
436 contract["schema"] = epg_schema_name
437 contract["schema_id"] = schema_cache.get(epg_schema_name)
438 else:
439 schema_id = schema_cache.get(contract.get("schema"))
440 contract["schema_id"] = schema_id if schema_id else mso.lookup_schema(contract.get("schema"))
441
442 if contract.get("template") is None:
443 contract["template"] = epg_template_name
444 else:
445 contract["template"] = contract.get("template").replace(" ", "")
446
447
448 if __name__ == "__main__":
449 main()