ansible的Host-pattern

双引号和单引号的使用要留意。

直接通配符

  1. all 表示所有主机列表中的主机
1
ansible all -m ping
    • 缺省通配符
1
ansible "*est" -m ping
  1. : 或关系
1
ansible "websrvs:appsrvs" -m ping
  1. :& 逻辑与

如:在A组且在B组中的主机

1
ansible "A:&B" -m ping
  1. :! 逻辑非
1
ansible 'A:!B' -m ping
  1. ~ 正则表达式
1
ansible "~(web|db).*"

ansible执行状态

  • 绿色表示执行成功且未做更改;

  • 黄色表示执行成功且做了更改;

  • 红色表示执行失败;

  • 蓝色表示详细过程;

  • 紫色表示警告;

  • 深灰表示debug;

  • 褐色表示弃用。

ansible常用模块

使用一个模块前,可以使用ansible-doc <moduel>查看一些帮助。

command模块

功能:在远程主机执行命令。

不好用,建议用shell模块代替

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
- argv
Passes the command as a list rather than a string.
Use `argv' to avoid quoting values that would otherwise be interpreted incorrectly (for example "user name").
Only the string or the list form can be provided, not both. One or the other must be provided.
[Default: (null)]
type: list
version_added: 2.6

- chdir
Change into this directory before running the command.
[Default: (null)]
type: path
version_added: 0.6

- cmd
The command to run.
[Default: (null)]
type: str

- creates
A filename or (since 2.0) glob pattern. If it already exists, this step *won't* be run.
[Default: (null)]
type: path

- free_form
The command module takes a free form command to run.
There is no actual parameter named 'free form'.
[Default: (null)]

- removes
A filename or (since 2.0) glob pattern. If it already exists, this step *will* be run.
[Default: (null)]
type: path
version_added: 0.8

- stdin
Set the stdin of the command directly to the specified value.
[Default: (null)]
version_added: 2.4

- stdin_add_newline
If set to `yes', append a newline to stdin data.
[Default: True]
type: bool
version_added: 2.8

- strip_empty_ends
Strip empty lines from the end of stdout/stderr in result.
[Default: True]
type: bool
version_added: 2.8

- warn
Enable or disable task warnings.
[Default: True]
type: bool
version_added: 1.8

不支持:$变量、特殊符号(分号,重定向,管道符等)。

shell模块

功能:调用bash,在远程主机执行命令。

在执行一些复杂命令时也可能会报错。一般解决方案为写脚本执行,再将结果拉回。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
OPTIONS (= is mandatory):

- chdir
Change into this directory before running the command.
[Default: (null)]
type: path
version_added: 0.6

- cmd
The command to run followed by optional arguments.
[Default: (null)]
type: str

- creates
A filename, when it already exists, this step will *not* be run.
[Default: (null)]
type: path

- executable
Change the shell used to execute the command.
This expects an absolute path to the executable.
[Default: (null)]
type: path
version_added: 0.9

- free_form
The shell module takes a free form command to run, as a string.
There is no actual parameter named 'free form'.
See the examples on how to use this module.
[Default: (null)]
type: str

- removes
A filename, when it does not exist, this step will *not* be run.
[Default: (null)]
type: path
version_added: 0.8

- stdin
Set the stdin of the command directly to the specified value.
[Default: (null)]
type: str
version_added: 2.4

- stdin_add_newline
Whether to append a newline to stdin data.
[Default: True]
type: bool
version_added: 2.8

- warn
Whether to enable task warnings.
[Default: True]
type: bool
version_added: 1.8

script模块

功能:运行脚本。自动完成复制脚本在远程主机完成。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
OPTIONS (= is mandatory):

- chdir
Change into this directory on the remote node before running the script.
[Default: (null)]
version_added: 2.4

- cmd
Path to the local script to run followed by optional arguments.
[Default: (null)]
type: str

- creates
A filename on the remote node, when it already exists, this step will *not* be run.
[Default: (null)]
version_added: 1.5

- decrypt
This option controls the autodecryption of source files using vault.
[Default: True]
type: bool
version_added: 2.4

- executable
Name or path of a executable to invoke the script with.
[Default: (null)]
version_added: 2.6

- free_form
Path to the local script file followed by optional arguments.
[Default: (null)]

- removes
A filename on the remote node, when it does not exist, this step will *not* be run.
[Default: (null)]
version_added: 1.5

copy模块

