Debian Codegraph @

lib/ansible/modules/file.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: (c) 2012, Michael DeHaan <[email protected]>
4 # Copyright: (c) 2017, Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import annotations
8
9
10 DOCUMENTATION = r"""
11 ---
12 module: file
13 version_added: historical
14 short_description: Manage files and file properties
15 extends_documentation_fragment: [files, action_common_attributes]
16 description:
17 - Set attributes of files, directories, or symlinks and their targets.
18 - Alternatively, remove files, symlinks or directories.
19 - Many other modules support the same options as the M(ansible.builtin.file) module - including M(ansible.builtin.copy),
20 M(ansible.builtin.template), and M(ansible.builtin.assemble).
21 - For Windows targets, use the M(ansible.windows.win_file) module instead.
22 options:
23 path:
24 description:
25 - Path to the file being managed.
26 type: path
27 required: yes
28 aliases: [ dest, name ]
29 state:
30 description:
31 - Defines the expectation for the file/path, see the choice values for details.
32 - All values, except V(absent), are expected to enforce the other options, like O(mode), O(owner) and O(access_time) as appropriate.
33 - When unspecified (default), the current state of the file on the target is assumed to be the desired state.
34 type: str
35 choices:
36 absent: The O(path) should not exist. As needed, files, hard links and symlinks will be unlinked, directories will be recursively deleted.
37 In the case of a directory, if C(diff) is declared, you will see the files and folders deleted listed under C(path_contents).
38 The action will not fail if the O(path) does not exist as the state did not change.
39 directory: The target is a directory. If needed, all intermediate subdirectories will be created,
40 using the supplied permissions.
41 file: The O(path) is a file. If no other options were specified, it can be used to query the current information of the O(path).
42 hard: The O(path) is a hard link to the specified O(src).
43 link: The O(path) is a symbolic link to the specified O(src). Other options can be applied depending on O(follow) setting,
44 depending on filesystem support. For example, O(mode) and O(owner) are often not applicable on the link itself.
45 touch: If the O(path) does not exist, an empty file will be created. Otherwise, an existing file or directory will
46 receive updated file access and modification times (similar to the way V(touch) works from the command line).
47 As such, this will always result in a V(changed) state.
48 src:
49 description:
50 - Path of the file to link to.
51 - This applies only to O(state=link) and O(state=hard).
52 - For O(state=link), this will also accept a non-existing path.
53 - Relative paths are relative to the file being created (O(path)) which is how
54 the Unix command C(ln -s SRC DEST) treats relative paths.
55 type: path
56 recurse:
57 description:
58 - Recursively set the specified file attributes on directory contents.
59 - This applies only when O(state) is set to V(directory).
60 type: bool
61 default: no
62 version_added: '1.1'
63 force:
64 description:
65 - >
66 Force the creation of the links in two cases: if the link type is symbolic and the source file does
67 not exist (but will appear later); the destination exists and is a file (so, we need to unlink the
68 O(path) file and create a link to the O(src) file in place of it).
69 type: bool
70 default: no
71 follow:
72 description:
73 - This flag indicates that filesystem links, if they exist, should be followed.
74 - O(follow=yes) and O(state=link) can modify O(src) when combined with parameters such as O(mode).
75 - Previous to Ansible 2.5, this was V(false) by default.
76 - While creating a symlink with a non-existent destination, set O(follow=false) to avoid a warning message related to permission issues.
77 The warning message is added to notify the user that we can not set permissions to the non-existent destination.
78 type: bool
79 default: yes
80 version_added: '1.8'
81 modification_time:
82 description:
83 - This parameter indicates the time the file's modification time should be set to.
84 - Should be V(preserve) when no modification is required, C(YYYYMMDDHHMM.SS) when using default time format, or V(now).
85 - Default is None meaning that V(preserve) is the default for O(state=[file,directory,link,hard]) and V(now) is default for O(state=touch).
86 type: str
87 version_added: "2.7"
88 modification_time_format:
89 description:
90 - When used with O(modification_time), indicates the time format that must be used.
91 - Based on default Python format (see time.strftime doc).
92 type: str
93 default: "%Y%m%d%H%M.%S"
94 version_added: '2.7'
95 access_time:
96 description:
97 - This parameter indicates the time the file's access time should be set to.
98 - Should be V(preserve) when no modification is required, C(YYYYMMDDHHMM.SS) when using default time format, or V(now).
99 - Default is V(None) meaning that V(preserve) is the default for O(state=[file,directory,link,hard]) and V(now) is default for O(state=touch).
100 type: str
101 version_added: '2.7'
102 access_time_format:
103 description:
104 - When used with O(access_time), indicates the time format that must be used.
105 - Based on default Python format (see time.strftime doc).
106 type: str
107 default: "%Y%m%d%H%M.%S"
108 version_added: '2.7'
109 seealso:
110 - module: ansible.builtin.assemble
111 - module: ansible.builtin.copy
112 - module: ansible.builtin.stat
113 - module: ansible.builtin.template
114 - module: ansible.windows.win_file
115 attributes:
116 check_mode:
117 support: full
118 diff_mode:
119 details: permissions and ownership will be shown but file contents on absent/touch will not.
120 support: partial
121 platform:
122 platforms: posix
123 author:
124 - Ansible Core Team
125 - Michael DeHaan
126 """
127
128 EXAMPLES = r"""
129 - name: Change file ownership, group and permissions
130 ansible.builtin.file:
131 path: /etc/foo.conf
132 owner: foo
133 group: foo
134 mode: '0644'
135
136 - name: Change file group using gid
137 ansible.builtin.file:
138 path: /etc/bar.conf
139 group: "1000"
140
141 - name: Give insecure permissions to an existing file
142 ansible.builtin.file:
143 path: /work
144 owner: root
145 group: root
146 mode: '1777'
147
148 - name: Create a symbolic link
149 ansible.builtin.file:
150 src: /file/to/link/to
151 dest: /path/to/symlink
152 owner: foo
153 group: foo
154 state: link
155
156 - name: Create two hard links
157 ansible.builtin.file:
158 src: '/tmp/{{ item.src }}'
159 dest: '{{ item.dest }}'
160 state: hard
161 loop:
162 - { src: x, dest: y }
163 - { src: z, dest: k }
164
165 - name: Touch a file, using symbolic modes to set the permissions (equivalent to 0644)
166 ansible.builtin.file:
167 path: /etc/foo.conf
168 state: touch
169 mode: u=rw,g=r,o=r
170
171 - name: Touch the same file, but add/remove some permissions
172 ansible.builtin.file:
173 path: /etc/foo.conf
174 state: touch
175 mode: u+rw,g-wx,o-rwx
176
177 - name: Touch again the same file, but do not change times this makes the task idempotent
178 ansible.builtin.file:
179 path: /etc/foo.conf
180 state: touch
181 mode: u+rw,g-wx,o-rwx
182 modification_time: preserve
183 access_time: preserve
184
185 - name: Create a directory if it does not exist
186 ansible.builtin.file:
187 path: /etc/some_directory
188 state: directory
189 mode: '0755'
190
191 - name: Update modification and access time of given file
192 ansible.builtin.file:
193 path: /etc/some_file
194 state: file
195 modification_time: now
196 access_time: now
197
198 - name: Set access time based on seconds from epoch value
199 ansible.builtin.file:
200 path: /etc/another_file
201 state: file
202 access_time: '{{ "%Y%m%d%H%M.%S" | strftime(stat_var.stat.atime) }}'
203
204 - name: Recursively change ownership of a directory
205 ansible.builtin.file:
206 path: /etc/foo
207 state: directory
208 recurse: yes
209 owner: foo
210 group: foo
211
212 - name: Remove file (delete file)
213 ansible.builtin.file:
214 path: /etc/foo.txt
215 state: absent
216
217 - name: Recursively remove directory
218 ansible.builtin.file:
219 path: /etc/foo
220 state: absent
221
222 """
223 RETURN = r"""
224 dest:
225 description: Destination file/path, equal to the value passed to O(path).
226 returned: O(state=touch), O(state=hard), O(state=link)
227 type: str
228 sample: /path/to/file.txt
229 path:
230 description: Destination file/path, equal to the value passed to O(path).
231 returned: O(state=absent), O(state=directory), O(state=file)
232 type: str
233 sample: /path/to/file.txt
234 src:
235 description: Source path of the symlink or hardlink.
236 returned: O(state=link), O(state=hard)
237 type: str
238 sample: /file/to/link/to
239 state:
240 description:
241 - State of the target after module execution.
242 - For O(state=absent), this is always V(absent).
243 - For every other state, the value is derived from the resulting path on the
244 filesystem. It is only returned when that path exists, so it may be omitted
245 (for example, a dangling symlink) or differ from the requested O(state).
246 returned: always for O(state=absent), otherwise when the target path exists
247 type: str
248 sample: absent
249 """
250
251 import errno
252 import os
253 import stat
254 import shutil
255 import time
256
257 from pwd import getpwnam, getpwuid
258 from grp import getgrnam, getgrgid
259
260 from ansible.module_utils.basic import AnsibleModule
261 from ansible.module_utils.common.text.converters import to_bytes, to_native
262 from ansible.module_utils.common.sentinel import Sentinel
263
264 # There will only be a single AnsibleModule object per module
265 module = None
266
267
268 class AnsibleModuleError(Exception):
269 def __init__(self, results):
270 self.results = results
271
272 def __repr__(self):
273 return 'AnsibleModuleError(results={0})'.format(self.results)
274
275
276 class ParameterError(AnsibleModuleError):
277 pass
278
279
280 def additional_parameter_handling(params):
281 """Additional parameter validation and reformatting"""
282 # When path is a directory, rewrite the pathname to be the file inside of the directory
283 # TODO: Why do we exclude link? Why don't we exclude directory? Should we exclude touch?
284 # I think this is where we want to be in the future:
285 # when isdir(path):
286 # if state == absent: Remove the directory
287 # if state == touch: Touch the directory
288 # if state == directory: Assert the directory is the same as the one specified
289 # if state == file: place inside of the directory (use _original_basename)
290 # if state == link: place inside of the directory (use _original_basename. Fallback to src?)
291 # if state == hard: place inside of the directory (use _original_basename. Fallback to src?)
292 if (params['state'] not in ("link", "absent") and os.path.isdir(to_bytes(params['path'], errors='surrogate_or_strict'))):
293 basename = None
294
295 if params['_original_basename']:
296 basename = params['_original_basename']
297 elif params['src']:
298 basename = os.path.basename(params['src'])
299
300 if basename:
301 params['path'] = os.path.join(params['path'], basename)
302
303 # state should default to file, but since that creates many conflicts,
304 # default state to 'current' when it exists.
305 prev_state = get_state(params['path'])
306
307 if params['state'] is None:
308 if prev_state != 'absent':
309 params['state'] = prev_state
310 elif params['recurse']:
311 params['state'] = 'directory'
312 else:
313 params['state'] = 'file'
314
315 # make sure the target path is a directory when we're doing a recursive operation
316 if params['recurse'] and params['state'] != 'directory':
317 module.fail_json(
318 msg="recurse option requires state to be 'directory'",
319 path=params["path"]
320 )
321
322 # Fail if 'src' but no 'state' is specified
323 if params['src'] and params['state'] not in ('link', 'hard'):
324 module.fail_json(
325 msg="src option requires state to be 'link' or 'hard'",
326 path=params['path']
327 )
328
329
330 def get_state(path):
331 """ Find out current state """
332
333 b_path = to_bytes(path, errors='surrogate_or_strict')
334 try:
335 st = os.lstat(b_path)
336 except FileNotFoundError:
337 return 'absent'
338 except PermissionError:
339 module.warn(f"Insufficient permissions to access {to_native(b_path)}. Treating as absent")
340 return 'absent'
341
342 if stat.S_ISLNK(st.st_mode):
343 return 'link'
344 elif stat.S_ISDIR(st.st_mode):
345 return 'directory'
346 elif st.st_nlink > 1:
347 return 'hard'
348
349 # could be many other things, but defaulting to file
350 return 'file'
351
352
353 # This should be moved into the common file utilities
354 def recursive_set_attributes(b_path, follow, file_args, mtime, atime):
355 changed = False
356
357 try:
358 for b_root, b_dirs, b_files in os.walk(b_path):
359 for b_fsobj in b_dirs + b_files:
360 b_fsname = os.path.join(b_root, b_fsobj)
361 if not os.path.islink(b_fsname):
362 tmp_file_args = file_args.copy()
363 tmp_file_args['path'] = to_native(b_fsname, errors='surrogate_or_strict')
364 changed |= module.set_fs_attributes_if_different(tmp_file_args, changed, expand=False)
365 changed |= update_timestamp_for_file(tmp_file_args['path'], mtime, atime)
366
367 else:
368 # Change perms on the link
369 tmp_file_args = file_args.copy()
370 tmp_file_args['path'] = to_native(b_fsname, errors='surrogate_or_strict')
371 changed |= module.set_fs_attributes_if_different(tmp_file_args, changed, expand=False)
372 changed |= update_timestamp_for_file(tmp_file_args['path'], mtime, atime)
373
374 if follow:
375 b_fsname = os.path.join(b_root, os.readlink(b_fsname))
376 # The link target could be nonexistent
377 if os.path.exists(b_fsname):
378 if os.path.isdir(b_fsname):
379 # Link is a directory so change perms on the directory's contents
380 changed |= recursive_set_attributes(b_fsname, follow, file_args, mtime, atime)
381
382 # Change perms on the file pointed to by the link
383 tmp_file_args = file_args.copy()
384 tmp_file_args['path'] = to_native(b_fsname, errors='surrogate_or_strict')
385 changed |= module.set_fs_attributes_if_different(tmp_file_args, changed, expand=False)
386 changed |= update_timestamp_for_file(tmp_file_args['path'], mtime, atime)
387 except RuntimeError as e:
388 # on Python3 "RecursionError" is raised which is derived from "RuntimeError"
389 # TODO once this function is moved into the common file utilities, this should probably raise more general exception
390 module.fail_json(
391 msg=f"Could not recursively set attributes on {to_native(b_path)}. Original error was: '{to_native(e)}'"
392 )
393
394 return changed
395
396
397 def initial_diff(path, state, prev_state):
398 diff = {'before': {'path': path},
399 'after': {'path': path},
400 }
401
402 if prev_state != state:
403 diff['before']['state'] = prev_state
404 diff['after']['state'] = state
405 if state == 'absent' and prev_state == 'directory':
406 walklist = {
407 'directories': [],
408 'files': [],
409 }
410 b_path = to_bytes(path, errors='surrogate_or_strict')
411 for base_path, sub_folders, files in os.walk(b_path):
412 for folder in sub_folders:
413 folderpath = os.path.join(base_path, folder)
414 walklist['directories'].append(folderpath)
415
416 for filename in files:
417 filepath = os.path.join(base_path, filename)
418 walklist['files'].append(filepath)
419
420 diff['before']['path_content'] = walklist
421
422 return diff
423
424 #
425 # States
426 #
427
428
429 def get_timestamp_for_time(formatted_time, time_format):
430 if formatted_time == 'preserve':
431 return None
432 if formatted_time == 'now':
433 return Sentinel
434 try:
435 struct = time.strptime(formatted_time, time_format)
436 struct_time = time.mktime(struct)
437 except (ValueError, OverflowError) as e:
438 module.fail_json(
439 msg=f"Error while obtaining timestamp for time {formatted_time} using format {time_format}: {to_native(e, nonstring='simplerepr')}",
440 )
441
442 return struct_time
443
444
445 def update_timestamp_for_file(path, mtime, atime, diff=None):
446 b_path = to_bytes(path, errors='surrogate_or_strict')
447
448 try:
449 # When mtime and atime are set to 'now', rely on utime(path, None) which does not require ownership of the file
450 # https://github.com/ansible/ansible/issues/50943
451 if mtime is Sentinel and atime is Sentinel:
452 # It's not exact but we can't rely on os.stat(path).st_mtime after setting os.utime(path, None) as it may
453 # not be updated. Just use the current time for the diff values
454 mtime = atime = time.time()
455
456 previous_mtime = os.stat(b_path).st_mtime
457 previous_atime = os.stat(b_path).st_atime
458
459 set_time = None
460 else:
461 # If both parameters are None 'preserve', nothing to do
462 if mtime is None and atime is None:
463 return False
464
465 previous_mtime = os.stat(b_path).st_mtime
466 previous_atime = os.stat(b_path).st_atime
467
468 if mtime is None:
469 mtime = previous_mtime
470 elif mtime is Sentinel:
471 mtime = time.time()
472
473 if atime is None:
474 atime = previous_atime
475 elif atime is Sentinel:
476 atime = time.time()
477
478 # If both timestamps are already ok, nothing to do
479 if mtime == previous_mtime and atime == previous_atime:
480 return False
481
482 set_time = (atime, mtime)
483
484 if not module.check_mode:
485 os.utime(b_path, set_time)
486
487 if diff is not None:
488 if 'before' not in diff:
489 diff['before'] = {}
490 if 'after' not in diff:
491 diff['after'] = {}
492 if mtime != previous_mtime:
493 diff['before']['mtime'] = previous_mtime
494 diff['after']['mtime'] = mtime
495 if atime != previous_atime:
496 diff['before']['atime'] = previous_atime
497 diff['after']['atime'] = atime
498 except OSError as e:
499 module.fail_json(
500 msg=f"Error while updating modification or access time: {to_native(e, nonstring='simplerepr')}",
501 path=path
502 )
503 return True
504
505
506 def keep_backward_compatibility_on_timestamps(parameter, state):
507 if state in ['file', 'hard', 'directory', 'link'] and parameter is None:
508 return 'preserve'
509 if state == 'touch' and parameter is None:
510 return 'now'
511 return parameter
512
513
514 def execute_diff_peek(path):
515 """Take a guess as to whether a file is a binary file"""
516 b_path = to_bytes(path, errors='surrogate_or_strict')
517 appears_binary = False
518 try:
519 with open(b_path, 'rb') as f:
520 head = f.read(8192)
521 except Exception:
522 # If we can't read the file, we're okay assuming it's text
523 pass
524 else:
525 if b"\x00" in head:
526 appears_binary = True
527
528 return appears_binary
529
530
531 def ensure_absent(path):
532 b_path = to_bytes(path, errors='surrogate_or_strict')
533 prev_state = get_state(path)
534 result = {}
535
536 if prev_state != 'absent':
537 diff = initial_diff(path, 'absent', prev_state)
538
539 if not module.check_mode:
540 if prev_state == 'directory':
541 try:
542 shutil.rmtree(b_path, ignore_errors=False)
543 except Exception as e:
544 module.fail_json(
545 msg=f"rmtree failed: {to_native(e)}"
546 )
547 else:
548 try:
549 os.unlink(b_path)
550 except FileNotFoundError:
551 pass
552 except OSError as ex:
553 module.fail_json(
554 msg="Unlinking failed.",
555 path=path,
556 exception=ex,
557 )
558
559 result.update({'path': path, 'changed': True, 'diff': diff, 'state': 'absent'})
560 else:
561 result.update({'path': path, 'changed': False, 'state': 'absent'})
562
563 return result
564
565
566 def execute_touch(path, follow, timestamps):
567 b_path = to_bytes(path, errors='surrogate_or_strict')
568 prev_state = get_state(path)
569 changed = False
570 result = {'dest': path}
571 mtime = get_timestamp_for_time(timestamps['modification_time'], timestamps['modification_time_format'])
572 atime = get_timestamp_for_time(timestamps['access_time'], timestamps['access_time_format'])
573
574 # If the file did not already exist
575 if prev_state == 'absent':
576 # if we are in check mode and the file is absent
577 # we can set the changed status to True and return
578 if module.check_mode:
579 result['changed'] = True
580 return result
581 # Create an empty file
582 try:
583 open(b_path, 'wb').close()
584 changed = True
585 except OSError as ex:
586 module.fail_json(
587 msg="Error, could not touch target.",
588 path=path,
589 exception=ex,
590 )
591 # Update the attributes on the file
592 diff = initial_diff(path, 'touch', prev_state)
593 file_args = module.load_file_common_arguments(module.params)
594 try:
595 changed = module.set_fs_attributes_if_different(file_args, changed, diff, expand=False)
596 changed |= update_timestamp_for_file(file_args['path'], mtime, atime, diff)
597 except SystemExit as e:
598 if e.code: # this is the exit code passed to sys.exit, not a constant -- pylint: disable=using-constant-test
599 # We take this to mean that fail_json() was called from
600 # somewhere in basic.py
601 if prev_state == 'absent':
602 # If we just created the file we can safely remove it
603 os.remove(b_path)
604 raise
605
606 result['changed'] = changed
607 result['diff'] = diff
608 return result
609
610
611 def ensure_file_attributes(path, follow, timestamps):
612 b_path = to_bytes(path, errors='surrogate_or_strict')
613 prev_state = get_state(path)
614 file_args = module.load_file_common_arguments(module.params)
615 mtime = get_timestamp_for_time(timestamps['modification_time'], timestamps['modification_time_format'])
616 atime = get_timestamp_for_time(timestamps['access_time'], timestamps['access_time_format'])
617
618 if prev_state != 'file':
619 if follow and prev_state == 'link':
620 # follow symlink and operate on original
621 b_path = os.path.realpath(b_path)
622 path = to_native(b_path, errors='strict')
623 prev_state = get_state(b_path)
624 file_args['path'] = path
625
626 if prev_state not in ('file', 'hard'):
627 # file is not absent and any other state is a conflict
628 module.fail_json(
629 msg=f"file ({path}) is {prev_state}, cannot continue",
630 path=path,
631 state=prev_state
632 )
633
634 diff = initial_diff(path, 'file', prev_state)
635 changed = module.set_fs_attributes_if_different(file_args, False, diff, expand=False)
636 changed |= update_timestamp_for_file(file_args['path'], mtime, atime, diff)
637 return {'path': path, 'changed': changed, 'diff': diff}
638
639
640 def ensure_directory(path, follow, recurse, timestamps):
641 b_path = to_bytes(path, errors='surrogate_or_strict')
642 prev_state = get_state(path)
643 file_args = module.load_file_common_arguments(module.params)
644 mtime = get_timestamp_for_time(timestamps['modification_time'], timestamps['modification_time_format'])
645 atime = get_timestamp_for_time(timestamps['access_time'], timestamps['access_time_format'])
646
647 # For followed symlinks, we need to operate on the target of the link
648 if follow and prev_state == 'link':
649 b_path = os.path.realpath(b_path)
650 path = to_native(b_path, errors='strict')
651 file_args['path'] = path
652 prev_state = get_state(b_path)
653
654 changed = False
655 diff = initial_diff(path, 'directory', prev_state)
656
657 if prev_state == 'absent':
658 # Create directory and assign permissions to it
659 if module.check_mode:
660 return {'path': path, 'changed': True, 'diff': diff}
661 curpath = ''
662
663 try:
664 # Split the path so we can apply filesystem attributes recursively
665 # from the root (/) directory for absolute paths or the base path
666 # of a relative path. We can then walk the appropriate directory
667 # path to apply attributes.
668 # Something like mkdir -p with mode applied to all of the newly created directories
669 for dirname in path.strip('/').split('/'):
670 curpath = '/'.join([curpath, dirname])
671 # Remove leading slash if we're creating a relative path
672 if not os.path.isabs(path):
673 curpath = curpath.lstrip('/')
674 b_curpath = to_bytes(curpath, errors='surrogate_or_strict')
675 if not os.path.exists(b_curpath):
676 try:
677 os.mkdir(b_curpath)
678 changed = True
679 except OSError as ex:
680 # Possibly something else created the dir since the os.path.exists
681 # check above. As long as it's a dir, we don't need to error out.
682 if not (ex.errno == errno.EEXIST and os.path.isdir(b_curpath)):
683 raise
684 tmp_file_args = file_args.copy()
685 tmp_file_args['path'] = curpath
686 changed = module.set_fs_attributes_if_different(tmp_file_args, changed, diff, expand=False)
687 changed |= update_timestamp_for_file(file_args['path'], mtime, atime, diff)
688 except Exception as e:
689 module.fail_json(
690 msg=f"There was an issue creating {curpath} as requested: {to_native(e)}",
691 path=path
692 )
693 return {'path': path, 'changed': changed, 'diff': diff}
694
695 elif prev_state != 'directory':
696 # We already know prev_state is not 'absent', therefore it exists in some form.
697 module.fail_json(
698 msg=f"{path} already exists as a {prev_state}",
699 path=path
700 )
701
702 #
703 # previous state == directory
704 #
705
706 changed = module.set_fs_attributes_if_different(file_args, changed, diff, expand=False)
707 changed |= update_timestamp_for_file(file_args['path'], mtime, atime, diff)
708 if recurse:
709 changed |= recursive_set_attributes(b_path, follow, file_args, mtime, atime)
710
711 return {'path': path, 'changed': changed, 'diff': diff}
712
713
714 def ensure_symlink(path, src, follow, force, timestamps):
715 b_path = to_bytes(path, errors='surrogate_or_strict')
716 b_src = to_bytes(src, errors='surrogate_or_strict')
717 prev_state = get_state(path)
718 mtime = get_timestamp_for_time(timestamps['modification_time'], timestamps['modification_time_format'])
719 atime = get_timestamp_for_time(timestamps['access_time'], timestamps['access_time_format'])
720 # source is both the source of a symlink or an informational passing of the src for a template module
721 # or copy module, even if this module never uses it, it is needed to key off some things
722 if src is None:
723 if follow and os.path.exists(b_path):
724 # use the current target of the link as the source
725 src = to_native(os.readlink(b_path), errors='strict')
726 b_src = to_bytes(src, errors='surrogate_or_strict')
727
728 if not os.path.islink(b_path) and os.path.isdir(b_path):
729 relpath = path
730 else:
731 b_relpath = os.path.dirname(b_path)
732 relpath = to_native(b_relpath, errors='strict')
733
734 # If src is None that means we are expecting to update an existing link.
735 if src is None:
736 absrc = None
737 else:
738 absrc = os.path.join(relpath, src)
739
740 b_absrc = to_bytes(absrc, errors='surrogate_or_strict')
741 if not force and src is not None and not os.path.exists(b_absrc):
742 module.fail_json(
743 msg="src file does not exist, use 'force=yes' if you"
744 f" really want to create the link: {absrc}",
745 path=path,
746 src=src
747 )
748
749 if prev_state == 'directory':
750 if not force:
751 module.fail_json(
752 msg=f'refusing to convert from {prev_state} to symlink for {path}',
753 path=path
754 )
755 elif os.listdir(b_path):
756 # refuse to replace a directory that has files in it
757 module.fail_json(
758 msg=f'the directory {path} is not empty, refusing to convert it',
759 path=path
760 )
761 elif prev_state in ('file', 'hard') and not force:
762 module.fail_json(
763 msg=f'refusing to convert from {prev_state} to symlink for {path}',
764 path=path
765 )
766
767 diff = initial_diff(path, 'link', prev_state)
768 changed = False
769
770 if prev_state in ('hard', 'file', 'directory', 'absent'):
771 if src is None:
772 module.fail_json(
773 msg='src is required for creating new symlinks',
774 )
775 changed = True
776 elif prev_state == 'link':
777 if src is not None:
778 b_old_src = os.readlink(b_path)
779 if b_old_src != b_src:
780 diff['before']['src'] = to_native(b_old_src, errors='strict')
781 diff['after']['src'] = src
782 changed = True
783 else:
784 module.fail_json(
785 msg='unexpected position reached',
786 dest=path,
787 src=src
788 )
789
790 if changed and not module.check_mode:
791 if prev_state != 'absent':
792 # try to replace atomically
793 b_tmppath = os.path.join(
794 os.path.dirname(b_path), to_bytes(".%s.%s.tmp" % (os.getpid(), time.time()))
795 )
796 try:
797 if prev_state == 'directory':
798 os.rmdir(b_path)
799 os.symlink(b_src, b_tmppath)
800 os.rename(b_tmppath, b_path)
801 except OSError as e:
802 if os.path.exists(b_tmppath):
803 os.unlink(b_tmppath)
804 module.fail_json(
805 msg=f"Error while replacing: {to_native(e, nonstring='simplerepr')}",
806 path=path
807 )
808 else:
809 try:
810 os.symlink(b_src, b_path)
811 except OSError as e:
812 module.fail_json(
813 msg=f"Error while linking: {to_native(e, nonstring='simplerepr')}",
814 path=path
815 )
816
817 if module.check_mode and not os.path.exists(b_path):
818 return {'dest': path, 'src': src, 'changed': changed, 'diff': diff}
819
820 # Now that we might have created the symlink, get the arguments.
821 # We need to do it now so we can properly follow the symlink if needed
822 # because load_file_common_arguments sets 'path' according
823 # the value of follow and the symlink existence.
824 file_args = module.load_file_common_arguments(module.params)
825
826 # Whenever we create a link to a nonexistent target we know that the nonexistent target
827 # cannot have any permissions set on it. Skip setting those and emit a warning (the user
828 # can set follow=False to remove the warning)
829 if follow and os.path.islink(b_path) and not os.path.exists(file_args['path']):
830 module.warn('Cannot set fs attributes on a non-existent symlink target. follow should be'
831 ' set to False to avoid this.')
832 else:
833 changed = module.set_fs_attributes_if_different(file_args, changed, diff, expand=False)
834 changed |= update_timestamp_for_file(file_args['path'], mtime, atime, diff)
835
836 return {'dest': path, 'src': src, 'changed': changed, 'diff': diff}
837
838
839 def ensure_hardlink(path, src, follow, force, timestamps):
840 b_path = to_bytes(path, errors='surrogate_or_strict')
841 b_src = to_bytes(src, errors='surrogate_or_strict')
842 prev_state = get_state(path)
843 file_args = module.load_file_common_arguments(module.params)
844 mtime = get_timestamp_for_time(timestamps['modification_time'], timestamps['modification_time_format'])
845 atime = get_timestamp_for_time(timestamps['access_time'], timestamps['access_time_format'])
846
847 # src is the source of a hardlink. We require it if we are creating a new hardlink.
848 # We require path in the argument_spec so we know it is present at this point.
849 if prev_state != 'hard' and src is None:
850 module.fail_json(
851 msg='src is required for creating new hardlinks'
852 )
853
854 # Even if the link already exists, if src was specified it needs to exist.
855 # The inode number will be compared to ensure the link has the correct target.
856 if src is not None and not os.path.exists(b_src):
857 module.fail_json(
858 msg='src does not exist',
859 dest=path,
860 src=src
861 )
862
863 diff = initial_diff(path, 'hard', prev_state)
864 changed = False
865
866 if prev_state == 'absent':
867 changed = True
868 elif prev_state == 'link':
869 b_old_src = os.readlink(b_path)
870 if b_old_src != b_src:
871 diff['before']['src'] = to_native(b_old_src, errors='strict')
872 diff['after']['src'] = src
873 changed = True
874 elif prev_state == 'hard':
875 if src is not None and os.stat(b_path).st_ino != os.stat(b_src).st_ino:
876 changed = True
877 if not force:
878 module.fail_json(
879 msg='Cannot link, different hard link exists at destination',
880 dest=path,
881 src=src
882 )
883 elif prev_state == 'file':
884 changed = True
885 if not force:
886 module.fail_json(
887 msg=f'Cannot link, {prev_state} exists at destination',
888 dest=path,
889 src=src
890 )
891 elif prev_state == 'directory':
892 changed = True
893 if os.path.exists(b_path):
894 if os.stat(b_path).st_ino == os.stat(b_src).st_ino:
895 return {'path': path, 'changed': False}
896 elif not force:
897 module.fail_json(
898 msg='Cannot link: different hard link exists at destination',
899 dest=path,
900 src=src
901 )
902 else:
903 module.fail_json(
904 msg='unexpected position reached',
905 dest=path,
906 src=src
907 )
908
909 if changed and not module.check_mode:
910 if prev_state != 'absent':
911 # try to replace atomically
912 b_tmppath = os.path.join(
913 os.path.dirname(b_path), to_bytes(".%s.%s.tmp" % (os.getpid(), time.time()))
914 )
915 try:
916 if prev_state == 'directory':
917 if os.path.exists(b_path):
918 try:
919 os.unlink(b_path)
920 except FileNotFoundError:
921 pass
922 os.link(b_src, b_tmppath)
923 os.rename(b_tmppath, b_path)
924 except OSError as e:
925 if os.path.exists(b_tmppath):
926 os.unlink(b_tmppath)
927 module.fail_json(
928 msg=f"Error while replacing: {to_native(e, nonstring='simplerepr')}",
929 path=path
930 )
931 else:
932 try:
933 if follow and os.path.islink(b_src):
934 b_src = os.readlink(b_src)
935 os.link(b_src, b_path)
936 except OSError as e:
937 module.fail_json(
938 msg=f"Error while linking: {to_native(e, nonstring='simplerepr')}",
939 path=path
940 )
941
942 if module.check_mode and not os.path.exists(b_path):
943 return {'dest': path, 'src': src, 'changed': changed, 'diff': diff}
944
945 changed = module.set_fs_attributes_if_different(file_args, changed, diff, expand=False)
946 changed |= update_timestamp_for_file(file_args['path'], mtime, atime, diff)
947
948 return {'dest': path, 'src': src, 'changed': changed, 'diff': diff}
949
950
951 def check_owner_exists(module, owner):
952 try:
953 uid = int(owner)
954 try:
955 getpwuid(uid).pw_name
956 except KeyError:
957 module.warn('failed to look up user with uid %s. Create user up to this point in real play' % uid)
958 except ValueError:
959 try:
960 getpwnam(owner).pw_uid
961 except KeyError:
962 module.warn('failed to look up user %s. Create user up to this point in real play' % owner)
963
964
965 def check_group_exists(module, group):
966 try:
967 gid = int(group)
968 try:
969 getgrgid(gid).gr_name
970 except KeyError:
971 module.warn('failed to look up group with gid %s. Create group up to this point in real play' % gid)
972 except ValueError:
973 try:
974 getgrnam(group).gr_gid
975 except KeyError:
976 module.warn('failed to look up group %s. Create group up to this point in real play' % group)
977
978
979 def main():
980
981 global module
982
983 module = AnsibleModule(
984 argument_spec=dict(
985 state=dict(type='str', choices=['absent', 'directory', 'file', 'hard', 'link', 'touch']),
986 path=dict(type='path', required=True, aliases=['dest', 'name']),
987 _original_basename=dict(type='str'), # Internal use only, for recursive ops
988 recurse=dict(type='bool', default=False),
989 force=dict(type='bool', default=False), # Note: Should not be in file_common_args in future
990 follow=dict(type='bool', default=True), # Note: Different default than file_common_args
991 _diff_peek=dict(type='bool'), # Internal use only, for internal checks in the action plugins
992 src=dict(type='path'), # Note: Should not be in file_common_args in future
993 modification_time=dict(type='str'),
994 modification_time_format=dict(type='str', default='%Y%m%d%H%M.%S'),
995 access_time=dict(type='str'),
996 access_time_format=dict(type='str', default='%Y%m%d%H%M.%S'),
997 ),
998 add_file_common_args=True,
999 supports_check_mode=True,
1000 )
1001
1002 try:
1003 additional_parameter_handling(module.params)
1004 params = module.params
1005
1006 state = params['state']
1007 recurse = params['recurse']
1008 force = params['force']
1009 follow = params['follow']
1010 path = params['path']
1011 src = params['src']
1012
1013 if module.check_mode and state != 'absent':
1014 file_args = module.load_file_common_arguments(module.params)
1015 if file_args['owner']:
1016 check_owner_exists(module, file_args['owner'])
1017 if file_args['group']:
1018 check_group_exists(module, file_args['group'])
1019
1020 timestamps = {}
1021 timestamps['modification_time'] = keep_backward_compatibility_on_timestamps(params['modification_time'], state)
1022 timestamps['modification_time_format'] = params['modification_time_format']
1023 timestamps['access_time'] = keep_backward_compatibility_on_timestamps(params['access_time'], state)
1024 timestamps['access_time_format'] = params['access_time_format']
1025
1026 # short-circuit for diff_peek
1027 if params['_diff_peek'] is not None:
1028 appears_binary = execute_diff_peek(to_bytes(path, errors='surrogate_or_strict'))
1029 module.exit_json(path=path, changed=False, appears_binary=appears_binary)
1030
1031 if state == 'file':
1032 result = ensure_file_attributes(path, follow, timestamps)
1033 elif state == 'directory':
1034 result = ensure_directory(path, follow, recurse, timestamps)
1035 elif state == 'link':
1036 result = ensure_symlink(path, src, follow, force, timestamps)
1037 elif state == 'hard':
1038 result = ensure_hardlink(path, src, follow, force, timestamps)
1039 elif state == 'touch':
1040 result = execute_touch(path, follow, timestamps)
1041 elif state == 'absent':
1042 result = ensure_absent(path)
1043 except AnsibleModuleError as ex:
1044 module.fail_json(**ex.results)
1045
1046 if not module._diff:
1047 result.pop('diff', None)
1048
1049 module.exit_json(**result)
1050
1051
1052 if __name__ == '__main__':
1053 main()