Debian Codegraph @

ansible_collections/community/sops/plugins/module_utils/io.py

raw
1 # Copyright (c), Yanis Guenane <[email protected]>, 2016
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 from __future__ import absolute_import, division, print_function
6 __metaclass__ = type
7
8
9 import os
10 import tempfile
11
12
13 # This is taken from community.crypto
14
15 def write_file(module, content):
16 '''
17 Writes content into destination file as securely as possible.
18 Uses file arguments from module.
19 '''
20 # Find out parameters for file
21 file_args = module.load_file_common_arguments(module.params)
22 # Create tempfile name
23 tmp_fd, tmp_name = tempfile.mkstemp(prefix=b'.ansible_tmp')
24 try:
25 os.close(tmp_fd)
26 except Exception:
27 pass
28 module.add_cleanup_file(tmp_name) # if we fail, let Ansible try to remove the file
29 try:
30 try:
31 # Create tempfile
32 file = os.open(tmp_name, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
33 os.write(file, content)
34 os.close(file)
35 except Exception as e:
36 try:
37 os.remove(tmp_name)
38 except Exception:
39 pass
40 module.fail_json(msg='Error while writing result into temporary file: {0}'.format(e))
41 # Update destination to wanted permissions
42 if os.path.exists(file_args['path']):
43 module.set_fs_attributes_if_different(file_args, False)
44 # Move tempfile to final destination
45 module.atomic_move(os.path.abspath(tmp_name), os.path.abspath(file_args['path']))
46 # Try to update permissions again
47 module.set_fs_attributes_if_different(file_args, False)
48 except Exception as e:
49 try:
50 os.remove(tmp_name)
51 except Exception:
52 pass
53 module.fail_json(msg='Error while writing result: {0}'.format(e))