Debian Codegraph @

ansible_collections/cisco/iosxr/plugins/modules/iosxr_banner.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2017, Ansible by Red Hat, 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
9
10 __metaclass__ = type
11
12
13 DOCUMENTATION = """
14 module: iosxr_banner
15 author:
16 - Trishna Guha (@trishnaguha)
17 - Kedar Kekan (@kedarX)
18 short_description: Module to configure multiline banners.
19 description:
20 - This module will configure both exec and motd banners on remote device running Cisco
21 IOS XR. It allows playbooks to add or remove banner text from the running configuration.
22 version_added: 1.0.0
23 requirements:
24 - ncclient >= 0.5.3 when using netconf
25 - lxml >= 4.1.1 when using netconf
26 extends_documentation_fragment:
27 - cisco.iosxr.iosxr
28 notes:
29 - This module works with connection C(network_cli) and C(netconf). See L(the IOS-XR
30 Platform Options,../network/user_guide/platform_iosxr.html).
31 options:
32 banner:
33 description:
34 - Specifies the type of banner to configure on remote device.
35 required: true
36 type: str
37 choices:
38 - login
39 - motd
40 text:
41 description:
42 - Banner text to be configured. Accepts multi line string, without empty lines.
43 When using a multi line string, the first and last characters must be the
44 start and end delimiters for the banner
45 Requires I(state=present).
46 type: str
47 state:
48 description:
49 - Existential state of the configuration on the device.
50 default: present
51 type: str
52 choices:
53 - present
54 - absent
55 """
56
57 EXAMPLES = """
58 - name: configure the login banner
59 cisco.iosxr.iosxr_banner:
60 banner: login
61 text: |
62 @this is my login banner
63 that contains a multiline
64 string@
65 state: present
66 - name: remove the motd banner
67 cisco.iosxr.iosxr_banner:
68 banner: motd
69 state: absent
70 - name: Configure banner from file
71 cisco.iosxr.iosxr_banner:
72 banner: motd
73 text: '{{ lookup(''file'', ''./config_partial/raw_banner.cfg'') }}'
74 state: present
75 """
76
77 RETURN = """
78 commands:
79 description: The list of configuration mode commands sent to device with transport C(cli)
80 returned: always (empty list when no commands to send)
81 type: list
82 sample:
83 - banner login
84 - "@this is my login banner"
85 - that contains a multiline
86 - string@
87
88 xml:
89 description: NetConf rpc xml sent to device with transport C(netconf)
90 returned: always (empty list when no xml rpc to send)
91 type: list
92 sample:
93 - '<config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">
94 <banners xmlns="http://cisco.com/ns/yang/Cisco-IOS-XR-infra-infra-cfg">
95 <banner xc:operation="merge">
96 <banner-name>motd</banner-name>
97 <banner-text>Ansible banner example</banner-text>
98 </banner>
99 </banners>
100 </config>'
101 """
102
103 import collections
104 import re
105
106 from ansible.module_utils.basic import AnsibleModule
107
108 from ansible_collections.cisco.iosxr.plugins.module_utils.network.iosxr.iosxr import (
109 build_xml,
110 etree_find,
111 get_config,
112 is_cliconf,
113 is_netconf,
114 load_config,
115 )
116
117
118 class ConfigBase(object):
119 def __init__(self, module):
120 self._module = module
121 self._result = {"changed": False, "warnings": []}
122 self._want = {}
123 self._have = {}
124
125 def map_params_to_obj(self):
126 text = self._module.params["text"]
127 if text:
128 text = "{0}".format(str(text).strip())
129 self._want.update(
130 {
131 "banner": self._module.params["banner"],
132 "text": text,
133 "state": self._module.params["state"],
134 },
135 )
136
137
138 class CliConfiguration(ConfigBase):
139 def __init__(self, module):
140 super(CliConfiguration, self).__init__(module)
141
142 def map_obj_to_commands(self):
143 commands = list()
144 state = self._module.params["state"]
145 if state == "absent":
146 if self._have.get("state") != "absent" and (
147 "text" in self._have.keys() and self._have["text"]
148 ):
149 commands.append("no banner {0!s}".format(self._module.params["banner"]))
150 elif state == "present":
151 if self._want["text"] and self._want["text"].encode().decode(
152 "unicode_escape",
153 ) != self._have.get("text"):
154 banner_cmd = "banner {0!s} ".format(self._module.params["banner"])
155 banner_cmd += self._want["text"].strip()
156 commands.append(banner_cmd)
157 self._result["commands"] = commands
158 if commands:
159 commit = not self._module.check_mode
160 diff = load_config(self._module, commands, commit=commit)
161 if diff:
162 self._result["diff"] = dict(prepared=diff)
163 self._result["changed"] = True
164
165 def map_config_to_obj(self):
166 cli_filter = "banner {0!s}".format(self._module.params["banner"])
167 output = get_config(self._module, config_filter=cli_filter)
168 match = re.search(r"banner (\S+) (.*)", output, re.DOTALL)
169 if match:
170 text = match.group(2)
171 else:
172 text = None
173 obj = {"banner": self._module.params["banner"], "state": "absent"}
174 if output:
175 obj["text"] = text
176 obj["state"] = "present"
177 self._have.update(obj)
178
179 def run(self):
180 self.map_params_to_obj()
181 self.map_config_to_obj()
182 self.map_obj_to_commands()
183
184 return self._result
185
186
187 class NCConfiguration(ConfigBase):
188 def __init__(self, module):
189 super(NCConfiguration, self).__init__(module)
190 self._banners_meta = collections.OrderedDict()
191 self._banners_meta.update(
192 [
193 ("banner", {"xpath": "banners/banner", "tag": True, "attrib": "operation"}),
194 ("a:banner", {"xpath": "banner/banner-name"}),
195 ("a:text", {"xpath": "banner/banner-text", "operation": "edit"}),
196 ],
197 )
198
199 def map_obj_to_xml_rpc(self):
200 state = self._module.params["state"]
201 _get_filter = build_xml(
202 "banners",
203 xmap=self._banners_meta,
204 params=self._module.params,
205 opcode="filter",
206 )
207
208 running = get_config(self._module, source="running", config_filter=_get_filter)
209
210 banner_name = None
211 banner_text = None
212 if etree_find(running, "banner-text") is not None:
213 banner_name = etree_find(running, "banner-name").text
214 banner_text = etree_find(running, "banner-text").text
215
216 opcode = None
217 if state == "absent" and banner_name == self._module.params["banner"] and len(banner_text):
218 opcode = "delete"
219 elif state == "present":
220 opcode = "merge"
221
222 self._result["xml"] = []
223 if opcode:
224 _edit_filter = build_xml(
225 "banners",
226 xmap=self._banners_meta,
227 params=self._module.params,
228 opcode=opcode,
229 )
230
231 if _edit_filter is not None:
232 commit = not self._module.check_mode
233 diff = load_config(
234 self._module,
235 _edit_filter,
236 commit=commit,
237 running=running,
238 nc_get_filter=_get_filter,
239 )
240
241 if diff:
242 self._result["xml"] = _edit_filter
243 if self._module._diff:
244 self._result["diff"] = dict(prepared=diff)
245
246 self._result["changed"] = True
247
248 def run(self):
249 self.map_params_to_obj()
250 self.map_obj_to_xml_rpc()
251
252 return self._result
253
254
255 def main():
256 """main entry point for module execution"""
257 argument_spec = dict(
258 banner=dict(required=True, choices=["login", "motd"]),
259 text=dict(),
260 state=dict(default="present", choices=["present", "absent"]),
261 )
262
263 required_if = [("state", "present", ("text",))]
264
265 module = AnsibleModule(
266 argument_spec=argument_spec,
267 required_if=required_if,
268 supports_check_mode=True,
269 )
270
271 config_object = None
272 if is_cliconf(module):
273 # Commenting the below cliconf deprecation support call for Ansible 2.9 as it'll be continued to be supported
274 config_object = CliConfiguration(module)
275 elif is_netconf(module):
276 config_object = NCConfiguration(module)
277
278 result = None
279 if config_object is not None:
280 result = config_object.run()
281 module.exit_json(**result)
282
283
284 if __name__ == "__main__":
285 main()