Manage information about regular files, directories, and special files on the minion, set/read user, group, mode, and data
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:
CLI Example:
salt '*' file.access /path/to/file f salt '*' file.access /path/to/file x
New in version 0.9.5.
Append text to the end of a 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']"
Return the contents after applying the templating engine
CLI Example:
salt '*' file.apply_template_on_contents \ contents='This is a {{ template }} string.' \ template=jinja \ "context={}" "defaults={'template': 'cool'}" \ saltenv=base
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'
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.
True
then, the markers and content will be appended to the file.True
then, the markers and content will be prepended to the file.False
to skip making a backup.True
, do not make any edits to the file and simply return the changes that would be made.True
, this function will return a unified diff of the changes made. If False, then it will return a boolean (True
if any changes were made, otherwise False
).Controls whether or not a newline is appended to the content block. If the value of this argument is True
then a newline will be added to the content block. If it is False
, then a newline will not be added to the content block. If it is None
then 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 None
to match the behavior of the file.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
New in version 2018.3.0.
Change the attributes of files. This function accepts one or more files and the following options:
add
or remove
. Determines whether attributes should be added or removed from filesaAcCdDeijPsStTu
, representing attributes to add to/remove from filesRVf
, 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
Check for the changes in the file metadata.
CLI Example:
salt '*' file.check_file_meta /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' base
Note
Supported hash types include sha512, sha384, sha256, sha224, sha1, and md5.
File checksum information as a dictionary
{hash_type: md5, hsum: <md5sum>}
Destination file attributes
New in version 2018.3.0.
Check if a file matches the given hash string
Returns True
if the hash matches, otherwise False
.
The hash to check against the file specified in the path
argument.
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
Check to see what changes need to be made for a file
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
Return a dictionary of what changes need to be made for a file
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
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_symlinks
option added
Change the group of a file
CLI Example:
salt '*' file.chgrp /etc/passwd root
Chown a file, pass the file the desired user and group
CLI Example:
salt '*' file.chown /etc/passwd root root
Deprecated since version 0.17.0: Use replace()
instead.
Comment out specified lines in a file
^
or $
characters outside the parenthesis (e.g., the pattern ^foo$
will be rewritten as ^(foo)$
)#
.bak
The file will be backed up before edit with this file extension
Warning
This backup will be overwritten each time sed
/ comment
/ uncomment
is called. Meaning the backup will only be useful after the first invocation.
CLI Example:
salt '*' file.comment /etc/modules pcspkr
Comment or Uncomment a line in a text file.
Parameters: |
|
---|---|
Returns: |
boolean Returns True if successful, False if not |
CLI Example:
The following example will comment out the pcspkr
line in the /etc/modules
file using the default #
character and create a backup file named modules.bak
salt '*' file.comment_line '/etc/modules' '^pcspkr'
CLI Example:
The following example will uncomment the log_level
setting in minion
config file if it is set to either warning
, info
, or debug
using the #
character and create a backup file named minion.bk
salt '*' file.comment_line 'C:\salt\conf\minion' '^log_level: (warning|info|debug)' '#' False '.bk'
Deprecated since version 0.17.0: Use search()
instead.
Return True
if the file at path
contains text
CLI Example:
salt '*' file.contains /etc/crontab 'mymaintenance.sh'
Deprecated since version 0.17.0: Use search()
instead.
Return True
if the given glob matches a string in the named file
CLI Example:
salt '*' file.contains_glob /etc/foobar '*cheese*'
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
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.managed
and states.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
New in version 0.17.0.
Delete a previous version of a file that was backed up using Salt's file state backup system.
file.list_backups
CLI Example:
salt '*' file.delete_backup /var/cache/salt/minion/file_backup/home/foo/bar/baz.txt 0
Tests to see if path is a valid directory. Returns True/False.
CLI Example:
salt '*' file.directory_exists /etc
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'
Recursively calculate disk usage of path and return it in bytes
CLI Example:
salt '*' file.diskusage /path/to/check
Changed in version 2016.3.5: Prior to this version, only the file_name
argument 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.gz
when the remote file was at https://mydomain.tld/different_name.tar.gz
. The file.managed
state now also passes this function the source URI as well as the source_hash_name
(if specified). In cases where source_hash_name
is specified, it takes precedence over both the file_name
and source
. When it is not specified, file_name
takes precedence over source
. 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_name
is specified. They will be used as fallback matches if there is no match to the source_hash_name
value.
This routine is called from the file.managed
state to pull a hash from a remote file. Regular expressions are used line by line on the source_hash
file, 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 *.dsc
files.
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 None
will 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
Tests to see if path is a valid file. Returns True/False.
CLI Example:
salt '*' file.file_exists /etc/passwd
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 user = 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=path
path-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 c
path-regex
: a Python Regex (regular expression) pattern to match pathnames
file-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 uids
groups
: a space and/or comma separated list of group names and/or gids
size-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: second
print-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 user: 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
Get major/minor info from a device
CLI Example:
salt '*' file.get_devmm /dev/chr
Return unified diff of two files
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.
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
)
False
to hide the filenames in the top two lines of the diff.False
, and there are differences, then instead of a diff a simple message stating that show_changes is set to False
will be returned.Set to True
if two templates are being compared. This is not useful except for within states, with the obfuscate_templates
option set to True
.
New in version 2018.3.0.
If file1
is 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.
If file2
is 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.
CLI Examples:
salt '*' file.get_diff /home/fred/.vimrc salt://users/fred/.vimrc salt '*' file.get_diff /tmp/foo.txt /tmp/bar.txt
Return the id of the group that owns a given file
CLI Example:
salt '*' file.get_gid /etc/passwd
Changed in version 0.16.4: follow_symlinks
option added
Return the group that owns a given file
CLI Example:
salt '*' file.get_group /etc/passwd
Changed in version 0.16.4: follow_symlinks
option added
Get the hash sum of a file
get_sum
for the following reasons:get_sum
cannot really be trusted since it is vulnerable to collisions: get_sum(..., 'xyz') == 'Hash xyz not supported'
CLI Example:
salt '*' file.get_hash /etc/shadow
Return the managed file data for file.managed
When source_hash
refers to a remote file, this specifies the filename to look for in that file.
New in version 2016.3.5.
Attributes of file
New in version 2018.3.0.
If True
, hash verification of remote file sources (http://
, https://
, ftp://
) will be skipped, and the source_hash
argument will be ignored.
New in version 2016.3.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
Return the mode of a file
CLI Example:
salt '*' file.get_mode /etc/passwd
Changed in version 2014.1.0: follow_symlinks
option added
Get an SELinux context from a given path
CLI Example:
salt '*' file.get_selinux_context /etc/hosts
New in version 2016.11.0.
Used by file.get_managed
to obtain the hash and hash type from the parameters specified below.
file.extract_hash
.file
and other states. If source_hash
refers to a file containing hashes, then this filename will be used to match a filename in that file. If the source_hash
is a hash expression, then this argument will be ignored.file
and other states. If this value refers to a remote URL or absolute path to a local file, it will be cached and file.extract_hash
will be used to obtain a hash from it.source_hash
refers to a remote file, used to disambiguate ambiguous matches.source_hash
refers to a file on the Salt fileserver (i.e. one beginning with salt://
).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
Return the checksum for the given file. The following checksum algorithms are supported:
CLI Example:
salt '*' file.get_sum /etc/passwd sha512
Return the id of the user that owns a given file
CLI Example:
salt '*' file.get_uid /etc/passwd
Changed in version 0.16.4: follow_symlinks
option added
Return the user that owns a given file
CLI Example:
salt '*' file.get_user /etc/passwd
Changed in version 0.16.4: follow_symlinks
option added
Convert the group id to the group name on this system
CLI Example:
salt '*' file.gid_to_group 0
Grep for a string in the specified file
Note
This function's return value is slated for refinement in future versions of Salt
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.
test
, or a[0-5]
Additional command-line flags to pass to the grep command. For example: -v
, or -i -B2
Note
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
Convert the group to the gid on this system
CLI Example:
salt '*' file.group_to_gid root
Check if a file exists and is a block device.
CLI Example:
salt '*' file.is_blkdev /dev/blk
Check if a file exists and is a character device.
CLI Example:
salt '*' file.is_chrdev /dev/chr
Check if a file exists and is a FIFO.
CLI Example:
salt '*' file.is_fifo /dev/fifo
Check if the path is a symbolic link
CLI Example:
salt '*' file.is_link /path/to/link
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'
Chown a file, pass the file the desired user and group without following symlinks.
CLI Example:
salt '*' file.chown /etc/passwd root root
New in version 2015.8.0.
Edit a line in the configuration file. The path
and content
arguments are required, as well as passing in one of the mode
options.
Match the target line for an action by a fragment of a string or regular expression.
If neither before
nor after
are provided, and match
is also None
, match becomes the content
value.
Defines how to edit a line. One of the following options is required:
content
argument.Note
If mode=insert
is used, at least one of the following options must also be defined: location
, before
, or after
. If location
is used, it takes precedence over the other two options.
Defines where to place content in the line. Note this option is only used when mode=insert
is specified. If a location is passed in, it takes precedence over both the before
and after
kwargs. Valid locations are:
ensure
or insert
mode is defined.ensure
or insert
mode is defined.Output a unified diff of the old file and the new file. If False
return a boolean if any changes were made. Default is True
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.
delete
mode is specified.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 of key=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"
New in version 2014.1.0.
Create a hard link to a file
CLI Example:
salt '*' file.link /path/to/file /path/to/link
New in version 0.17.0.
Lists the previous versions of a file backed up using Salt's file state backup system.
CLI Example:
salt '*' file.list_backups /foo/bar/baz.txt
Lists the previous versions of a directory backed up using Salt's file state backup system.
CLI Example:
salt '*' file.list_backups_dir /foo/bar/baz/
New in version 2018.3.0.
Changed in version 2018.3.1: If lsattr
is not installed on the system, None
is returned.
Changed in version 2018.3.4: If on AIX
, None
is returned even if in filesystem as lsattr on AIX
is 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.
CLI Example:
salt '*' file.lsattr foo1.txt
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
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/
Taken and modified from os.makedirs to set user, group and mode for each directory created.
CLI Example:
salt '*' file.makedirs_perms /opt/code
Checks the destination against what was retrieved with get_managed and makes the appropriate modifications (if necessary).
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()
None
to use the default structure.attributes to be set on file: '' means remove all of them
New in version 2018.3.0.
If True
, hash verification of remote file sources (http://
, https://
, ftp://
) will be skipped, and the source_hash
argument will be ignored.
New in version 2016.3.0.
If True
, and the source
is 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
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.
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.
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_symlinks
option added
Ensure that a directory is available.
CLI Example:
salt '*' file.mkdir /opt/jetty/context
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
New in version 0.17.0.
Create a block device.
CLI Example:
salt '*' file.mknod_blkdev /dev/blk 8 999
New in version 0.17.0.
Create a character device.
CLI Example:
salt '*' file.mknod_chrdev /dev/chr 180 31
New in version 0.17.0.
Create a FIFO pipe.
CLI Example:
salt '*' file.mknod_fifo /dev/fifo
Move a file or directory
CLI Example:
salt '*' file.move /path/to/src /path/to/dst
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/..'
Return a list of all physical open files on the system.
CLI Examples:
salt '*' file.open_files salt '*' file.open_files by_pid=True
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
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
CLI Example:
salt '*' file.patch /opt/file.txt /tmp/file.txt.patch
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*
New in version 2014.7.0.
Prepend text to the beginning of a 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']"
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>"
after
before
''
before
.bak
sed
/comment
/uncomment
is called will overwrite this backupgMS
g
: Replace all occurrences of the pattern, not just the first.I
: Ignore case.L
: Make \w
, \W
, \b
, \B
, \s
and \S
dependent 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
, \s
and \S
dependent on Unicode.X
: Verbose (whitespace is ignored).False
Forward slashes and single quotes will be escaped automatically in the before
and after
patterns.
CLI Example:
salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info'
New in version 2017.7.0.
Return the content of the file.
CLI Example:
salt '*' file.read /path/to/file
New in version 2014.1.0.
Return a list containing the contents of a directory
CLI Example:
salt '*' file.readdir /path/to/dir/
New in version 2014.1.0.
Return the path that a symlink points to If canonicalize is set to True, then it return the final target
CLI Example:
salt '*' file.readlink /path/to/link
Remove the named file. If a directory is supplied, it will be recursively deleted.
CLI Example:
salt '*' file.remove /tmp/foo
Rename a file or directory
CLI Example:
salt '*' file.rename /path/to/src /path/to/dst
New in version 0.17.0.
Replace occurrences of a pattern in a file. If show_changes
is True
, then a diff of what changed will be returned, otherwise a True
will be returned when changes are made, and False
when no changes are made.
This is a pure Python implementation that wraps Python's sub()
.
search()
.n
, only n
occurrences will be replaced, otherwise all occurrences will be replaced.re
module 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, flags
may be an int, with a value corresponding to the XOR (|
) of all the desired flags. Defaults to 8 (which supports 'MULTILINE').1
processes one line at a time. The special value file
may be specified which will read the entire file into memory before processing.New in version 2014.7.0.
If set to True
, and pattern is not found, then the content will be appended to the file.
New in version 2014.7.0.
If set to True
and pattern is not found, then the content will be prepended to the file.
New in version 2014.7.0.
Content to use for append/prepend if not found. If None (default), uses repl
. Useful when repl
uses references to group in pattern.
False
to skip making a backup.True
, no changes will be made to the file, the function will just return the changes that would have been made (or a True
/False
value if show_changes
is set to False
).True
if the pattern was matched, and False
if not.If True
, return a diff of changes made. Otherwise, return True
if changes were made, and False
if 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.
New in version 2015.8.0.
If set to True
, this function will simply return False
if the file doesn't exist. Otherwise, an error will be thrown.
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 using backup
to create a backup copy).
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 format key=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]'
New in version 0.17.0.
Restore a previous version of a file that was backed up using Salt's file state backup system.
file.list_backups
CLI Example:
salt '*' file.restore_backup /foo/bar/baz.txt 0
Reset the SELinux context on a given path
CLI Example:
salt '*' file.restorecon /home/user/.ssh/authorized_keys
New in version 2014.1.0.
Remove the specified directory. Fails if a directory is not empty.
CLI Example:
salt '*' file.rmdir /tmp/foo/
New in version 0.17.0.
Search for occurrences of a pattern in a file
Except for multiline, params are identical to replace()
.
If true, inserts 'MULTILINE' into flags
and sets bufsize
to 'file'.
New in version 2015.8.0.
CLI Example:
salt '*' file.search /etc/crontab 'mymaintenance.sh'
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>"
after
before
''
before
.bak
sed
/comment
/uncomment
is called will overwrite this backup-r -e
g
i
for case-insensitive pattern matchingNegate the search command (!
)
New in version 0.17.0.
Forward slashes and single quotes will be escaped automatically in the before
and after
patterns.
CLI Example:
salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info'
Deprecated since version 0.17.0: Use search()
instead.
Return True if the file at path
contains text
. Utilizes sed to perform the search (line-wise search).
Note: the p
flag will be added to any flags you pass in.
CLI Example:
salt '*' file.contains /etc/crontab 'mymaintenance.sh'
New in version 2014.1.0.
Seek to a position on a file and read it
CLI Example:
salt '*' file.seek_read /path/to/file 4096 0
New in version 2014.1.0.
Seek to a position on a file and write to it
CLI Example:
salt '*' file.seek_write /path/to/file 'some data' 4096
Set the mode of a file
CLI Example:
salt '*' file.set_mode /etc/passwd 0644
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
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
Return a dict containing the stats for a given file
CLI Example:
salt '*' file.stats /etc/passwd
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
Create a symbolic link (symlink, soft link) to a file
CLI Example:
salt '*' file.symlink /path/to/file /path/to/link
New in version 0.9.5.
Just like the touch
command, create a file if it doesn't exist or simply update the atime and mtime if it already does.
CLI Example:
salt '*' file.touch /var/log/emptyfile
New in version 2014.1.0.
Seek to a position on a file and delete everything after that point
CLI Example:
salt '*' file.truncate /path/to/file 512
Convert a uid to a user name
CLI Example:
salt '*' file.uid_to_user 0
Deprecated since version 0.17.0: Use replace()
instead.
Uncomment specified commented lines in a file
^
character will be stripped for convenience (for easily switching between comment() and uncomment()).#
.bak
sed
/comment
/uncomment
is called will overwrite this backupCLI Example:
salt '*' file.uncomment /etc/hosts.deny 'ALL: PARANOID'
Convert user name to a uid
CLI Example:
salt '*' file.user_to_uid root
New in version 2014.7.0.
Write text to a file, overwriting any existing contents.
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']"
© 2019 SaltStack.
Licensed under the Apache License, Version 2.0.
https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.file.html