salt.modules.file

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

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

2014.1.0 新版功能.

Test whether the Salt process has the specified access to the file. One of the following modes must be specified:

CLI 范例:

salt '*' file.access /path/to/file f
salt '*' file.access /path/to/file x
salt.modules.file.append(path, *args, **kwargs)

0.9.5 新版功能.

Append text to the end of a file

path
path to file
*args
strings to append to file

CLI 范例:

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.basename(path)

Returns the final component of a pathname

2015.5.0 新版功能.

This can be useful at the CLI but is frequently useful when scripting.

{%- set filename = salt['file.basename'](source_file) %}

CLI 范例:

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)

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.

注解

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 a line as the end 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
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 True then, the markers and content will be appended to the file.
prepend_if_not_found : False
If markers are not found and set to True then, the markers and content will be prepended to the file.
backup
The file extension to use for a backup of the file if any edit is made. Set to False to skip making a backup.
dry_run
Don't make any edits to the file.
show_changes
Output a unified diff of the old file and the new file. If False, return a boolean if any changes were made.

CLI 范例:

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.check_file_meta(name, sfn, source, source_sum, user, group, mode, saltenv, contents=None)

Check for the changes in the file metadata.

CLI 范例:

salt '*' file.check_file_meta /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' base

注解

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
saltenv
Salt environment used to resolve source files
contents
File contents
salt.modules.file.check_hash(path, file_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 范例:

salt '*' file.check_hash /etc/fstab md5:<md5sum>
salt.modules.file.check_managed(name, source, source_hash, user, group, mode, template, context, defaults, saltenv, contents=None, skip_verify=False, **kwargs)

Check to see what changes need to be made for a file

CLI 范例:

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, user, group, mode, template, context, defaults, saltenv, contents=None, skip_verify=False, **kwargs)

Return a dictionary of what changes need to be made for a file

CLI 范例:

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, follow_symlinks=False)

Check the permissions on files and chown if needed

CLI 范例:

salt '*' file.check_perms /etc/sudoers '{}' root root 400

在 2014.1.3 版更改: follow_symlinks option added

salt.modules.file.chgrp(path, group)

Change the group of a file

path
path to the file or directory
group
group owner

CLI 范例:

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 范例:

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

0.17.0 版后已移除: Use replace() instead.

Comment out specified lines in a file

path

要编辑的文件的完整路径

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

警告

This backup will be overwritten each time sed / comment / uncomment is called. Meaning the backup will only be useful after the first invocation.

CLI 范例:

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.

参数:
  • 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 .bak
返回:

boolean Returns True if successful, False if not

CLI 范例:

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 范例:

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'
salt.modules.file.contains(path, text)

0.17.0 版后已移除: Use search() instead.

Return True if the file at path contains text

CLI 范例:

salt '*' file.contains /etc/crontab 'mymaintenance.sh'
salt.modules.file.contains_glob(path, glob_expr)

0.17.0 版后已移除: Use search() instead.

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

CLI 范例:

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

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 范例:

salt '*' file.contains_regex /etc/crontab
salt.modules.file.contains_regex_multiline(path, regex)

0.17.0 版后已移除: Use search() instead.

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

Traverses multiple lines at a time, via the salt BufferedReader (reads in chunks)

CLI 范例:

salt '*' file.contains_regex_multiline /etc/crontab '^maint'
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.

CLI 范例:

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)

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 范例:

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 范例:

salt '*' file.directory_exists /etc
salt.modules.file.dirname(path)

Returns the directory component of a pathname

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 范例:

salt '*' file.dirname 'test/path/filename.config'
salt.modules.file.diskusage(path)

Recursively calculate disk usage of path and return it in bytes

CLI 范例:

salt '*' file.diskusage /path/to/check
salt.modules.file.extract_hash(hash_fn, hash_type='sha256', file_name='')

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 lay out rules. It specifically permits pulling hash codes from debian *.dsc files.

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 范例:

salt '*' file.extract_hash /etc/foo sha512 /path/to/hash/file
salt.modules.file.file_exists(path)

Tests to see if path is a valid file. Returns True/False.

CLI 范例:

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
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范例:

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 范例:

salt '*' file.get_devmm /dev/chr
salt.modules.file.get_diff(minionfile, masterfile, saltenv='base')

Return unified diff of file compared to file on master

CLI 范例:

salt '*' file.get_diff /home/fred/.vimrc salt://users/fred/.vimrc
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 范例:

salt '*' file.get_gid /etc/passwd

在 0.16.4 版更改: follow_symlinks option 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 范例:

salt '*' file.get_group /etc/passwd

在 0.16.4 版更改: follow_symlinks option added

salt.modules.file.get_hash(path, form='sha256', chunk_size=65536)

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'

path
path to the file or directory
form
desired sum format
chunk_size
amount to sum at once

CLI 范例:

salt '*' file.get_hash /etc/shadow
salt.modules.file.get_managed(name, template, source, source_hash, user, group, mode, saltenv, context, defaults, skip_verify, **kwargs)

Return the managed file data for file.managed

