salt.modules.file#
Manage information about regular files, directories, and special files on the minion, set/read user, group, mode, and data
- class salt.modules.file.AttrChanges(added, removed)#
- added#
Alias for field number 0
- removed#
Alias for field number 1
- salt.modules.file.access(path, mode)#
New in version 2014.1.0.
Test whether the Salt process has the specified access to the file. One of the following modes must be specified:
f: Test the existence of the path r: Test the readability of the path w: Test the writability of the path x: Test whether the path can be executed
CLI Example:
salt '*' file.access /path/to/file f salt '*' file.access /path/to/file x
- salt.modules.file.append(path, *args, **kwargs)#
New in version 0.9.5.
Append text to the end of a file
- path
path to file
- *args
strings to append to file
CLI Example:
salt '*' file.append /etc/motd \ "With all thine offerings thou shalt offer salt." \ "Salt is what makes things taste bad when it isn't in them."
Attention
If you need to pass a string to append and that string contains an equal sign, you must include the argument name, args. For example:
salt '*' file.append /etc/motd args='cheese=spam' salt '*' file.append /etc/motd args="['cheese=spam','spam=cheese']"
- salt.modules.file.apply_template_on_contents(contents, template, context, defaults, saltenv)#
Return the contents after applying the templating engine
- contents
template string
- template
template format
- context
Overrides default context variables passed to the template.
- defaults
Default context passed to the template.
CLI Example:
salt '*' file.apply_template_on_contents \ contents='This is a {{ template }} string.' \ template=jinja \ context="{}" defaults="{'template': 'cool'}" \ saltenv=base
- salt.modules.file.basename(path)#
Returns the final component of a pathname
New in version 2015.5.0.
This can be useful at the CLI but is frequently useful when scripting.
{%- set filename = salt['file.basename'](source_file) %}
CLI Example:
salt '*' file.basename 'test/test.config'
- salt.modules.file.blockreplace(path, marker_start='#-- start managed zone --', marker_end='#-- end managed zone --', content='', append_if_not_found=False, prepend_if_not_found=False, backup='.bak', dry_run=False, show_changes=True, append_newline=False, insert_before_match=None, insert_after_match=None)#
New in version 2014.1.0.
Replace content of a text block in a file, delimited by line markers
A block of content delimited by comments can help you manage several lines entries without worrying about old entries removal.
Note
This function will store two copies of the file in-memory (the original version and the edited version) in order to detect changes and only edit the targeted file if necessary.
- path
Filesystem path to the file to be edited
- marker_start
The line content identifying a line as the start of the content block. Note that the whole line containing this marker will be considered, so whitespace or extra content before or after the marker is included in final output
- marker_end
The line content identifying the end of the content block. As of versions 2017.7.5 and 2018.3.1, everything up to the text matching the marker will be replaced, so it's important to ensure that your marker includes the beginning of the text you wish to replace.
- content
The content to be used between the two lines identified by marker_start and marker_stop.
- append_if_not_found: False
If markers are not found and set to
Truethen, the markers and content will be appended to the file.- prepend_if_not_found: False
If markers are not found and set to
Truethen, the markers and content will be prepended to the file.- insert_before_match
If markers are not found, this parameter can be set to a regex which will insert the block before the first found occurrence in the file.
New in version 3001.
- insert_after_match
If markers are not found, this parameter can be set to a regex which will insert the block after the first found occurrence in the file.
New in version 3001.
- backup
The file extension to use for a backup of the file if any edit is made. Set to
Falseto skip making a backup.- dry_run: False
If
True, do not make any edits to the file and simply return the changes that would be made.- show_changes: True
Controls how changes are presented. If
True, this function will return a unified diff of the changes made. If False, then it will return a boolean (Trueif any changes were made, otherwiseFalse).- append_newline: False
Controls whether or not a newline is appended to the content block. If the value of this argument is
Truethen a newline will be added to the content block. If it isFalse, then a newline will not be added to the content block. If it isNonethen a newline will only be added to the content block if it does not already end in a newline.New in version 2016.3.4.
Changed in version 2017.7.5,2018.3.1: New behavior added when value is
None.Changed in version 2019.2.0: The default value of this argument will change to
Noneto match the behavior of thefile.blockreplace state
CLI Example:
salt '*' file.blockreplace /etc/hosts '#-- start managed zone foobar : DO NOT EDIT --' \ '#-- end managed zone foobar --' $'10.0.1.1 foo.foobar\n10.0.1.2 bar.foobar' True
- salt.modules.file.chattr(*files, **kwargs)#
New in version 2018.3.0.
Change the attributes of files. This function accepts one or more files and the following options:
- operator
Can be wither
addorremove. Determines whether attributes should be added or removed from files- attributes
One or more of the following characters:
aAcCdDeijPsStTu, representing attributes to add to/remove from files- version
a version number to assign to the file(s)
- flags
One or more of the following characters:
RVf, representing flags to assign to chattr (recurse, verbose, suppress most errors)
CLI Example:
salt '*' file.chattr foo1.txt foo2.txt operator=add attributes=ai salt '*' file.chattr foo3.txt operator=remove attributes=i version=2
- salt.modules.file.check_file_meta(name, sfn, source, source_sum, user, group, mode, attrs, saltenv, contents=None, seuser=None, serole=None, setype=None, serange=None, verify_ssl=True, follow_symlinks=False, ignore_ordering=False, ignore_whitespace=False, ignore_comment_characters=None, new_file_diff=False)#
Check for the changes in the file metadata.
CLI Example:
salt '*' file.check_file_meta /etc/httpd/conf.d/httpd.conf None salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root root '755' None base
Note
Supported hash types include sha512, sha384, sha256, sha224, sha1, and md5.
- name
Path to file destination
- sfn
Template-processed source file contents
- source
URL to file source
- source_sum
File checksum information as a dictionary
{hash_type: md5, hsum: <md5sum>}
- user
Destination file user owner
- group
Destination file group owner
- mode
Destination file permissions mode
- attrs
Destination file attributes
New in version 2018.3.0.
- saltenv
Salt environment used to resolve source files
- contents
File contents
- seuser
selinux user attribute
New in version 3001.
- serole
selinux role attribute
New in version 3001.
- setype
selinux type attribute
New in version 3001.
- serange
selinux range attribute
New in version 3001.
- verify_ssl
If
False, remote https file sources (https://) will not attempt to validate the servers certificate. Default is True.New in version 3002.
- follow_symlinks
If the desired path is a symlink, follow it and check the permissions of the file to which the symlink points.
New in version 3005.
- ignore_ordering
If
True, changes in line order will be ignored ONLY for the purposes of triggering watch/onchanges requisites. Changes will still be made to the file to bring it into alignment with requested state, and also reported during the state run. This behavior is useful for bringing existing application deployments under Salt configuration management without disrupting production applications with a service restart.New in version 3007.0.
- ignore_whitespace
If
True, changes in whitespace will be ignored ONLY for the purposes of triggering watch/onchanges requisites. Changes will still be made to the file to bring it into alignment with requested state, and also reported during the state run. This behavior is useful for bringing existing application deployments under Salt configuration management without disrupting production applications with a service restart. Impliesignore_ordering=TrueNew in version 3007.0.
- ignore_comment_characters
If set to a chacter string, the presence of changes after that string will be ignored in changes found in the file ONLY for the purposes of triggering watch/onchanges requisites. Changes will still be made to the file to bring it into alignment with requested state, and also reported during the state run. This behavior is useful for bringing existing application deployments under Salt configuration management without disrupting production applications with a service restart. Implies
ignore_ordering=TrueNew in version 3007.0.
- new_file_diff
If
True, creation of new files will still show a diff in the changes return.New in version 3008.0.
- salt.modules.file.check_hash(path, file_hash)#
Check if a file matches the given hash string
Returns
Trueif the hash matches, otherwiseFalse.- path
Path to a file local to the minion.
- hash
The hash to check against the file specified in the
pathargument.Changed in version 2016.11.4.
For this and newer versions the hash can be specified without an accompanying hash type (e.g.
e138491e9d5b97023cea823fe17bac22), but for earlier releases it is necessary to also specify the hash type in the format<hash_type>=<hash_value>(e.g.md5=e138491e9d5b97023cea823fe17bac22).
CLI Example:
salt '*' file.check_hash /etc/fstab e138491e9d5b97023cea823fe17bac22 salt '*' file.check_hash /etc/fstab md5=e138491e9d5b97023cea823fe17bac22
- salt.modules.file.check_managed(name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, seuser=None, serole=None, setype=None, serange=None, follow_symlinks=False, **kwargs)#
Check to see what changes need to be made for a file
- follow_symlinks
If the desired path is a symlink, follow it and check the permissions of the file to which the symlink points.
New in version 3005.
CLI Example:
salt '*' file.check_managed /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base
- salt.modules.file.check_managed_changes(name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, keep_mode=False, seuser=None, serole=None, setype=None, serange=None, verify_ssl=True, follow_symlinks=False, ignore_ordering=False, ignore_whitespace=False, ignore_comment_characters=None, new_file_diff=False, **kwargs)#
Return a dictionary of what changes need to be made for a file
Changed in version 3001: selinux attributes added
- verify_ssl
If
False, remote https file sources (https://) and source_hash will not attempt to validate the servers certificate. Default is True.New in version 3002.
- follow_symlinks
If the desired path is a symlink, follow it and check the permissions of the file to which the symlink points.
New in version 3005.
- ignore_ordering
If
True, changes in line order will be ignored ONLY for the purposes of triggering watch/onchanges requisites. Changes will still be made to the file to bring it into alignment with requested state, and also reported during the state run. This behavior is useful for bringing existing application deployments under Salt configuration management without disrupting production applications with a service restart.New in version 3007.0.
- ignore_whitespace
If
True, changes in whitespace will be ignored ONLY for the purposes of triggering watch/onchanges requisites. Changes will still be made to the file to bring it into alignment with requested state, and also reported during the state run. This behavior is useful for bringing existing application deployments under Salt configuration management without disrupting production applications with a service restart. Impliesignore_ordering=TrueNew in version 3007.0.
- ignore_comment_characters
If set to a chacter string, the presence of changes after that string will be ignored in changes found in the file ONLY for the purposes of triggering watch/onchanges requisites. Changes will still be made to the file to bring it into alignment with requested state, and also reported during the state run. This behavior is useful for bringing existing application deployments under Salt configuration management without disrupting production applications with a service restart. Implies
ignore_ordering=TrueNew in version 3007.0.
- new_file_diff
If
True, creation of new files will still show a diff in the changes return.New in version 3008.0.
CLI Example:
salt '*' file.check_managed_changes /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base
- salt.modules.file.check_perms(name, ret, user, group, mode, attrs=None, follow_symlinks=False, seuser=None, serole=None, setype=None, serange=None)#
Changed in version 3001: Added selinux options
Check the permissions on files, modify attributes and chown if needed. File attributes are only verified if lsattr(1) is installed.
CLI Example:
salt '*' file.check_perms /etc/sudoers '{}' root root 400 ai
Changed in version 2014.1.3:
follow_symlinksoption added
- salt.modules.file.chgrp(path, group)#
Change the group of a file
- path
path to the file or directory
- group
group owner
CLI Example:
salt '*' file.chgrp /etc/passwd root
- salt.modules.file.chown(path, user, group)#
Chown a file, pass the file the desired user and group
- path
path to the file or directory
- user
user owner
- group
group owner
CLI Example:
salt '*' file.chown /etc/passwd root root
- salt.modules.file.comment(path, regex, char='#', backup='.bak')#
Deprecated since version 0.17.0: Use
replace()instead.Comment out specified lines in a file
- path
The full path to the file to be edited
- regex
A regular expression used to find the lines that are to be commented; this pattern will be wrapped in parenthesis and will move any preceding/trailing
^or$characters outside the parenthesis (e.g., the pattern^foo$will be rewritten as^(foo)$)- char:
# The character to be inserted at the beginning of a line in order to comment it out
- backup:
.bak The file will be backed up before edit with this file extension
Warning
This backup will be overwritten each time
sed/comment/uncommentis called. Meaning the backup will only be useful after the first invocation.
CLI Example:
salt '*' file.comment /etc/modules pcspkr
- salt.modules.file.comment_line(path, regex, char='#', cmnt=True, backup='.bak')#
Comment or Uncomment a line in a text file.
- Parameters:
path -- string The full path to the text file.
regex -- string A regex expression that begins with
^that will find the line you wish to comment. Can be as simple as^color =char -- string The character used to comment a line in the type of file you're referencing. Default is
#cmnt -- boolean True to comment the line. False to uncomment the line. Default is True.
backup -- string The file extension to give the backup file. Default is
.bakSet to False/None to not keep a backup.
- Returns:
boolean Returns True if successful, False if not
CLI Example:
The following example will comment out the
pcspkrline in the/etc/modulesfile using the default#character and create a backup file namedmodules.baksalt '*' file.comment_line '/etc/modules' '^pcspkr'
CLI Example:
The following example will uncomment the
log_levelsetting inminionconfig file if it is set to eitherwarning,info, ordebugusing the#character and create a backup file namedminion.bksalt '*' file.comment_line 'C:\salt\conf\minion' '^log_level: (warning|info|debug)' '#' False '.bk'
- salt.modules.file.contains(path, text)#
Deprecated since version 0.17.0: Use
search()instead.Return
Trueif the file atpathcontainstextCLI Example:
salt '*' file.contains /etc/crontab 'mymaintenance.sh'
- salt.modules.file.contains_glob(path, glob_expr)#
Deprecated since version 0.17.0: Use
search()instead.Return
Trueif the given glob matches a string in the named fileCLI Example:
salt '*' file.contains_glob /etc/foobar '*cheese*'
- salt.modules.file.contains_regex(path, regex, lchar='')#
Deprecated since version 0.17.0: Use
search()instead.Return True if the given regular expression matches on any line in the text of a given file.
If the lchar argument (leading char) is specified, it will strip lchar from the left side of each line before trying to match
CLI Example:
salt '*' file.contains_regex /etc/crontab
- salt.modules.file.copy(src, dst, recurse=False, remove_existing=False)#
Copy a file or directory from source to dst
In order to copy a directory, the recurse flag is required, and will by default overwrite files in the destination with the same path, and retain all other existing files. (similar to cp -r on unix)
remove_existing will remove all files in the target directory, and then copy files from the source.
Note
The copy function accepts paths that are local to the Salt minion. This function does not support salt://, http://, or the other additional file paths that are supported by
states.file.managedandstates.file.recurse.CLI Example:
salt '*' file.copy /path/to/src /path/to/dst salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True salt '*' file.copy /path/to/src_dir /path/to/dst_dir recurse=True remove_existing=True
- salt.modules.file.delete_backup(path, backup_id)#
New in version 0.17.0.
Delete a previous version of a file that was backed up using Salt's file state backup system.
- path
The path on the minion to check for backups
- backup_id
The numeric id for the backup you wish to delete, as found using
file.list_backups
CLI Example:
salt '*' file.delete_backup /var/cache/salt/minion/file_backup/home/foo/bar/baz.txt 0
- salt.modules.file.directory_exists(path)#
Tests to see if path is a valid directory. Returns True/False.
CLI Example:
salt '*' file.directory_exists /etc
- salt.modules.file.dirname(path)#
Returns the directory component of a pathname
New in version 2015.5.0.
This can be useful at the CLI but is frequently useful when scripting.
{%- from salt['file.dirname'](tpldir) + '/vars.jinja' import parent_vars %}
CLI Example:
salt '*' file.dirname 'test/path/filename.config'
- salt.modules.file.diskusage(path)#
Recursively calculate disk usage of path and return it in bytes
CLI Example:
salt '*' file.diskusage /path/to/check
- salt.modules.file.extract_hash(hash_fn, hash_type='sha256', file_name='', source='', source_hash_name=None)#
Changed in version 2016.3.5: Prior to this version, only the
file_nameargument was considered for filename matches in the hash file. This would be problematic for cases in which the user was relying on a remote checksum file that they do not control, and they wished to use a different name for that file on the minion from the filename on the remote server (and in the checksum file). For example, managing/tmp/myfile.tar.gzwhen the remote file was athttps://mydomain.tld/different_name.tar.gz. Thefile.managedstate now also passes this function the source URI as well as thesource_hash_name(if specified). In cases wheresource_hash_nameis specified, it takes precedence over both thefile_nameandsource. When it is not specified,file_nametakes precedence oversource. This allows for better capability for matching hashes.Changed in version 2016.11.0: File name and source URI matches are no longer disregarded when
source_hash_nameis specified. They will be used as fallback matches if there is no match to thesource_hash_namevalue.This routine is called from the
file.managedstate to pull a hash from a remote file. Regular expressions are used line by line on thesource_hashfile, to find a potential candidate of the indicated hash type. This avoids many problems of arbitrary file layout rules. It specifically permits pulling hash codes from debian*.dscfiles.If no exact match of a hash and filename are found, then the first hash found (if any) will be returned. If no hashes at all are found, then
Nonewill be returned.For example:
openerp_7.0-latest-1.tar.gz: file.managed: - name: /tmp/openerp_7.0-20121227-075624-1_all.deb - source: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.tar.gz - source_hash: http://nightly.openerp.com/7.0/nightly/deb/openerp_7.0-20121227-075624-1.dsc
CLI Example:
salt '*' file.extract_hash /path/to/hash/file sha512 /etc/foo
- salt.modules.file.file_exists(path)#
Tests to see if path is a valid file. Returns True/False.
CLI Example:
salt '*' file.file_exists /etc/passwd
- salt.modules.file.find(path, *args, **kwargs)#
Approximate the Unix
find(1)command and return a list of paths that meet the specified criteria.The options include match criteria:
name = path-glob # case sensitive iname = path-glob # case insensitive regex = path-regex # case sensitive iregex = path-regex # case insensitive type = file-types # match any listed type owner = users # match any listed user group = groups # match any listed group size = [+-]number[size-unit] # default unit = byte mtime = interval # modified since date grep = regex # search file contents
and/or actions:
delete [= file-types] # default type = 'f' exec = command [arg ...] # where {} is replaced by pathname print [= print-opts]and/or depth criteria:
maxdepth = maximum depth to transverse in path mindepth = minimum depth to transverse before checking files or directories
The default action is
print=pathpath-glob:* = match zero or more chars ? = match any char [abc] = match a, b, or c [!abc] or [^abc] = match anything except a, b, and c [x-y] = match chars x through y [!x-y] or [^x-y] = match anything except chars x through y {a,b,c} = match a or b or cpath-regex: a Python Regex (regular expression) pattern to match pathnamesfile-types: a string of one or more of the following:a: all file types b: block device c: character device d: directory p: FIFO (named pipe) f: plain file l: symlink s: socket
users: a space and/or comma separated list of user names and/or uidsgroups: a space and/or comma separated list of group names and/or gidssize-unit:b: bytes k: kilobytes m: megabytes g: gigabytes t: terabytes
interval:
[<num>w] [<num>d] [<num>h] [<num>m] [<num>s] where: w: week d: day h: hour m: minute s: secondprint-opts: a comma and/or space separated list of one or more of the following:
group: group name md5: MD5 digest of file contents mode: file permissions (as integer) mtime: last modification time (as time_t) name: file basename path: file absolute path size: file size in bytes type: file type owner: user name
CLI Examples:
salt '*' file.find / type=f name=\*.bak size=+10m salt '*' file.find /var mtime=+30d size=+10m print=path,size,mtime salt '*' file.find /var/log name=\*.[0-9] mtime=+30d size=+10m delete
- salt.modules.file.get_devmm(name)#
Get major/minor info from a device
CLI Example:
salt '*' file.get_devmm /dev/chr
- salt.modules.file.get_diff(file1, file2, saltenv='base', show_filenames=True, show_changes=True, template=False, source_hash_file1=None, source_hash_file2=None, ignore_ordering=False, ignore_whitespace=False, ignore_comment_characters=None)#
Return unified diff of two files
- file1
The first file to feed into the diff utility
Changed in version 2018.3.0: Can now be either a local or remote file. In earlier releases, thuis had to be a file local to the minion.
- file2
The second file to feed into the diff utility
Changed in version 2018.3.0: Can now be either a local or remote file. In earlier releases, this had to be a file on the salt fileserver (i.e.
salt://somefile.txt)- show_filenames: True
Set to
Falseto hide the filenames in the top two lines of the diff.- show_changes: True
If set to
False, and there are differences, then instead of a diff a simple message stating that show_changes is set toFalsewill be returned.- template: False
Set to
Trueif two templates are being compared. This is not useful except for within states, with theobfuscate_templatesoption set toTrue.New in version 2018.3.0.
- source_hash_file1
If
file1is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash.New in version 2018.3.0.
- source_hash_file2
If
file2is an http(s)/ftp URL and the file exists in the minion's file cache, this option can be passed to keep the minion from re-downloading the archive if the cached copy matches the specified hash.New in version 2018.3.0.
- ignore_ordering
If
True, changes in line order will be ignored ONLY for the purposes of triggering watch/onchanges requisites. Changes will still be made to the file to bring it into alignment with requested state, and also reported during the state run. This behavior is useful for bringing existing application deployments under Salt configuration management without disrupting production applications with a service restart.New in version 3007.0.
- ignore_whitespace
If
True, changes in whitespace will be ignored ONLY for the purposes of triggering watch/onchanges requisites. Changes will still be made to the file to bring it into alignment with requested state, and also reported during the state run. This behavior is useful for bringing existing application deployments under Salt configuration management without disrupting production applications with a service restart. Impliesignore_ordering=TrueNew in version 3007.0.
- ignore_comment_characters
If set to a chacter string, the presence of changes after that string will be ignored in changes found in the file ONLY for the purposes of triggering watch/onchanges requisites. Changes will still be made to the file to bring it into alignment with requested state, and also reported during the state run. This behavior is useful for bringing existing application deployments under Salt configuration management without disrupting production applications with a service restart. Implies
ignore_ordering=TrueNew in version 3007.0.
CLI Examples:
salt '*' file.get_diff /home/fred/.vimrc salt://users/fred/.vimrc salt '*' file.get_diff /tmp/foo.txt /tmp/bar.txt
- salt.modules.file.get_gid(path, follow_symlinks=True)#
Return the id of the group that owns a given file
- path
file or directory of which to get the gid
- follow_symlinks
indicated if symlinks should be followed
CLI Example:
salt '*' file.get_gid /etc/passwd
Changed in version 0.16.4:
follow_symlinksoption added
- salt.modules.file.get_group(path, follow_symlinks=True)#
Return the group that owns a given file
- path
file or directory of which to get the group
- follow_symlinks
indicated if symlinks should be followed
CLI Example:
salt '*' file.get_group /etc/passwd
Changed in version 0.16.4:
follow_symlinksoption added
- salt.modules.file.get_hash(path, form='sha256', chunk_size=65536)#
Get the hash sum of a file
- This is better than
get_sumfor the following reasons: It does not read the entire file into memory.
- It does not return a string on error. The returned value of
get_sumcannot really be trusted since it is vulnerable to collisions:get_sum(..., 'xyz') == 'Hash xyz not supported'
- path
path to the file or directory
- form
desired sum format
- chunk_size
amount to sum at once
CLI Example:
salt '*' file.get_hash /etc/shadow
- This is better than
- salt.modules.file.get_managed(name, template, source, source_hash, source_hash_name, user, group, mode, attrs, saltenv, context, defaults, skip_verify=False, verify_ssl=True, use_etag=False, source_hash_sig=None, signed_by_any=None, signed_by_all=None, keyring=None, gnupghome=None, ignore_ordering=False, ignore_whitespace=False, ignore_comment_characters=None, sig_backend='gpg', **kwargs)#
Return the managed file data for file.managed
- name
location where the file lives on the minion
- template
template format
- source
managed source file
- source_hash
hash of the source file
- source_hash_name
When
source_hashrefers to a remote file, this specifies the filename to look for in that file.New in version 2016.3.5.
- user
Owner of file
- group
Group owner of file
- mode
Permissions of file
- attrs
Attributes of file
New in version 2018.3.0.
- context
Variables to add to the template context
- defaults
Default values of for context_dict
- skip_verify
If
True, hash verification of remote file sources (http://,https://,ftp://) will be skipped, and thesource_hashargument will be ignored.New in version 2016.3.0.
- verify_ssl
If
False, remote https file sources (https://) and source_hash will not attempt to validate the servers certificate. Default is True.New in version 3002.
- use_etag
If
True, remote http/https file sources will attempt to use the ETag header to determine if the remote file needs to be downloaded. This provides a lightweight mechanism for promptly refreshing files changed on a web server without requiring a full hash comparison via thesource_hashparameter.New in version 3005.
- source_hash_sig
When
sourceis a remote file source,source_hashis a file,skip_verifyis not true anduse_etagis not true, ensure a valid signature exists on the source hash file. Set this totruefor an inline (clearsigned) signature, or to a file URI retrievable by :py:func:`cp.cache_file <salt.modules.cp.cache_file> for a detached one.New in version 3007.0.
- signed_by_any
When verifying
source_hash_sig, require at least one valid signature from one of a list of keys. By default, this is passed togpg.verify, meaning a key is identified by its fingerprint.New in version 3007.0.
- signed_by_all
When verifying
source_hash_sig, require a valid signature from each of the keys in this list. By default, this is passed togpg.verify, meaning a key is identified by its fingerprint.New in version 3007.0.
- keyring
When verifying
source_hash_sig, use this keyring.New in version 3007.0.
- gnupghome
When verifying
source_hash_sig, use this GnuPG home.New in version 3007.0.
- ignore_ordering
If
True, changes in line order will be ignored ONLY for the purposes of triggering watch/onchanges requisites. Changes will still be made to the file to bring it into alignment with requested state, and also reported during the state run. This behavior is useful for bringing existing application deployments under Salt configuration management without disrupting production applications with a service restart.New in version 3007.0.
- ignore_whitespace
If
True, changes in whitespace will be ignored ONLY for the purposes of triggering watch/onchanges requisites. Changes will still be made to the file to bring it into alignment with requested state, and also reported during the state run. This behavior is useful for bringing existing application deployments under Salt configuration management without disrupting production applications with a service restart. Impliesignore_ordering=TrueNew in version 3007.0.
- ignore_comment_characters
If set to a chacter string, the presence of changes after that string will be ignored in changes found in the file ONLY for the purposes of triggering watch/onchanges requisites. Changes will still be made to the file to bring it into alignment with requested state, and also reported during the state run. This behavior is useful for bringing existing application deployments under Salt configuration management without disrupting production applications with a service restart. Implies
ignore_ordering=TrueNew in version 3007.0.
- sig_backend
When verifying signatures, use this execution module as a backend. It must be compatible with the
gpg.verifyAPI. Defaults togpg. All signature-related parameters are passed through.New in version 3008.0.
CLI Example:
salt '*' file.get_managed /etc/httpd/conf.d/httpd.conf jinja salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' None root root '755' base None None
- salt.modules.file.get_mode(path, follow_symlinks=True)#
Return the mode of a file
- path
file or directory of which to get the mode
- follow_symlinks
indicated if symlinks should be followed
CLI Example:
salt '*' file.get_mode /etc/passwd
Changed in version 2014.1.0:
follow_symlinksoption added
- salt.modules.file.get_selinux_context(path)#
Get an SELinux context from a given path
CLI Example:
salt '*' file.get_selinux_context /etc/hosts
- salt.modules.file.get_source_sum(file_name='', source='', source_hash=None, source_hash_name=None, saltenv='base', verify_ssl=True, source_hash_sig=None, signed_by_any=None, signed_by_all=None, keyring=None, gnupghome=None, sig_backend='gpg')#
New in version 2016.11.0.
Used by
file.get_managedto obtain the hash and hash type from the parameters specified below.- file_name
Optional file name being managed, for matching with
file.extract_hash.- source
Source file, as used in
fileand other states. Ifsource_hashrefers to a file containing hashes, then this filename will be used to match a filename in that file. If thesource_hashis a hash expression, then this argument will be ignored.- source_hash
Hash file/expression, as used in
fileand other states. If this value refers to a remote URL or absolute path to a local file, it will be cached andfile.extract_hashwill be used to obtain a hash from it.- source_hash_name
Specific file name to look for when
source_hashrefers to a remote file, used to disambiguate ambiguous matches.- saltenv: base
Salt fileserver environment from which to retrieve the source_hash. This value will only be used when
source_hashrefers to a file on the Salt fileserver (i.e. one beginning withsalt://).- verify_ssl
If
False, remote https file sources (https://) and source_hash will not attempt to validate the servers certificate. Default is True.New in version 3002.
- source_hash_sig
When
sourceis a remote file source andsource_hashis a file, ensure a valid signature exists on the source hash file. Set this totruefor an inline (clearsigned) signature, or to a file URI retrievable by :py:func:`cp.cache_file <salt.modules.cp.cache_file> for a detached one.New in version 3007.0.
- signed_by_any
When verifying
source_hash_sig, require at least one valid signature from one of a list of keys. By default, this is passed togpg.verify, meaning a key is identified by its fingerprint.New in version 3007.0.
- signed_by_all
When verifying
source_hash_sig, require a valid signature from each of the keys in this list. By default, this is passed togpg.verify, meaning a key is identified by its fingerprint.New in version 3007.0.
- keyring
When verifying
source_hash_sig, use this keyring.New in version 3007.0.
- gnupghome
When verifying
source_hash_sig, use this GnuPG home.New in version 3007.0.
- sig_backend
When verifying signatures, use this execution module as a backend. It must be compatible with the
gpg.verifyAPI. Defaults togpg. All signature-related parameters are passed through.New in version 3008.0.
CLI Example:
salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=499ae16dcae71eeb7c3a30c75ea7a1a6 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 salt '*' file.get_source_sum /tmp/foo.tar.gz source=http://mydomain.tld/foo.tar.gz source_hash=https://mydomain.tld/hashes.md5 source_hash_name=./dir2/foo.tar.gz
- salt.modules.file.get_sum(path, form='sha256')#
Return the checksum for the given file. The following checksum algorithms are supported:
md5
sha1
sha224
sha256 (default)
sha384
sha512
- path
path to the file or directory
- form
desired sum format
CLI Example:
salt '*' file.get_sum /etc/passwd sha512
- salt.modules.file.get_uid(path, follow_symlinks=True)#
Return the id of the user that owns a given file
- path
file or directory of which to get the uid
- follow_symlinks
indicated if symlinks should be followed
CLI Example:
salt '*' file.get_uid /etc/passwd
Changed in version 0.16.4:
follow_symlinksoption added
- salt.modules.file.get_user(path, follow_symlinks=True)#
Return the user that owns a given file
- path
file or directory of which to get the user
- follow_symlinks
indicated if symlinks should be followed
CLI Example:
salt '*' file.get_user /etc/passwd
Changed in version 0.16.4:
follow_symlinksoption added
- salt.modules.file.gid_to_group(gid)#
Convert the group id to the group name on this system
- gid
gid to convert to a group name
CLI Example:
salt '*' file.gid_to_group 0
- salt.modules.file.grep(path, pattern, *opts)#
Grep for a string in the specified file
Note
This function's return value is slated for refinement in future versions of Salt
Windows does not support the
grepfunctionality.- path
Path to the file to be searched
Note
Globbing is supported (i.e.
/var/log/foo/*.log, but if globbing is being used then the path should be quoted to keep the shell from attempting to expand the glob expression.- pattern
Pattern to match. For example:
test, ora[0-5]- opts
Additional command-line flags to pass to the grep command. For example:
-v, or-i -B2Note
The options should come after a double-dash (as shown in the examples below) to keep Salt's own argument parser from interpreting them.
CLI Example:
salt '*' file.grep /etc/passwd nobody salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i salt '*' file.grep /etc/sysconfig/network-scripts/ifcfg-eth0 ipaddr -- -i -B2 salt '*' file.grep "/etc/sysconfig/network-scripts/*" ipaddr -- -i -l
- salt.modules.file.group_to_gid(group)#
Convert the group to the gid on this system
- group
group to convert to its gid
CLI Example:
salt '*' file.group_to_gid root
- salt.modules.file.is_blkdev(name)#
Check if a file exists and is a block device.
CLI Example:
salt '*' file.is_blkdev /dev/blk
- salt.modules.file.is_chrdev(name)#
Check if a file exists and is a character device.
CLI Example:
salt '*' file.is_chrdev /dev/chr
- salt.modules.file.is_fifo(name)#
Check if a file exists and is a FIFO.
CLI Example:
salt '*' file.is_fifo /dev/fifo
- salt.modules.file.is_hardlink(path)#
Check if the path is a hard link by verifying that the number of links is larger than 1
CLI Example:
salt '*' file.is_hardlink /path/to/link
- salt.modules.file.is_link(path, nostat=False)#
Check if the path is a symbolic link
- Parameters:
path (str) -- The path to check if it is a link.
nostat (bool) --
Use information from parent directory to determine if entry is a symbolic link. This avoids the stat operation, which may hang under certain circumstances. For example, NFS mounts which have gone offline or are suffering some network issues. This will make the check quite slower on parent directories with a lot of files, but will reduce the chances of hanging.
New in version 3008.0.
- Returns:
Trueif a symbolic link, otherwise returnsFalse.- Return type:
CLI Example:
salt '*' file.is_link /path/to/link
- salt.modules.file.join(*args)#
Return a normalized file system path for the underlying OS
New in version 2014.7.0.
This can be useful at the CLI but is frequently useful when scripting combining path variables:
{% set www_root = '/var' %} {% set app_dir = 'myapp' %} myapp_config: file: - managed - name: {{ salt['file.join'](www_root, app_dir, 'config.yaml') }}
CLI Example:
salt '*' file.join '/' 'usr' 'local' 'bin'
- salt.modules.file.lchown(path, user, group)#
Chown a file, pass the file the desired user and group without following symlinks.
- path
path to the file or directory
- user
user owner
- group
group owner
CLI Example:
salt '*' file.chown /etc/passwd root root
- salt.modules.file.line(path, content=None, match=None, mode=None, location=None, before=None, after=None, show_changes=True, backup=False, quiet=False, indent=True)#
New in version 2015.8.0.
Line-focused editing of a file.
Note
file.lineexists for historic reasons, and is not generally recommended. It has a lot of quirks. You may findfile.replaceto be more suitable.file.lineis most useful if you have single lines in a file (potentially a config file) that you would like to manage. It can remove, add, and replace a single line at a time.- path
Filesystem path to the file to be edited.
- content
Content of the line. Allowed to be empty if
mode='delete'.- match
Match the target line for an action by a fragment of a string or regular expression.
If neither
beforenorafterare provided, andmatchis alsoNone, match falls back to thecontentvalue.- mode
Defines how to edit a line. One of the following options is required:
- ensure
If line does not exist, it will be added. If
beforeandafterare specified either zero lines, or lines that contain thecontentline are allowed to be in betweenbeforeandafter. If there are lines, and none of them match then it will produce an error.
- replace
If line already exists, the entire line will be replaced.
- delete
Delete the line, if found.
- insert
Nearly identical to
ensure. If a line does not exist, it will be added.The differences are that multiple (and non-matching) lines are allowed between
beforeandafter, if they are specified. The line will always be inserted right beforebefore.insertalso allows the use oflocationto specify that the line should be added at the beginning or end of the file.
Note
If
mode='insert'is used, at least one oflocation,before, orafteris required. Iflocationis used,beforeandafterare ignored.- location
In
mode='insert'only, whether to place thecontentat the beginning or end of a the file. Iflocationis provided,beforeandafterare ignored. Valid locations:- start
Place the content at the beginning of the file.
- end
Place the content at the end of the file.
- before
Regular expression or an exact case-sensitive fragment of the string. Will be tried as both a regex and a part of the line. Must match exactly one line in the file. This value is only used in
ensureandinsertmodes. Thecontentwill be inserted just before this line, with matching indentation unlessindent=False.- after
Regular expression or an exact case-sensitive fragment of the string. Will be tried as both a regex and a part of the line. Must match exactly one line in the file. This value is only used in
ensureandinsertmodes. Thecontentwill be inserted directly after this line, unlessbeforeis also provided. Ifbeforeis not provided, indentation will match this line, unlessindent=False.- show_changes
Output a unified diff of the old file and the new file. If
Falsereturn a boolean if any changes were made. Default isTrueNote
Using this option will store two copies of the file in-memory (the original version and the edited version) in order to generate the diff.
- backup
Create a backup of the original file with the extension: "Year-Month-Day-Hour-Minutes-Seconds".
- quiet
Do not raise any exceptions. E.g. ignore the fact that the file that is tried to be edited does not exist and nothing really happened.
- indent
Keep indentation with the previous line. This option is not considered when the
deletemode is specified. Default isTrue
CLI Example:
salt '*' file.line /etc/nsswitch.conf "networks: files dns" after="hosts:.*?" mode='ensure'
Note
If an equal sign (
=) appears in an argument to a Salt command, it is interpreted as a keyword argument in the format ofkey=val. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg:salt '*' file.line /path/to/file content="CREATEMAIL_SPOOL=no" match="CREATE_MAIL_SPOOL=yes" mode="replace"
Examples:
Here's a simple config file.
[some_config] # Some config file # this line will go away here=False away=True goodybe=away
salt \* file.line /some/file.conf mode=delete match=away
This will produce:
[some_config] # Some config file here=False away=True goodbye=away
If that command is executed 2 more times, this will be the result:
[some_config] # Some config file here=False
If we reset the file to its original state and run
salt \* file.line /some/file.conf mode=replace match=away content=here
Three passes will this state will result in this file:
[some_config] # Some config file here here=False here here
Each pass replacing the first line found.
Given this file:
insert after me something insert before me
The following command
salt \* file.line /some/file.txt mode=insert after="insert after me" before="insert before me" content=thrice
If that command is executed 3 times, the result will be:
insert after me something thrice thrice thrice insert before me
If the mode is
ensureinstead, it will fail each time. To succeed, we need to remove the incorrect line between before and after:insert after me insert before me
With an ensure mode, this will insert
thricethe first time and make no changes for subsequent calls. For something simple this is fine, but if you have instead blocks like this:Begin SomeBlock foo = bar End Begin AnotherBlock another = value EndAnd you try to use ensure this way:
salt \* file.line /tmp/fun.txt mode="ensure" content="this = should be my content" after="Begin SomeBlock" before="End"
This will fail because there are multiple
Endlines. Without that problem, it still would fail because there is a non-matching line,foo = bar. Ensure only allows either zero, or the matching line present to be present in betweenbeforeandafter.
- salt.modules.file.link(src, path)#
New in version 2014.1.0.
Create a hard link to a file
CLI Example:
salt '*' file.link /path/to/file /path/to/link
- salt.modules.file.list_backup(path, limit=None)#
This function is an alias of
list_backups.New in version 0.17.0.
Lists the previous versions of a file backed up using Salt's file state backup system.
- path
The path on the minion to check for backups
- limit
Limit the number of results to the most recent N backups
CLI Example:
salt '*' file.list_backups /foo/bar/baz.txt
- salt.modules.file.list_backups(path, limit=None)#
New in version 0.17.0.
Lists the previous versions of a file backed up using Salt's file state backup system.
- path
The path on the minion to check for backups
- limit
Limit the number of results to the most recent N backups
CLI Example:
salt '*' file.list_backups /foo/bar/baz.txt
- salt.modules.file.list_backups_dir(path, limit=None)#
Lists the previous versions of a directory backed up using Salt's file state backup system.
- path
The directory on the minion to check for backups
- limit
Limit the number of results to the most recent N backups
CLI Example:
salt '*' file.list_backups_dir /foo/bar/baz/
- salt.modules.file.lsattr(path)#
New in version 2018.3.0.
Changed in version 2018.3.1: If
lsattris not installed on the system,Noneis returned.Changed in version 2018.3.4: If on
AIX,Noneis returned even if in filesystem as lsattr onAIXis not the same thing as the linux version.Obtain the modifiable attributes of the given file. If path is to a directory, an empty list is returned.
- path
path to file to obtain attributes of. File/directory must exist.
CLI Example:
salt '*' file.lsattr foo1.txt
- salt.modules.file.lstat(path)#
New in version 2014.1.0.
Returns the lstat attributes for the given file or dir. Does not support symbolic links.
CLI Example:
salt '*' file.lstat /path/to/file
- salt.modules.file.makedirs_(path, user=None, group=None, mode=None)#
Ensure that the directory containing this path is available.
Note
The path must end with a trailing slash otherwise the directory/directories will be created up to the parent directory. For example if path is
/opt/code, then it would be treated as/opt/but if the path ends with a trailing slash like/opt/code/, then it would be treated as/opt/code/.CLI Example:
salt '*' file.makedirs /opt/code/
- salt.modules.file.makedirs_perms(name, user=None, group=None, mode='0755')#
Taken and modified from os.makedirs to set user, group and mode for each directory created.
CLI Example:
salt '*' file.makedirs_perms /opt/code
- salt.modules.file.manage_file(name, sfn, ret, source, source_sum, user, group, mode, attrs, saltenv, backup, makedirs=False, template=None, show_changes=True, contents=None, dir_mode=None, follow_symlinks=True, skip_verify=False, keep_mode=False, encoding=None, encoding_errors='strict', seuser=None, serole=None, setype=None, serange=None, verify_ssl=True, use_etag=False, signature=None, source_hash_sig=None, signed_by_any=None, signed_by_all=None, keyring=None, gnupghome=None, ignore_ordering=False, ignore_whitespace=False, ignore_comment_characters=None, new_file_diff=False, sig_backend='gpg', **kwargs)#
Checks the destination against what was retrieved with get_managed and makes the appropriate modifications (if necessary).
- name
The location of the file to be managed, as an absolute path.
- sfn
location of cached file on the minion
This is the path to the file stored on the minion. This file is placed on the minion using cp.cache_file. If the hash sum of that file matches the source_sum, we do not transfer the file to the minion again.
This file is then grabbed and if it has template set, it renders the file to be placed into the correct place on the system using salt.files.utils.copyfile()
- ret
The initial state return data structure. Pass in
Noneto use the default structure.- source
The source file to download to the minion, this source file can be hosted on either the salt master server (
salt://), the salt minion local file system (/), or on an HTTP or FTP server (http(s)://,ftp://).Both HTTPS and HTTP are supported as well as downloading directly from Amazon S3 compatible URLs with both pre-configured and automatic IAM credentials. (see s3.get state documentation) File retrieval from Openstack Swift object storage is supported via swift://container/object_path URLs, see swift.get documentation. For files hosted on the salt file server, if the file is located on the master in the directory named spam, and is called eggs, the source string is salt://spam/eggs. If source is left blank or None (use ~ in YAML), the file will be created as an empty file and the content will not be managed. This is also the case when a file already exists and the source is undefined; the contents of the file will not be changed or managed. If source is left blank or None, please also set replaced to False to make your intention explicit.
If the file is hosted on a HTTP or FTP server then the source_hash argument is also required.
- source_sum
sum hash for source
- user
The user to own the file, this defaults to the user salt is running as on the minion
- group
The group ownership set for the file, this defaults to the group salt is running as on the minion. On Windows, this is ignored
- mode
The permissions to set on this file, e.g.
644,0775, or4664.The default mode for new files and directories corresponds to the umask of the salt process. The mode of existing files and directories will only be changed if
modeis specified.Note
This option is not supported on Windows.
- attrs
The attributes to have on this file, e.g.
a,i. The attributes can be any or a combination of the following characters:aAcCdDeijPsStTu.Note
This option is not supported on Windows.
New in version 2018.3.0.
- saltenv
Specify the environment from which to retrieve the file indicated by the
sourceparameter. If not provided, this defaults to the environment from which the state is being executed.Note
Ignored when the source file is from a non-
salt://source..- backup
Overrides the default backup mode for this specific file. See backup_mode documentation for more details.
- makedirs
If set to
True, then the parent directories will be created to facilitate the creation of the named file. IfFalse, and the parent directory of the destination file doesn't exist, the state will fail.- template
If this setting is applied, the named templating engine will be used to render the downloaded file. The following templates are supported:
Note
The template option is required when recursively applying templates.
- show_changes
Output a unified diff of the old file and the new file. If
Falsereturn a boolean if any changes were made. Default isTrueNote
Using this option will store two copies of the file in-memory (the original version and the edited version) in order to generate the diff.
- contents:
Specify the contents of the file. Cannot be used in combination with
source. Ignores hashes and does not use a templating engine.- dir_mode
If directories are to be created, passing this option specifies the permissions for those directories. If this is not set, directories will be assigned permissions by adding the execute bit to the mode of the files.
The default mode for new files and directories corresponds umask of salt process. For existing files and directories it's not enforced.
- skip_verify: False
If
True, hash verification of remote file sources (http://,https://,ftp://) will be skipped, and thesource_hashargument will be ignored.New in version 2016.3.0.
- keep_mode: False
If
True, and thesourceis a file from the Salt fileserver (or a local file on the minion), the mode of the destination file will be set to the mode of the source file.Note
keep_mode does not work with salt-ssh.
As a consequence of how the files are transferred to the minion, and the inability to connect back to the master with salt-ssh, salt is unable to stat the file as it exists on the fileserver and thus cannot mirror the mode on the salt-ssh minion
- encoding
If specified, then the specified encoding will be used. Otherwise, the file will be encoded using the system locale (usually UTF-8). See https://docs.python.org/3/library/codecs.html#standard-encodings for the list of available encodings.
New in version 2017.7.0.
- encoding_errors: 'strict'
Default is
`'strict'`. See https://docs.python.org/2/library/codecs.html#codec-base-classes for the error handling schemes.New in version 2017.7.0.
- seuser
selinux user attribute
New in version 3001.
- serange
selinux range attribute
New in version 3001.
- setype
selinux type attribute
New in version 3001.
- serange
selinux range attribute
New in version 3001.
- verify_ssl
If
False, remote https file sources (https://) will not attempt to validate the servers certificate. Default is True.New in version 3002.
- use_etag
If
True, remote http/https file sources will attempt to use the ETag header to determine if the remote file needs to be downloaded. This provides a lightweight mechanism for promptly refreshing files changed on a web server without requiring a full hash comparison via thesource_hashparameter.New in version 3005.
- signature
Ensure a valid signature exists on the selected
sourcefile. Set this to true for inline signatures, or to a file URI retrievable by :py:func:`cp.cache_file <salt.modules.cp.cache_file> for a detached one.Note
A signature is only enforced directly after caching the file, before it is moved to its final destination. Existing target files (with the correct checksum) will neither be checked nor deleted.
It will be enforced regardless of source type and will be required on the final output, therefore this does not lend itself well when templates are rendered. The file will not be modified, meaning inline signatures are not removed.
New in version 3007.0.
- source_hash_sig
When
sourceis a remote file source,source_hashis a file,skip_verifyis not true anduse_etagis not true, ensure a valid signature exists on the source hash file. Set this totruefor an inline (clearsigned) signature, or to a file URI retrievable by :py:func:`cp.cache_file <salt.modules.cp.cache_file> for a detached one.Note
A signature on the
source_hashfile is enforced regardless of changes since its contents are used to check if an existing file is in the correct state - but only for remote sources! As forsignature, existing target files will not be modified, only the cached source_hash and source_hash_sig files will be removed.New in version 3007.0.
- signed_by_any
When verifying signatures either on the managed file or its source hash file, require at least one valid signature from one of a list of keys. By default, this is passed to
gpg.verify, meaning a key is identified by its fingerprint.New in version 3007.0.
- signed_by_all
When verifying signatures either on the managed file or its source hash file, require a valid signature from each of the keys in this list. By default, this is passed to
gpg.verify, meaning a key is identified by its fingerprint.New in version 3007.0.
- keyring
When verifying signatures, use this keyring.
New in version 3007.0.
- gnupghome
When verifying signatures, use this GnuPG home.
New in version 3007.0.
- ignore_ordering
If
True, changes in line order will be ignored ONLY for the purposes of triggering watch/onchanges requisites. Changes will still be made to the file to bring it into alignment with requested state, and also reported during the state run. This behavior is useful for bringing existing application deployments under Salt configuration management without disrupting production applications with a service restart.New in version 3007.0.
- ignore_whitespace
If
True, changes in whitespace will be ignored ONLY for the purposes of triggering watch/onchanges requisites. Changes will still be made to the file to bring it into alignment with requested state, and also reported during the state run. This behavior is useful for bringing existing application deployments under Salt configuration management without disrupting production applications with a service restart. Impliesignore_ordering=TrueNew in version 3007.0.
- ignore_comment_characters
If set to a chacter string, the presence of changes after that string will be ignored in changes found in the file ONLY for the purposes of triggering watch/onchanges requisites. Changes will still be made to the file to bring it into alignment with requested state, and also reported during the state run. This behavior is useful for bringing existing application deployments under Salt configuration management without disrupting production applications with a service restart. Implies
ignore_ordering=TrueNew in version 3007.0.
- new_file_diff
If
True, creation of new files will still show a diff in the changes return.New in version 3008.0.
- sig_backend
When verifying signatures, use this execution module as a backend. It must be compatible with the
gpg.verifyAPI. Defaults togpg. All signature-related parameters are passed through.New in version 3008.0.
CLI Example:
salt '*' file.manage_file /etc/httpd/conf.d/httpd.conf '' '{}' salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root root '755' '' base ''
Changed in version 2014.7.0:
follow_symlinksoption added
- salt.modules.file.mkdir(dir_path, user=None, group=None, mode=None)#
Ensure that a directory is available.
CLI Example:
salt '*' file.mkdir /opt/jetty/context
- salt.modules.file.mknod(name, ntype, major=0, minor=0, user=None, group=None, mode='0600')#
New in version 0.17.0.
Create a block device, character device, or fifo pipe. Identical to the gnu mknod.
CLI Examples:
salt '*' file.mknod /dev/chr c 180 31 salt '*' file.mknod /dev/blk b 8 999 salt '*' file.nknod /dev/fifo p
- salt.modules.file.mknod_blkdev(name, major, minor, user=None, group=None, mode='0660')#
New in version 0.17.0.
Create a block device.
CLI Example:
salt '*' file.mknod_blkdev /dev/blk 8 999
- salt.modules.file.mknod_chrdev(name, major, minor, user=None, group=None, mode='0660')#
New in version 0.17.0.
Create a character device.
CLI Example:
salt '*' file.mknod_chrdev /dev/chr 180 31
- salt.modules.file.mknod_fifo(name, user=None, group=None, mode='0660')#
New in version 0.17.0.
Create a FIFO pipe.
CLI Example:
salt '*' file.mknod_fifo /dev/fifo
- salt.modules.file.move(src, dst, disallow_copy_and_unlink=False)#
Move a file or directory
- disallow_copy_and_unlink
If
True, the operation is offloaded to thefile.renameexecution module function. This will useos.renameunderneath, which will fail in the event thatsrcanddstare on different filesystems. IfFalse(the default),shutil.movewill be used in order to fall back on a "copy then unlink" approach, which is required for moving across filesystems.New in version 3006.0.
CLI Example:
salt '*' file.move /path/to/src /path/to/dst
- salt.modules.file.normpath(path)#
Returns Normalize path, eliminating double slashes, etc.
New in version 2015.5.0.
This can be useful at the CLI but is frequently useful when scripting.
{%- from salt['file.normpath'](tpldir + '/../vars.jinja') import parent_vars %}
CLI Example:
salt '*' file.normpath 'a/b/c/..'
- salt.modules.file.open_files(by_pid=False)#
Return a list of all physical open files on the system.
CLI Examples:
salt '*' file.open_files salt '*' file.open_files by_pid=True
- salt.modules.file.pardir()#
Return the relative parent directory path symbol for underlying OS
New in version 2014.7.0.
This can be useful when constructing Salt Formulas.
{% set pardir = salt['file.pardir']() %} {% set final_path = salt['file.join']('subdir', pardir, 'confdir') %}
CLI Example:
salt '*' file.pardir
- salt.modules.file.patch(originalfile, patchfile, options='', dry_run=False)#
New in version 0.10.4.
Apply a patch to a file or directory.
Equivalent to:
patch <options> -i <patchfile> <originalfile>
Or, when a directory is patched:
patch <options> -i <patchfile> -d <originalfile> -p0
- originalfile
The full path to the file or directory to be patched
- patchfile
A patch file to apply to
originalfile- options
Options to pass to patch.
Note
Windows now supports using patch as of 3004.
In order to use this function in Windows, please install the patch binary through your own means and ensure it's found in the system Path. If installing through git-for-windows, please select the optional "Use Git and optional Unix tools from the Command Prompt" option when installing Git.
CLI Example:
salt '*' file.patch /opt/file.txt /tmp/file.txt.patch salt '*' file.patch C:\file1.txt C:\file3.patch
- salt.modules.file.path_exists_glob(path)#
Tests to see if path after expansion is a valid path (file or directory). Expansion allows usage of ? * and character ranges []. Tilde expansion is not supported. Returns True/False.
New in version 2014.7.0.
CLI Example:
salt '*' file.path_exists_glob /etc/pam*/pass*
- salt.modules.file.prepend(path, *args, **kwargs)#
New in version 2014.7.0.
Prepend text to the beginning of a file
- path
path to file
- *args
strings to prepend to the file
CLI Example:
salt '*' file.prepend /etc/motd \ "With all thine offerings thou shalt offer salt." \ "Salt is what makes things taste bad when it isn't in them."
Attention
If you need to pass a string to append and that string contains an equal sign, you must include the argument name, args. For example:
salt '*' file.prepend /etc/motd args='cheese=spam' salt '*' file.prepend /etc/motd args="['cheese=spam','spam=cheese']"
- salt.modules.file.psed(path, before, after, limit='', backup='.bak', flags='gMS', escape_all=False, multi=False)#
Deprecated since version 0.17.0: Use
replace()instead.Make a simple edit to a file (pure Python version)
Equivalent to:
sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>"
- path
The full path to the file to be edited
- before
A pattern to find in order to replace with
after- after
Text that will replace
before- limit:
'' An initial pattern to search for before searching for
before- backup:
.bak The file will be backed up before edit with this file extension; WARNING: each time
sed/comment/uncommentis called will overwrite this backup- flags:
gMS - Flags to modify the search. Valid values are:
g: Replace all occurrences of the pattern, not just the first.I: Ignore case.L: Make\w,\W,\b,\B,\sand\Sdependent on the locale.M: Treat multiple lines as a single line.S: Make . match all characters, including newlines.U: Make\w,\W,\b,\B,\d,\D,\sand\Sdependent on Unicode.X: Verbose (whitespace is ignored).
- multi:
False If True, treat the entire file as a single line
Forward slashes and single quotes will be escaped automatically in the
beforeandafterpatterns.CLI Example:
salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info'
- salt.modules.file.read(path, binary=False)#
New in version 2017.7.0.
Return the content of the file.
- Parameters:
binary (bool) -- Whether to read and return binary data
CLI Example:
salt '*' file.read /path/to/file
- salt.modules.file.readdir(path)#
New in version 2014.1.0.
Return a list containing the contents of a directory
CLI Example:
salt '*' file.readdir /path/to/dir/
- salt.modules.file.readlink(path, canonicalize=False)#
New in version 2014.1.0.
Return the path that a symlink points to
- Parameters:
- Returns:
The path that the symlink points to
- Return type:
- Raises:
SaltInvocationError -- path is not absolute
SaltInvocationError -- path is not a link
CommandExecutionError -- error reading the symbolic link
CLI Example:
salt '*' file.readlink /path/to/link
- salt.modules.file.remove(path, **kwargs)#
Remove the named file. If a directory is supplied, it will be recursively deleted.
CLI Example:
salt '*' file.remove /tmp/foo
Changed in version 3000: The method now works on all types of file system entries, not just files, directories and symlinks.
- salt.modules.file.remove_backup(path, backup_id)#
This function is an alias of
delete_backup.New in version 0.17.0.
Delete a previous version of a file that was backed up using Salt's file state backup system.
- path
The path on the minion to check for backups
- backup_id
The numeric id for the backup you wish to delete, as found using
file.list_backups
CLI Example:
salt '*' file.delete_backup /var/cache/salt/minion/file_backup/home/foo/bar/baz.txt 0
- salt.modules.file.rename(src, dst)#
Rename a file or directory
CLI Example:
salt '*' file.rename /path/to/src /path/to/dst
- salt.modules.file.replace(path, pattern, repl, count=0, flags=8, bufsize=1, append_if_not_found=False, prepend_if_not_found=False, not_found_content=None, backup='.bak', dry_run=False, search_only=False, show_changes=True, ignore_if_missing=False, preserve_inode=True, backslash_literal=False)#
New in version 0.17.0.
Replace occurrences of a pattern in a file. If
show_changesisTrue, then a diff of what changed will be returned, otherwise aTruewill be returned when changes are made, andFalsewhen no changes are made.This is a pure Python implementation that wraps Python's
sub().- path
Filesystem path to the file to be edited. If a symlink is specified, it will be resolved to its target.
- pattern
A regular expression, to be matched using Python's
search().- repl
The replacement text
- count: 0
Maximum number of pattern occurrences to be replaced. If count is a positive integer
n, onlynoccurrences will be replaced, otherwise all occurrences will be replaced.- flags (list or int)
A list of flags defined in the
remodule documentation from the Python standard library. Each list item should be a string that will correlate to the human-friendly flag name. E.g.,['IGNORECASE', 'MULTILINE']. Optionally,flagsmay be an int, with a value corresponding to the XOR (|) of all the desired flags. Defaults to 8 (which supports 'MULTILINE').- bufsize (int or str)
How much of the file to buffer into memory at once. The default value
1processes one line at a time. The special valuefilemay be specified which will read the entire file into memory before processing.- append_if_not_found: False
New in version 2014.7.0.
If set to
True, and pattern is not found, then the content will be appended to the file.- prepend_if_not_found: False
New in version 2014.7.0.
If set to
Trueand pattern is not found, then the content will be prepended to the file.- not_found_content
New in version 2014.7.0.
Content to use for append/prepend if not found. If None (default), uses
repl. Useful whenrepluses references to group in pattern.- backup: .bak
The file extension to use for a backup of the file before editing. Set to
Falseto skip making a backup.- dry_run: False
If set to
True, no changes will be made to the file, the function will just return the changes that would have been made (or aTrue/Falsevalue ifshow_changesis set toFalse).- search_only: False
If set to true, this no changes will be performed on the file, and this function will simply return
Trueif the pattern was matched, andFalseif not.- show_changes: True
If
True, return a diff of changes made. Otherwise, returnTrueif changes were made, andFalseif not.Note
Using this option will store two copies of the file in memory (the original version and the edited version) in order to generate the diff. This may not normally be a concern, but could impact performance if used with large files.
- ignore_if_missing: False
New in version 2015.8.0.
If set to
True, this function will simply returnFalseif the file doesn't exist. Otherwise, an error will be thrown.- preserve_inode: True
New in version 2015.8.0.
Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by copying the file, reading from the copy, and writing to the file at the original inode. If
False, the file will be moved rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if usingbackupto create a backup copy).- backslash_literal: False
New in version 2016.11.7.
Interpret backslashes as literal backslashes for the repl and not escape characters. This will help when using append/prepend so that the backslashes are not interpreted for the repl on the second run of the state.
If an equal sign (
=) appears in an argument to a Salt command it is interpreted as a keyword argument in the formatkey=val. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg:salt '*' file.replace /path/to/file pattern='=' repl=':' salt '*' file.replace /path/to/file pattern="bind-address\s*=" repl='bind-address:'
CLI Examples:
salt '*' file.replace /etc/httpd/httpd.conf pattern='LogLevel warn' repl='LogLevel info' salt '*' file.replace /some/file pattern='before' repl='after' flags='[MULTILINE, IGNORECASE]'
- salt.modules.file.restore_backup(path, backup_id)#
New in version 0.17.0.
Restore a previous version of a file that was backed up using Salt's file state backup system.
- path
The path on the minion to check for backups
- backup_id
The numeric id for the backup you wish to restore, as found using
file.list_backups
CLI Example:
salt '*' file.restore_backup /foo/bar/baz.txt 0
- salt.modules.file.restorecon(path, recursive=False)#
Reset the SELinux context on a given path
CLI Example:
salt '*' file.restorecon /home/user/.ssh/authorized_keys
- salt.modules.file.rmdir(path, recurse=False, verbose=False, older_than=None)#
New in version 2014.1.0.
Changed in version 3006.0: Changed return value for failure to a boolean.
Remove the specified directory. Fails if a directory is not empty.
- recurse
When
recurseis set toTrue, all empty directories within the path are pruned.New in version 3006.0.
- verbose
When
verboseis set toTrue, a dictionary is returned which contains more information about the removal process.New in version 3006.0.
- older_than
When
older_thanis set to a number, it is used to determine the number of days which must have passed since the last modification timestamp before a directory will be allowed to be removed. Setting the value to 0 is equivalent to leaving it at the default ofNone.New in version 3006.0.
CLI Example:
salt '*' file.rmdir /tmp/foo/
- salt.modules.file.search(path, pattern, flags=8, bufsize=1, ignore_if_missing=False, multiline=False)#
New in version 0.17.0.
Search for occurrences of a pattern in a file
Except for multiline, params are identical to
replace().- multiline
If true, inserts 'MULTILINE' into
flagsand setsbufsizeto 'file'.New in version 2015.8.0.
CLI Example:
salt '*' file.search /etc/crontab 'mymaintenance.sh'
- salt.modules.file.sed(path, before, after, limit='', backup='.bak', options='-r -e', flags='g', escape_all=False, negate_match=False)#
Deprecated since version 0.17.0: Use
replace()instead.Make a simple edit to a file
Equivalent to:
sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>"
- path
The full path to the file to be edited
- before
A pattern to find in order to replace with
after- after
Text that will replace
before- limit:
'' An initial pattern to search for before searching for
before- backup:
.bak The file will be backed up before edit with this file extension; WARNING: each time
sed/comment/uncommentis called will overwrite this backup- options:
-r -e Options to pass to sed
- flags:
g Flags to modify the sed search; e.g.,
ifor case-insensitive pattern matching- negate_match: False
Negate the search command (
!)New in version 0.17.0.
Forward slashes and single quotes will be escaped automatically in the
beforeandafterpatterns.CLI Example:
salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info'
- salt.modules.file.sed_contains(path, text, limit='', flags='g')#
Deprecated since version 0.17.0: Use
search()instead.Return True if the file at
pathcontainstext. Utilizes sed to perform the search (line-wise search).Note: the
pflag will be added to any flags you pass in.CLI Example:
salt '*' file.contains /etc/crontab 'mymaintenance.sh'
- salt.modules.file.seek_read(path, size, offset)#
New in version 2014.1.0.
Seek to a position on a file and read it
- path
path to file
- seek
amount to read at once
- offset
offset to start into the file
CLI Example:
salt '*' file.seek_read /path/to/file 4096 0
- salt.modules.file.seek_write(path, data, offset)#
New in version 2014.1.0.
Seek to a position on a file and write to it
- path
path to file
- data
data to write to file
- offset
position in file to start writing
CLI Example:
salt '*' file.seek_write /path/to/file 'some data' 4096
- salt.modules.file.set_mode(path, mode)#
Set the mode of a file
- path
file or directory of which to set the mode
- mode
mode to set the path to
CLI Example:
salt '*' file.set_mode /etc/passwd 0644
- salt.modules.file.set_selinux_context(path, user=None, role=None, type=None, range=None, persist=False)#
Changed in version 3001: Added persist option
Set a specific SELinux label on a given path
CLI Example:
salt '*' file.set_selinux_context path <user> <role> <type> <range> salt '*' file.set_selinux_context /etc/yum.repos.d/epel.repo system_u object_r system_conf_t s0
- salt.modules.file.source_list(source, source_hash, saltenv)#
Check the source list and return the source to use
CLI Example:
salt '*' file.source_list salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' base
- salt.modules.file.stats(path, hash_type=None, follow_symlinks=True)#
Return a dict containing the stats for a given file
CLI Example:
salt '*' file.stats /etc/passwd
- salt.modules.file.statvfs(path)#
New in version 2014.1.0.
Perform a statvfs call against the filesystem that the file resides on
CLI Example:
salt '*' file.statvfs /path/to/file
- salt.modules.file.symlink(src, path, force=False, atomic=False, follow_symlinks=True)#
Create a symbolic link (symlink, soft link) to a file
- Parameters:
src (str) -- The path to a file or directory
path (str) -- The path to the link. Must be an absolute path
force (bool) -- Overwrite an existing symlink with the same name .. versionadded:: 3005
atomic (bool) -- Use atomic file operations to create the symlink .. versionadded:: 3006.0
follow_symlinks (bool) -- If set to
False, useos.path.lexists()for existence checks instead ofos.path.exists(). .. versionadded:: 3007.0
- Returns:
Trueif successful, otherwise raisesCommandExecutionError- Return type:
CLI Example:
salt '*' file.symlink /path/to/file /path/to/link
- salt.modules.file.touch(name, atime=None, mtime=None)#
New in version 0.9.5.
Just like the
touchcommand, create a file if it doesn't exist or simply update the atime and mtime if it already does.- atime:
Access time in Unix epoch time. Set it to 0 to set atime of the file with Unix date of birth. If this parameter isn't set, atime will be set with current time.
- mtime:
Last modification in Unix epoch time. Set it to 0 to set mtime of the file with Unix date of birth. If this parameter isn't set, mtime will be set with current time.
CLI Example:
salt '*' file.touch /var/log/emptyfile
- salt.modules.file.truncate(path, length)#
New in version 2014.1.0.
Seek to a position on a file and delete everything after that point
- path
path to file
- length
offset into file to truncate
CLI Example:
salt '*' file.truncate /path/to/file 512
- salt.modules.file.uid_to_user(uid)#
Convert a uid to a user name
- uid
uid to convert to a username
CLI Example:
salt '*' file.uid_to_user 0
- salt.modules.file.uncomment(path, regex, char='#', backup='.bak')#
Deprecated since version 0.17.0: Use
replace()instead.Uncomment specified commented lines in a file
- path
The full path to the file to be edited
- regex
A regular expression used to find the lines that are to be uncommented. This regex should not include the comment character. A leading
^character will be stripped for convenience (for easily switching between comment() and uncomment()).- char:
# The character to remove in order to uncomment a line
- backup:
.bak The file will be backed up before edit with this file extension; WARNING: each time
sed/comment/uncommentis called will overwrite this backup
CLI Example:
salt '*' file.uncomment /etc/hosts.deny 'ALL: PARANOID'
- salt.modules.file.user_to_uid(user)#
Convert user name to a uid
- user
user name to convert to its uid
CLI Example:
salt '*' file.user_to_uid root
- salt.modules.file.write(path, *args, **kwargs)#
New in version 2014.7.0.
Write text to a file, overwriting any existing contents.
- path
path to file
- *args
strings to write to the file
CLI Example:
salt '*' file.write /etc/motd \ "With all thine offerings thou shalt offer salt."
Attention
If you need to pass a string to append and that string contains an equal sign, you must include the argument name, args. For example:
salt '*' file.write /etc/motd args='cheese=spam' salt '*' file.write /etc/motd args="['cheese=spam','spam=cheese']"