forked from caphrim007/f5-ansible
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiworkflow_iapp_template.py
383 lines (334 loc) · 11.6 KB
/
iworkflow_iapp_template.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2017 F5 Networks Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {
'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.0'
}
DOCUMENTATION = '''
---
module: iworkflow_iapp_template
short_description: Manages iApp templates
description:
- Manages TCL iApp services on a BIG-IP.
version_added: "2.4"
options:
name:
description:
- The name of the iApp template that you want to create on the
device. This is usually included in the template itself. This
option is typically used in cases where the template no longer
exists on disk (to reference) and the C(state) is C(absent).
template_content:
description:
- The contents of a valid iApp template in a tmpl file. This iApp
Template should be versioned and tested for compatibility with
iWorkflow Tenant Services and a BIG-IP version of 11.5.3.2 or later.
This option is only required when creating new template in iWorkflow.
When you are deleting iApp templates, you will need to specify either
one of C(name) or C(template_content).
device:
description:
- Managed BIG-IP that you want to get template JSON from. This option
is only required when C(state) is C(present).
state:
description:
- When C(present), ensures that the iApp service is created and running.
When C(absent), ensures that the iApp service has been removed.
default: present
choices:
- present
- absent
notes:
- Requires the f5-sdk Python package on the host. This is as easy as pip
install f5-sdk.
extends_documentation_fragment: f5
requirements:
- f5-sdk >= 2.3.0
- iWorkflow >= 2.1.0
author:
- Tim Rupp (@caphrim007)
'''
EXAMPLES = '''
- name: Add AppSvcs Integration to iWorkflow
iworkflow_iapp_template:
device: "my-bigip-1"
template_content: "{{ lookup('file', 'appsvcs_integration_v2.0_001.tmpl') }}"
password: "secret"
server: "lb.mydomain.com"
state: "present"
user: "admin"
delegate_to: localhost
- name: Remove AppSvcs Integration from iWorkflow
iworkflow_iapp_template:
name: "appsvcs_integration_v2.0_001"
password: "secret"
server: "lb.mydomain.com"
state: "present"
user: "admin"
delegate_to: localhost
'''
RETURN = '''
'''
import re
import time
from ansible.module_utils.f5_utils import (
AnsibleF5Client,
AnsibleF5Parameters,
defaultdict,
F5ModuleError,
HAS_F5SDK,
iControlUnexpectedHTTPError,
iteritems,
)
from f5.utils.iapp_parser import (
IappParser,
NonextantTemplateNameException
)
class Parameters(AnsibleF5Parameters):
api_map = {
'templateContent': 'template_content'
}
api_attributes = [
'templateContent', 'deviceForJSONTransformation'
]
returnables = []
updatables = [
'template_content',
]
def __init__(self, params=None):
self._values = defaultdict(lambda: None)
if params:
self.update(params=params)
def update(self, params=None):
if params:
for k, v in iteritems(params):
if self.api_map is not None and k in self.api_map:
map_key = self.api_map[k]
else:
map_key = k
# Handle weird API parameters like `dns.proxy.__iter__` by
# using a map provided by the module developer
class_attr = getattr(type(self), map_key, None)
if isinstance(class_attr, property):
# There is a mapped value for the api_map key
if class_attr.fset is None:
# If the mapped value does not have an associated setter
self._values[map_key] = v
else:
# The mapped value has a setter
setattr(self, map_key, v)
else:
# If the mapped value is not a @property
self._values[map_key] = v
def to_return(self):
result = {}
for returnable in self.returnables:
result[returnable] = getattr(self, returnable)
result = self._filter_params(result)
return result
def api_params(self):
result = {}
for api_attribute in self.api_attributes:
if self.api_map is not None and api_attribute in self.api_map:
result[api_attribute] = getattr(self, self.api_map[api_attribute])
else:
result[api_attribute] = getattr(self, api_attribute)
result = self._filter_params(result)
return result
def _squash_template_name_prefix(self):
name = self._get_template_name()
pattern = r'sys\s+application\s+template\s+/Common/{0}'.format(name)
replace = 'sys application template {0}'.format(name)
self._values['template_content'] = re.sub(pattern, replace, self._values['template_content'])
def _get_template_name(self):
parser = IappParser(self._values['template_content'])
tmpl = parser.parse_template()
return tmpl['name']
def _get_device_collection(self):
dg = self.client.api.shared.resolver.device_groups
result = dg.cm_cloud_managed_devices.devices_s.get_collection()
return result
def _get_device_selflink(self, device, collection):
for resource in collection:
if str(resource.product) != "BIG-IP":
continue
# The supplied device can be in several formats.
if str(resource.hostname) == device:
return str(resource.selfLink)
elif str(resource.address) == device:
return str(resource.selfLink)
elif str(resource.managementAddress) == device:
return str(resource.selfLink)
raise F5ModuleError(
"Device {0} was not found".format(device)
)
@property
def name(self):
if self._values['name']:
return self._values['name']
if self._values['template_content']:
try:
self._squash_template_name_prefix()
name = self._get_template_name()
self._values['name'] = name
return name
except NonextantTemplateNameException:
return F5ModuleError(
"No template name was found in the template"
)
return None
@property
def device(self):
if isinstance(self._values['device'], basestring):
collection = self._get_device_collection()
result = self._get_device_selflink(str(self._values['device']), collection)
return result
elif 'deviceForJSONTransformation' in self._values['device']:
# Case for the REST API
item = self._values['device']['deviceForJSONTransformation']
return str(item['deviceReference']['link'])
@device.setter
def device(self, value):
self._values['device'] = value
@property
def deviceForJSONTransformation(self):
result = dict(
link=self.device
)
return result
class ModuleManager(object):
def __init__(self, client):
self.client = client
self.have = None
self.want = Parameters()
self.want.client = self.client
self.want.update(self.client.module.params)
self.changes = Parameters()
self.changes.client = self.client
def _set_changed_options(self):
changed = {}
for key in Parameters.returnables:
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = Parameters()
self.changes.client = self.client
self.changes.update(changed)
def _update_changed_options(self):
changed = {}
for key in Parameters.updatables:
if getattr(self.want, key) is not None:
attr1 = getattr(self.want, key)
attr2 = getattr(self.have, key)
if attr1 != attr2:
changed[key] = attr1
if changed:
self.changes = Parameters()
self.changes.client = self.client
self.changes.update(changed)
return True
return False
def exec_module(self):
changed = False
result = dict()
state = self.want.state
try:
if state == "present":
changed = self.present()
elif state == "absent":
changed = self.absent()
except iControlUnexpectedHTTPError as e:
raise F5ModuleError(str(e))
result.update(**self.changes.to_return())
result.update(dict(changed=changed))
return result
def exists(self):
return self.client.api.cm.cloud.templates.iapps.iapp.exists(
name=self.want.name
)
def present(self):
if self.exists():
return False
else:
return self.create()
def create(self):
if self.client.check_mode:
return True
if self.want.template_content is None:
raise F5ModuleError(
""
)
self.create_on_device()
return True
def create_on_device(self):
params = self.want.api_params()
params['name'] = self.want.name
self.client.api.cm.cloud.templates.iapps.iapp.create(
**params
)
time.sleep(5)
def absent(self):
if self.exists():
return self.remove()
return False
def remove(self):
if self.client.check_mode:
return True
self.remove_from_device()
if self.exists():
raise F5ModuleError("Failed to delete the iApp template")
return True
def remove_from_device(self):
resource = self.client.api.cm.cloud.templates.iapps.iapp.load(
name=self.want.name
)
if resource:
resource.delete()
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
self.argument_spec = dict(
name=dict(),
template_content=dict(required=False),
device=dict(),
state=dict(
default='present',
choices=['absent', 'present']
)
)
self.f5_product_name = 'iworkflow'
def main():
if not HAS_F5SDK:
raise F5ModuleError("The python f5-sdk module is required")
spec = ArgumentSpec()
client = AnsibleF5Client(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
f5_product_name=spec.f5_product_name
)
try:
mm = ModuleManager(client)
results = mm.exec_module()
client.module.exit_json(**results)
except F5ModuleError as e:
client.module.fail_json(msg=str(e))
if __name__ == '__main__':
main()