Debian Codegraph @

ansible_collections/cisco/nxos/plugins/modules/nxos_file_copy.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
19 from __future__ import absolute_import, division, print_function
20
21
22 __metaclass__ = type
23
24 DOCUMENTATION = """
25 module: nxos_file_copy
26 extends_documentation_fragment:
27 - cisco.nxos.nxos
28 short_description: Copy a file to a remote NXOS device.
29 description:
30 - This module supports two different workflows for copying a file to flash (or bootflash)
31 on NXOS devices. Files can either be (1) pushed from the Ansible controller to
32 the device or (2) pulled from a remote SCP file server to the device. File copies
33 are initiated from the NXOS device to the remote SCP server. This module only supports
34 the use of connection C(network_cli) or C(Cli) transport with connection C(local).
35 version_added: 1.0.0
36 author:
37 - Jason Edelman (@jedelman8)
38 - Gabriele Gerbino (@GGabriele)
39 - Rewritten as a plugin by (@mikewiebe)
40 notes:
41 - Tested against NXOS 7.0(3)I2(5), 7.0(3)I4(6), 7.0(3)I5(3), 7.0(3)I6(1), 7.0(3)I7(3),
42 6.0(2)A8(8), 7.0(3)F3(4), 7.3(0)D1(1), 8.3(0), 9.2, 9.3
43 - Limited Support for Cisco MDS
44 - When pushing files (file_pull is False) to the NXOS device, feature scp-server must
45 be enabled.
46 - When pulling files (file_pull is True) to the NXOS device, feature scp-server is
47 not required.
48 - When pulling files (file_pull is True) to the NXOS device, no transfer will take
49 place if the file is already present.
50 - Check mode will tell you if the file would be copied.
51 requirements:
52 - paramiko or libssh (required when file_pull is False)
53 - scp (required when file_pull is False)
54 options:
55 local_file:
56 description:
57 - When (file_pull is False) this is the path to the local file on the Ansible
58 controller. The local directory must exist.
59 - When (file_pull is True) this is the target file name on the NXOS device.
60 type: path
61 remote_file:
62 description:
63 - When (file_pull is False) this is the remote file path on the NXOS device. If
64 omitted, the name of the local file will be used. The remote directory must
65 exist.
66 - When (file_pull is True) this is the full path to the file on the remote SCP
67 server to be copied to the NXOS device.
68 type: path
69 file_system:
70 description:
71 - The remote file system on the nxos device. If omitted, devices that support
72 a I(file_system) parameter will use their default values.
73 default: 'bootflash:'
74 type: str
75 connect_ssh_port:
76 description:
77 - B(Deprecated)
78 - This option has been deprecated and will be removed in a release after 2024-06-01.
79 - To maintain backwards compatibility, this option will continue to override the value of I(ansible_port) until removed.
80 - HORIZONTALLINE
81 - SSH server port used for file transfer.
82 - Only used when I(file_pull) is C(True).
83 default: 22
84 type: int
85 file_pull:
86 description:
87 - When (False) file is copied from the Ansible controller to the NXOS device.
88 - When (True) file is copied from a remote SCP server to the NXOS device. In this
89 mode, the file copy is initiated from the NXOS device.
90 - If the file is already present on the device it will be overwritten and therefore
91 the operation is NOT idempotent.
92 type: bool
93 default: false
94 file_pull_protocol:
95 description:
96 - When file_pull is True, this can be used to define the transfer protocol for
97 copying file from remote to the NXOS device.
98 - When (file_pull is False), this is not used.
99 default: 'scp'
100 choices:
101 - scp
102 - sftp
103 - ftp
104 - http
105 - https
106 - tftp
107 type: str
108 file_pull_compact:
109 description:
110 - When file_pull is True, this is used to compact nxos image files. This option
111 can only be used with nxos image files.
112 - When (file_pull is False), this is not used.
113 type: bool
114 default: false
115 file_pull_kstack:
116 description:
117 - When file_pull is True, this can be used to speed up file copies when the nxos
118 running image supports the use-kstack option.
119 - When (file_pull is False), this is not used.
120 type: bool
121 default: false
122 local_file_directory:
123 description:
124 - When (file_pull is True) file is copied from a remote SCP server to the NXOS
125 device, and written to this directory on the NXOS device. If the directory does
126 not exist, it will be created under the file_system. This is an optional parameter.
127 - When (file_pull is False), this is not used.
128 type: path
129 file_pull_timeout:
130 description:
131 - B(Deprecated)
132 - This option has been deprecated and will be removed in a release after 2024-06-01.
133 - To maintain backwards compatibility, this option will continue to override the value of I(ansible_command_timeout) until removed.
134 - HORIZONTALLINE
135 - Use this parameter to set timeout in seconds, when transferring large files
136 or when the network is slow.
137 - When (file_pull is False), this is not used.
138 default: 300
139 type: int
140 remote_scp_server:
141 description:
142 - The remote scp server address when file_pull is True. This is required if file_pull
143 is True.
144 - When (file_pull is False), this is not used.
145 type: str
146 remote_scp_server_user:
147 description:
148 - The remote scp server username when file_pull is True. This is required if file_pull
149 is True.
150 - When (file_pull is False), this is not used.
151 type: str
152 remote_scp_server_password:
153 description:
154 - The remote scp server password when file_pull is True. This is required if file_pull
155 is True.
156 - When (file_pull is False), this is not used.
157 type: str
158 vrf:
159 description:
160 - The VRF used to pull the file. Useful when no vrf management is defined.
161 - This option is not applicable for MDS switches.
162 default: management
163 type: str
164 """
165
166 EXAMPLES = """
167 # File copy from ansible controller to nxos device
168 - name: copy from server to device
169 cisco.nxos.nxos_file_copy:
170 local_file: ./test_file.txt
171 remote_file: test_file.txt
172
173 # Initiate file copy from the nxos device to transfer file from an SCP server back to the nxos device
174 - name: initiate file copy from device
175 cisco.nxos.nxos_file_copy:
176 file_pull: true
177 local_file: xyz
178 local_file_directory: dir1/dir2/dir3
179 remote_file: /mydir/abc
180 remote_scp_server: 192.168.0.1
181 remote_scp_server_user: myUser
182 remote_scp_server_password: myPassword
183 vrf: management
184
185 # Initiate file copy from the nxos device to transfer file from a ftp server back to the nxos device.
186 # remote_scp_server_user and remote_scp_server_password are used to login to the FTP server.
187 - name: initiate file copy from device
188 cisco.nxos.nxos_file_copy:
189 file_pull: true
190 file_pull_protocol: ftp
191 local_file: xyz
192 remote_file: /mydir/abc
193 remote_scp_server: 192.168.0.1
194 remote_scp_server_user: myUser
195 remote_scp_server_password: myPassword
196 vrf: management
197 """
198
199 RETURN = """
200 transfer_status:
201 description: Whether a file was transferred to the nxos device.
202 returned: success
203 type: str
204 sample: 'Sent'
205 local_file:
206 description: The path of the local file.
207 returned: success
208 type: str
209 sample: '/path/to/local/file'
210 remote_file:
211 description: The path of the remote file.
212 returned: success
213 type: str
214 sample: '/path/to/remote/file'
215 remote_scp_server:
216 description: The name of the scp server when file_pull is True.
217 returned: success
218 type: str
219 sample: 'fileserver.example.com'
220 changed:
221 description: Indicates whether or not the file was copied.
222 returned: success
223 type: bool
224 sample: true
225 """
226
227 import hashlib
228 import os
229 import re
230
231 from ansible.module_utils._text import to_bytes, to_text
232 from ansible.module_utils.basic import AnsibleModule
233 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.network import (
234 get_resource_connection,
235 )
236
237
238 class FileCopy:
239 def __init__(self, module):
240 self._module = module
241 self._connection = get_resource_connection(self._module)
242 device_info = self._connection.get_device_info()
243 self._model = device_info.get("network_os_model", "")
244 self._platform = device_info.get("network_os_platform", "")
245
246
247 class FilePush(FileCopy):
248 def __init__(self, module):
249 super(FilePush, self).__init__(module)
250 self.result = {}
251
252 def md5sum_check(self, dst, file_system):
253 command = "show file {0}{1} md5sum".format(file_system, dst)
254 remote_filehash = self._connection.run_commands(command)[0]
255 remote_filehash = to_bytes(remote_filehash, errors="surrogate_or_strict")
256
257 local_file = self._module.params["local_file"]
258 try:
259 with open(local_file, "rb") as f:
260 filecontent = f.read()
261 except (OSError, IOError) as exc:
262 self._module.fail_json("Error reading the file: {0}".format(to_text(exc)))
263
264 filecontent = to_bytes(filecontent, errors="surrogate_or_strict")
265 local_filehash = hashlib.md5(filecontent).hexdigest()
266
267 decoded_rhash = remote_filehash.decode("UTF-8")
268
269 if local_filehash == decoded_rhash:
270 return True
271 else:
272 return False
273
274 def remote_file_exists(self, remote_file, file_system):
275 command = "dir {0}/{1}".format(file_system, remote_file)
276 body = self._connection.run_commands(command)[0]
277
278 if "No such file" in body:
279 return False
280 else:
281 return self.md5sum_check(remote_file, file_system)
282
283 def get_flash_size(self, file_system):
284 command = "dir {0}".format(file_system)
285 body = self._connection.run_commands(command)[0]
286
287 match = re.search(r"(\d+) bytes free", body)
288 if match:
289 bytes_free = match.group(1)
290 return int(bytes_free)
291
292 match = re.search(r"No such file or directory", body)
293 if match:
294 self._module.fail_json("Invalid nxos filesystem {0}".format(file_system))
295 else:
296 self._module.fail_json("Unable to determine size of filesystem {0}".format(file_system))
297
298 def enough_space(self, file, file_system):
299 flash_size = self.get_flash_size(file_system)
300 file_size = os.path.getsize(file)
301 if file_size > flash_size:
302 return False
303
304 return True
305
306 def transfer_file_to_device(self, remote_file):
307 local_file = self._module.params["local_file"]
308 file_system = self._module.params["file_system"]
309
310 if not self.enough_space(local_file, file_system):
311 self._module.fail_json("Could not transfer file. Not enough space on device.")
312
313 # frp = full_remote_path, flp = full_local_path
314 frp = remote_file
315 if not file_system.startswith("bootflash:"):
316 frp = "{0}{1}".format(file_system, remote_file)
317 flp = os.path.join(os.path.abspath(local_file))
318
319 try:
320 self._connection.copy_file(
321 source=flp,
322 destination=frp,
323 proto="scp",
324 timeout=self._connection.get_option("persistent_command_timeout"),
325 )
326 self.result["transfer_status"] = "Sent: File copied to remote device."
327 except Exception as exc:
328 self.result["failed"] = True
329 self.result["msg"] = "Exception received : %s" % exc
330
331 def run(self):
332 local_file = self._module.params["local_file"]
333 remote_file = self._module.params["remote_file"] or os.path.basename(local_file)
334 file_system = self._module.params["file_system"]
335
336 if not os.path.isfile(local_file):
337 self._module.fail_json("Local file {0} not found".format(local_file))
338
339 remote_file = remote_file or os.path.basename(local_file)
340 remote_exists = self.remote_file_exists(remote_file, file_system)
341
342 if not remote_exists:
343 self.result["changed"] = True
344 file_exists = False
345 else:
346 self.result["transfer_status"] = "No Transfer: File already copied to remote device."
347 file_exists = True
348
349 if not self._module.check_mode and not file_exists:
350 self.transfer_file_to_device(remote_file)
351
352 self.result["local_file"] = local_file
353 if remote_file is None:
354 remote_file = os.path.basename(local_file)
355 self.result["remote_file"] = remote_file
356 self.result["file_system"] = file_system
357
358 return self.result
359
360
361 class FilePull(FileCopy):
362 def __init__(self, module):
363 super(FilePull, self).__init__(module)
364 self.result = {}
365
366 def mkdir(self, directory):
367 local_dir_root = "/"
368 dir_array = directory.split("/")
369 for each in dir_array:
370 if each:
371 mkdir_cmd = "mkdir " + local_dir_root + each
372 self._connection.run_commands(mkdir_cmd)
373 local_dir_root += each + "/"
374 return local_dir_root
375
376 def copy_file_from_remote(self, local, local_file_directory, file_system):
377 # Build copy command components that will be used to initiate copy from the nxos device.
378 cmdroot = "copy " + self._module.params["file_pull_protocol"] + "://"
379 ruser = self._module.params["remote_scp_server_user"] + "@"
380 rserver = self._module.params["remote_scp_server"]
381 rserverpassword = self._module.params["remote_scp_server_password"]
382 rfile = self._module.params["remote_file"] + " "
383 if not rfile.startswith("/"):
384 rfile = "/" + rfile
385
386 if not self._platform.startswith("DS-") and "MDS" not in self._model:
387 vrf = " vrf " + self._module.params["vrf"]
388 else:
389 vrf = ""
390 if self._module.params["file_pull_compact"]:
391 compact = " compact "
392 else:
393 compact = ""
394 if self._module.params["file_pull_kstack"]:
395 kstack = " use-kstack "
396 else:
397 kstack = ""
398
399 # Create local file directory under NX-OS filesystem if
400 # local_file_directory playbook parameter is set.
401 local_dir_root = "/"
402 if local_file_directory:
403 local_dir_root = self.mkdir(local_file_directory)
404
405 copy_cmd = (
406 cmdroot
407 + ruser
408 + rserver
409 + rfile
410 + file_system
411 + local_dir_root
412 + local
413 + compact
414 + vrf
415 + kstack
416 )
417
418 self.result["copy_cmd"] = copy_cmd
419 pulled = self._connection.pull_file(command=copy_cmd, remotepassword=rserverpassword)
420 if pulled:
421 self.result["transfer_status"] = (
422 "Received: File copied/pulled to nxos device from remote scp server."
423 )
424 else:
425 self.result["failed"] = True
426
427 def run(self):
428 self.result["failed"] = False
429 remote_file = self._module.params["remote_file"]
430 local_file = self._module.params["local_file"] or remote_file.split("/")[-1]
431 file_system = self._module.params["file_system"]
432 # Note: This is the local file directory on the remote nxos device.
433 local_file_dir = self._module.params["local_file_directory"]
434
435 if not self._module.check_mode:
436 self.copy_file_from_remote(local_file, local_file_dir, file_system)
437
438 self.result["remote_file"] = remote_file
439 if local_file_dir:
440 dir = local_file_dir
441 else:
442 dir = ""
443 self.result["local_file"] = file_system + dir + "/" + local_file
444 self.result["remote_scp_server"] = self._module.params["remote_scp_server"]
445 self.result["file_system"] = self._module.params["file_system"]
446
447 if not self.result["failed"]:
448 self.result["changed"] = True
449
450 return self.result
451
452
453 def main():
454 argument_spec = dict(
455 vrf=dict(type="str", default="management"),
456 connect_ssh_port=dict(type="int", default=22),
457 file_system=dict(type="str", default="bootflash:"),
458 file_pull=dict(type="bool", default=False),
459 file_pull_timeout=dict(type="int", default=300),
460 file_pull_protocol=dict(
461 type="str",
462 default="scp",
463 choices=["scp", "sftp", "http", "https", "tftp", "ftp"],
464 ),
465 file_pull_compact=dict(type="bool", default=False),
466 file_pull_kstack=dict(type="bool", default=False),
467 local_file=dict(type="path"),
468 local_file_directory=dict(type="path"),
469 remote_file=dict(type="path"),
470 remote_scp_server=dict(type="str"),
471 remote_scp_server_user=dict(type="str"),
472 remote_scp_server_password=dict(no_log=True),
473 )
474
475 module = AnsibleModule(
476 argument_spec=argument_spec,
477 required_if=[("file_pull", True, ("remote_file", "remote_scp_server"))],
478 required_together=[("remote_scp_server", "remote_scp_server_user")],
479 supports_check_mode=True,
480 )
481
482 file_pull = module.params["file_pull"]
483
484 warnings = list()
485
486 if file_pull:
487 result = FilePull(module).run()
488 else:
489 result = FilePush(module).run()
490
491 result["warnings"] = warnings
492
493 module.exit_json(**result)
494
495
496 if __name__ == "__main__":
497 main()