Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2022, Shreyas Srish (@shrsr) <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 ANSIBLE_METADATA = {"metadata_version": "1.1", "status": ["preview"], "supported_by": "community"}
12
13 DOCUMENTATION = r"""
14 ---
15 module: mso_schema_site_service_graph
16 short_description: Manage Service Graph in schema sites
17 description:
18 - Manage Service Graph in schema sites on Cisco ACI Multi-Site.
19 - This module is only supported in MSO/NDO version 3.3 and above.
20 author:
21 - Shreyas Srish (@shrsr)
22 options:
23 schema:
24 description:
25 - The name of the schema.
26 type: str
27 required: true
28 template:
29 description:
30 - The name of the template.
31 type: str
32 required: true
33 site:
34 description:
35 - The name of the site.
36 type: str
37 required: true
38 tenant:
39 description:
40 - The name of the tenant.
41 type: str
42 service_graph:
43 description:
44 - The name of the Service Graph to manage.
45 type: str
46 aliases: [ name ]
47 devices:
48 description:
49 - A list of devices to be associated with the Service Graph.
50 type: list
51 elements: dict
52 suboptions:
53 device_name:
54 description:
55 - The name of the device
56 required: true
57 type: str
58 aliases: [ name ]
59 provider_interface:
60 description:
61 - The name of the provider interface for the Azure CNC L4-L7 device.
62 type: str
63 provider_connector_type:
64 description:
65 - The provider connector type for the Azure CNC site service graph.
66 - Defaults to C(none) when unset during creation.
67 type: str
68 choices: [ none, redirect, source_nat, destination_nat, source_and_destination_nat ]
69 consumer_interface:
70 description:
71 - The name of the consumer interface for the Azure CNC L4-L7 device.
72 type: str
73 consumer_connector_type:
74 description:
75 - The consumer connector type for the Azure CNC site service graph.
76 - Defaults to C(none) when unset during creation.
77 type: str
78 choices: [ none, redirect ]
79 state:
80 description:
81 - Use C(present) or C(absent) for adding or removing.
82 - Use C(query) for listing an object or multiple objects.
83 type: str
84 choices: [ absent, present, query ]
85 default: present
86 extends_documentation_fragment: cisco.mso.modules
87 """
88
89 EXAMPLES = r"""
90 - name: Add a Service Graph
91 cisco.mso.mso_schema_site_service_graph_node:
92 host: mso_host
93 username: admin
94 password: SomeSecretPassword
95 schema: Schema1
96 template: Template1
97 service_graph: SG1
98 site: site1
99 tenant: tenant1
100 devices:
101 - name: ansible_test_firewall
102 - name: ansible_test_adc
103 - name: ansible_test_other
104 state: present
105
106 - name: Add a Site service graph for the Azure cloud CNC
107 cisco.mso.mso_schema_site_service_graph:
108 host: mso_host
109 username: admin
110 password: SomeSecretPassword
111 schema: Schema1
112 template: Template1
113 service_graph: SG1
114 site: site1
115 tenant: tenant1
116 devices:
117 - name: ans_tnt_firewall1
118 provider_connector_type: source_nat
119 provider_interface: TP_FW_Inf1
120 consumer_connector_type: redirect
121 consumer_interface: TP_FW_Inf1
122 - name: ans_tnt_app_lb
123 - name: ans_tnt_other
124 provider_connector_type: destination_nat
125 consumer_connector_type: redirect
126 state: present
127
128 - name: Remove a Service Graph
129 cisco.mso.mso_schema_site_service_graph_node:
130 host: mso_host
131 username: admin
132 password: SomeSecretPassword
133 schema: Schema1
134 template: Template1
135 service_graph: SG1
136 site: site1
137 state: absent
138
139 - name: Query a specific Service Graph
140 cisco.mso.mso_schema_site_service_graph_node:
141 host: mso_host
142 username: admin
143 password: SomeSecretPassword
144 schema: Schema1
145 template: Template1
146 service_graph: SG1
147 site: site1
148 state: query
149 register: query_result
150
151 - name: Query all Service Graphs
152 cisco.mso.mso_schema_site_service_graph_node:
153 host: mso_host
154 username: admin
155 password: SomeSecretPassword
156 schema: Schema1
157 template: Template1
158 site: site1
159 state: query
160 register: query_result
161 """
162
163 RETURN = r"""
164 """
165
166
167 from ansible.module_utils.basic import AnsibleModule
168 from ansible_collections.cisco.mso.plugins.module_utils.mso import (
169 MSOModule,
170 mso_argument_spec,
171 mso_service_graph_node_device_spec,
172 service_node_ref_str_to_dict,
173 )
174 from ansible_collections.cisco.mso.plugins.module_utils.constants import AZURE_L4L7_CONNECTOR_TYPE_MAP
175
176
177 def main():
178 argument_spec = mso_argument_spec()
179 argument_spec.update(
180 schema=dict(type="str", required=True),
181 template=dict(type="str", required=True),
182 service_graph=dict(type="str", aliases=["name"]),
183 tenant=dict(type="str"),
184 site=dict(type="str", required=True),
185 devices=dict(type="list", elements="dict", options=mso_service_graph_node_device_spec()),
186 state=dict(type="str", default="present", choices=["absent", "present", "query"]),
187 )
188
189 module = AnsibleModule(
190 argument_spec=argument_spec,
191 supports_check_mode=True,
192 required_if=[
193 ["state", "absent", ["service_graph"]],
194 ["state", "present", ["service_graph", "devices"]],
195 ],
196 )
197
198 schema = module.params.get("schema")
199 template = module.params.get("template").replace(" ", "")
200 service_graph = module.params.get("service_graph")
201 devices = module.params.get("devices")
202 site = module.params.get("site")
203 tenant = module.params.get("tenant")
204 state = module.params.get("state")
205
206 mso = MSOModule(module)
207
208 # Get schema
209 schema_id, schema_path, schema_obj = mso.query_schema(schema)
210
211 # Get template
212 templates = schema_obj.get("templates")
213 template_names = [t.get("name") for t in templates]
214 if template not in template_names:
215 mso.fail_json(
216 msg="Provided template '{template}' does not exist. Existing templates: {templates}".format(template=template, templates=", ".join(template_names))
217 )
218 template_idx = template_names.index(template)
219
220 # Get site
221 site_id = mso.lookup_site(site)
222
223 # Get site_idx
224 if not schema_obj.get("sites"):
225 mso.fail_json(msg="No site associated with template '{0}'. Associate the site with the template using mso_schema_site.".format(template))
226 sites = [(s.get("siteId"), s.get("templateName")) for s in schema_obj.get("sites")]
227 if (site_id, template) not in sites:
228 mso.fail_json(msg="Provided site-template association '{0}-{1}' does not exist.".format(site, template))
229
230 # Schema-access uses indexes
231 site_idx = sites.index((site_id, template))
232 # Path-based access uses site_id-template
233 site_template = "{0}-{1}".format(site_id, template)
234
235 mso.existing = {}
236 service_graph_idx = None
237
238 # Get Service Graph
239 service_graph_ref = mso.service_graph_ref(schema_id=schema_id, template=template, service_graph=service_graph)
240 service_graph_refs = [f.get("serviceGraphRef") for f in schema_obj.get("sites")[site_idx]["serviceGraphs"]]
241 if service_graph is not None and service_graph_ref in service_graph_refs:
242 service_graph_idx = service_graph_refs.index(service_graph_ref)
243 mso.existing = schema_obj.get("sites")[site_idx]["serviceGraphs"][service_graph_idx]
244
245 if state == "query":
246 if service_graph is None:
247 mso.existing = schema_obj.get("sites")[site_idx]["serviceGraphs"]
248 elif service_graph is not None and service_graph_idx is None:
249 mso.fail_json(msg="Service Graph '{service_graph}' not found".format(service_graph=service_graph))
250 mso.exit_json()
251
252 service_graphs_path = "/sites/{0}/serviceGraphs/-".format(site_template)
253 service_graph_path = "/sites/{0}/serviceGraphs/{1}".format(site_template, service_graph)
254 ops = []
255
256 mso.previous = mso.existing
257 if mso.previous.get("serviceNodes") is not None and len(mso.previous.get("serviceNodes")) > 0:
258 for node in mso.previous.get("serviceNodes"):
259 node["serviceNodeRef"] = service_node_ref_str_to_dict(node.get("serviceNodeRef"))
260
261 devices_payload = []
262
263 if state == "absent":
264 if mso.existing:
265 mso.sent = mso.existing = {}
266 ops.append(dict(op="remove", path=service_graph_path))
267
268 elif state == "present":
269 service_graphs = templates[template_idx]["serviceGraphs"]
270 service_node_types_from_template = []
271 for graph in service_graphs:
272 if graph.get("name") == service_graph:
273 service_node_types_from_template = graph["serviceNodes"]
274 break
275
276 user_number_devices = len(devices)
277 number_of_nodes_in_template = len(service_node_types_from_template)
278 if user_number_devices != number_of_nodes_in_template:
279 mso.fail_json(
280 msg="Service Graph '{0}' has '{1}' service node type(s) but '{2}' service node(s) were given for the service graph".format(
281 service_graph, number_of_nodes_in_template, user_number_devices
282 )
283 )
284
285 if devices is not None:
286 query_device_data = mso.lookup_service_node_device(site_id, tenant, device_name=None, service_node_type=None)
287 for index, device in enumerate(devices):
288 if query_device_data:
289 for device_data in query_device_data:
290 if device.get("device_name") == device_data.get("dn").split("/")[-1].split("-")[-1]:
291 device_payload = dict()
292 device_payload["device"] = dict(
293 dn=device_data.get("dn"),
294 funcType=device_data.get("funcType"),
295 )
296 device_payload["serviceNodeRef"] = dict(
297 serviceNodeName="node{0}".format(index + 1),
298 serviceGraphName=service_graph,
299 templateName=template,
300 schemaId=schema_id,
301 )
302
303 if mso.cloud_provider_type == "azure":
304 consumer_interface = device.get("consumer_interface")
305 provider_interface = device.get("provider_interface")
306 provider_connector_type = device.get("provider_connector_type")
307 consumer_connector_type = device.get("consumer_connector_type")
308
309 if (
310 device_data.get("deviceVendorType") == "NATIVELB"
311 and device_data.get("devType") == "application"
312 and (
313 consumer_interface is not None
314 or provider_interface is not None
315 or provider_connector_type is not None
316 or consumer_connector_type is not None
317 )
318 ):
319 # Application Load Balancer - Consumer Interface, Consumer Connector Type,
320 # Provider Interface, Provider Connector Type - not supported
321 mso.fail_json(
322 msg="Unsupported attributes: provider_connector_type, provider_interface, "
323 + "consumer_connector_type, consumer_interface should be 'None' for the "
324 + "Application Load Balancer device."
325 )
326 elif (
327 device_data.get("deviceVendorType") == "NATIVELB"
328 and device_data.get("devType") == "network"
329 and (consumer_interface is not None or provider_interface is not None)
330 ):
331 # Network Load Balancer - Consumer Interface, Provider Interface - not supported
332 mso.fail_json(
333 msg="Unsupported attributes: provider_interface and consumer_interface should "
334 + "be 'None' for the Network Load Balancer device."
335 )
336 elif (
337 device_data.get("deviceVendorType") == "ADC"
338 and device_data.get("devType") == "CLOUD"
339 and (provider_connector_type is not None or consumer_connector_type is not None)
340 ):
341 # Third-Party Load Balancer - Consumer Connector Type,
342 # Provider Connector Type - not supported
343 mso.fail_json(
344 msg="Unsupported attributes: provider_connector_type and "
345 + "consumer_connector_type should be 'None' for the "
346 + "Third-Party Load Balancer."
347 )
348
349 # (FW) Third-Party Firewall - Consumer Interface, Consumer Connector Type,
350 # Provider Interface, Provider Connector Type - supported
351 device_payload["consumerInterface"] = consumer_interface
352 device_payload["providerInterface"] = provider_interface
353 device_payload["providerConnectorType"] = AZURE_L4L7_CONNECTOR_TYPE_MAP.get(provider_connector_type)
354 device_payload["consumerConnectorType"] = AZURE_L4L7_CONNECTOR_TYPE_MAP.get(consumer_connector_type)
355
356 devices_payload.append(device_payload)
357
358 payload = dict(
359 serviceGraphRef=dict(
360 serviceGraphName=service_graph,
361 templateName=template,
362 schemaId=schema_id,
363 ),
364 serviceNodes=devices_payload,
365 )
366
367 mso.sanitize(payload, collate=True)
368
369 if not mso.existing:
370 # The site service graph reference will be added automatically when the site is associated with the template
371 # So the add(create) part will not be used for the NDO v4.2
372 ops.append(dict(op="add", path=service_graphs_path, value=payload))
373 else:
374 ops.append(dict(op="replace", path=service_graph_path, value=mso.sent))
375
376 mso.existing = mso.proposed
377
378 if not module.check_mode:
379 mso.request(schema_path, method="PATCH", data=ops)
380
381 mso.exit_json()
382
383
384 if __name__ == "__main__":
385 main()