Salt States可以在系统中主动操纵文件。已经有许多方式可以管理文件。
Regular files can be enforced with the file.managed
state. This state downloads files from the salt
master and places them on the target system. Managed 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 %}
It is also possible to use the py renderer
as a
templating option. The template would be a Python script which would need to
contain a function called run()
, which returns a string. All arguments
to the state will be made available to the Python script as globals. The
returned string will be the contents of the managed file. For example:
def run():
lines = ['foo', 'bar', 'baz']
lines.extend([source, name, user, context]) # Arguments as globals
return '\n\n'.join(lines)
注解
The defaults
and context
arguments require extra indentation (four
spaces instead of the normal two) in order to create a nested dictionary.
More information.
如果使用模板,任何自定义的模板变量定义在 source
文件必须通过使用 defaults
和/或 context
参数。通常最佳实践是定义默认值在 defaults
,然后条件覆盖写在 context
,就像上面看到的那样。
The template will receive a variable custom_var
, which would be accessed in
the template using {{ custom_var }}
. If the operating system is Ubuntu, the
value of the variable custom_var
would be override, otherwise it is the
default default value
source
参数可以作为一个列表指定。如果这样做的话,那么会使用第一个匹配到的文件。这个特性允许你如果请求的文件不存在于salt文件服务器时有一个默认的文件回溯。以下是一个范例:
/etc/foo.conf:
file.managed:
- source:
- salt://foo.conf.{{ grains['fqdn'] }}
- salt://foo.conf.fallback
- user: foo
- group: users
- mode: 644
- backup: minion
注解
Salt supports backing up managed files via the backup option. For more details on this functionality please review the backup_mode documentation.
source
参数同样可以指定一个在另一个Salt环境的文件。在这个例子中 foo.conf
将会使用 dev
环境中的来替代。
/etc/foo.conf:
file.managed:
- source:
- salt://foo.conf?saltenv=dev
- user: foo
- group: users
- mode: '0644'
警告
当使用一个包含一个前导零 0 的模式时你必须用单引号引起这个值。如果没有用引号引起这个值,会被YAML作为一个八进制整数读取。
特殊文件可以通过 mknod
函数管理。这个函数会创建特殊文件并赋予权限。这个函数支持创建字符设备,块设备,和fifo管道。如果这个文件被minion需要时,该函数会为这个特殊文件创建相应的目录结构。这个函数不会对已存在的特殊文件覆盖或操作(更改主/次数字),除了用户,组,和权限。在大多数情况下,创建特殊文件需要在minion上有root权限。这将要求minion使用root用户运行。这是一个关于字符设备的范例:
/var/named/chroot/dev/random:
file.mknod:
- ntype: c
- major: 1
- minor: 8
- user: named
- group: named
- mode: 660
这是一个关于块设备的例子:
/var/named/chroot/dev/loop0:
file.mknod:
- ntype: b
- major: 7
- minor: 0
- user: named
- group: named
- mode: 660
这是一个关于fifo管道的例子:
/var/named/chroot/var/log/logfifo:
file.mknod:
- ntype: p
- user: named
- group: named
- mode: 660
目录可以通过 directory
函数管理。这个函数可以创建一个目录并赋予权限。一个目录声明会看起来像这样:
/srv/stuff/substuf:
file.directory:
- user: fred
- group: users
- mode: 755
- makedirs: True
如果你需要递归目录结构更改用户和/或组所有者或权限,你可以通过添加一个 recurse
指令实现:
/srv/stuff/substuf:
file.directory:
- user: fred
- group: users
- mode: 755
- makedirs: True
- recurse:
- user
- group
- mode
默认情况下, mode
会决定 dir_mode
和 file_mode
,同时指定目录和文件的权限,使用这个形式:
/srv/stuff/substuf:
file.directory:
- user: fred
- group: users
- file_mode: 744
- dir_mode: 755
- makedirs: True
- recurse:
- user
- group
- mode
软连接可以很容易的创建;软连接功能非常简单,只需要几个参数:
/etc/grub.conf:
file.symlink:
- target: /boot/grub/grub.conf
递归目录管理同样可以通过设置 recurse
函数完成。递归目录管理允许一个在salt master上的目录递归的复制到minion。这是一个部署大型代码和配置系统的强大的工具。一个使用 recurse
的state看起来会是这样:
/opt/code/flask:
file.recurse:
- source: salt://code/flask
- include_empty: True
A more complex recurse
example:
{% set site_user = 'testuser' %}
{% set site_name = 'test_site' %}
{% set project_name = 'test_proj' %}
{% set sites_dir = 'test_dir' %}
django-project:
file.recurse:
- name: {{ sites_dir }}/{{ site_name }}/{{ project_name }}
- user: {{ site_user }}
- dir_mode: 2775
- file_mode: '0644'
- template: jinja
- source: salt://project/templates_dir
- include_empty: True
salt.states.file.
absent
(name)¶Make sure that the named file or directory is absent. If it exists, it will be deleted. This will work to reverse any of the functions in the file state module. If a directory is supplied, it will be recursively 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. It can also be used in file.blockreplace.
累加器的名字
将会收到这个累加器中的文件名 (参见file.managed state文档关于 name
的部分)
要加入累加器的字符串或列表
当中一个必须确保在我们管理文件之前装填进累加器。可能与filename相同
范例:
Given the following:
animals_doing_things:
file.accumulated:
- filename: /tmp/animal_file.txt
- text: ' jumps over the lazy dog.'
- require_in:
- file: animal_file
animal_file:
file.managed:
- name: /tmp/animal_file.txt
- source: salt://animal_file.txt
- template: jinja
One might write a template for animal_file.txt
like the following:
The quick brown fox{% for animal in accumulator['animals_doing_things'] %}{{ animal }}{% endfor %}
Collectively, the above states and template file will produce:
The quick brown fox jumps over the lazy dog.
Multiple accumulators can be "chained" together.
注解
The 'accumulator' data structure is a Python dictionary. Do not expect any loop over the keys in a deterministic order!
salt.states.file.
append
(name, text=None, makedirs=False, source=None, source_hash=None, template='jinja', sources=None, source_hashes=None, defaults=None, context=None, ignore_whitespace=True)¶Ensure that some text appears at the end of a file.
The text will not be appended if it already exists in the file. A single string of text or a list of strings may be appended.
A single source file to append. This source file can be hosted on either the salt master server, or on an HTTP or FTP server. Both HTTPS and HTTP are supported as well as downloading directly from Amazon S3 compatible URLs with both pre-configured and automatic IAM credentials (see s3.get state documentation). File retrieval from Openstack Swift object storage is supported via swift://container/object_path URLs (see swift.get documentation).
For files hosted on the salt file server, if the file is located on the master in the directory named spam, and is called eggs, the source string is salt://spam/eggs.
If the file is hosted on an HTTP or FTP server, the source_hash argument is also required.
The function accepts the first encountered long unbroken alphanumeric string of correct length as a valid hash, in order from most secure to least secure:
Type Length
====== ======
sha512 128
sha384 96
sha256 64
sha224 56
sha1 40
md5 32
The file can contain several checksums for several files. Each line must contain both the file name and the hash. If no file name is matched, the first hash encountered will be used, otherwise the most secure hash with the correct source file name will be used.
Debian file type *.dsc
is supported.
Examples:
/etc/rc.conf ef6e82e4006dee563d98ada2a2a80a27
sha254c8525aee419eb649f0233be91c151178b30f0dff8ebbdcc8de71b1d5c8bcc06a /etc/resolv.conf
ead48423703509d37c4a90e6a0d53e143b6fc268
If the remote server URL has the hash file as an apparent sub-directory of the source file, the module will discover that it has already cached a directory where a file should be cached. For example:
tomdroid-src-0.7.3.tar.gz:
file.managed:
- name: /tmp/tomdroid-src-0.7.3.tar.gz
- source: https://launchpad.net/tomdroid/beta/0.7.3/+download/tomdroid-src-0.7.3.tar.gz
- source_hash: https://launchpad.net/tomdroid/beta/0.7.3/+download/tomdroid-src-0.7.3.tar.gz/+md5
jinja
2015.8.4 新版功能.
Spaces and Tabs in text are ignored by default, when searching for the
appending content, one space or multiple tabs are the same for salt.
Set this option to False
if you want to change this behavior.
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
0.9.5 新版功能.
salt.states.file.
blockreplace
(name, marker_start='#-- start managed zone --', marker_end='#-- end managed zone --', source=None, source_hash=None, template='jinja', sources=None, source_hashes=None, defaults=None, context=None, content='', append_if_not_found=False, prepend_if_not_found=False, backup='.bak', show_changes=True)¶Maintain an edit in a file in a zone delimited by two line markers
2014.1.0 新版功能.
A block of content delimited by comments can help you manage several lines entries without worrying about old entries removal. This can help you maintaining an un-managed file containing manual edits. 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.
marker_start
and marker_end
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. Both HTTPS and HTTP are supported as well as downloading directly from Amazon S3 compatible URLs with both pre-configured and automatic IAM credentials. (see s3.get state documentation) File retrieval from Openstack Swift object storage is supported via swift://container/object_path URLs, see swift.get documentation. For files hosted on the salt file server, if the file is located on the master in the directory named spam, and is called eggs, the source string is salt://spam/eggs. If source is left blank or None (use ~ in YAML), the file will be created as an empty file and the content will not be managed. This is also the case when a file already exists and the source is undefined; the contents of the file will not be changed or managed.
If the file is hosted on a HTTP or FTP server then the source_hash argument is also required
A list of sources can also be passed in to provide a default source and a set of fallbacks. The first source in the list that is found to exist will be used and subsequent entries in the list will be ignored.
file_override_example:
file.managed:
- source:
- salt://file_that_does_not_exist
- salt://file_that_exists
The function accepts the first encountered long unbroken alphanumeric string of correct length as a valid hash, in order from most secure to least secure:
Type Length
====== ======
sha512 128
sha384 96
sha256 64
sha224 56
sha1 40
md5 32
The file can contain several checksums for several files. Each line must contain both the file name and the hash. If no file name is matched, the first hash encountered will be used, otherwise the most secure hash with the correct source file name will be used.
When using a source hash file the source_hash argument needs to be a url, the standard download urls are supported, ftp, http, salt etc:
范例:
tomdroid-src-0.7.3.tar.gz:
file.managed:
- name: /tmp/tomdroid-src-0.7.3.tar.gz
- source: https://launchpad.net/tomdroid/beta/0.7.3/+download/tomdroid-src-0.7.3.tar.gz
- source_hash: https://launchpad.net/tomdroid/beta/0.7.3/+download/tomdroid-src-0.7.3.hash
The following is an example of the supported source_hash format:
/etc/rc.conf ef6e82e4006dee563d98ada2a2a80a27
sha254c8525aee419eb649f0233be91c151178b30f0dff8ebbdcc8de71b1d5c8bcc06a /etc/resolv.conf
ead48423703509d37c4a90e6a0d53e143b6fc268
Debian file type *.dsc
files are also supported.
Examples:
tomdroid-src-0.7.3.tar.gz:
file.managed:
- name: /tmp/tomdroid-src-0.7.3.tar.gz
- source: https://launchpad.net/tomdroid/beta/0.7.3/+download/tomdroid-src-0.7.3.tar.gz
- source_hash: md5=79eef25f9b0b2c642c62b7f737d4f53f
False
False
False
to skip making a backup.False
return a boolean if any changes were madeExample of usage with an accumulator and with a variable:
{% set myvar = 42 %}
hosts-config-block-{{ myvar }}:
file.blockreplace:
- name: /etc/hosts
- marker_start: "# START managed zone {{ myvar }} -DO-NOT-EDIT-"
- marker_end: "# END managed zone {{ myvar }} --"
- content: 'First line of content'
- append_if_not_found: True
- backup: '.bak'
- show_changes: True
hosts-config-block-{{ myvar }}-accumulated1:
file.accumulated:
- filename: /etc/hosts
- name: my-accumulator-{{ myvar }}
- text: "text 2"
- require_in:
- file: hosts-config-block-{{ myvar }}
hosts-config-block-{{ myvar }}-accumulated2:
file.accumulated:
- filename: /etc/hosts
- name: my-accumulator-{{ myvar }}
- text: |
text 3
text 4
- require_in:
- file: hosts-config-block-{{ myvar }}
will generate and maintain a block of content in /etc/hosts
:
# START managed zone 42 -DO-NOT-EDIT-
First line of content
text 2
text 3
text 4
# END managed zone 42 --
salt.states.file.
comment
(name, regex, char='#', backup='.bak')¶在文件中注释掉指定行。
要编辑的文件的完整路径
^
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.#
.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.
Usage:
/etc/fstab:
file.comment:
- regex: ^bind 127.0.0.1
0.9.5 新版功能.
salt.states.file.
copy
(name, source, force=False, makedirs=False, preserve=False, user=None, group=None, mode=None, subdir=False, **kwargs)¶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.
2015.5.0 新版功能.
Set preserve: True
to preserve user/group ownership and mode
after copying. Default is False
. If preserve
is set to True
,
then user/group/mode attributes will be ignored.
2015.5.0 新版功能.
The user to own the copied file, this defaults to the user salt is
running as on the minion. If preserve
is set to True
, then
this will be ignored
2015.5.0 新版功能.
The group to own the copied file, this defaults to the group salt is
running as on the minion. If preserve
is set to True
or on
Windows this will be ignored
2015.5.0 新版功能.
The permissions to set on the copied file, aka 644, '0775', '4664'.
If preserve
is set to True
, then this will be ignored.
Not supported on Windows
2015.5.0 新版功能.
If the name is a directory then place the file inside the named directory
salt.states.file.
decode
(name, encoded_data=None, contents_pillar=None, encoding_type='base64', checksum='md5')¶Decode an encoded file and write it to disk
2016.3.0 新版功能.
contents_pillar
must be
specified.pillar.get
. The
hashutil.base64_encodefile
function can load encoded
content into Pillar. Either this option or encoded_data
must be
specified.base64
md5
hashutil.digest
execution
function.Usage:
write_base64_encoded_string_to_a_file:
file.decode:
- name: /tmp/new_file
- encoding_type: base64
- contents_pillar: mypillar:thefile
# or
write_base64_encoded_string_to_a_file:
file.decode:
- name: /tmp/new_file
- encoding_type: base64
- encoded_data: |
Z2V0IHNhbHRlZAo=
Be careful with multi-line strings that the YAML indentation is correct. E.g.,
write_base64_encoded_string_to_a_file:
file.decode:
- name: /tmp/new_file
- encoding_type: base64
- encoded_data: |
{{ salt.pillar.get('path:to:data') | indent(8) }}
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, follow_symlinks=False, force=False, backupname=None, allow_symlink=True, **kwargs)¶Ensure that a named directory is present and has the right perms
Enforce user/group ownership and mode of directory recursively. Accepts
a list of strings representing what you would like to recurse. If
mode
is defined, will recurse on both file_mode
and dir_mode
if
they are defined. If ignore_files
or ignore_dirs
is included, files or
directories will be left unchanged respectively.
Example:
/var/log/httpd:
file.directory:
- user: root
- group: root
- dir_mode: 755
- file_mode: 644
- recurse:
- user
- group
- mode
Leave files or directories unchanged:
/var/log/httpd:
file.directory:
- user: root
- group: root
- dir_mode: 755
- file_mode: 644
- recurse:
- user
- group
- mode
- ignore_dirs
2015.5.0 新版功能.
If the desired path is a symlink (or recurse
is defined and a
symlink is encountered while recursing), follow it and check the
permissions of the directory/file to which the symlink points.
2014.1.4 新版功能.
If the name of the directory exists and is not a directory and force is set to False, the state will fail. If force is set to True, the file in the way of the directory will be deleted to make room for the directory, unless backupname is set, then it will be renamed.
2014.7.0 新版功能.
If the name of the directory exists and is not a directory, it will be renamed to the backupname. If the backupname already exists and force is False, the state will fail. Otherwise, the backupname will be removed first.
2014.7.0 新版功能.
If allow_symlink is True and the specified path is a symlink, it will be allowed to remain if it points to a directory. If allow_symlink is False then the state will fail, unless force is also set to True, in which case it will be removed or renamed, depending on the value of the backupname argument.
2014.7.0 新版功能.
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.
salt.states.file.
line
(name, content, match=None, mode=None, location=None, before=None, after=None, show_changes=True, backup=False, quiet=False, indent=True, create=False, user=None, group=None, file_mode=None)¶Line-based editing of a file.
2015.8.0 新版功能.
参数: |
|
---|
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.states.file.
managed
(name, source=None, source_hash='', user=None, group=None, mode=None, template=None, makedirs=False, dir_mode=None, context=None, replace=True, defaults=None, backup='', show_changes=True, create=True, contents=None, contents_pillar=None, contents_grains=None, contents_newline=True, contents_delimiter=':', allow_empty=True, follow_symlinks=True, check_cmd=None, skip_verify=False, **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.
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. Both HTTPS and HTTP are supported as well as downloading directly from Amazon S3 compatible URLs with both pre-configured and automatic IAM credentials. (see s3.get state documentation) File retrieval from Openstack Swift object storage is supported via swift://container/object_path URLs, see swift.get documentation. For files hosted on the salt file server, if the file is located on the master in the directory named spam, and is called eggs, the source string is salt://spam/eggs. If source is left blank or None (use ~ in YAML), the file will be created as an empty file and the content will not be managed. This is also the case when a file already exists and the source is undefined; the contents of the file will not be changed or managed.
If the file is hosted on a HTTP or FTP server then the source_hash argument is also required
A list of sources can also be passed in to provide a default source and a set of fallbacks. The first source in the list that is found to exist will be used and subsequent entries in the list will be ignored. Source list functionality only supports local files and remote files hosted on the salt master server or retrievable via HTTP, HTTPS, or FTP.
file_override_example:
file.managed:
- source:
- salt://file_that_does_not_exist
- salt://file_that_exists
The function accepts the first encountered long unbroken alphanumeric string of correct length as a valid hash, in order from most secure to least secure:
Type Length
====== ======
sha512 128
sha384 96
sha256 64
sha224 56
sha1 40
md5 32
The file can contain several checksums for several files. Each line must contain both the file name and the hash. If no file name is matched, the first hash encountered will be used, otherwise the most secure hash with the correct source file name will be used.
When using a source hash file the source_hash argument needs to be a url, the standard download urls are supported, ftp, http, salt etc:
范例:
tomdroid-src-0.7.3.tar.gz:
file.managed:
- name: /tmp/tomdroid-src-0.7.3.tar.gz
- source: https://launchpad.net/tomdroid/beta/0.7.3/+download/tomdroid-src-0.7.3.tar.gz
- source_hash: https://launchpad.net/tomdroid/beta/0.7.3/+download/tomdroid-src-0.7.3.hash
The following is an example of the supported source_hash format:
/etc/rc.conf ef6e82e4006dee563d98ada2a2a80a27
sha254c8525aee419eb649f0233be91c151178b30f0dff8ebbdcc8de71b1d5c8bcc06a /etc/resolv.conf
ead48423703509d37c4a90e6a0d53e143b6fc268
Debian file type *.dsc
files are also supported.
Examples:
tomdroid-src-0.7.3.tar.gz:
file.managed:
- name: /tmp/tomdroid-src-0.7.3.tar.gz
- source: https://launchpad.net/tomdroid/beta/0.7.3/+download/tomdroid-src-0.7.3.tar.gz
- source_hash: md5=79eef25f9b0b2c642c62b7f737d4f53f
If the remote server URL has the hash file as an apparent sub-directory of the source file, the module will discover that it has already cached a directory where a file should be cached. For example:
tomdroid-src-0.7.3.tar.gz:
file.managed:
- name: /tmp/tomdroid-src-0.7.3.tar.gz
- source: https://launchpad.net/tomdroid/beta/0.7.3/+download/tomdroid-src-0.7.3.tar.gz
- source_hash: https://launchpad.net/tomdroid/beta/0.7.3/+download/tomdroid-src-0.7.3.tar.gz/+md5
True
, then the parent directories will be created to
facilitate the creation of the named file. If False
, and the parent
directory of the destination file doesn't exist, the state will fail.False
and the file already exists, the file will not be
modified even if changes would otherwise be made. Permissions and
ownership will still be enforced, however.False
return a boolean if any changes were made.False
, then the file will only be managed if the file
already exists on the system.Specify the contents of the file. Cannot be used in combination with
source
. Ignores hashes and does not use a templating engine.
This value can be either a single string, a multiline YAML string or a list of strings. If a list of strings, then the strings will be joined together with newlines in the resulting file. For example, the below two example states would result in identical file contents:
/path/to/file1:
file.managed:
- contents:
- This is line 1
- This is line 2
/path/to/file2:
file.managed:
- contents: |
This is line 1
This is line 2
0.17.0 新版功能.
Operates like contents
, but draws from a value stored in pillar,
using the pillar path syntax used in pillar.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.
For example, the following could be used to deploy an SSH private key:
/home/deployer/.ssh/id_rsa:
file.managed:
- user: deployer
- group: deployer
- mode: 600
- contents_pillar: userdata:deployer:id_rsa
This would populate /home/deployer/.ssh/id_rsa
with the contents of
pillar['userdata']['deployer']['id_rsa']
. An example of this pillar
setup would be like so:
userdata:
deployer:
id_rsa: |
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAoQiwO3JhBquPAalQF9qP1lLZNXVjYMIswrMe2HcWUVBgh+vY
U7sCwx/dH6+VvNwmCoqmNnP+8gTPKGl1vgAObJAnMT623dMXjVKwnEagZPRJIxDy
B/HaAre9euNiY3LvIzBTWRSeMfT+rWvIKVBpvwlgGrfgz70m0pqxu+UyFbAGLin+
GpxzZAMaFpZw4sSbIlRuissXZj/sHpQb8p9M5IeO4Z3rjkCP1cxI
-----END RSA PRIVATE KEY-----
注解
The private key above is shortened to keep the example brief, but shows how to do multiline string in YAML. The key is followed by a pipe character, and the mutliline string is indented two more spaces.
To avoid the hassle of creating an indented multiline YAML string,
the file_tree external pillar
can
be used instead. However, this will not work for binary files in
Salt releases before 2015.8.4.
2014.7.0 新版功能.
Same as contents_pillar
, but with grains
2014.7.0 新版功能.
在 2015.8.4 版更改: This option is now ignored if the contents being deployed contain binary data.
If True
, files managed using contents
, contents_pillar
, or
contents_grains
will have a newline added to the end of the file if
one is not present. Setting this option to False
will omit this
final newline.
2015.8.4 新版功能.
Can be used to specify an alternate delimiter for contents_pillar
or contents_grains
. This delimiter will be passed through to
pillar.get
or grains.get
when retrieving the contents.
2015.8.4 新版功能.
If set to False
, then the state will fail if the contents specified
by contents_pillar
or contents_grains
are empty.
2014.7.0 新版功能.
If the desired path is a symlink follow it and make changes to the file to which the symlink points.
2014.7.0 新版功能.
The specified command will be run with an appended argument of a temporary file containing the new managed contents. If the command exits with a zero status the new managed contents will be written to the managed destination. If the command exits with a nonzero exit code, the state will fail and no changes will be made to the file.
For example, the following could be used to verify sudoers before making changes:
/etc/sudoers:
file.managed:
- user: root
- group: root
- mode: 0440
- source: salt://sudoers/files/sudoers.jinja
- template: jinja
- check_cmd: /usr/sbin/visudo -c -f
NOTE: This check_cmd
functions differently than the requisite
check_cmd
.
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 新版功能.
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.
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), and b
(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 'nix mknod
. 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.
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
0.17.0 新版功能.
salt.states.file.
mod_run_check_cmd
(cmd, filename, **check_cmd_opts)¶Execute the check_cmd logic.
Return a result dict if check_cmd
succeeds (check_cmd == 0)
otherwise return True
salt.states.file.
patch
(name, source=None, hash=None, options='', dry_run_first=True, **kwargs)¶Apply a patch to a file or directory.
注解
A suitable patch
executable must be available on the minion when
using this state function.
True
--dry-run
first to check if it will apply cleanly.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.
prepend
(name, text=None, makedirs=False, source=None, source_hash=None, template='jinja', sources=None, source_hashes=None, defaults=None, context=None)¶Ensure that some text appears at the beginning of a file
The text will not be prepended 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.prepend:
- 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.prepend:
- 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:
- prepend
- template: jinja
- sources:
- salt://motd/devops-messages.tmpl
- salt://motd/hr-messages.tmpl
- salt://motd/general-messages.tmpl
2014.7.0 新版功能.
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, 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.
注解
The template option is required when recursively applying templates.
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 this pattern from the source when copying. 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
When copying, only copy paths which are of 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
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.
salt.states.file.
replace
(name, pattern, repl, count=0, flags=8, bufsize=1, append_if_not_found=False, prepend_if_not_found=False, not_found_content=None, backup='.bak', show_changes=True)¶Maintain an edit in a file.
0.17.0 新版功能.
search()
.['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.If set to True
, and pattern is not found, then the content will be
appended to the file.
2014.7.0 新版功能.
If set to True
and pattern is not found, then the content will be
prepended to the file.
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.
2014.7.0 新版功能.
False
to skip making a backup.False
return a boolean if any changes were made. Returns a boolean or a
string.For complex regex patterns, it can be useful to avoid the need for complex quoting and escape sequences by making use of YAML's multiline string syntax.
complex_search_and_replace:
file.replace:
# <...snip...>
- pattern: |
CentOS \(2.6.32[^\n]+\n\s+root[^\n]+\n\)+
注解
When using YAML multiline string syntax in pattern:
, make sure to
also use that syntax in the repl:
part, or you might loose line
feeds.
salt.states.file.
serialize
(name, dataset=None, dataset_pillar=None, user=None, group=None, mode=None, backup='', makedirs=False, show_diff=True, create=True, merge_if_exists=False, **kwargs)¶Serializes dataset and store it into managed file. Useful for sharing simple configuration files.
Operates like dataset
, but draws from a value stored in pillar,
using the pillar path syntax used in pillar.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.
FIXME 新版功能.
Write the data as this format. Supported output formats:
Create parent directories for destination file.
2014.1.3 新版功能.
Default is False, if merge_if_exists is True then the existing file will be parsed and the dataset passed in will be merged with the existing content
2014.7.0 新版功能.
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 manage 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, backupname=None, makedirs=False, user=None, group=None, mode=None, **kwargs)¶Create a symbolic link (symlink, soft link)
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, if it is to be renamed, pass a backupname.
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 the source
/template
/contents
arguments, and it will just create the file and/or check its permissions,
without messing with contents)
Usage:
/var/log/httpd/logrotate.empty:
file.touch
0.9.5 新版功能.
salt.states.file.
uncomment
(name, regex, char='#', backup='.bak')¶Uncomment specified commented lines in a file
要编辑的文件的完整路径
^
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]*')#
.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.
Usage:
/etc/adduser.conf:
file.uncomment:
- regex: EXTRA_GROUPS
0.9.5 新版功能.