Debian Codegraph @

ansible_collections/cisco/meraki/plugins/modules/meraki_config_template.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, Kevin Breit (@kbreit) <[email protected]>
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 ANSIBLE_METADATA = {
11 'metadata_version': '1.1',
12 "status": ['deprecated'],
13 'supported_by': 'community'
14 }
15
16 DOCUMENTATION = r'''
17 ---
18 module: meraki_config_template
19 short_description: Manage configuration templates in the Meraki cloud
20 version_added: "1.0.0"
21 description:
22 - Allows for querying, deleting, binding, and unbinding of configuration templates.
23 notes:
24 - Module is not idempotent as the Meraki API is limited in what information it provides about configuration templates.
25 - Meraki's API does not support creating new configuration templates.
26 - To use the configuration template, simply pass its ID via C(net_id) parameters in Meraki modules.
27 deprecated:
28 removed_in: '3.0.0'
29 why: Updated modules released with increased functionality
30 alternative: cisco.meraki.organizations_config_templates
31 options:
32 state:
33 description:
34 - Specifies whether configuration template information should be queried, modified, or deleted.
35 choices: ['absent', 'query', 'present']
36 default: query
37 type: str
38 org_name:
39 description:
40 - Name of organization containing the configuration template.
41 type: str
42 org_id:
43 description:
44 - ID of organization associated to a configuration template.
45 type: str
46 config_template:
47 description:
48 - Name of the configuration template within an organization to manipulate.
49 aliases: ['name']
50 type: str
51 net_name:
52 description:
53 - Name of the network to bind or unbind configuration template to.
54 type: str
55 net_id:
56 description:
57 - ID of the network to bind or unbind configuration template to.
58 type: str
59 auto_bind:
60 description:
61 - Optional boolean indicating whether the network's switches should automatically bind to profiles of the same model.
62 - This option only affects switch networks and switch templates.
63 - Auto-bind is not valid unless the switch template has at least one profile and has at most one profile per switch model.
64 type: bool
65
66 author:
67 - Kevin Breit (@kbreit)
68 extends_documentation_fragment: cisco.meraki.meraki
69 '''
70
71 EXAMPLES = r'''
72 - name: Query configuration templates
73 meraki_config_template:
74 auth_key: abc12345
75 org_name: YourOrg
76 state: query
77 delegate_to: localhost
78
79 - name: Bind a template from a network
80 meraki_config_template:
81 auth_key: abc123
82 state: present
83 org_name: YourOrg
84 net_name: YourNet
85 config_template: DevConfigTemplate
86 delegate_to: localhost
87
88 - name: Unbind a template from a network
89 meraki_config_template:
90 auth_key: abc123
91 state: absent
92 org_name: YourOrg
93 net_name: YourNet
94 config_template: DevConfigTemplate
95 delegate_to: localhost
96
97 - name: Delete a configuration template
98 meraki_config_template:
99 auth_key: abc123
100 state: absent
101 org_name: YourOrg
102 config_template: DevConfigTemplate
103 delegate_to: localhost
104 '''
105
106 RETURN = r'''
107 data:
108 description: Information about queried object.
109 returned: success
110 type: complex
111 contains:
112 id:
113 description: Unique identification number of organization.
114 returned: success
115 type: int
116 sample: L_2930418
117 name:
118 description: Name of configuration template.
119 returned: success
120 type: str
121 sample: YourTemplate
122 product_types:
123 description: List of products which can exist in the network.
124 returned: success
125 type: list
126 sample: [ "appliance", "switch" ]
127 time_zone:
128 description: Timezone applied to each associated network.
129 returned: success
130 type: str
131 sample: "America/Chicago"
132
133 '''
134
135 from ansible.module_utils.basic import AnsibleModule, json
136 from ansible_collections.cisco.meraki.plugins.module_utils.network.meraki.meraki import MerakiModule, meraki_argument_spec
137
138
139 def get_config_templates(meraki, org_id):
140 path = meraki.construct_path('get_all', org_id=org_id)
141 response = meraki.request(path, 'GET')
142 if meraki.status != 200:
143 meraki.fail_json(msg='Unable to get configuration templates')
144 return response
145
146
147 def get_template_id(meraki, name, data):
148 for template in data:
149 if name == template['name']:
150 return template['id']
151 meraki.fail_json(msg='No configuration template named {0} found'.format(name))
152
153
154 def is_template_valid(meraki, nets, template_id):
155 for net in nets:
156 if net['id'] == template_id:
157 return True
158 return False
159
160
161 def is_network_bound(meraki, nets, net_id, template_id):
162 for net in nets:
163 if net['id'] == net_id:
164 try:
165 if net['configTemplateId'] == template_id:
166 return True
167 except KeyError:
168 pass
169 return False
170
171
172 def delete_template(meraki, org_id, name, data):
173 template_id = get_template_id(meraki, name, data)
174 path = meraki.construct_path('delete', org_id=org_id)
175 path = path + '/' + template_id
176 response = meraki.request(path, 'DELETE')
177 if meraki.status != 204:
178 meraki.fail_json(msg='Unable to remove configuration template')
179 return response
180
181
182 def bind(meraki, net_id, template_id):
183 path = meraki.construct_path('bind', net_id=net_id)
184 payload = {'configTemplateId': template_id}
185 if meraki.params['auto_bind']:
186 payload['autoBind'] = meraki.params['auto_bind']
187 r = meraki.request(path, method='POST', payload=json.dumps(payload))
188 return r
189
190
191 def unbind(meraki, net_id):
192 path = meraki.construct_path('unbind', net_id=net_id)
193 meraki.result['changed'] = True
194 return meraki.request(path, method='POST')
195
196
197 def main():
198
199 # define the available arguments/parameters that a user can pass to
200 # the module
201 argument_spec = meraki_argument_spec()
202 argument_spec.update(state=dict(type='str', choices=['absent', 'query', 'present'], default='query'),
203 config_template=dict(type='str', aliases=['name']),
204 net_name=dict(type='str'),
205 net_id=dict(type='str'),
206 # config_template_id=dict(type='str', aliases=['id']),
207 auto_bind=dict(type='bool'),
208 )
209
210 # the AnsibleModule object will be our abstraction working with Ansible
211 # this includes instantiation, a couple of common attr would be the
212 # args/params passed to the execution, as well as if the module
213 # supports check mode
214 module = AnsibleModule(argument_spec=argument_spec,
215 supports_check_mode=True,
216 )
217 meraki = MerakiModule(module, function='config_template')
218 meraki.params['follow_redirects'] = 'all'
219
220 query_urls = {'config_template': '/organizations/{org_id}/configTemplates'}
221 delete_urls = {'config_template': '/organizations/{org_id}/configTemplates'}
222 bind_urls = {'config_template': '/networks/{net_id}/bind'}
223 unbind_urls = {'config_template': '/networks/{net_id}/unbind'}
224
225 meraki.url_catalog['get_all'].update(query_urls)
226 meraki.url_catalog['delete'] = delete_urls
227 meraki.url_catalog['bind'] = bind_urls
228 meraki.url_catalog['unbind'] = unbind_urls
229
230 # if the user is working with this module in only check mode we do not
231 # want to make any changes to the environment, just return the current
232 # state with no modifications
233
234 # execute checks for argument completeness
235
236 # manipulate or modify the state as needed (this is going to be the
237 # part where your module will do what it needs to do)
238 org_id = meraki.params['org_id']
239 if meraki.params['org_name']:
240 org_id = meraki.get_org_id(meraki.params['org_name'])
241 net_id = meraki.params['net_id']
242 nets = None
243 if net_id is None:
244 if meraki.params['net_name'] is not None:
245 nets = meraki.get_nets(org_id=org_id)
246 net_id = meraki.get_net_id(net_name=meraki.params['net_name'], data=nets)
247 else:
248 nets = meraki.get_nets(org_id=org_id)
249
250 if meraki.params['state'] == 'query':
251 meraki.result['data'] = get_config_templates(meraki, org_id)
252 elif meraki.params['state'] == 'present':
253 template_id = get_template_id(meraki,
254 meraki.params['config_template'],
255 get_config_templates(meraki, org_id))
256 if nets is None:
257 nets = meraki.get_nets(org_id=org_id)
258 if is_network_bound(meraki, nets, net_id, template_id) is False: # Bind template
259 if meraki.check_mode is True:
260 meraki.result['data'] = {}
261 meraki.result['changed'] = True
262 meraki.exit_json(**meraki.result)
263 template_bind = bind(meraki,
264 net_id,
265 template_id)
266 if meraki.status != 200:
267 meraki.fail_json(msg='Unable to bind configuration template to network')
268 meraki.result['changed'] = True
269 meraki.result['data'] = template_bind
270 else: # Network is already bound, being explicit
271 if meraki.check_mode is True: # Include to be explicit
272 meraki.result['data'] = {}
273 meraki.result['changed'] = False
274 meraki.exit_json(**meraki.result)
275 meraki.result['data'] = {}
276 meraki.result['changed'] = False
277 meraki.exit_json(**meraki.result)
278 elif meraki.params['state'] == 'absent':
279 template_id = get_template_id(meraki,
280 meraki.params['config_template'],
281 get_config_templates(meraki, org_id))
282 if not meraki.params['net_name'] and not meraki.params['net_id']: # Delete template
283 if is_template_valid(meraki, nets, template_id) is True:
284 if meraki.check_mode is True:
285 meraki.result['data'] = {}
286 meraki.result['changed'] = True
287 meraki.exit_json(**meraki.result)
288 meraki.result['data'] = delete_template(meraki,
289 org_id,
290 meraki.params['config_template'],
291 get_config_templates(meraki, org_id))
292 if meraki.status == 204:
293 meraki.result['data'] = {}
294 meraki.result['changed'] = True
295 else:
296 meraki.fail_json(msg="No template named {0} found.".format(meraki.params['config_template']))
297 else: # Unbind template
298 if nets is None:
299 nets = meraki.get_nets(org_id=org_id)
300 if meraki.check_mode is True:
301 meraki.result['data'] = {}
302 if is_template_valid(meraki, nets, template_id) is True:
303 meraki.result['changed'] = True
304 else:
305 meraki.result['changed'] = False
306 meraki.exit_json(**meraki.result)
307 template_id = get_template_id(meraki,
308 meraki.params['config_template'],
309 get_config_templates(meraki, org_id))
310 if is_network_bound(meraki, nets, net_id, template_id) is True:
311 if meraki.check_mode is True:
312 meraki.result['data'] = {}
313 meraki.result['changed'] = True
314 meraki.exit_json(**meraki.result)
315 config_unbind = unbind(meraki,
316 net_id)
317 if meraki.status != 200:
318 meraki.fail_json(msg='Unable to unbind configuration template from network')
319 meraki.result['changed'] = True
320 meraki.result['data'] = config_unbind
321 else: # No network is bound, nothing to do
322 if meraki.check_mode is True: # Include to be explicit
323 meraki.result['data'] = {}
324 meraki.result['changed'] = False
325 meraki.exit_json(**meraki.result)
326 meraki.result['data'] = {}
327 meraki.result['changed'] = False
328
329 # in the event of a successful module execution, you will want to
330 # simple AnsibleModule.exit_json(), passing the key/value results
331 meraki.exit_json(**meraki.result)
332
333
334 if __name__ == '__main__':
335 main()