ansible常用模块

1. ansible常用模块使用详解

ansible常用模块有:

  • ping
  • yum
  • template
  • copy
  • user
  • group
  • service
  • raw
  • command
  • shell
  • script

ansible常用模块rawcommandshell的区别:

  • shell模块调用的/bin/sh指令执行
  • command模块不是调用的shell的指令,所以没有bash的环境变量
  • raw很多地方和shell类似,更多的地方建议使用shell和command模块。但是如果是使用老版本python,需要用到raw,又或者是客户端是路由器,因为没有安装python模块,那就需要使用raw模块了

2. ansible常用模块之ping

ping模块用于检查指定节点机器是否连通,用法很简单,不涉及参数,主机如果在线,则回复pong

Ansible最基础的模块是ping模块,主要用于判断远程客户端是否在线,用于ping本身服务器,返回值是changed、ping

使用Ansible ping服务器状态,代码为ansible -k all -m ping 因为我的ansible服务器已经做了免密登录,所以不用到-k参数,关于ansible的各个参数在ansible原理篇里详解

//将IP加入/etc/ansible/inventory文件
[root@localhost ~]# cat /etc/ansible/inventory 
[webservers]
192.168.91.139
192.168.91.145

//生成密钥,使用密钥进行连接
[root@localhost ~]# ssh-keygen 
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:JzYY+xIGjlAcqFCZrqvjOOKSrvNxSM0J0WJQJiQgh20 root@localhost
The key's randomart image is:
+---[RSA 3072]----+
|OXO=             |
|*=E..            |
|++... .          |
|...* o +         |
| .o = = S .      |
|.. . . + +       |
| oo . . .        |
|X  o   .         |
|%O.              |
+----[SHA256]-----+
[root@localhost ~]# ssh-copy-id 192.168.91.139
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.91.139's password: 




//执行命令测试Ping模块
[root@localhost ~]# ansible 192.168.91.139 -m ping   //进行连接之后,使用ping模块就可以看到是否可以受管理
192.168.91.139 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}


//这是没有连接的,不能被ansible管理
[root@localhost ~]# ansible 192.168.91.145 -m ping
192.168.91.145 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: Host key verification failed.",
    "unreachable": true
}

//删除密钥连接
[root@localhost ~]# vim .ssh/known_hosts
192.168.91.139 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBODIALfgfkN5PuJ4pUNykIuFNCJ+7zC++SMvnwq5nHVJGZjL43S7iDzXHpkFIIN4gzXXG1XsfvdLgvZ0jOcGWmo=
192.168.91.145 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBPiexznZGVc3t7P4TfQWZUVvjbMqT6G7TTtiLulQe14Ob4poBF76W/+vcgS7FFbvRQ2rVmmM0fxzJfjCuldtx1M=

[root@localhost ~]# ansible all -m ping  //删除145,检查就发现145就不受管理了
192.168.91.145 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: Warning: Permanently added '192.168.91.145' (ECDSA) to the list of known hosts.\r\nroot@192.168.91.145: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).",
    "unreachable": true
}
192.168.91.139 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}



//询问输入密码ping,ssh第一次连接的时候一般会提示输入yes 进行确认为将key字符串加入到 ~/.ssh/known_hosts 文件中,在本地先SSH登录一下对方设备,下次ansible 就可以正常操作了
[root@localhost ~]# ssh 192.168.91.145
The authenticity of host '192.168.91.145 (192.168.91.145)' can't be established.
ECDSA key fingerprint is SHA256:ai55icxtZEkM+W06aJOkBfTbJqrkgGlzR5uDcgEUCvk.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.91.145' (ECDSA) to the list of known hosts.
root@192.168.91.145's password: 
Last login: Sat Oct 22 12:38:42 2022 from 192.168.91.134
[root@145 ~]# exit
logout
Connection to 192.168.91.145 closed.
[root@localhost ~]# ansible 192.168.91.145 -m ping -k
SSH password: 
192.168.91.145 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}

