salt.states.file¶
Operations on regular files, special files, directories, and symlinks.¶
Salt States can aggressively manipulate files on a system. There are a number of ways in which files can be managed.
Regular files can be enforced with the managed
function. This function
downloads files from the salt master and places them on the target system.
The downloaded files can be rendered as a jinja, mako, or wempy template,
adding a dynamic component to file management. An example of file.managed
which makes use of the jinja templating system would look like this:
/etc/http/conf/http.conf:
file.managed:
- source: salt://apache/http.conf
- user: root
- group: root
- mode: 644
- template: jinja
- defaults:
custom_var: "default value"
other_var: 123
{% if grains['os'] == 'Ubuntu' %}
- context:
custom_var: "override"
{% endif %}
If using a template, any user-defined template variables in the file defined in
source
must be passed in using the defaults
and/or context
arguments. The general best practice is to place default values in
defaults
, with conditional overrides going into context
, as seen above.
The source
parameter can be specified as a list. If this is done, then the
first file to be matched will be the one that is used. This allows you to have
a default file on which to fall back if the desired file does not exist on the
salt fileserver. Here's an example:
/etc/foo.conf:
file.managed:
- source:
- salt://foo.conf.{{ grains['fqdn'] }}
- salt://foo.conf.fallback
- user: foo
- group: users
- mode: 644
The source
parameter can also specify a file in another Salt environment.
In this example foo.conf
in the dev
environment will be used instead.
/etc/foo.conf:
file.managed:
- source:
- salt://foo.conf?env=dev
- user: foo
- group: users
- mode: '0644'
Warning
When using a mode that includes a leading zero you must wrap the value in single quotes. If the value is not wrapped in quotes it will be read by YAML as an integer and evaluated as an octal.
Special files can be managed via the mknod
function. This function will
create and enforce the permissions on a special file. The function supports the
creation of character devices, block devices, and fifo pipes. The function will
create the directory structure up to the special file if it is needed on the
minion. The function will not overwrite or operate on (change major/minor
numbers) existing special files with the exception of user, group, and
permissions. In most cases the creation of some special files require root
permisisons on the minion. This would require that the minion to be run as the
root user. Here is an example of a character device:
/var/named/chroot/dev/random:
file.mknod:
- ntype: c
- major: 1
- minor: 8
- user: named
- group: named
- mode: 660
Here is an example of a block device:
/var/named/chroot/dev/loop0:
file.mknod:
- ntype: b
- major: 7
- minor: 0
- user: named
- group: named
- mode: 660
Here is an example of a fifo pipe:
/var/named/chroot/var/log/logfifo:
file.mknod:
- ntype: p
- user: named
- group: named
- mode: 660
Directories can be managed via the directory
function. This function can
create and enforce the permissions on a directory. A directory statement will
look like this:
/srv/stuff/substuf:
file.directory:
- user: fred
- group: users
- mode: 755
- makedirs: True
If you need to enforce user and/or group ownership or permissions recursively
on the directory's contents, you can do so by adding a recurse
directive:
/srv/stuff/substuf:
file.directory:
- user: fred
- group: users
- mode: 755
- makedirs: True
- recurse:
- user
- group
- mode
As a default, mode
will resolve to dir_mode
and file_mode
, to
specify both directory and file permissions, use this form:
/srv/stuff/substuf:
file.directory:
- user: fred
- group: users
- file_mode: 744
- dir_mode: 755
- makedirs: True
- recurse:
- user
- group
- mode
Symlinks can be easily created; the symlink function is very simple and only takes a few arguments:
/etc/grub.conf:
file.symlink:
- target: /boot/grub/grub.conf
Recursive directory management can also be set via the recurse
function. Recursive directory management allows for a directory on the salt
master to be recursively copied down to the minion. This is a great tool for
deploying large code and configuration systems. A state using recurse
would look something like this:
/opt/code/flask:
file.recurse:
- source: salt://code/flask
- include_empty: True
-
salt.states.file.
absent
(name)¶ Verify that the named file or directory is absent, this will work to reverse any of the functions in the file state module.
- name
- The path which should be deleted
-
salt.states.file.
accumulated
(name, filename, text, **kwargs)¶ Prepare accumulator which can be used in template in file.managed state. Accumulator dictionary becomes available in template.
- name
- Accumulator name
- filename
- Filename which would receive this accumulator (see file.managed state
documentation about
name
) - text
- String or list for adding in accumulator
- require_in / watch_in
- One of them required for sure we fill up accumulator before we manage the file. Probably the same as filename
-
salt.states.file.
append
(name, text=None, makedirs=False, source=None, source_hash=None, __env__='base', template='jinja', sources=None, source_hashes=None, defaults=None, context=None)¶ Ensure that some text appears at the end of a file
The text will not be appended again if it already exists in the file. You may specify a single line of text or a list of lines to append.
Multi-line example:
/etc/motd: file.append: - text: | Thou hadst better eat salt with the Philosophers of Greece, than sugar with the Courtiers of Italy. - Benjamin Franklin
Multiple lines of text:
/etc/motd: file.append: - text: - Trust no one unless you have eaten much salt with him. - "Salt is born of the purest of parents: the sun and the sea."
Gather text from multiple template files:
/etc/motd: file: - append - template: jinja - sources: - salt://motd/devops-messages.tmpl - salt://motd/hr-messages.tmpl - salt://motd/general-messages.tmpl
New in version 0.9.5.
-
salt.states.file.
comment
(name, regex, char='#', backup='.bak')¶ Comment out specified lines in a file.
- name
- 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)$
) Note that you _need_ the leading ^, otherwise each time you run highstate, another comment char will be inserted. - 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
/uncomment
is called. Meaning the backup will only be useful after the first invocation.
Usage:
/etc/fstab: file.comment: - regex: ^bind 127.0.0.1
New in version 0.9.5.
-
salt.states.file.
copy
(name, source, force=False, makedirs=False)¶ If the source file exists on the system, copy it to the named file. The named file will not be overwritten if it already exists unless the force option is set to True.
- name
- The location of the file to copy to
- source
- The location of the file to copy to the location specified with name
- force
- If the target location is present then the file will not be moved, specify "force: True" to overwrite the target file
- makedirs
- If the target subdirectories don't exist create them
-
salt.states.file.
directory
(name, user=None, group=None, recurse=None, dir_mode=None, file_mode=None, makedirs=False, clean=False, require=None, exclude_pat=None, **kwargs)¶ Ensure that a named directory is present and has the right perms
- name
- The location to create or manage a directory
- user
- The user to own the directory; this defaults to the user salt is running as on the minion
- group
- The group ownership set for the directory; this defaults to the group salt is running as on the minion
- recurse
Enforce user/group ownership and mode of directory recursively. Accepts a list of strings representing what you would like to recurse. Example:
/var/log/httpd: file.directory: - user: root - group: root - dir_mode: 755 - file_mode: 644 - recurse: - user - group - mode
- dir_mode / mode
- The permissions mode to set any directories created.
- file_mode
- The permissions mode to set any files created if 'mode' is ran in 'recurse'. This defaults to dir_mode.
- makedirs
- If the directory is located in a path without a parent directory, then the state will fail. If makedirs is set to True, then the parent directories will be created to facilitate the creation of the named file.
- clean
- Make sure that only files that are set up by salt and required by this function are kept. If this option is set then everything in this directory will be deleted unless it is required.
- require
- Require other resources such as packages or files
- exclude_pat
- When 'clean' is set to True, exclude this pattern from removal list and preserve in the destination.
-
salt.states.file.
exists
(name)¶ Verify that the named file or directory is present or exists. Ensures pre-requisites outside of Salt's purview (e.g., keytabs, private keys, etc.) have been previously satisfied before deployment.
- name
- Absolute path which must exist
-
salt.states.file.
managed
(name, source=None, source_hash='', user=None, group=None, mode=None, template=None, makedirs=False, context=None, replace=True, defaults=None, env=None, backup='', show_diff=True, create=True, contents=None, contents_pillar=None, **kwargs)¶ Manage a given file, this function allows for a file to be downloaded from the salt master and potentially run through a templating system.
- name
- The location of the file to manage
- source
The source file to download to the minion, this source file can be hosted on either the salt master server, or on an HTTP or FTP server. 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, the file will be created as an empty file and the content will not be managed
If the file is hosted on a HTTP or FTP server then the source_hash argument is also required
- source_hash:
This can be either a file which contains a source hash string for the source, or a source hash string. The source hash string is the hash algorithm followed by the hash of the file: md5=e138491e9d5b97023cea823fe17bac22
The file can contain checksums for several files, in this case every line must consist of full name of the file and checksum separated by space:
Example:
/etc/rc.conf md5=ef6e82e4006dee563d98ada2a2a80a27 /etc/resolv.conf sha256=c8525aee419eb649f0233be91c151178b30f0dff8ebbdcc8de71b1d5c8bcc06a
- 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
- mode
- The permissions to set on this file, aka 644, 0775, 4664
- template
- If this setting is applied then the named templating engine will be used to render the downloaded file, currently jinja, mako, and wempy are supported
- makedirs
- If the file is located in a path without a parent directory, then the state will fail. If makedirs is set to True, then the parent directories will be created to facilitate the creation of the named file.
- replace
- If this file should be replaced. If false, this command will not overwrite file contents but will enforce permissions if the file exists already. Default is True.
- context
- Overrides default context variables passed to the template.
- defaults
- Default context passed to the template.
- backup
- Overrides the default backup mode for this specific file.
- show_diff
- If set to False, the diff will not be shown.
- create
- Default is True, if create is set to False then the file will only be managed if the file already exists on the system.
- contents
- Default is None. If specified, will use the given string as the contents of the file. Should not be used in conjunction with a source file of any kind. Ignores hashes and does not use a templating engine.
- contents_pillar
New in version 0.17.0.
Operates like
contents
, but draws from a value stored in pillar, using the pillar path syntax used inpillar.get
. This is useful when the pillar value contains newlines, as referencing a pillar variable using a jinja/mako template can result in YAML formatting issues due to the newlines causing indentation mismatches.
-
salt.states.file.
missing
(name)¶ Verify that the named file or directory is missing, this returns True only if the named file is missing but does not remove the file if it is present.
- name
- Absolute path which must NOT exist
-
salt.states.file.
mknod
(name, ntype, major=0, minor=0, user=None, group=None, mode='0600')¶ Create a special file similar to the 'nix mknod command. The supported device types are
p
(fifo pipe),c
(character device), andb
(block device). Provide the major and minor numbers when specifying a character device or block device. A fifo pipe does not require this information. The command will create the necessary dirs if needed. If a file of the same name not of the same type/major/minor exists, it will not be overwritten or unlinked (deleted). This is logically in place as a safety measure because you can really shoot yourself in the foot here and it is the behavior of 'nixmknod
. It is also important to note that not just anyone can create special devices. Usually this is only done as root. If the state is executed as none other than root on a minion, you may receive a permission error.- name
- name of the file
- ntype
- node type 'p' (fifo pipe), 'c' (character device), or 'b' (block device)
- major
- major number of the device does not apply to a fifo pipe
- minor
- minor number of the device does not apply to a fifo pipe
- user
- owning user of the device/pipe
- group
- owning group of the device/pipe
- mode
- permissions on the device/pipe
Usage:
/dev/chr: file.mknod: - ntype: c - major: 180 - minor: 31 - user: root - group: root - mode: 660 /dev/blk: file.mknod: - ntype: b - major: 8 - minor: 999 - user: root - group: root - mode: 660 /dev/fifo: file.mknod: - ntype: p - user: root - group: root - mode: 660
New in version 0.17.0.
-
salt.states.file.
patch
(name, source=None, hash=None, options='', dry_run_first=True, env=None, **kwargs)¶ Apply a patch to a file. Note: a suitable
patch
executable must be available on the minion when using this state function.- name
- The file to with the patch will be applied.
- source
- The source patch to download to the minion, this source file must be hosted on the salt master server. If the file is located in the directory named spam, and is called eggs, the source string is salt://spam/eggs. A source is required.
- hash
- Hash of the patched file. If the hash of the target file matches this value then the patch is assumed to have been applied. The hash string is the hash algorithm followed by the hash of the file: md5=e138491e9d5b97023cea823fe17bac22
- options
- Extra options to pass to patch.
- dry_run_first :
True
- Run patch with
--dry-run
first to check if it will apply cleanly. - env
- Specify the environment from which to retrieve the patch file indicated
by the
source
parameter. If not provided, this defaults to the environment from which the state is being executed.
Usage:
# Equivalent to ``patch --forward /opt/file.txt file.patch`` /opt/file.txt: file.patch: - source: salt://file.patch - hash: md5=e138491e9d5b97023cea823fe17bac22
-
salt.states.file.
recurse
(name, source, clean=False, require=None, user=None, group=None, dir_mode=None, file_mode=None, sym_mode=None, template=None, context=None, defaults=None, env=None, include_empty=False, backup='', include_pat=None, exclude_pat=None, maxdepth=None, keep_symlinks=False, force_symlinks=False, **kwargs)¶ Recurse through a subdirectory on the master and copy said subdirectory over to the specified path.
- name
- The directory to set the recursion in
- source
- The source directory, this directory is located on the salt master file server and is specified with the salt:// protocol. If the directory is located on the master in the directory named spam, and is called eggs, the source string is salt://spam/eggs
- clean
- Make sure that only files that are set up by salt and required by this function are kept. If this option is set then everything in this directory will be deleted unless it is required.
- require
- Require other resources such as packages or files
- user
- The user to own the directory, this defaults to the user salt is running as on the minion
- group
- The group ownership set for the directory, this defaults to the group salt is running as on the minion
- dir_mode
- The permissions mode to set any directories created
- file_mode
- The permissions mode to set any files created
- sym_mode
- The permissions mode to set on any symlink created
- template
- If this setting is applied then the named templating engine will be used to render the downloaded file, currently jinja, mako, and wempy are supported
- context
- Overrides default context variables passed to the template.
- defaults
- Default context passed to the template.
- include_empty
- Set this to True if empty directories should also be created (default is False)
- include_pat
When copying, include only this pattern from the source. Default is glob match; if prefixed with 'E@', then regexp match. Example:
- include_pat: hello* :: glob matches 'hello01', 'hello02' ... but not 'otherhello' - include_pat: E@hello :: regexp matches 'otherhello', 'hello01' ...
- exclude_pat
When copying, exclude this pattern from the source. If both include_pat and exclude_pat are supplied, then it will apply conditions cumulatively. i.e. first select based on include_pat, and then within that result apply exclude_pat.
Also, when 'clean=True', exclude this pattern from the removal list and preserve in the destination. Example:
- exclude_pat: APPDATA* :: glob matches APPDATA.01, APPDATA.02,.. for exclusion - exclude_pat: E@(APPDATA)|(TEMPDATA) :: regexp matches APPDATA or TEMPDATA for exclusion
- maxdepth
When copying, only copy paths which are depth maxdepth from the source path. Example:
- maxdepth: 0 :: Only include files located in the source directory - maxdepth: 1 :: Only include files located in the source or immediate subdirectories
- keep_symlinks
- Keep symlinks when copying from the source. This option will cause the copy operation to terminate at the symlink. If you are after rsync-ish behavior, then set this to True.
- force_symlinks
- Force symlink creation. This option will force the symlink creation. If a file or directory is obstructing symlink creation it will be recursively removed so that symlink creation can proceed. This option is usually not needed except in special circumstances.
-
salt.states.file.
rename
(name, source, force=False, makedirs=False)¶ If the source file exists on the system, rename it to the named file. The named file will not be overwritten if it already exists unless the force option is set to True.
- name
- The location of the file to rename to
- source
- The location of the file to move to the location specified with name
- force
- If the target location is present then the file will not be moved, specify "force: True" to overwrite the target file
- makedirs
- If the target subdirectories don't exist create them
-
salt.states.file.
replace
(name, pattern, repl, count=0, flags=0, bufsize=1, backup='.bak', show_changes=True)¶ Maintain an edit in a file
New in version 0.17.0.
Params are identical to
replace()
.
-
salt.states.file.
sed
(name, before, after, limit='', backup='.bak', options='-r -e', flags='g', negate_match=False)¶ Deprecated since version 0.17.0: Use
replace()
instead.Maintain a simple edit to a file
The file will be searched for the
before
pattern before making the edit. In general thelimit
pattern should be as specific as possible andbefore
andafter
should contain the minimal text to be changed.- before
- A pattern that should exist in the file before the edit.
- after
- A pattern that should exist in the file after the edit.
- limit
- An optional second pattern that can limit the scope of the before pattern.
- backup : '.bak'
- The extension for the backed-up version of the file before the edit. If no backups is desired, pass in the empty string: ''
- options :
-r -e
- Any options to pass to the
sed
command.-r
uses extended regular expression syntax and-e
denotes that what follows is an expression that sed will execute. - flags :
g
- Any flags to append to the sed expression.
g
specifies the edit should be made globally (and not stop after the first replacement). - negate_match : False
Negate the search command (
!
)New in version 0.17.0.
Usage:
# Disable the epel repo by default /etc/yum.repos.d/epel.repo: file.sed: - before: 1 - after: 0 - limit: ^enabled= # Remove ldap from nsswitch /etc/nsswitch.conf: file.sed: - before: 'ldap' - after: '' - limit: '^passwd:'
New in version 0.9.5.
-
salt.states.file.
serialize
(name, dataset, user=None, group=None, mode=None, env=None, backup='', show_diff=True, create=True, **kwargs)¶ Serializes dataset and store it into managed file. Useful for sharing simple configuration files.
- name
- The location of the symlink to create
- dataset
- the dataset that will be serialized
- formatter
- the formatter, currently only yaml and json are supported
- user
- The user to own the directory, this defaults to the user salt is running as on the minion
- group
- The group ownership set for the directory, this defaults to the group salt is running as on the minion
- mode
- The permissions to set on this file, aka 644, 0775, 4664
- backup
- Overrides the default backup mode for this specific file.
- show_diff
- If set to False, the diff will not be shown.
- create
- Default is True, if create is set to False then the file will only be managed if the file already exists on the system.
For example, this state:
/etc/dummy/package.json: file.serialize: - dataset: name: naive description: A package using naive versioning author: A confused individual <iam@confused.com> dependencies: express: >= 1.2.0 optimist: >= 0.1.0 engine: node 0.4.1 - formatter: json
will manages the file
/etc/dummy/package.json
:{ "author": "A confused individual <iam@confused.com>", "dependencies": { "express": ">= 1.2.0", "optimist": ">= 0.1.0" }, "description": "A package using naive versioning", "engine": "node 0.4.1" "name": "naive", }
-
salt.states.file.
symlink
(name, target, force=False, makedirs=False, user=None, group=None, mode=None, **kwargs)¶ Create a symlink
If the file already exists and is a symlink pointing to any location other than the specified target, the symlink will be replaced. If the symlink is a regular file or directory then the state will return False. If the regular file or directory is desired to be replaced with a symlink pass force: True.
- name
- The location of the symlink to create
- target
- The location that the symlink points to
- force
- If the location of the symlink exists and is not a symlink then the state will fail, set force to True and any file or directory in the way of the symlink file will be deleted to make room for the symlink
- makedirs
- If the location of the symlink does not already have a parent directory then the state will fail, setting makedirs to True will allow Salt to create the parent directory
-
salt.states.file.
touch
(name, atime=None, mtime=None, makedirs=False)¶ Replicate the 'nix "touch" command to create a new empty file or update the atime and mtime of an existing file.
Note that if you just want to create a file and don't care about atime or mtime, you should use
file.managed
instead, as it is more feature-complete. (Just leave out thesource
/template
/contents
arguments, and it will just create the file and/or check its permissions, without messing with contents)- name
- name of the file
- atime
- atime of the file
- mtime
- mtime of the file
- makedirs
- whether we should create the parent directory/directories in order to touch the file
Usage:
/var/log/httpd/logrotate.empty: file.touch
New in version 0.9.5.
-
salt.states.file.
uncomment
(name, regex, char='#', backup='.bak')¶ Uncomment specified commented lines in a file
- name
- 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()). The regex will be searched for from the beginning of the line, ignoring leading spaces (we prepend '^[ t]*') - 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
/uncomment
is called will overwrite this backup
Usage:
/etc/adduser.conf: file.uncomment: - regex: EXTRA_GROUPS
New in version 0.9.5.