Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_hostname.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2017, F5 Networks Inc.
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 DOCUMENTATION = r'''
11 ---
12 module: bigip_hostname
13 short_description: Manage the hostname of a BIG-IP
14 description:
15 - Manage the hostname of a BIG-IP device.
16 version_added: "1.0.0"
17 options:
18 hostname:
19 description:
20 - Hostname of the BIG-IP host.
21 type: str
22 required: True
23 extends_documentation_fragment: f5networks.f5_modules.f5
24 author:
25 - Tim Rupp (@caphrim007)
26 - Matthew Lam (@mryanlam)
27 - Wojciech Wypior (@wojtek0806)
28 '''
29
30 EXAMPLES = r'''
31 - name: Set the hostname of the BIG-IP
32 bigip_hostname:
33 hostname: bigip.localhost.localdomain
34 provider:
35 user: admin
36 password: secret
37 server: lb.mydomain.com
38 delegate_to: localhost
39 '''
40
41 RETURN = r'''
42 hostname:
43 description: The new hostname of the device.
44 returned: changed
45 type: str
46 sample: big-ip01.internal
47 '''
48 from datetime import datetime
49 from ansible.module_utils.basic import AnsibleModule
50
51 from ..module_utils.bigip import F5RestClient
52 from ..module_utils.common import (
53 F5ModuleError, AnsibleF5Parameters, f5_argument_spec
54 )
55 from ..module_utils.icontrol import tmos_version
56 from ..module_utils.teem import send_teem
57
58
59 class Parameters(AnsibleF5Parameters):
60 api_attributes = ['hostname']
61 updatables = ['hostname']
62 returnables = ['hostname']
63
64 def to_return(self):
65 result = {}
66 try:
67 for returnable in self.returnables:
68 result[returnable] = getattr(self, returnable)
69 result = self._filter_params(result)
70 except Exception:
71 raise
72 return result
73
74 @property
75 def hostname(self):
76 if self._values['hostname'] is None:
77 return None
78 return str(self._values['hostname'])
79
80
81 class ApiParameters(Parameters):
82 pass
83
84
85 class ModuleParameters(Parameters):
86 pass
87
88
89 class Changes(Parameters):
90 pass
91
92
93 class UsableChanges(Changes):
94 pass
95
96
97 class ReportableChanges(Changes):
98 pass
99
100
101 class Difference(object):
102 def __init__(self, want, have=None):
103 self.want = want
104 self.have = have
105
106 def compare(self, param):
107 try:
108 result = getattr(self, param)
109 return result
110 except AttributeError:
111 return self.__default(param)
112
113 def __default(self, param):
114 attr1 = getattr(self.want, param)
115 try:
116 attr2 = getattr(self.have, param)
117 if attr1 != attr2:
118 return attr1
119 except AttributeError:
120 return attr1
121
122
123 class ModuleManager(object):
124 def __init__(self, *args, **kwargs):
125 self.module = kwargs.get('module', None)
126 self.client = F5RestClient(**self.module.params)
127 self.have = ApiParameters()
128 self.want = ModuleParameters(params=self.module.params)
129 self.changes = UsableChanges()
130
131 def _set_changed_options(self):
132 changed = {}
133 for key in Parameters.returnables:
134 if getattr(self.want, key) is not None:
135 changed[key] = getattr(self.want, key)
136 if changed:
137 self.changes = UsableChanges(params=changed)
138
139 def _update_changed_options(self):
140 diff = Difference(self.want, self.have)
141 updatables = Parameters.updatables
142 changed = dict()
143 for k in updatables:
144 change = diff.compare(k)
145 if change is None:
146 continue
147 else:
148 changed[k] = change
149 if changed:
150 self.changes = UsableChanges(params=changed)
151 return True
152 return False
153
154 def exec_module(self):
155 start = datetime.now().isoformat()
156 version = tmos_version(self.client)
157 result = dict()
158
159 changed = self.update()
160
161 reportable = ReportableChanges(params=self.changes.to_return())
162 changes = reportable.to_return()
163 result.update(**changes)
164 result.update(dict(changed=changed))
165 self._announce_deprecations(result)
166 send_teem(start, self.client, self.module, version)
167 return result
168
169 def _announce_deprecations(self, result):
170 warnings = result.pop('__warnings', [])
171 for warning in warnings:
172 self.module.deprecate(
173 msg=warning['msg'],
174 version=warning['version']
175 )
176
177 def _read_global_settings_from_device(self):
178 uri = "https://{0}:{1}/mgmt/tm/sys/global-settings/".format(
179 self.client.provider['server'],
180 self.client.provider['server_port'],
181 )
182 resp = self.client.api.get(uri)
183 try:
184 response = resp.json()
185 except ValueError as ex:
186 raise F5ModuleError(str(ex))
187
188 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
189 return response
190 raise F5ModuleError(resp.content)
191
192 def read_current_from_device(self):
193 result = self._read_global_settings_from_device()
194 uri = "https://{0}:{1}/mgmt/tm/cm/device/".format(
195 self.client.provider['server'],
196 self.client.provider['server_port'],
197 )
198 resp = self.client.api.get(uri)
199 try:
200 response = resp.json()
201 except ValueError as ex:
202 raise F5ModuleError(str(ex))
203
204 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
205 self_device = next((x['name'] for x in response['items'] if x['selfDevice'] == "true"), None)
206 result['self_device'] = self_device
207 return ApiParameters(params=result)
208 raise F5ModuleError(resp.content)
209
210 def update(self):
211 self.have = self.read_current_from_device()
212 if not self.should_update():
213 return False
214 if self.module.check_mode:
215 return True
216 self.update_on_device()
217 return True
218
219 def should_update(self):
220 result = self._update_changed_options()
221 if result:
222 return True
223 return False
224
225 def update_on_device(self):
226 params = self.want.api_params()
227 uri = "https://{0}:{1}/mgmt/tm/sys/global-settings/".format(
228 self.client.provider['server'],
229 self.client.provider['server_port'],
230 )
231 resp = self.client.api.patch(uri, json=params)
232 try:
233 response = resp.json()
234 except ValueError as ex:
235 raise F5ModuleError(str(ex))
236
237 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
238 raise F5ModuleError(resp.content)
239
240 if self.have.self_device:
241 uri = "https://{0}:{1}/mgmt/tm/cm/device".format(
242 self.client.provider['server'],
243 self.client.provider['server_port'],
244 )
245 args = dict(
246 command='mv',
247 name=self.have.self_device,
248 target=self.want.hostname
249 )
250 resp = self.client.api.post(uri, json=args)
251
252 try:
253 response = resp.json()
254 except ValueError as ex:
255 raise F5ModuleError(str(ex))
256
257 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
258 raise F5ModuleError(resp.content)
259
260 return True
261
262
263 class ArgumentSpec(object):
264 def __init__(self):
265 self.supports_check_mode = True
266 argument_spec = dict(
267 hostname=dict(
268 required=True
269 )
270 )
271 self.argument_spec = {}
272 self.argument_spec.update(f5_argument_spec)
273 self.argument_spec.update(argument_spec)
274
275
276 def main():
277 spec = ArgumentSpec()
278
279 module = AnsibleModule(
280 argument_spec=spec.argument_spec,
281 supports_check_mode=spec.supports_check_mode
282 )
283
284 try:
285 mm = ModuleManager(module=module)
286 results = mm.exec_module()
287 module.exit_json(**results)
288 except F5ModuleError as ex:
289 module.fail_json(msg=str(ex))
290
291
292 if __name__ == '__main__':
293 main()