Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2020, Anvitha Jain (@anvitha-jain) <[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_rest
16 short_description: Direct access to the Cisco MSO REST API
17 description:
18 - Enables the management of the Cisco MSO fabric through direct access to the Cisco MSO REST API.
19 - This module is not idempotent and does not report changes.
20 options:
21 method:
22 description:
23 - The HTTP method of the request.
24 - Using C(delete) is typically used for deleting objects.
25 - Using C(get) is typically used for querying objects.
26 - Using C(post) is typically used for modifying objects.
27 - Using C(put) is typically used for modifying existing objects.
28 - Using C(patch) is typically also used for modifying existing objects.
29 type: str
30 choices: [ delete, get, post, put, patch ]
31 default: get
32 aliases: [ action ]
33 path:
34 description:
35 - URI being used to execute API calls.
36 type: str
37 required: true
38 aliases: [ uri ]
39 content:
40 description:
41 - Sets the payload of the API request directly.
42 - This may be convenient to template simple requests.
43 - For anything complex use the C(template) lookup plugin (see examples).
44 type: raw
45 aliases: [ payload ]
46 extends_documentation_fragment:
47 - cisco.mso.modules
48
49 notes:
50 - Most payloads are known not to be idempotent, so be careful when constructing payloads.
51 seealso:
52 - module: cisco.mso.mso_tenant
53 author:
54 - Anvitha Jain (@anvitha-jain)
55 """
56
57 EXAMPLES = r"""
58 - name: Add schema (JSON)
59 cisco.mso.mso_rest:
60 host: mso
61 username: admin
62 password: SomeSecretPassword
63 path: /mso/api/v1/schemas
64 method: post
65 content:
66 {
67 "displayName": "{{ mso_schema | default('ansible_test') }}",
68 "templates": [{
69 "name": "Template_1",
70 "tenantId": "{{ add_tenant.jsondata.id }}",
71 "displayName": "Template_1",
72 "templateSubType": [],
73 "templateType": "stretched-template",
74 "anps": [],
75 "contracts": [],
76 "vrfs": [],
77 "bds": [],
78 "filters": [],
79 "externalEpgs": [],
80 "serviceGraphs": [],
81 "intersiteL3outs": []
82 }],
83 "sites": [],
84 "_updateVersion": 0
85 }
86
87 - name: Query schema
88 cisco.mso.mso_rest:
89 host: mso
90 username: admin
91 password: SomeSecretPassword
92 path: /mso/api/v1/schemas
93 method: get
94 register: query_result
95
96 - name: Patch schema (YAML)
97 cisco.mso.mso_rest:
98 host: mso
99 username: admin
100 password: SomeSecretPassword
101 path: "/mso/api/v1/schemas/{{ add_schema.jsondata.id }}"
102 method: patch
103 content:
104 - op: add
105 path: /templates/Template_1/anps/-
106 value:
107 name: AP2
108 displayName: AP2
109 epgs: []
110 _updateVersion: 0
111
112 - name: Add a tenant from a templated payload file from templates
113 cisco.mso.mso_rest:
114 host: mso
115 username: admin
116 password: SomeSecretPassword
117 method: post
118 path: /api/v1/tenants
119 content: "{{ lookup('template', 'mso/tenant.json.j2') }}"
120 """
121
122 RETURN = r"""
123 """
124
125 # Optional, only used for YAML validation
126 try:
127 import yaml
128
129 HAS_YAML = True
130 except Exception:
131 HAS_YAML = False
132
133 from ansible.module_utils.basic import AnsibleModule
134 from ansible_collections.cisco.mso.plugins.module_utils.mso import MSOModule, mso_argument_spec
135 from ansible.module_utils._text import to_text
136
137
138 def main():
139 argument_spec = mso_argument_spec()
140 argument_spec.update(
141 path=dict(type="str", required=True, aliases=["uri"]),
142 method=dict(type="str", default="get", choices=["delete", "get", "post", "put", "patch"], aliases=["action"]),
143 content=dict(type="raw", aliases=["payload"]),
144 )
145
146 module = AnsibleModule(
147 argument_spec=argument_spec,
148 )
149
150 content = module.params.get("content")
151 path = module.params.get("path")
152
153 mso = MSOModule(module)
154
155 # Validate content/payload
156 if content and isinstance(content, str) and HAS_YAML:
157 try:
158 # Validate YAML/JSON string
159 content = yaml.safe_load(content)
160 except Exception as e:
161 module.fail_json(msg="Failed to parse provided JSON/YAML payload: %s" % to_text(e), exception=to_text(e), payload=content)
162
163 mso.method = mso.params.get("method").upper()
164
165 # Perform request
166 if module.check_mode:
167 mso.result["jsondata"] = content
168 else:
169 mso.result["jsondata"] = mso.request(path, method=mso.method, data=content, api_version=None)
170
171 mso.result["status"] = mso.status
172
173 if mso.method != "GET":
174 mso.result["changed"] = True
175 if mso.method == "DELETE":
176 mso.result["jsondata"] = None
177
178 # Report success
179 mso.exit_json(**mso.result)
180
181
182 if __name__ == "__main__":
183 main()