//设置参数为不检查key
[root@localhost ~]# vim /etc/ansible/ansible.cfg
......
host_key_checking = False   //取消注释

3. ansible常用模块之command

command模块用于在远程主机上执行命令,ansible默认就是使用command模块。

command 模块可以帮助我们在远程主机上执行命令。
注意:使用 command 模块在远程主机中执行命令时,不会经过远程主机的 shell 处理,在使用 command 模块时,如果需要执行的命令中含有重定向、管道符等操作时,这些符号也会失效,比如”<”, “>”, “|”, “;” 和 “&” 这些符号,如果你需要这些功能,可以参考后面介绍的 shell 模块。还有一点需要注意,如果远程节点是 windows 操作系统,则需要使用 win_command 模块。
执行 ansible 时,不加 -m 默认使用 command ,可以在 /etc/ansible/ansible.cfg 中修改。

# default module name for /usr/bin/ansible
#module_name = command

常用参数
free_form参数 :必须参数,指定需要远程执行的命令。需要说明一点,free_form 参数与其他参数(如果想要使用一个参数,那么则需要为这个参数赋值,也就是name=value模式)并不相同。比如,当我们想要在远程主机上执行 ls 命令时,我们并不需要写成”free_form=ls” ,这样写反而是错误的,因为并没有任何参数的名字是 free_form,当我们想要在远程主机中执行 ls 命令时,直接写成 ls 即可。因为 command 模块的作用是执行命令,所以,任何一个可以在远程主机上执行的命令都可以被称为 free_form。

chdir参数 : 此参数的作用就是指定一个目录,在执行对应的命令之前,会先进入到 chdir 参数指定的目录中。

creates参数 :看到 creates,你可能会从字面上理解这个参数,但是使用这个参数并不会帮助我们创建文件,它的作用是当指定的文件存在时,就不执行对应命令,比如,如果 /testdir/test文件存在,就不执行我们指定的命令。

removes参数 :与 creates 参数的作用正好相反,它的作用是当指定的文件不存在时,就不执行对应命令,比如,如果 /testdir/tests 文件不存在,就不执行我们指定的命令,此参数并不会帮助我们删除文件。

实例

命令在192.168.91.139主机上执行touch 新建一个文件

[root@localhost ~]# ansible 192.168.91.139 -m command -a 'touch /root/test '
[WARNING]: Consider using the file module with state=touch rather than running
'touch'.  If you need to use command because file is insufficient you can add
'warn: false' to this command task or set 'command_warnings=False' in
ansible.cfg to get rid of this message.
192.168.91.139 | CHANGED | rc=0 >>

命令表示在 192.168.91.139 主机上执行 ls 命令,因为使用的是 root 用户,所以默认情况下,ls 出的结果是 192.168.91.139 主机中 root 用户家目录中的文件列表。

[root@localhost ~]# ansible 192.168.91.139 -m command -a 'ls /root '
192.168.91.139 | CHANGED | rc=0 >>
anaconda-ks.cfg
test

chdir 参数表示执行命令之前,会先进入到指定的目录中,所以上面命令表示查看 192.168.91.139 主机上 /usr/local 目录中的文件列表,返回显示有2个文件。

[root@localhost ~]# ansible 192.168.91.139 -m command -a 'chdir=/usr/local ls'
192.168.91.139 | CHANGED | rc=0 >>
bin
etc
games
include
lib
lib64
libexec

上面命令表示 /opt/date 文件存在于远程主机中,则不执行对应命令。/opt/date 不存在,才执行”echo test”命令。

[root@localhost ~]# ansible 192.168.91.139 -m command -a 'creates=/opt/date echo test'
192.168.91.139 | CHANGED | rc=0 >>
test                               //不存在
 
[root@localhost ~]# ansible 192.168.91.139 -m command -a 'creates=/opt/date echo test'
192.168.91.139 | SUCCESS | rc=0 >>
skipped, since /opt/date exists    //这是存在

/opt/date 存在,才执行”echo test”命令。

[root@localhost ~]# ansible 192.168.91.139 -m command -a 'removes=/opt/date echo test'
192.168.91.139 | CHANGED | rc=0 >>
test                                 //存在

