Debian Codegraph @

ansible_collections/cisco/ios/plugins/modules/ios_system.py

raw
1 #!/usr/bin/python
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17 #
18 from __future__ import absolute_import, division, print_function
19
20
21 __metaclass__ = type
22
23 DOCUMENTATION = """
24 module: ios_system
25 author: Peter Sprygada (@privateip)
26 short_description: Module to manage the system attributes.
27 description:
28 - This module provides declarative management of node system attributes on Cisco IOS
29 devices. It provides an option to configure host system parameters or remove those
30 parameters from the device active configuration.
31 version_added: 1.0.0
32 extends_documentation_fragment:
33 - cisco.ios.ios
34 notes:
35 - Tested against Cisco IOSXE Version 17.3 on CML.
36 - This module works with connection C(network_cli).
37 See U(https://docs.ansible.com/ansible/latest/network/user_guide/platform_ios.html)
38 options:
39 hostname:
40 description:
41 - Configure the device hostname parameter. This option takes an ASCII string value.
42 type: str
43 domain_name:
44 description:
45 - Configure the IP domain name on the remote device to the provided value. Value
46 should be in the dotted name form and will be appended to the C(hostname) to
47 create a fully-qualified domain name.
48 type: list
49 elements: raw
50 domain_search:
51 description:
52 - Provides the list of domain suffixes to append to the hostname for the purpose
53 of doing name resolution. This argument accepts a list of names and will be
54 reconciled with the current active configuration on the running node.
55 type: list
56 elements: raw
57 lookup_source:
58 description:
59 - Provides one or more source interfaces to use for performing DNS lookups. The
60 interface provided in C(lookup_source) must be a valid interface configured
61 on the device.
62 type: str
63 lookup_enabled:
64 description:
65 - Administrative control for enabling or disabling DNS lookups. When this argument
66 is set to True, lookups are performed and when it is set to False, lookups are
67 not performed.
68 type: bool
69 name_servers:
70 description:
71 - List of DNS name servers by IP address to use to perform name resolution lookups. This
72 argument accepts either a list of DNS servers See examples.
73 type: list
74 elements: raw
75 state:
76 description:
77 - State of the configuration values in the device's current active configuration. When
78 set to I(present), the values should be configured in the device active configuration
79 and when set to I(absent) the values should not be in the device active configuration
80 default: present
81 choices:
82 - present
83 - absent
84 type: str
85 """
86
87 EXAMPLES = """
88 - name: Configure hostname and domain name
89 cisco.ios.ios_system:
90 hostname: ios01
91 domain_name: test.example.com
92 domain_search:
93 - ansible.com
94 - redhat.com
95 - cisco.com
96
97 - name: Remove configuration
98 cisco.ios.ios_system:
99 state: absent
100
101 - name: Configure DNS lookup sources
102 cisco.ios.ios_system:
103 lookup_source: MgmtEth0/0/CPU0/0
104 lookup_enabled: true
105
106 - name: Configure name servers
107 cisco.ios.ios_system:
108 name_servers:
109 - 8.8.8.8
110 - 8.8.4.4
111 """
112
113 RETURN = """
114 commands:
115 description: The list of configuration mode commands to send to the device
116 returned: always
117 type: list
118 sample:
119 - hostname ios01
120 - ip domain name test.example.com
121 """
122 import re
123
124 from ansible.module_utils.basic import AnsibleModule
125 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import (
126 ComplexList,
127 )
128
129 from ansible_collections.cisco.ios.plugins.module_utils.network.ios.ios import (
130 get_config,
131 load_config,
132 )
133
134
135 _CONFIGURED_VRFS = None
136
137
138 def has_vrf(module, vrf):
139 global _CONFIGURED_VRFS
140 if _CONFIGURED_VRFS is not None:
141 return vrf in _CONFIGURED_VRFS
142 config = get_config(module)
143 _CONFIGURED_VRFS = re.findall("vrf definition (\\S+)", config)
144 return vrf in _CONFIGURED_VRFS
145
146
147 def requires_vrf(module, vrf):
148 if not has_vrf(module, vrf):
149 module.fail_json(msg="vrf %s is not configured" % vrf)
150
151
152 def diff_list(want, have):
153 adds = [w for w in want if w not in have]
154 removes = [h for h in have if h not in want]
155 return adds, removes
156
157
158 def map_obj_to_commands(want, have, module):
159 commands = list()
160 state = module.params["state"]
161
162 def needs_update(x):
163 return want.get(x) is not None and want.get(x) != have.get(x)
164
165 if state == "absent":
166 if have["hostname"] != "Router":
167 commands.append("no hostname")
168 if have["lookup_source"]:
169 commands.append("no ip domain lookup source-interface %s" % have["lookup_source"])
170 if have["lookup_enabled"] is False:
171 commands.append("ip domain lookup")
172 vrfs = set()
173 for item in have["domain_name"]:
174 if item["vrf"] and item["vrf"] not in vrfs:
175 vrfs.add(item["vrf"])
176 commands.append("no ip domain name vrf %s" % item["vrf"])
177 elif None not in vrfs:
178 vrfs.add(None)
179 commands.append("no ip domain name")
180 vrfs = set()
181 for item in have["domain_search"]:
182 if item["vrf"] and item["vrf"] not in vrfs:
183 vrfs.add(item["vrf"])
184 commands.append("no ip domain list vrf %s" % item["vrf"])
185 elif None not in vrfs:
186 vrfs.add(None)
187 commands.append("no ip domain list")
188 vrfs = set()
189 for item in have["name_servers"]:
190 if item["vrf"] and item["vrf"] not in vrfs:
191 vrfs.add(item["vrf"])
192 commands.append("no ip name-server vrf %s" % item["vrf"])
193 elif None not in vrfs:
194 vrfs.add(None)
195 commands.append("no ip name-server")
196 elif state == "present":
197 if needs_update("hostname"):
198 commands.append("hostname %s" % want["hostname"])
199 if needs_update("lookup_source"):
200 commands.append("ip domain lookup source-interface %s" % want["lookup_source"])
201 if needs_update("lookup_enabled"):
202 cmd = "ip domain lookup"
203 if want["lookup_enabled"] is False:
204 cmd = "no %s" % cmd
205 commands.append(cmd)
206 if want["domain_name"]:
207 adds, removes = diff_list(want["domain_name"], have["domain_name"])
208 for item in removes:
209 if item["vrf"]:
210 commands.append("no ip domain name vrf %s %s" % (item["vrf"], item["name"]))
211 else:
212 commands.append("no ip domain name %s" % item["name"])
213 for item in adds:
214 if item["vrf"]:
215 requires_vrf(module, item["vrf"])
216 commands.append("ip domain name vrf %s %s" % (item["vrf"], item["name"]))
217 else:
218 commands.append("ip domain name %s" % item["name"])
219 if want["domain_search"]:
220 adds, removes = diff_list(want["domain_search"], have["domain_search"])
221 for item in removes:
222 if item["vrf"]:
223 commands.append("no ip domain list vrf %s %s" % (item["vrf"], item["name"]))
224 else:
225 commands.append("no ip domain list %s" % item["name"])
226 for item in adds:
227 if item["vrf"]:
228 requires_vrf(module, item["vrf"])
229 commands.append("ip domain list vrf %s %s" % (item["vrf"], item["name"]))
230 else:
231 commands.append("ip domain list %s" % item["name"])
232 if want["name_servers"]:
233 adds, removes = diff_list(want["name_servers"], have["name_servers"])
234 for item in removes:
235 if item["vrf"]:
236 commands.append("no ip name-server vrf %s %s" % (item["vrf"], item["server"]))
237 else:
238 commands.append("no ip name-server %s" % item["server"])
239 for item in adds:
240 if item["vrf"]:
241 requires_vrf(module, item["vrf"])
242 commands.append("ip name-server vrf %s %s" % (item["vrf"], item["server"]))
243 else:
244 commands.append("ip name-server %s" % item["server"])
245 return commands
246
247
248 def parse_hostname(config):
249 match = re.search("^hostname (\\S+)", config, re.M)
250 return match.group(1)
251
252
253 def parse_domain_name(config):
254 match = re.findall("^ip domain[- ]name (?:vrf (\\S+) )*(\\S+)", config, re.M)
255 matches = list()
256 for vrf, name in match:
257 if not vrf:
258 vrf = None
259 matches.append({"name": name, "vrf": vrf})
260 return matches
261
262
263 def parse_domain_search(config):
264 match = re.findall("^ip domain[- ]list (?:vrf (\\S+) )*(\\S+)", config, re.M)
265 matches = list()
266 for vrf, name in match:
267 if not vrf:
268 vrf = None
269 matches.append({"name": name, "vrf": vrf})
270 return matches
271
272
273 def parse_name_servers(config):
274 match = re.findall("^ip name-server (?:vrf (\\S+) )*(.*)", config, re.M)
275 matches = list()
276 for vrf, servers in match:
277 if not vrf:
278 vrf = None
279 for server in servers.split():
280 matches.append({"server": server, "vrf": vrf})
281 return matches
282
283
284 def parse_lookup_source(config):
285 match = re.search("ip domain[- ]lookup source-interface (\\S+)", config, re.M)
286 if match:
287 return match.group(1)
288
289
290 def map_config_to_obj(module):
291 config = get_config(module)
292 return {
293 "hostname": parse_hostname(config),
294 "domain_name": parse_domain_name(config),
295 "domain_search": parse_domain_search(config),
296 "lookup_source": parse_lookup_source(config),
297 "lookup_enabled": "no ip domain lookup" not in config
298 and "no ip domain-lookup" not in config,
299 "name_servers": parse_name_servers(config),
300 }
301
302
303 def map_params_to_obj(module):
304 obj = {
305 "hostname": module.params["hostname"],
306 "lookup_source": module.params["lookup_source"],
307 "lookup_enabled": module.params["lookup_enabled"],
308 }
309 domain_name = ComplexList(dict(name=dict(key=True), vrf=dict()), module)
310 domain_search = ComplexList(dict(name=dict(key=True), vrf=dict()), module)
311 name_servers = ComplexList(dict(server=dict(key=True), vrf=dict()), module)
312 for arg, cast in [
313 ("domain_name", domain_name),
314 ("domain_search", domain_search),
315 ("name_servers", name_servers),
316 ]:
317 if module.params[arg]:
318 obj[arg] = cast(module.params[arg])
319 else:
320 obj[arg] = None
321 return obj
322
323
324 def main():
325 """Main entry point for Ansible module execution"""
326 argument_spec = dict(
327 hostname=dict(),
328 domain_name=dict(type="list", elements="raw"),
329 domain_search=dict(type="list", elements="raw"),
330 name_servers=dict(type="list", elements="raw"),
331 lookup_source=dict(),
332 lookup_enabled=dict(type="bool"),
333 state=dict(choices=["present", "absent"], default="present"),
334 )
335 module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
336 result = {"changed": False}
337 warnings = list()
338 result["warnings"] = warnings
339 want = map_params_to_obj(module)
340 have = map_config_to_obj(module)
341 commands = map_obj_to_commands(want, have, module)
342 result["commands"] = commands
343 if commands:
344 if not module.check_mode:
345 load_config(module, commands)
346 result["changed"] = True
347 module.exit_json(**result)
348
349
350 if __name__ == "__main__":
351 main()