name
location where the file lives on the server
模板
template format
source
managed source file
source_hash
hash of the source file
user
user owner
group
group owner
mode
file mode
context
variables to add to the environment
defaults
default values of for context_dict
skip_verify

If True, hash verification of remote file sources (http://, https://, ftp://) will be skipped, and the source_hash argument will be ignored.

2016.3.0 新版功能.

CLI 范例:

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, 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 范例:

salt '*' file.get_mode /etc/passwd

在 2014.1.0 版更改: follow_symlinks option added

salt.modules.file.get_selinux_context(path)

Get an SELinux context from a given path

CLI 范例:

salt '*' file.get_selinux_context /etc/hosts
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 范例:

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 范例:

salt '*' file.get_uid /etc/passwd

在 0.16.4 版更改: follow_symlinks option 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 范例:

salt '*' file.get_user /etc/passwd

在 0.16.4 版更改: follow_symlinks option 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 范例:

salt '*' file.gid_to_group 0
salt.modules.file.grep(path, pattern, *opts)

Grep for a string in the specified file

注解

This function's return value is slated for refinement in future versions of Salt

path

Path to the file to be searched

注解

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, or a[0-5]
opts

Additional command-line flags to pass to the grep command. For example: -v, or -i -B2

注解

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 范例:

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 范例:

salt '*' file.group_to_gid root
salt.modules.file.is_blkdev(name)

Check if a file exists and is a block device.

CLI 范例:

salt '*' file.is_blkdev /dev/blk
salt.modules.file.is_chrdev(name)

Check if a file exists and is a character device.

CLI 范例:

salt '*' file.is_chrdev /dev/chr
salt.modules.file.is_fifo(name)

Check if a file exists and is a FIFO.

CLI 范例:

salt '*' file.is_fifo /dev/fifo

Check if the path is a symbolic link

CLI 范例:

salt '*' file.is_link /path/to/link
salt.modules.file.join(*args)

Return a normalized file system path for the underlying OS

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 范例:

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 范例:

salt '*' file.chown /etc/passwd root root
salt.modules.file.line(path, content, match=None, mode=None, location=None, before=None, after=None, show_changes=True, backup=False, quiet=False, indent=True)

2015.8.0 新版功能.

Edit a line in the configuration file.

参数:
  • path -- Filesystem path to the file to be edited.
  • content -- Content of the line.
  • match -- Match the target line for an action by a fragment of a string or regular expression.
  • mode --
    Ensure:If line does not exist, it will be added.
    Replace:If line already exist, it will be replaced.
    Delete:Delete the line, once found.
    Insert:Insert a line.
  • location --
    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.
  • after -- Regular expression or an exact case-sensitive fragment of the string.
  • show_changes --

    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

    注解

    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.

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"

CLI范例:

salt '*' file.line /etc/nsswitch.conf "networks:        files dns" after="hosts:.*?" mode='ensure'

2014.1.0 新版功能.

Create a hard link to a file

CLI 范例:

salt '*' file.link /path/to/file /path/to/link
salt.modules.file.list_backups(path, limit=None)

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 范例:

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 范例:

salt '*' file.list_backups_dir /foo/bar/baz/
salt.modules.file.lstat(path)

2014.1.0 新版功能.

Returns the lstat attributes for the given file or dir. Does not support symbolic links.

CLI 范例:

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.

注解

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 范例:

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 范例:

salt '*' file.makedirs_perms /opt/code
salt.modules.file.manage_file(name, sfn, ret, source, source_sum, user, group, mode, saltenv, backup, makedirs=False, template=None, show_changes=True, contents=None, dir_mode=None, follow_symlinks=True, skip_verify=False)

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

name
location to place the file
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 None to use the default structure.
source
file reference on the master
source_hash
sum hash for source
user
user owner
group
group owner
backup
backup_mode
makedirs
make directories if they do not exist
模板
format of templating
show_changes
Include diff in state return
contents:
contents to be placed in the file
dir_mode
mode for directories created with makedirs
skip_verify : False

If True, hash verification of remote file sources (http://, https://, ftp://) will be skipped, and the source_hash argument will be ignored.

2016.3.0 新版功能.

CLI 范例:

salt '*' file.manage_file /etc/httpd/conf.d/httpd.conf '' '{}' salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root root '755' base ''

在 2014.7.0 版更改: follow_symlinks option added

salt.modules.file.mkdir(dir_path, user=None, group=None, mode=None)

Ensure that a directory is available.

CLI 范例:

salt '*' file.mkdir /opt/jetty/context
salt.modules.file.mknod(name, ntype, major=0, minor=0, user=None, group=None, mode='0600')

0.17.0 新版功能.

Create a block device, character device, or fifo pipe. Identical to the gnu mknod.

CLI范例:

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')

0.17.0 新版功能.

Create a block device.

CLI 范例:

salt '*' file.mknod_blkdev /dev/blk 8 999
salt.modules.file.mknod_chrdev(name, major, minor, user=None, group=None, mode='0660')

0.17.0 新版功能.

Create a character device.

CLI 范例:

salt '*' file.mknod_chrdev /dev/chr 180 31
salt.modules.file.mknod_fifo(name, user=None, group=None, mode='0660')

0.17.0 新版功能.

Create a FIFO pipe.

CLI 范例:

salt '*' file.mknod_fifo /dev/fifo
salt.modules.file.move(src, dst)

Move a file or directory

CLI 范例:

salt '*' file.move /path/to/src /path/to/dst
salt.modules.file.normpath(path)

Returns Normalize path, eliminating double slashes, etc.

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 范例:

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范例:

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

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 范例:

salt '*' file.pardir
salt.modules.file.patch(originalfile, patchfile, options='', dry_run=False)

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.

CLI 范例:

salt '*' file.patch /opt/file.txt /tmp/file.txt.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.

Hellium 新版功能.

CLI 范例:

salt '*' file.path_exists_glob /etc/pam*/pass*
salt.modules.file.prepend(path, *args, **kwargs)

2014.7.0 新版功能.

Prepend text to the beginning of a file

path
path to file
*args
strings to prepend to the file

CLI 范例:

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)

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

要编辑的文件的完整路径

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
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, \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).
multi: False
If True, treat the entire file as a single line