[root@localhost ~]# ansible 192.168.91.139 -m command -a 'removes=/opt/date echo test'
192.168.91.139 | SUCCESS | rc=0 >>
skipped, since /opt/date does not exist       //不存在

4. ansible常用模块之raw

raw模块用于在远程主机上执行命令,其支持管道符与重定向

[root@localhost ~]# ansible 192.168.91.139 -m raw -a ' touch /opt/date  '
192.168.91.139 | CHANGED | rc=0 >>
Shared connection to 192.168.91.139 closed.

//支持重定向
[root@localhost ~]# ansible 192.168.91.139 -m raw -a ' echo test > /opt/date  '
192.168.91.139 | CHANGED | rc=0 >>
Shared connection to 192.168.91.139 closed.

[root@localhost ~]# ansible 192.168.91.139 -m raw -a ' cat /opt/date  '
192.168.91.139 | CHANGED | rc=0 >>
test
Shared connection to 192.168.91.139 closed.

5. ansible常用模块之shell

shell 模块可以帮助我们在远程主机上执行命令。与 command 模块不同的是,shell 模块在远程主机中执行命令时,会经过远程主机上的 /bin/sh 程序处理。

shell 模块中 chdir、creates、removes 参数的作用与 command 模块中的作用都是相同的

使用 shell 模块可以在远程服务器上执行命令,它支持管道与重定向等符号。

示例

上面命令打印出test1并写入test文件。

[root@localhost ~]# ansible 192.168.91.139 -m shell -a 'chdir=/opt echo test1 > test '
192.168.91.139 | CHANGED | rc=0 >>

命令列出了 /testdir 下面的文件

[root@localhost ~]# ansible 192.168.91.139 -m shell -a 'chdir=/opt ls '
192.168.91.139 | CHANGED | rc=0 >>
CentOS-SIG-ansible-29.repo
date
qwer
test

命令列出了 test 文件的内容

[root@localhost ~]# ansible 192.168.91.139 -m shell -a 'chdir=/opt cat test '
192.168.91.139 | CHANGED | rc=0 >>
test1

6. ansible常用模块之script

script模块用于在受控机上执行主控机上的脚本

示例

使用script模块到对象节点上执行本地脚本

[root@localhost ~]# vim /opt/aa       //创建一个脚本
#!/bin/bash
  
for ((i=1;i<=10;i++))
 do
    echo $i >> /opt/test
done

[root@localhost ~]# ansible 192.168.91.139 -m script -a  '/opt/aa'
192.168.91.139 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 192.168.91.139 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 192.168.91.139 closed."
    ],
    "stdout": "",
    "stdout_lines": []
}
[root@localhost ~]# ansible 192.168.91.139 -a ' cat /opt/test'    //执行后确认
192.168.91.139 | CHANGED | rc=0 >>
1
2
3
4
5
6
7
8
9
10

7. ansible常用模块之template

template模块用于生成一个模板,并可将其传输至远程主机上。

示例

//src把本地的/opt/aa,dest传到主机上的/opt/,mode权限
[root@localhost ~]# ansible 192.168.91.139 -m template -a 'src=/opt/aa dest=/opt/ mode=0644'
192.168.91.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "checksum": "f00549e79cc505f7fefbd1297a3911caa75e70e0",
    "dest": "/opt/aa",
    "gid": 0,
    "group": "root",
    "md5sum": "9b341df1b37e599b46798042fbde3aed",
    "mode": "0644",
    "owner": "root",
    "size": 74,
    "src": "/root/.ansible/tmp/ansible-tmp-1666431250.5554152-3778077-255135502931895/source",
    "state": "file",
    "uid": 0
}

[root@localhost ~]# ansible 192.168.91.139  -a 'ls -l /opt/'
192.168.91.139 | CHANGED | rc=0 >>
total 4
-rw-r--r-- 1 root root 74 Oct 22 17:34 aa

8. ansible常用模块之yum

