1.5.1:command 模块
官方文档:https://docs.ansible.com/ansible/latest/collections/ansible/builtin/command_module.html#ansible-collections-ansible-builtin-command-module
command为ansible的默认模块,用于在远程主机上执行指定命令。
注意:
- command模块的命令不通过shell执行,所以不支持shell的相关特性,比如变量、操作符("*"
,
"<",
">",
"|",
";",
"&")。 - command执行的操作不具有幂等性。
1.5.1.1:常用模块参数
参数 | 说明 |
---|---|
FREE_FORM | FREE_FORM不是一个特定的参数,是free form的字符串,表示可执行的命令。 |
chdir | 在执行命令前切换到指定的目录。 |
creates | 条件判断,指定一个文件名称(支持glob模式),如果文件存在,则不执行指定的操作(只有在指定文件不存在的情况下才进行本次操作)。 |
removes | 条件判断,指定一个文件名称(支持glob模式),当指定文件存在时,才执行本次操作。 |
1.5.1.2:示例
chdir 示例
切换到/etc
目录,查看fstab
文件:
[root@ansible ~]# ansible websrvs -a "chdir=/etc cat fstab"
192.168.1.111 | CHANGED | rc=0 >>
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point> <type> <options> <dump> <pass>
# / was on /dev/sda1 during installation
UUID=f69d0f38-e303-4845-bdc0-06417f84381c / ext4 errors=remount-ro 0 1
/swapfile none swap sw 0 0
creates 示例
当/tmp/test.txt
存在时,不进行操作:
#第一次执行了ls的操作,因为/tmp/test.txt不存在
[root@ansible ~]# ansible websrvs -a "creates=/tmp/test.txt ls"
192.168.1.111 | CHANGED | rc=0 >>
gittest
Memcached_Stats.sh
Nginx-Status.sh
Redis_Info.sh
sample.war
test3.txt
test4.txt
test-app1
test.sh
test.txt
web1
zabbix-release_4.0-3+bionic_all.deb
#在目标主机上创建了/tmp/test.txt文件后,再次用creates作为判断条件,因为文件存在,所以跳过本次操作
[root@ansible ~]# ansible websrvs -a "touch /tmp/test.txt"
192.168.1.111 | CHANGED | rc=0 >>
[root@ansible ~]# ansible websrvs -a "creates=/tmp/test.txt ls"
192.168.1.111 | SUCCESS | rc=0 >>
skipped, since /tmp/test.txt exists
removes 示例
当/tmp/test.txt
存在时,才执行操作:
#上一个示例中,因为`/tmp/test.txt`存在,所以用creates作为判断条件时,不执行操作;换为removes作为判断条件,则正好相反,会执行操作
[root@ansible ~]# ansible websrvs -a "removes=/tmp/test.txt ls"
192.168.1.111 | CHANGED | rc=0 >>
gittest
Memcached_Stats.sh
Nginx-Status.sh
Redis_Info.sh
sample.war
test3.txt
test4.txt
test-app1
test.sh
test.txt
web1
zabbix-release_4.0-3+bionic_all.deb
#但当删除了/tmp/test.txt后,用removes作为判断条件时,就不会执行操作了,因为/tmp/test.txt文件已经不存在了
[root@ansible ~]# ansible websrvs -a "rm -f /tmp/test.txt"
192.168.1.111 | CHANGED | rc=0 >>
[root@ansible ~]# ansible websrvs -a "removes=/tmp/test.txt ls"
192.168.1.111 | SUCCESS | rc=0 >>
skipped, since /tmp/test.txt does not exist