o nnh֠@sXddlmZdZdZdZddlZddlZddlZddlZddl Z ddl m Z m Z ddl mZmZddlmZdd lmZmZdaGd d d eZGd d d eZGdddeZddZddZddZddZddZddZ d5ddZ!ddZ"d d!Z#d"d#Z$d$d%Z%d&d'Z&d(d)Z'd*d+Z(d,d-Z)d.d/Z*d0d1Z+d2d3Z,e-d4kre,dSdS)6) annotationsa --- module: file version_added: historical short_description: Manage files and file properties extends_documentation_fragment: [files, action_common_attributes] description: - Set attributes of files, directories, or symlinks and their targets. - Alternatively, remove files, symlinks or directories. - Many other modules support the same options as the M(ansible.builtin.file) module - including M(ansible.builtin.copy), M(ansible.builtin.template), and M(ansible.builtin.assemble). - For Windows targets, use the M(ansible.windows.win_file) module instead. options: path: description: - Path to the file being managed. type: path required: yes aliases: [ dest, name ] state: description: - If V(absent), directories will be recursively deleted, and files or symlinks will be unlinked. In the case of a directory, if C(diff) is declared, you will see the files and folders deleted listed under C(path_contents). Note that V(absent) will not cause M(ansible.builtin.file) to fail if the O(path) does not exist as the state did not change. - If V(directory), all intermediate subdirectories will be created if they do not exist. Since Ansible 1.7 they will be created with the supplied permissions. - If V(file), with no other options, returns the current state of C(path). - If V(file), even with other options (such as O(mode)), the file will be modified if it exists but will NOT be created if it does not exist. Set to V(touch) or use the M(ansible.builtin.copy) or M(ansible.builtin.template) module if you want to create the file if it does not exist. - If V(hard), the hard link will be created or changed. - If V(link), the symbolic link will be created or changed. - If V(touch) (new in 1.4), an empty file will be created if the file does not exist, while an existing file or directory will receive updated file access and modification times (similar to the way V(touch) works from the command line). - Default is the current state of the file if it exists, V(directory) if O(recurse=yes), or V(file) otherwise. type: str choices: [ absent, directory, file, hard, link, touch ] src: description: - Path of the file to link to. - This applies only to O(state=link) and O(state=hard). - For O(state=link), this will also accept a non-existing path. - Relative paths are relative to the file being created (O(path)) which is how the Unix command C(ln -s SRC DEST) treats relative paths. type: path recurse: description: - Recursively set the specified file attributes on directory contents. - This applies only when O(state) is set to V(directory). type: bool default: no version_added: '1.1' force: description: - > Force the creation of the symlinks in two cases: the source file does not exist (but will appear later); the destination exists and is a file (so, we need to unlink the O(path) file and create a symlink to the O(src) file in place of it). type: bool default: no follow: description: - This flag indicates that filesystem links, if they exist, should be followed. - O(follow=yes) and O(state=link) can modify O(src) when combined with parameters such as O(mode). - Previous to Ansible 2.5, this was V(false) by default. - While creating a symlink with a non-existent destination, set O(follow) to V(false) to avoid a warning message related to permission issues. The warning message is added to notify the user that we can not set permissions to the non-existent destination. type: bool default: yes version_added: '1.8' modification_time: description: - This parameter indicates the time the file's modification time should be set to. - Should be V(preserve) when no modification is required, C(YYYYMMDDHHMM.SS) when using default time format, or V(now). - 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). type: str version_added: "2.7" modification_time_format: description: - When used with O(modification_time), indicates the time format that must be used. - Based on default Python format (see time.strftime doc). type: str default: "%Y%m%d%H%M.%S" version_added: '2.7' access_time: description: - This parameter indicates the time the file's access time should be set to. - Should be V(preserve) when no modification is required, C(YYYYMMDDHHMM.SS) when using default time format, or V(now). - 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). type: str version_added: '2.7' access_time_format: description: - When used with O(access_time), indicates the time format that must be used. - Based on default Python format (see time.strftime doc). type: str default: "%Y%m%d%H%M.%S" version_added: '2.7' seealso: - module: ansible.builtin.assemble - module: ansible.builtin.copy - module: ansible.builtin.stat - module: ansible.builtin.template - module: ansible.windows.win_file attributes: check_mode: support: full diff_mode: details: permissions and ownership will be shown but file contents on absent/touch will not. support: partial platform: platforms: posix author: - Ansible Core Team - Michael DeHaan a$ - name: Change file ownership, group and permissions ansible.builtin.file: path: /etc/foo.conf owner: foo group: foo mode: '0644' - name: Give insecure permissions to an existing file ansible.builtin.file: path: /work owner: root group: root mode: '1777' - name: Create a symbolic link ansible.builtin.file: src: /file/to/link/to dest: /path/to/symlink owner: foo group: foo state: link - name: Create two hard links ansible.builtin.file: src: '/tmp/{{ item.src }}' dest: '{{ item.dest }}' state: hard loop: - { src: x, dest: y } - { src: z, dest: k } - name: Touch a file, using symbolic modes to set the permissions (equivalent to 0644) ansible.builtin.file: path: /etc/foo.conf state: touch mode: u=rw,g=r,o=r - name: Touch the same file, but add/remove some permissions ansible.builtin.file: path: /etc/foo.conf state: touch mode: u+rw,g-wx,o-rwx - name: Touch again the same file, but do not change times this makes the task idempotent ansible.builtin.file: path: /etc/foo.conf state: touch mode: u+rw,g-wx,o-rwx modification_time: preserve access_time: preserve - name: Create a directory if it does not exist ansible.builtin.file: path: /etc/some_directory state: directory mode: '0755' - name: Update modification and access time of given file ansible.builtin.file: path: /etc/some_file state: file modification_time: now access_time: now - name: Set access time based on seconds from epoch value ansible.builtin.file: path: /etc/another_file state: file access_time: '{{ "%Y%m%d%H%M.%S" | strftime(stat_var.stat.atime) }}' - name: Recursively change ownership of a directory ansible.builtin.file: path: /etc/foo state: directory recurse: yes owner: foo group: foo - name: Remove file (delete file) ansible.builtin.file: path: /etc/foo.txt state: absent - name: Recursively remove directory ansible.builtin.file: path: /etc/foo state: absent a} dest: description: Destination file/path, equal to the value passed to O(path). returned: O(state=touch), O(state=hard), O(state=link) type: str sample: /path/to/file.txt path: description: Destination file/path, equal to the value passed to O(path). returned: O(state=absent), O(state=directory), O(state=file) type: str sample: /path/to/file.txt N)getpwnamgetpwuid)getgrnamgetgrgid) AnsibleModule)to_bytes to_nativec@seZdZddZddZdS)AnsibleModuleErrorcCs ||_dSNresults)selfr r?/usr/local/lib/python3.10/dist-packages/ansible/modules/file.py__init__s zAnsibleModuleError.__init__cCs d|jS)NzAnsibleModuleError(results={0}))formatr )rrrr__repr__s zAnsibleModuleError.__repr__N)__name__ __module__ __qualname__rrrrrrr s r c@s eZdZdS)ParameterErrorN)rrrrrrrrsrc@seZdZddZdS)SentinelcOs|Sr r)clsargskwargsrrr__new__szSentinel.__new__N)rrrrrrrrrs rcCs2t|trtjdi|jdSt|||dS)Nr) issubclassr module fail_jsonr sys__excepthook__)exc_type exc_valuetbrrr_ansible_excepthook s r%cCs|ddvr6tjt|dddr6d}|dr|d}n |dr)tj|d}|r6tj|d||d<tt|ddd}|ddur\|d krO||d<n |d rXd |d<nd |d<|d rp|dd krptd |ddd|dr|ddvrtd|ddddSdS)z0Additional parameter validation and reformattingstate)linkabsentpathsurrogate_or_stricterrorsN_original_basenamesrcr(recurse directoryfilez/recurse option requires state to be 'directory'msgr)r )r'hardz0src option requires state to be 'link' or 'hard')osr)isdirrbasenamejoin get_stater)paramsr7 prev_staterrradditional_parameter_handlings0$       r<c Cst|dd}z)tj|r-tj|rWdStj|rWdSt|jdkr*WdSWdSWdStyI}z|j t j krDWYd }~dSd }~ww) z Find out current state r*r+r'r0r4r1r(N) rr5r)lexistsislinkr6statst_nlinkOSErrorerrnoENOENT)r)b_patherrrr9?s"     r9c Csd}zt|D]\}}}||D]} tj|| } tj| sA|} t| dd| d<|tj| |ddO}|t | d||O}q|} t| dd| d<|tj| |ddO}|t | d||O}|rtj|t | } tj | rtj | r|t | ||||O}|} t| dd| d<|tj| |ddO}|t | d||O}qqW|Sty} ztddt|t| fidd} ~ ww) NFr*r+r)expandr3zDCould not recursively set attributes on %s. Original error was: '%s'r )r5walkr)r8r?copyr rset_fs_attributes_if_differentupdate_timestamp_for_filereadlinkexistsr6recursive_set_attributes RuntimeErrorr ) rEfollow file_argsmtimeatimechangedb_rootb_dirsb_filesb_fsobjb_fsname tmp_file_argsrFrrrrOXsB    $rOc Csd|id|id}||krc||dd<||dd<|dkrc|dkrcggd}t|d d }t|D]+\}}}|D]} tj|| } |d | q8|D]} tj|| } |d | qKq1||dd <|S)Nr))beforeafterr\r&r]r(r0) directoriesfilesr*r+r^r_ path_content)rr5rIr)r8append) r)r&r;diffwalklistrE base_path sub_foldersr_folder folderpathfilenamefilepathrrr initial_diffs*    rjc Csr|dkrdS|dkr tSzt||}t|}W|Sttfy8}ztdd||t|ddfidd}~ww)Npreservenowr3z?Error while obtaining timestamp for time %s using format %s: %s simplerepr nonstringr )rtimestrptimemktime ValueError OverflowErrorr r )formatted_time time_formatstruct struct_timerFrrrget_timestamp_for_times   ryc Cst|dd}z|tur$|tur$t}}t|j}t|j}d}nD|dur/|dur/WdSt|j}t|j}|durB|}n|turJt}|durQ|}n|turYt}||krd||krdWdS||f}tjsqt |||durd|vr}i|d<d|vri|d<||kr||dd<||dd<||kr||dd<||dd<Wd SWd SWd St y}zt dt |d d |d d d}~ww)Nr*r+Fr\r]rSrTz4Error while updating modification or access time: %srmrnr2r T) rrrpr5r@st_mtimest_atimer check_modeutimerBr r ) r)rSrTrbrEprevious_mtimeprevious_atimeset_timerFrrrrLs`            rLcCs,|dvr |dur dS|dkr|durdS|S)N)r1r4r0r'rktouchrlr) parameterr&rrr)keep_backward_compatibility_on_timestampss rcCsnt|dd}d}zt|d }|d}Wdn1swYWn ty.Y|Swd|vr5d}|S) z2Take a guess as to whether a file is a binary filer*r+Frbi NT)ropenread Exception)r)rEappears_binaryfheadrrrexecute_diff_peeks    rc Cst|dd}t|}i}|dkrvt|d|}tjsj|dkr>z tj|ddWnCty=}z tddt |id d}~wwzt |Wn$t yi}z|j t jkr_td t ||d d WYd}~nd}~ww||d |dd |S||ddd|S)Nr*r+r(r0F) ignore_errorsr3zrmtree failed: %sr zunlinking failed: %s r2T)r)rUrbr&)r)rUr&)rr9rjrr|shutilrmtreerr r r5unlinkrBrCrDupdate)r)rEr;resultrbrFrrr ensure_absents6     rc Cs:t|dd}t|}d}d|i}t|d|d}t|d|d}|d krWtjr/d |d <|Sz t|d d }WnttfyV} zt d t | dd|ddd} ~ wwt |d|} t tj } ztj| || dd}|t| d||| O}Wnty} z | jr|d krt|d} ~ ww||d <| |d<|S)Nr*r+Fdestmodification_timemodification_time_format access_timeaccess_time_formatr(TrUwbz!Error, could not touch target: %srmrnr2r rrGr)rb)rr9ryrr|rcloserBIOErrorr r rjload_file_common_argumentsr:rKrL SystemExitcoder5remove) r)rQ timestampsrEr;rUrrSrTrFrbrRrrr execute_touch%sH       rc Cst|dd}t|}ttj}t|d|d}t|d|d}|dkr@|r@|dkr@tj|}t |d d}t|}||d <|d vrQt d ||f||d dt |d|}tj |d|dd} | t |d |||O} || |dS)Nr*r+rrrrr1r'strictr)r1r4z file (%s) is %s, cannot continue)r3r)r&r FrGr)rUrb)rr9rrr:ryr5r)realpathr r rjrKrL) r)rQrrEr;rRrSrTrbrUrrrensure_file_attributesPs&        rc Cs6t|dd}t|}ttj}t|d|d}t|d|d}|r<|dkrsL vZ  .+ ; +GoZE