yum模块用于在指定节点机器上通过yum管理软件,其支持的参数主要有两个

  • name:要管理的包名
  • state:要进行的操作

state常用的值:

  • latest:安装软件
  • installed:安装软件
  • present:安装软件
  • removed:卸载软件
  • absent:卸载软件

若想使用yum来管理软件,请确保受控机上的yum源无异常。

//在受控机上查询看vsftpd软件是否安装
[root@139 ~]# rpm -qa |grep httpd

//在ansible主机上使用yum模块在受控机上安装httpd
[root@localhost ~]# ansible 192.168.91.139 -m yum -a 'name=httpd state=present ' 
192.168.91.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "msg": "",
    "rc": 0,
    "results": [
        "Installed: apr-util-bdb-1.6.1-6.el8.x86_64",
        "Installed: httpd-tools-2.4.37-43.module_el8.5.0+1022+b541f3b1.x86_64",
        "Installed: centos-logos-httpd-85.8-2.el8.noarch",
        "Installed: mod_http2-1.15.7-3.module_el8.4.0+778+c970deab.x86_64",
        "Installed: apr-util-openssl-1.6.1-6.el8.x86_64",
        "Installed: mailcap-2.1.48-3.el8.noarch",
        "Installed: httpd-2.4.37-43.module_el8.5.0+1022+b541f3b1.x86_64",
        "Installed: apr-1.6.3-12.el8.x86_64",
        "Installed: httpd-filesystem-2.4.37-43.module_el8.5.0+1022+b541f3b1.noarch",
        "Installed: apr-util-1.6.1-6.el8.x86_64"
    ]
}

//查看受控机上是否安装了httpd
[root@139 ~]# rpm -qa |grep httpd
httpd-tools-2.4.37-43.module_el8.5.0+1022+b541f3b1.x86_64
centos-logos-httpd-85.8-2.el8.noarch
httpd-filesystem-2.4.37-43.module_el8.5.0+1022+b541f3b1.noarch
httpd-2.4.37-43.module_el8.5.0+1022+b541f3b1.x86_64

9. ansible常用模块之copy

copy模块用于复制文件至远程受控机

[root@localhost ~]# ansible 192.168.91.139 -m copy -a 'src=/scripts/test dest=/opt/scripts/'
192.168.91.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
    "dest": "/opt/scripts/test",
    "gid": 0,
    "group": "root",
    "md5sum": "d41d8cd98f00b204e9800998ecf8427e",
    "mode": "0644",
    "owner": "root",
    "size": 0,
    "src": "/root/.ansible/tmp/ansible-tmp-1666432750.6381063-3845571-212906032729888/source",
    "state": "file",
    "uid": 0
}


[root@localhost ~]# ansible 192.168.91.139 -a 'ls /opt/scripts'
192.168.91.139 | CHANGED | rc=0 >>
test


10. ansible常用模块之group

group模块用于在受控机上添加或删除组。

//在受控机上添加一个系统组,其gid为123,组名为httpd
[root@localhost ~]# ansible 192.168.91.139 -m group -a 'name=httpd gid=123 state=present'
192.168.91.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "gid": 123,
    "name": "httpd",
    "state": "present",
    "system": false
}
[root@localhost ~]# ansible 192.168.91.139 -m shell -a 'grep httpd /etc/group'
192.168.91.139 | CHANGED | rc=0 >>
httpd:x:123:


//删除受控机上的httpd组
[root@localhost ~]# ansible 192.168.91.139 -m group -a 'name=httpd state=absent' 
192.168.91.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "name": "httpd",
    "state": "absent"
}
[root@localhost ~]# ansible 192.168.91.139 -m shell -a 'grep httpd /etc/group'
192.168.91.139 | FAILED | rc=1 >>
non-zero return code

11. ansible常用模块之user

user模块用于管理受控机的用户帐号。