复制文件至远程主机。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#请用ansible-doc copy查看
copy:
attributes: # The attributes the resulting file or directory should have. To get supported flags look at the man page for `chattr' on the
target system. This string should contain the attributes in the same order as the one displayed
by `lsattr'. The `=' operator is assumed as default, otherwise `+' or `-' operators need to be
included in the string.
backup: # Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it
incorrectly.
checksum: # SHA1 checksum of the file being transferred. Used to validate that the copy of the file was successful. If this is not
provided, ansible will use the local calculated checksum of the src file.
content: # When used instead of `src', sets the contents of a file directly to the specified value. Works only when `dest' is a file.
Creates the file if it does not exist. For advanced formatting or if `content' contains a
variable, use the [template] module.
decrypt: # This option controls the autodecryption of source files using vault.
dest: # (required) Remote absolute path where the file should be copied to. If `src' is a directory, this must be a directory too. If
`dest' is a non-existent path and if either `dest' ends with "/" or `src' is a directory,
`dest' is created. If `dest' is a relative path, the starting directory is determined by the
remote host. If `src' and `dest' are files, the parent directory of `dest' is not created and
the task fails if it does not already exist.
directory_mode: # When doing a recursive copy set the mode for the directories. If this is not set we will use the system defaults. The mode is
only set on directories which are newly created, and will not affect those that already
existed.
follow: # This flag indicates that filesystem links in the destination, if they exist, should be followed.
force: # Influence whether the remote file must always be replaced. If `yes', the remote file will be replaced when contents are
different than the source. If `no', the file will only be transferred if the destination does
not exist. Alias `thirsty' has been deprecated and will be removed in 2.13.
group: # Name of the group that should own the file/directory, as would be fed to `chown'.
local_follow: # This flag indicates that filesystem links in the source tree, if they exist, should be followed.
mode: # The permissions of the destination file or directory. For those used to `/usr/bin/chmod' remember that modes are actually
octal numbers. You must either add a leading zero so that Ansible's YAML parser knows it is an
octal number (like `0644' or `01777')or quote it (like `'644'' or `'1777'') so Ansible receives
a string and can do its own conversion from string into number. Giving Ansible a number without
following one of these rules will end up with a decimal number which will have unexpected
results. As of Ansible 1.8, the mode may be specified as a symbolic mode (for example, `u+rwx'
or `u=rw,g=r,o=r'). As of Ansible 2.3, the mode may also be the special string `preserve'.
`preserve' means that the file will be given the same permissions as the source file.
owner: # Name of the user that should own the file/directory, as would be fed to `chown'.
remote_src: # Influence whether `src' needs to be transferred or already is present remotely. If `no', it will search for `src' at
originating/master machine. If `yes' it will go to the remote/target machine for the `src'.
`remote_src' supports recursive copying as of version 2.8. `remote_src' only works with
`mode=preserve' as of version 2.6.
selevel: # The level part of the SELinux file context. This is the MLS/MCS attribute, sometimes known as the `range'. When set to
`_default', it will use the `level' portion of the policy if available.
serole: # The role part of the SELinux file context. When set to `_default', it will use the `role' portion of the policy if available.
setype: # The type part of the SELinux file context. When set to `_default', it will use the `type' portion of the policy if available.
seuser: # The user part of the SELinux file context. By default it uses the `system' policy, where applicable. When set to `_default',
it will use the `user' portion of the policy if available.
src: # Local path to a file to copy to the remote server. This can be absolute or relative. If path is a directory, it is copied
recursively. In this case, if path ends with "/", only inside contents of that directory are
copied to destination. Otherwise, if it does not end with "/", the directory itself with all
contents is copied. This behavior is similar to the `rsync' command line tool.
unsafe_writes: # Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target file. By default this
module uses atomic operations to prevent data corruption or inconsistent reads from the target
files, but sometimes systems are configured or just broken in ways that prevent this. One
example is docker mounted files, which cannot be updated atomically from inside the container
and can only be written in an unsafe manner. This option allows Ansible to fall back to unsafe
methods of updating files when atomic operations fail (however, it doesn't force Ansible to
perform unsafe writes). IMPORTANT! Unsafe writes are subject to race conditions and can lead to
data corruption.
validate: # The validation command to run before copying into place. The path to the file to validate is passed in via '%s' which must be
present as in the examples below. The command is passed securely so shell features like
expansion and pipes will not work.

fetch模块

从远程主机拉取文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
fetch:
dest: # (required) A directory to save the file into. For example, if the `dest' directory is `/backup' a `src' file named
`/etc/profile' on host `host.example.com', would be saved into
`/backup/host.example.com/etc/profile'. The host name is based on the inventory name.
fail_on_missing: # When set to `yes', the task will fail if the remote file cannot be read for any reason. Prior to Ansible 2.5, setting this
would only fail if the source file was missing. The default was changed to `yes' in Ansible
2.5.
flat: # Allows you to override the default behavior of appending hostname/path/to/file to the destination. If `dest' ends with '/', it
will use the basename of the source file, similar to the copy module. This can be useful if
working with a single host, or if retrieving files that are uniquely named per host. If using
multiple hosts with the same filename, the file will be overwritten for each host.
src: # (required) The file on the remote system to fetch. This `must' be a file, not a directory. Recursive fetching may be supported
in a later release.
validate_checksum: # Verify that the source and destination checksums match after the files are fetched.

file模块

管理文件和文件属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
access_time:           # This parameter indicates the time the file's access time should be set to. Should be `preserve' when no modification is
required, `YYYYMMDDHHMM.SS' when using default time format, or `now'. Default is `None' meaning
that `preserve' is the default for `state=[file,directory,link,hard]' and `now' is default for
`state=touch'.
access_time_format: # When used with `access_time', indicates the time format that must be used. Based on default Python format (see time.strftime
doc).
attributes: # The attributes the resulting file or directory should have. To get supported flags look at the man page for `chattr' on the
target system. This string should contain the attributes in the same order as the one displayed
by `lsattr'. The `=' operator is assumed as default, otherwise `+' or `-' operators need to be
included in the string.
follow: # This flag indicates that filesystem links, if they exist, should be followed. Previous to Ansible 2.5, this was `no' by
default.
force: # Force the creation of the symlinks in two cases: the source file does not exist (but will appear later); the destination
exists and is a file (so, we need to unlink the `path' file and create symlink to the `src'
file in place of it).
group: # Name of the group that should own the file/directory, as would be fed to `chown'.
mode: # The permissions the resulting file or directory should have. For those used to `/usr/bin/chmod' remember that modes are
actually octal numbers. You must either add a leading zero so that Ansible's YAML parser knows
it is an octal number (like `0644' or `01777') or quote it (like `'644'' or `'1777'') so
Ansible receives a string and can do its own conversion from string into number. Giving Ansible
a number without following one of these rules will end up with a decimal number which will have
unexpected results. As of Ansible 1.8, the mode may be specified as a symbolic mode (for
example, `u+rwx' or `u=rw,g=r,o=r').
modification_time: # This parameter indicates the time the file's modification time should be set to. Should be `preserve' when no modification is
required, `YYYYMMDDHHMM.SS' when using default time format, or `now'. Default is None meaning
that `preserve' is the default for `state=[file,directory,link,hard]' and `now' is default for
`state=touch'.
modification_time_format: # When used with `modification_time', indicates the time format that must be used. Based on default Python format (see
time.strftime doc).
owner: # Name of the user that should own the file/directory, as would be fed to `chown'.
path: # (required) Path to the file being managed.
recurse: # Recursively set the specified file attributes on directory contents. This applies only when `state' is set to `directory'.
selevel: # The level part of the SELinux file context. This is the MLS/MCS attribute, sometimes known as the `range'. When set to
`_default', it will use the `level' portion of the policy if available.
serole: # The role part of the SELinux file context. When set to `_default', it will use the `role' portion of the policy if available.
setype: # The type part of the SELinux file context. When set to `_default', it will use the `type' portion of the policy if available.
seuser: # The user part of the SELinux file context. By default it uses the `system' policy, where applicable. When set to `_default',
it will use the `user' portion of the policy if available.
src: # Path of the file to link to. This applies only to `state=link' and `state=hard'. For `state=link', this will also accept a
non-existing path. Relative paths are relative to the file being created (`path') which is how
the Unix command `ln -s SRC DEST' treats relative paths.
state: # If `absent', directories will be recursively deleted, and files or symlinks will be unlinked. In the case of a directory, if
`diff' is declared, you will see the files and folders deleted listed under `path_contents'.
Note that `absent' will not cause `file' to fail if the `path' does not exist as the state did
not change. If `directory', all intermediate subdirectories will be created if they do not
exist. Since Ansible 1.7 they will be created with the supplied permissions. If `file', without
any other options this works mostly as a 'stat' and will return the current state of `path'.
Even with other options (i.e `mode'), the file will be modified but will NOT be created if it
does not exist; see the `touch' value or the [copy] or [template] module if you want that
behavior. If `hard', the hard link will be created or changed. If `link', the symbolic link
will be created or changed. If `touch' (new in 1.4), an empty file will be created if the
`path' does not exist, while an existing file or directory will receive updated file access and
modification times (similar to the way `touch' works from the command line).
unsafe_writes: # Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target file. By default this
module uses atomic operations to prevent data corruption or inconsistent reads from the target
files, but sometimes systems are configured or just broken in ways that prevent this. One
example is docker mounted files, which cannot be updated atomically from inside the container
and can only be written in an unsafe manner. This option allows Ansible to fall back to unsafe
methods of updating files when atomic operations fail (however, it doesn't force Ansible to
perform unsafe writes). IMPORTANT! Unsafe writes are subject to race conditions and can lead to
data corruption.