Forward slashes and single quotes will be escaped automatically in the before and after patterns.

CLI 范例:

salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info'
salt.modules.file.readdir(path)

2014.1.0 新版功能.

Return a list containing the contents of a directory

CLI 范例:

salt '*' file.readdir /path/to/dir/

2014.1.0 新版功能.

Return the path that a symlink points to If canonicalize is set to True, then it return the final target

CLI 范例:

salt '*' file.readlink /path/to/link
salt.modules.file.remove(path)

Remove the named file. If a directory is supplied, it will be recursively deleted.

CLI 范例:

salt '*' file.remove /tmp/foo
salt.modules.file.rename(src, dst)

Rename a file or directory

CLI 范例:

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)

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 returnd when changes are made, and False when no changes are made.

This is a pure Python implementation that wraps Python's sub().

path
Filesystem path to the file to be edited
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, only n occurrences will be replaced, otherwise all occurrences will be replaced.
flags (list or int)
A list of flags defined in the re module documentation. 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').
bufsize (int or str)
How much of the file to buffer into memory at once. The default value 1 processes one line at a time. The special value file may be specified which will read the entire file into memory before processing.
append_if_not_found : False

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

2014.7.0 新版功能.

If set to True and pattern is not found, then the content will be prepended to the file.

not_found_content

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.

backup : .bak
The file extension to use for a backup of the file before editing. Set to False to 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 a True/False value if show_changes is set to False).
search_only : False
If set to true, this no changes will be perfomed on the file, and this function will simply return True if the pattern was matched, and False if not.
show_changes : True

If True, return a diff of changes made. Otherwise, return True if changes were made, and False if not.

注解

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

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.

preserve_inode : True

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

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范例:

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)

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 范例:

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 范例:

salt '*' file.restorecon /home/user/.ssh/authorized_keys
salt.modules.file.rmdir(path)

2014.1.0 新版功能.

Remove the specified directory. Fails if a directory is not empty.

CLI 范例:

salt '*' file.rmdir /tmp/foo/
salt.modules.file.search(path, pattern, flags=8, bufsize=1, ignore_if_missing=False, multiline=False)

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 flags and sets bufsize to 'file'.

2015.8.0 新版功能.

CLI 范例:

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)

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

要编辑的文件的完整路径

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-insensitive pattern matching
negate_match : False

Negate the search command (!)

0.17.0 新版功能.

Forward slashes and single quotes will be escaped automatically in the before and after patterns.

CLI 范例:

salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info'
salt.modules.file.sed_contains(path, text, limit='', flags='g')

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 范例:

salt '*' file.contains /etc/crontab 'mymaintenance.sh'
salt.modules.file.seek_read(path, size, offset)

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 范例:

salt '*' file.seek_read /path/to/file 4096 0
salt.modules.file.seek_write(path, data, offset)

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 范例:

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 范例:

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 范例:

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

Check the source list and return the source to use

CLI 范例:

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 范例:

salt '*' file.stats /etc/passwd
salt.modules.file.statvfs(path)

2014.1.0 新版功能.

Perform a statvfs call against the filesystem that the file resides on

CLI 范例:

salt '*' file.statvfs /path/to/file

Create a symbolic link (symlink, soft link) to a file

CLI 范例:

salt '*' file.symlink /path/to/file /path/to/link
salt.modules.file.touch(name, atime=None, mtime=None)

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.

atime:
Access time in Unix epoch time
mtime:
Last modification in Unix epoch time

CLI 范例:

salt '*' file.touch /var/log/emptyfile
salt.modules.file.truncate(path, length)

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 范例:

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 范例:

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

0.17.0 版后已移除: Use replace() instead.

Uncomment specified commented lines in a file

path

要编辑的文件的完整路径

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/uncomment is called will overwrite this backup

CLI 范例:

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 范例:

salt '*' file.user_to_uid root
salt.modules.file.write(path, *args, **kwargs)

2014.7.0 新版功能.

Write text to a file, overwriting any existing contents.

path
path to file
*args
strings to write to the file

CLI 范例:

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']"