//在受控机上添加一个系统用户,用户名为httpd,uid为999,设置其shell为/sbin/nologin,无家目录
[root@localhost ~]# ansible 192.168.91.139 -m user -a 'name=httpd uid=456 system=yes create_home=no shell=/sbin/nologin state=present'
192.168.91.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "comment": "",
    "create_home": false,
    "group": 456,
    "home": "/home/httpd",
    "name": "httpd",
    "shell": "/sbin/nologin",
    "state": "present",
    "system": true,
    "uid": 456
}
[root@localhost ~]# ansible 192.168.91.139 -m shell -a 'grep httpd /etc/passwd'
192.168.91.139 | CHANGED | rc=0 >>
httpd:x:456:456::/home/httpd:/sbin/nologin

[root@localhost ~]# ansible 192.168.91.139 -m shell -a 'ls /home'
192.168.91.139 | CHANGED | rc=0 >>
www

//修改mysql用户的uid为555
[root@localhost ~]# ansible 192.168.91.139 -m user -a 'name=httpd uid=555'
192.168.91.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "append": false,
    "changed": true,
    "comment": "",
    "group": 456,
    "home": "/home/httpd",
    "move_home": false,
    "name": "httpd",
    "shell": "/sbin/nologin",
    "state": "present",
    "uid": 555
}
[root@localhost ~]# ansible 192.168.91.139 -m shell -a 'grep httpd /etc/passwd'
192.168.91.139 | CHANGED | rc=0 >>
httpd:x:555:456::/home/httpd:/sbin/nologin

//删除受控机上的httpd用户
[root@localhost ~]# ansible 192.168.91.139 -m user -a 'name=httpd state=absent'
 192.168.91.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "force": false,
    "name": "httpd",
    "remove": false,
    "state": "absent"
}
[root@localhost ~]# ansible 192.168.91.139 -m shell -a 'grep httpd /etc/passwd'
192.168.91.139 | CHANGED | rc=0 >>
non-zero return code

12. ansible常用模块之service

service模块用于管理受控机上的服务。

常用参数
name参数:此参数用于指定需要操作的服务名称,比如 nginx。
state参数:此参数用于指定服务的状态,比如,我们想要启动远程主机中的 nginx,则可以将 state 的值设置为 started;如果想要停止远程主机中的服务,则可以将 state 的值设置为 stopped。此参数的可用值有 started、stopped、restarted、reloaded。
enabled参数:此参数用于指定是否将服务设置为开机 启动项,设置为 yes 表示将对应服务设置为开机启动,设置为 no 表示不会开机启动。

//查看受控机上的sshd服务是否启动
[root@localhost ~]# ansible 192.168.91.139 -m shell -a 'systemctl is-active httpd'
192.168.91.139 | FAILED | rc=3 >>
inactivenon-zero return code

