ping模块
ping模块用于检查指定节点机器是否连通,用法很简单,不涉及参数,主机如果在线,则回复pong
[root@localhost project]# ansible httpd -m ping
Enter passphrase for key '/root/.ssh/id_rsa':
192.168.143.20 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/libexec/platform-python"
},
"changed": false,
"ping": "pong"
}
raw模块
raw模块用于在远程主机上执行命令,其支持管道符与重定向
[root@localhost project]# ansible httpd -m raw -a 'echo "hello world" > /tmp/test'
Enter passphrase for key '/root/.ssh/id_rsa':
192.168.143.20 | CHANGED | rc=0 >>
Shared connection to 192.168.143.20 closed.
[root@localhost project]# ansible httpd -m raw -a 'echo "hello world" > /tmp/test'
192.168.143.20 | CHANGED | rc=0 >>
Shared connection to 192.168.143.20 closed.
[root@localhost project]#
[root@localhost project]# ansible httpd -m raw -a 'cat /tmp/test |grep -Eo hello'
Enter passphrase for key '/root/.ssh/id_rsa':
192.168.143.20 | CHANGED | rc=0 >>
hello
Shared connection to 192.168.143.20 closed.
file模块
ansible内置的可以查看模块用法的命令如下:
[root@localhost ~]# ansible-doc -s file
- name: Manage files and file properties
file:
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'). As of Ansible 2.6, the mode may also be the special string
`preserve'. When set to `preserve' the file will be given the same permissions as
the source file.
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.
file模块用来设置文件属性,并且创建或者删除目录,创建连接。
相关选项如下:
force:需要在两种情况下强制创建软链接,一种是源文件不存在,但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no
group:定义文件/目录的属组
mode:定义文件/目录的权限
owner:定义文件/目录的属主
path:必选项,定义文件/目录的路径
recurse:递归设置文件的属性,只对目录有效
src:被链接的源文件路径,只应用于state=link的情况
dest:被链接到的路径,只应用于state=link的情况
state:
directory:如果目录不存在,就创建目录
file:即使文件不存在,也不会被创建
link:创建软链接
hard:创建硬链接
touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间
absent:删除目录、文件或者取消链接文件
copy模块
[root@localhost ~]# ansible test -m copy -a "src=/etc/sysconfig dest=/test owner=root mode=600"
192.168.143.20 | CHANGED => {
"changed": true,
"dest": "/test/",
"src": "/etc/sysconfig"
}
[root@localhost ~]# ansible test -a "ls -l /test/"
192.168.143.20 | CHANGED | rc=0 >>
总用量 4
drwxr-xr-x. 5 root root 4096 7月 29 22:09 sysconfig
主要的作用是复制文件到远程主机:
相关选项如下:
backup:在覆盖之前,将源文件备份,备份文件包含时间信息。有两个选项:yes|no
content:用于替代“src”,可以直接设定指定文件的值
dest:必选项。要将源文件复制到的远程主机的绝对路径,如果源文件是一个目录,那么该路径也必须是个目录
directory_mode:递归设定目录的权限,默认为系统默认权限
force:如果目标主机包含该文件,但内容不同,如果设置为yes,则强制覆盖,如果为no,则只有当目标主机的目标位置不存在该文件时,才复制。默认为yes
others:所有的file模块里的选项都可以在这里使用
src:被复制到远程主机的本地文件,可以是绝对路径,也可以是相对路径。如果路径是一个目录,它将递归复制。在这种情况下,如果路径使用“/”来结尾,则只复制目录里的内容,如果没有使用“/”来结尾,则包含目录在内的整个内容全部复制,类似于rsync
cron模块
我们知道crontab的主要作用就是制定定时计划任务,cron模块的主要作用和crontab命令是一样的。
我们知道在linux中添加一个计划任务需要指定计划任务执行的时间,执行的命令。而cron模块也是这样。
[root@localhost ~]# ansible test -m cron -a 'name="custom job" minute=30 hour=2 day=* month=* weekday=1-5 job="sh tesh.sh"'
192.168.143.20| CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": [
"custom job"
]
}
[root@localhost ~]# ansible test -a 'crontab -l'
192.168.143.20 | CHANGED | rc=0 >>
#Ansible: custom job
30 2 * * 1-5 sh tesh.sh
[root@localhost ~]# ansible test -m cron -a 'name="custom job" minute=30 hour=2 day=* month=* weekday=1-5 job="sh tesh.sh" disabled=yes'
192.168.143.20 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": [
"custom job"
]
}
[root@localhost ~]# ansible test -a 'crontab -l'
192.168.143.20| CHANGED | rc=0 >>
#Ansible: custom job
#30 2 * * 1-5 sh tesh.sh
[root@localhost ~]# ansible test -m cron -a 'name="custom job" state=absent'
192.168.143.20 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": []
}
[root@localhost ~]# ansible test -a 'crontab -l'
192.168.143.20 | CHANGED | rc=0 >>
yum 模块
可以执行yum命令
[root@localhost ~]# ansible test -m yum -a "name=httpd state=absent"
192.168.143.20 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"removed": [
"httpd"
]
},
"msg": "",
"rc": 0,
"results": [
"已加载插件:fastestmirror\n正在解决依赖关系\n--> 正在检查事务\n---> 软件包 httpd.x86_64.0.2.4.6-93.el7.centos 将被 删除\n--> 解决依赖关系完成\n\n依赖关系解决\n\n================================================================================\n Package 架构 版本 源 大小\n================================================================================\n正在删除:\n httpd x86_64 2.4.6-93.el7.centos @base 9.4 M\n\n事务概要\n================================================================================\n移除 1 软件包\n\n安装大小:9.4 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n 正在删除 : httpd-2.4.6-93.el7.centos.x86_64 1/1 \n 验证中 : httpd-2.4.6-93.el7.centos.x86_64 1/1 \n\n删除:\n httpd.x86_64 0:2.4.6-93.el7.centos \n\n完毕!\n"
]
}
[root@localhost ~]# ansible test -m yum -a "name=httpd"
192.168.143.20 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"installed": [
"httpd"
]
},
"msg": "",
"rc": 0,
"results": [
"Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirror.upsi.edu.my\n * extras: centos.mirror.myduniahost.com\n * updates: centos.mirror.angkasa.id\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-93.el7.centos will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n httpd x86_64 2.4.6-93.el7.centos base 2.7 M\n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal download size: 2.7 M\nInstalled size: 9.4 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : httpd-2.4.6-93.el7.centos.x86_64 1/1 \n Verifying : httpd-2.4.6-93.el7.centos.x86_64 1/1 \n\nInstalled:\n httpd.x86_64 0:2.4.6-93.el7.centos \n\nComplete!\n"
]
}
service模块
service模块主要用来对系统中的服务进行管理。
[root@ansible ~]# ansible-doc -s service
- name: Manage services
service:
arguments: # Additional arguments provided on the command line.
enabled: # Whether the service should start on boot. *At least one of state and enabled are required.*
name: # (required) Name of the service.
pattern: # If the service does not respond to the status command, name a substring to look for as would be found in the output
of the `ps' command as a stand-in for a status result. If the string is found, the
service will be assumed to be started.
runlevel: # For OpenRC init scripts (e.g. Gentoo) only. The runlevel that this service belongs to.
sleep: # If the service is being `restarted' then sleep this many seconds between the stop and start command. This helps to
work around badly-behaving init scripts that exit immediately after signaling a
process to stop. Not all service managers support sleep, i.e when using systemd this
setting will be ignored.
state: # `started'/`stopped' are idempotent actions that will not run commands unless necessary. `restarted' will always
bounce the service. `reloaded' will always reload. *At least one of state and
enabled are required.* Note that reloaded will start the service if it is not
already started, even if your chosen init system wouldn't normally.
use: # The service module actually uses system specific modules, normally through auto detection, this setting can force a
specific module. Normally it uses the value of the 'ansible_service_mgr' fact and
falls back to the old 'service' module when none matching is found.
[root@ansible ~]#
相关参数如下:
name: 指定服务的名称。
state:指定对服务进行的操作,started, stopped, restarted, reloaded。【是对应动词的过去分词形式】
enabled: yes|no, 是否加入开机自启动。
runlevel: 启动的级别。
command模块
command 模块可以帮助我们在远程主机上执行命令。
注意:使用 command 模块在远程主机中执行命令时,不会经过远程主机的 shell 处理,在使用 command 模块时,如果需要执行的命令中含有重定向、管道符等操作时,这些符号也会失效,比如”<”, “>”, “|”, “;” 和 “&” 这些符号,如果你需要这些功能,可以参考后面介绍的 shell 模块。还有一点需要注意,如果远程节点是 windows 操作系统,则需要使用 win_command 模块。执行 ansible 时,不加 -m 默认使用 command ,可以在 /etc/ansible/ansible.cfg 中修改。
command模块的几个选项如下:
相关选项如下:
creates:一个文件名,当该文件存在,则该命令不执行
free_form:要执行的linux指令,这里的free_form不需要写成赋值的形式,直接写要执行的命令即可。
chdir:在执行指令之前,先切换到该目录
removes:一个文件名,当该文件不存在,则该选项不执行
executable:切换shell来执行指令,该执行路径必须是一个绝对路径
[root@localhost ~]# ansible -i /root/hosts all -a "w"
10.0.102.212 | SUCCESS | rc=0 >>
10:25:27 up 8 days, 13:04, 2 users, load average: 0.09, 0.03, 0.05
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root tty1 12Feb19 8days 0.01s 0.01s -bash
root pts/1 10.0.102.209 10:25 0.00s 0.12s 0.02s w
10.0.102.200 | SUCCESS | rc=0 >>
10:25:30 up 9 days, 17:52, 3 users, load average: 0.05, 0.04, 0.06
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root tty1 11Feb19 9days 0.01s 0.01s -bash
root pts/1 172.16.100.19 08:02 2:19m 0.02s 0.01s /usr/local/mysql/bin/mysql -uroot -px xxxx
root pts/2 10.0.102.209 10:25 0.00s 0.16s 0.03s w
10.0.102.162 | SUCCESS | rc=0 >>
10:25:30 up 9 days, 17:52, 3 users, load average: 0.16, 0.05, 0.06
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root tty1 11Feb19 9days 0.07s 0.07s -bash
root pts/1 172.16.100.19 08:02 2:20m 0.03s 0.01s /usr/local/mysql/bin/mysql -uroot -px xxxx
root pts/2 10.0.102.209 10:25 1.00s 0.21s 0.03s w
[root@localhost ~]# ansible -i /root/hosts all -a "w creates=/tmp/test"
10.0.102.212 | SUCCESS | rc=0 >>
skipped, since /tmp/test exists
10.0.102.200 | SUCCESS | rc=0 >>
skipped, since /tmp/test exists
10.0.102.162 | SUCCESS | rc=0 >>
skipped, since /tmp/test exists
script模块
script 模块可以帮助我们在远程主机上执行 ansible 管理主机上的脚本,也就是说,脚本一直存在于 ansible 管理主机本地,不需要手动拷贝到远程主机后再执行。
参数如下:
[root@localhost tasks]# ansible-doc -s script
- name: Runs a local script on a remote node after transferring it
script:
chdir: # cd into this directory on the remote node before running the script
creates: # a filename, when it already exists, this step will *not* be run.
decrypt: # This option controls the autodecryption of source files using vault.
free_form: # (required) Path to the local script file followed by optional arguments. There is no parameter actually named 'free form'; see the
examples!
removes: # a filename, when it does not exist, this step will *not* be run.
hostname模块
[root@localhost ~]# ansible 192.168.143.20 -m hostname -a 'name=test'
192.168.143.20 | CHANGED => {
"ansible_facts": {
"ansible_domain": "",
"ansible_fqdn": "test",
"ansible_hostname": "test",
"ansible_nodename": "test",
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"name": "test"
}
[root@localhost ~]# ansible 192.168.143.20 -a 'hostname'
192.168.143.20 | CHANGED | rc=0 >>
test