salt.modules.file

Manage information about files on the minion, set/read user, group, and mode data

salt.modules.file.append(path, *args)

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."

New in version 0.9.5.

salt.modules.file.check_file_meta(name, sfn, source, source_sum, user, group, mode, env)

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
salt.modules.file.check_hash(path, hash)

Check if a file matches the given hash string

Returns true if the hash matched, otherwise false. Raises ValueError if the hash was not formatted correctly.

path
A file path
hash
A string in the form <hash_type>=<hash_value>. For example: md5=e138491e9d5b97023cea823fe17bac22

CLI Example:

salt '*' file.check_hash /etc/fstab md5=<md5sum>
salt.modules.file.check_managed(name, source, source_hash, user, group, mode, template, makedirs, context, defaults, env, **kwargs)

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
salt.modules.file.check_perms(name, ret, user, group, mode)

Check the permissions on files and chown if needed

Note: 'mode' here is expected to be either a string or an integer,

in which case it will be converted into a base-10 string.

What this means is that in your YAML salt file, you can specify mode as an integer(eg, 644) or as a string(eg, '644'). But, to specify mode 0777, for example, it must be specified as the string, '0777' otherwise, 0777 will be parsed as an octal and you'd get 511 instead.

CLI Example:

salt '*' file.check_perms /etc/sudoers '{}' root root 400
salt.modules.file.chgrp(path, group)

Change the group of a file

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

CLI Example:

salt '*' file.chown /etc/passwd root root
salt.modules.file.comment(path, regex, char='#', backup='.bak')

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 / uncomment is called. Meaning the backup will only be useful after the first invocation.

CLI Example:

salt '*' file.comment /etc/modules pcspkr

New in version 0.9.5.

salt.modules.file.contains(path, text)

Return True if the file at path contains text

CLI Example:

salt '*' file.contains /etc/crontab 'mymaintenance.sh'

New in version 0.9.5.

salt.modules.file.contains_glob(path, glob)

Return True if the given glob matches a string in the named file

CLI Example:

salt '*' file.contains_glob /etc/foobar '*cheese*'
salt.modules.file.contains_regex(path, regex, lchar='')

Return True if the given regular expression matches anything in the text of a given file

CLI Example:

salt '*' file.contains_regex /etc/crontab '^maint'
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.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, **kwargs)

Approximate the Unix find(1) command and return a list of paths that meet the specified critera.

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]

The default action is 'print=path'.

file-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 re (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
salt.modules.file.get_diff(minionfile, masterfile, env='base')

Return unified diff of file compared to file on master

CLI Example:

salt \* file.get_diff /home/fred/.vimrc salt://users/fred/.vimrc
salt.modules.file.get_gid(path)

Return the id of the group that owns a given file

CLI Example:

salt '*' file.get_gid /etc/passwd
salt.modules.file.get_group(path)

Return the group that owns a given file

CLI Example:

salt '*' file.get_group /etc/passwd
salt.modules.file.get_hash(path, form='md5', chunk_size=4096)

Get the hash sum of a file

This is better than get_sum for 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_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
salt.modules.file.get_managed(name, template, source, source_hash, user, group, mode, env, context, defaults, **kwargs)

Return the managed file data for file.managed

CLI Example:

salt '*' file.get_managed /etc/httpd/conf.d/httpd.conf jinja salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root root '755' base None None
salt.modules.file.get_mode(path)

Return the mode of a file

CLI Example:

salt '*' file.get_mode /etc/passwd
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_sum(path, form='md5')

Return the sum for the given file, default is md5, sha1, sha224, sha256, sha384, sha512 are supported

CLI Example:

salt '*' file.get_sum /etc/passwd sha512
salt.modules.file.get_uid(path)

Return the id of the user that owns a given file

CLI Example:

salt '*' file.get_uid /etc/passwd
salt.modules.file.get_user(path)

Return the user that owns a given file

CLI Example:

salt '*' file.get_user /etc/passwd
salt.modules.file.gid_to_group(gid)

Convert the group id to the group name on this system

CLI Example:

salt '*' file.gid_to_group 0
salt.modules.file.group_to_gid(group)

Convert the group to the gid on this system

CLI Example:

salt '*' file.group_to_gid root
salt.modules.file.makedirs(path, user=None, group=None, mode=None)

Ensure that the directory containing this path is available.

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, env, backup)

Checks the destination against what was retrieved with get_managed and makes the appropriate modifications (if necessary).

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 ''
salt.modules.file.patch(originalfile, patchfile, options='', dry_run=False)

Apply a patch to a file

Equivalent to:

patch <options> <originalfile> <patchfile>
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.

CLI Example:

salt '*' file.patch /opt/file.txt /tmp/file.txt.patch

New in version 0.10.4.

salt.modules.file.remove(path)

Remove the named file

CLI Example:

salt '*' file.remove /tmp/foo
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.sed(path, before, after, limit='', backup='.bak', options='-r -e', flags='g', escape_all=False)

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/uncomment is called will overwrite this backup
options : -r -e
Options to pass to sed
flags : g
Flags to modify the sed search; e.g., i for case-insensitve pattern matching

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 0.9.5.

salt.modules.file.set_mode(path, mode)

Set the mode of a file

CLI Example:

salt '*' file.set_mode /etc/passwd 0644
salt.modules.file.set_selinux_context(path, user=None, role=None, type=None, range=None)

Set a specific SELinux label on a given path

CLI Example:

salt '*' file.set_selinux_context path <role> <type> <range>
salt.modules.file.source_list(source, source_hash, env)

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='md5', follow_symlink=False)

Return a dict containing the stats for a given file

CLI Example:

salt '*' file.stats /etc/passwd
salt.modules.file.touch(name, atime=None, mtime=None)

Just like 'nix's "touch" command, 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
mtime:
Last modification in Unix epoch time

CLI Example:

salt '*' file.touch /var/log/emptyfile

New in version 0.9.5.

salt.modules.file.uid_to_user(uid)

Convert a uid to a user name

CLI Example:

salt '*' file.uid_to_user 0
salt.modules.file.uncomment(path, regex, char='#', backup='.bak')

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; if a single whitespace character follows the comment it will also be removed
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

CLI Example:

salt '*' file.uncomment /etc/hosts.deny 'ALL: PARANOID'

New in version 0.9.5.

salt.modules.file.user_to_uid(user)

Convert user name to a uid

CLI Example:

salt '*' file.user_to_uid root

Parent topic

Previous topic

salt.modules.extfs

Next topic

salt.modules.freebsdjail