//启动受控机上的vsftpd服务
[root@localhost ~]# ansible 192.168.91.139 -m service -a 'name=httpd state=started'
192.168.91.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "name": "httpd",
    "state": "started",
    "status": {
        "ActiveEnterTimestampMonotonic": "0",
.........

//查看受控机上的httpd服务是否启动
[root@localhost ~]# ansible 192.168.91.139 -m shell -a 'systemctl status httpd'
 192.168.91.139 | CHANGED | rc=0 >>
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
   Active: active (running) since Sun 2022-10-23 10:36:40 CST; 3min 36s ago
     Docs: man:httpd.service(8)
 Main PID: 2611540 (httpd)

[root@localhost ~]# ansible 192.168.91.139 -m shell -a 'systemctl is-active httpd'
192.168.91.139 | CHANGED | rc=0 >>
active

//受控机上的httpd服务设置为停止状态。
[root@localhost ~]# ansible 192.168.91.139 -m shell -a 'systemctl status httpd'
 192.168.91.139 | CHANGED | rc=0 >>
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
   Active: active (running) since Sun 2022-10-23 10:36:40 CST; 3min 36s ago
     Docs: man:httpd.service(8)
 Main PID: 2611540 (httpd)
......
[root@localhost ~]# ansible 192.168.91.139 -m shell -a 'systemctl is-active httpd'
192.168.91.139 | FAILED | rc=3 >>
inactivenon-zero return code

// 受控机上的httpd服务被设置为开机自动启动。
[root@localhost ~]# ansible 192.168.91.139 -m service -a 'name=httpd enabled=yes'
192.168.91.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "enabled": true,
    "name": "httpd",
    "status": {
        "ActiveEnterTimestampMonotonic": "0",
        
        
[root@localhost ~]# ansible 192.168.91.139 -m shell -a 'systemctl status httpd'
  192.168.91.139 | FAILED | rc=3 >>
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)

13-Ansible常用模块-file模块

file 模块可以帮助我们完成一些对文件的基本操作。比如,创建文件或目录、删除文件或目录、修改文件权限等。

常用参数
path参数 :必须参数,用于指定要操作的文件或目录,在之前版本的ansible中,使用dest参数或者name参数指定要操作的文件或目录,为了兼容之前的版本,使用dest或name也可以。

state参数 :此参数非常灵活,其对应的值需要根据情况设定。比如,我们想要在远程主机上创建/test/a/b目录,那么则需要设置path=/test/a/b,但是,我们无法从”/test/a/b“这个路径看出b是一个文件还是一个目录,ansible也同样无法单单从一个字符串就知道你要创建文件还是目录,所以,我们需要通过state参数进行说明。当我们想要创建的/test/a/b是一个目录时,需要将state的值设置为directory,”directory”为目录之意,当它与path结合,ansible就能知道我们要操作的目标是一个目录。同理,当我们想要操作的/test/a/b是一个文件时,则需要将state的值设置为touch。当我们想要创建软链接文件时,需将state设置为link。想要创建硬链接文件时,需要将state设置为hard。当我们想要删除一个文件时(删除时不用区分目标是文件、目录、还是链接),则需要将state的值设置为absent,”absent”为缺席之意,当我们想让操作的目标”缺席”时,就表示我们想要删除目标。

src参数 :当state设置为link或者hard时,表示我们想要创建一个软链或者硬链,所以,我们必须指明软链或硬链链接的哪个文件,通过src参数即可指定链接源。

force参数 : 当state=link的时候,可配合此参数强制创建链接文件,当force=yes时,表示强制创建链接文件。不过强制创建链接文件分为三种情况。情况一:当要创建的链接文件指向的源文件并不存在时,使用此参数,可以先强制创建出链接文件。情况二:当要创建链接文件的目录中已经存在与链接文件同名的文件时,将force设置为yes,会将同名文件覆盖为链接文件,相当于删除同名文件,创建链接文件。情况三:当要创建链接文件的目录中已经存在与链接文件同名的文件,并且链接文件指向的源文件也不存在,这时会强制替换同名文件为链接文件。

owner参数 :用于指定被操作文件的属主,属主对应的用户必须在远程主机中存在,否则会报错。

group参数 :用于指定被操作文件的属组,属组对应的组必须在远程主机中存在,否则会报错。

mode参数:用于指定被操作文件的权限,比如,如果想要将文件权限设置为”rw-r-x—“,则可以使用mode=650进行设置,或者使用mode=0650,效果也是相同的。如果想要设置特殊权限,比如为二进制文件设置suid,则可以使用mode=4700。

recurse参数:当要操作的文件为目录,将recurse设置为yes,可以递归的修改目录中文件的属性。

state:

  • directory:如果目录不存在,创建目录
  • file:即使文件不存在,也不会被创建
  • link:创建软链接
  • hard:创建硬链接
  • touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间
  • absent:删除目录、文件或者取消链接文件

示例

在 192.168.91.139主机上创建一个名为 test 的文件,如果 test 文件已经存在,则会更新文件的时间戳,与 touch 命令的作用相同。

[root@ansible ~]# ansible 192.168.91.139 -m file -a 'path=/test state=touch'
  192.168.91.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "dest": "/test",
    "gid": 0,
    "group": "root",
    "mode": "0644",
    "owner": "root",
    "secontext": "unconfined_u:object_r:etc_runtime_t:s0",
    "size": 0,
    "state": "file",
    "uid": 0
}

在 192.168.91.139主机上创建一个名为 /data/test 的目录,如果 /data/test 目录已经存在,则不进行任何操作。

[root@ansible ~]# ansible 192.168.91.139 -m file -a "path=/data/test state=directory"
192.168.91.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "gid": 0,
    "group": "root",
    "mode": "0755",
    "owner": "root",
    "path": "/data/test",
    "secontext": "unconfined_u:object_r:default_t:s0",
    "size": 6,
    "state": "directory",
    "uid": 0
}

3.在 192.168.91.139 上为 test 文件创建软链接文件,软链接名为 test1,执行下面命令的时候,test 已经存在。

[root@ansible ~]# ansible 192.168.91.139 -m file -a "path=/test1 state=link src=/test"
192.168.91.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "dest": "/test1",
    "gid": 0,
    "group": "root",
    "mode": "0777",
    "owner": "root",
    "secontext": "unconfined_u:object_r:root_t:s0",
    "size": 5,
    "src": "/test",
    "state": "link",
    "uid": 0
}

4.在 192.168.91.139 上为 test2 文件创建硬链接文件,硬链接名为 file2,执行下面命令的时候,test2 已经存在。

[root@ansible ~]# ansible 192.168.91.139 -m file -a 'path=/file2 state=hard src=/test2 '
192.168.91.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "dest": "/file2",
    "gid": 0,
    "group": "root",
    "mode": "0644",
    "owner": "root",
    "secontext": "unconfined_u:object_r:etc_runtime_t:s0",
    "size": 0,
    "src": "/test2",
    "state": "hard",
    "uid": 0
}

5.在创建链接文件时,如果源文件不存在,或者链接文件与其他文件同名时,强制覆盖同名文件或者创建链接文件,链接名为 file2,文件test2

[root@ansible ~]# ansible 192.168.91.139 -m file -a "path=/file2 state=link src=/test2 force=yes"
192.168.91.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "dest": "/file2",
    "gid": 0,
    "group": "root",
    "mode": "0777",
    "owner": "root",
    "secontext": "unconfined_u:object_r:root_t:s0",
    "size": 6,
    "src": "/test2",
    "state": "link",
    "uid": 0
}
[root@ansible ~]# ansible 192.168.91.139 -m shell  -a 'ls -l / |grep test2'
192.168.91.139 | CHANGED | rc=0 >>
lrwxrwxrwx.   1 root root    6 Oct 23 23:15 file2 -> /test2

6.删除远程机器上的指定文件或目录。

[root@ansible ~]# ansible 192.168.91.139 -m file -a 'path=/test1 state=absent '
192.168.91.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "path": "/test1",
    "state": "absent"
}

7.在创建文件或目录的时候指定属主,或者修改远程主机上的文件或目录的属主。

[root@ansible ~]# ansible 192.168.91.139  -m file -a "path=/opt/abc state=touch owner=aa"
192.168.91.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "dest": "/opt/abc",
    "gid": 0,
    "group": "root",
    "mode": "0644",
    "owner": "aa",
    "secontext": "unconfined_u:object_r:usr_t:s0",
    "size": 0,
    "state": "file",
    "uid": 1234
}

[root@ansible ~]# ansible 192.168.91.139 -a 'ls -l /opt/'
192.168.91.139 | CHANGED | rc=0 >>
total 4
-rw-r--r--. 1 aa    root     0 Oct 23 23:20 abc


[root@ansible ~]# ansible 192.168.91.139  -m file -a 'path=/opt/abc owner=ww '
192.168.91.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "gid": 0,
    "group": "root",
    "mode": "0644",
    "owner": "ww",
    "path": "/opt/abc",
    "secontext": "unconfined_u:object_r:usr_t:s0",
    "size": 0,
    "state": "file",
    "uid": 1235
}
[root@ansible ~]# ansible 192.168.91.139 -a 'ls -l /opt/'
  192.168.91.139 | CHANGED | rc=0 >>
total 4
-rw-r--r--. 1 ww    root     0 Oct 23 23:20 abc