欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

ANSIBLE安装和常用模块模块使用详细教程

程序员文章站 2022-05-22 21:46:23
ANSIBLE安装和各种模块应用功能 [toc] 安装配置ANSIBLE 1. 下载ANSIBLE 2. 确认安装 3. 修改主机清单文件(添加要管理的主机) 4. ANSIBLE选项使用 bash ansible doc 查看各种模块帮助 [root@ansible ~] ansible doc ......

ansible安装和各种模块应用功能

安装配置ansible

  1. 下载ansible
[root@ansible ~]#yum install ansible
  1. 确认安装
[root@ansible ~]#ansible --version
ansible 2.9.1
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, oct 30 2018, 23:45:53) [gcc 4.8.5 20150623 (red hat 4.8.5-36)]
  1. 修改主机清单文件(添加要管理的主机)
[root@ansible ~]#vim /etc/ansible/hosts
[websrvs]
192.168.39.27
192.168.39.37
192.168.39.47

[appsrvs]
192.168.39.57
192.168.39.77
192.168.39.8
  1. ansible选项使用
# ansible-doc 查看各种模块帮助
[root@ansible ~]#ansible-doc ping 
> ping    (/usr/lib/python2.7/site-packages/ansible/modules/system/ping.py)

        a trivial test module, this module always returns `pong' on
        successful contact. it does not make sense in playbooks, but
        it is useful from `/usr/bin/ansible' to verify the ability to
        login and that a usable python is configured. this is not icmp
        ping, this is just a trivial test module that requires python
        on the remote-node. for windows targets, use the [win_ping]
        module instead. for network targets, use the [net_ping] module
        instead.

  * this module is maintained by the ansible core team
options (= is mandatory):

- data
        data to return for the `ping' return value.
        if this parameter is set to `crash', the module will cause an
        exception.
        [default: pong]
        type: str


see also:
      * module net_ping
           the official documentation on the net_ping module.
           https://docs.ansible.com/ansible/2.9/modules/net_ping
        _module.html
      * module win_ping
           the official documentation on the win_ping module.
           https://docs.ansible.com/ansible/2.9/modules/win_ping
        _module.html


author: ansible core team, michael dehaan
        metadata:
          status:
          - stableinterface
          supported_by: core

# -s 简单帮助
[root@ansible ~]#ansible-doc -s ping
- name: try to connect to host, verify a usable python and return `pong' on success
  ping:
      data:                  # data to return for the `ping' return value. if this
                               parameter is set to
                               `crash', the module
                               will cause an
                               exception.
# -m 调用指定模块
[root@ansible ~]#ansible websrvs -m ping   # 这样调用是链接不上的
the authenticity of host '192.168.39.37 (192.168.39.37)' can't be established.
ecdsa key fingerprint is sha256:vyjfahhade2ci7v5wrkzj6idukqfzozpmny56d9qkfi.
ecdsa key fingerprint is md5:22:72:17:9a:a8:93:1a:02:d8:09:17:f4:85:fe:b3:f5.
are you sure you want to continue connecting (yes/no)? the authenticity of host '192.168.39.47 (192.168.39.47)' can't be established.
ecdsa key fingerprint is sha256:vyjfahhade2ci7v5wrkzj6idukqfzozpmny56d9qkfi.
ecdsa key fingerprint is md5:22:72:17:9a:a8:93:1a:02:d8:09:17:f4:85:fe:b3:f5.
are you sure you want to continue connecting (yes/no)? the authenticity of host '192.168.39.27 (192.168.39.27)' can't be established.
ecdsa key fingerprint is sha256:vyjfahhade2ci7v5wrkzj6idukqfzozpmny56d9qkfi.
ecdsa key fingerprint is md5:22:72:17:9a:a8:93:1a:02:d8:09:17:f4:85:fe:b3:f5.
are you sure you want to continue connecting (yes/no)? yes
192.168.39.37 | unreachable! => {
    "changed": false, 
    "msg": "failed to connect to the host via ssh: warning: permanently added '192.168.39.37' (ecdsa) to the list of known hosts.\r\npermission denied (publickey,gssapi-keyex,gssapi-with-mic,password).", 
    "unreachable": true
}
yes
192.168.39.47 | unreachable! => {
    "changed": false, 
    "msg": "failed to connect to the host via ssh: warning: permanently added '192.168.39.47' (ecdsa) to the list of known hosts.\r\npermission denied (publickey,gssapi-keyex,gssapi-with-mic,password).", 
    "unreachable": true
}
yes
192.168.39.27 | unreachable! => {
    "changed": false, 
    "msg": "failed to connect to the host via ssh: warning: permanently added '192.168.39.27' (ecdsa) to the list of known hosts.\r\npermission denied (publickey,gssapi-keyex,gssapi-with-mic,password).", 
    "unreachable": true
}
# -k 提示输入密码(密码都一样的话这样链接可以都链接成功(最好都是基于key验证))
[root@ansible ~]#ansible websrvs -k  -m ping
ssh password: 
192.168.39.27 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.39.37 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.39.47 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
  1. 做key验证链接
  • 使用sshpass实现key验证
[root@ansible ~]#yum install sshpass -y  # 使用这个工具批量实现key验证

# 使用口令提交直接查看远程主机信息
[root@ansible ~]#sshpass -p 123456 ssh 192.168.39.27 cat /etc/redhat-release 
centos linux release 7.6.1810 (core) 
[root@ansible ~]#sshpass -p 123456 ssh 192.168.39.37 cat /etc/redhat-release 
centos linux release 7.6.1810 (core) 
[root@ansible ~]#sshpass -p 123456 ssh 192.168.39.47 cat /etc/redhat-release 
centos linux release 7.6.1810 (core) 

[root@ansible ~]#ll ~/.ssh/  # 查看一下有生成的key的公钥私钥吗?
total 4
-rw-r--r-- 1 root root 525 dec  4 19:49 known_hosts
[root@ansible ~]#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:xnbwv9kykg8b9b9q4lbudt2m8ssjn2k5yfzuyxdifqk root@ansible
the key's randomart image is:
+---[rsa 2048]----+
|            .    |
|           . ..  |
|          ...o.= |
|          .o+oo.o|
|        s ox=*.o.|
|       . o*.@+o..|
|        .e @ b=. |
|          + *.o* |
|           .o++ .|
+----[sha256]-----+

[root@ansible ~]#ll ~/.ssh/   # 查看一下公钥私钥对生成成功
total 12
-rw------- 1 root root 1675 dec  4 20:07 id_rsa
-rw-r--r-- 1 root root  394 dec  4 20:07 id_rsa.pub
-rw-r--r-- 1 root root  525 dec  4 19:49 known_hosts
  • 使用for循环来进行批量部署key验证
# 因为之前连过三台机子所以连接过的配置成功了
[root@ansible ~]#net=192.168.39;for i in 7 27 37 47 57 77 8 ;do sshpass -p 123456 ssh-copy-id $net.$i ;done
/usr/bin/ssh-copy-id: info: source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/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

number of key(s) added: 1

now try logging into the machine, with:   "ssh '192.168.39.27'"
and check to make sure that only the key(s) you wanted were added.

/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

number of key(s) added: 1

now try logging into the machine, with:   "ssh '192.168.39.37'"
and check to make sure that only the key(s) you wanted were added.

/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

number of key(s) added: 1

now try logging into the machine, with:   "ssh '192.168.39.47'"
and check to make sure that only the key(s) you wanted were added.

/usr/bin/ssh-copy-id: info: source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: info: source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: info: source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
  • 修改配置文件来进行key验证
# 在第一次远程连接的时候都会有一个提示就是输入yes/no(这个选项会影响第一次连接的服务器配置key所以在配置文件里修改一个选项来绕过这步)
[root@ansible ~]#vim /etc/ssh/ssh_config 

# host *
#   forwardagent no
#   forwardx11 no
#   rhostsrsaauthentication no
#   rsaauthentication yes
#   passwordauthentication yes
#   hostbasedauthentication no
#   gssapiauthentication no
#   gssapidelegatecredentials no
#   gssapikeyexchange no
#   gssapitrustdns no
#   batchmode no
#   checkhostip yes
#   addressfamily any
#   connecttimeout 0
 stricthostkeychecking no  # 这一项本来是注释掉的,去掉注释在后面改为no就可以了
#   identityfile ~/.ssh/identity
#   identityfile ~/.ssh/id_rsa
#   identityfile ~/.ssh/id_dsa
#   identityfile ~/.ssh/id_ecdsa
#   identityfile ~/.ssh/id_ed25519
#   port 22
  • 再次进行配置(之前配置好的不会在配置)
[root@ansible ~]#net=192.168.39;for i in 7 27 37 47 57 77 8 ;do sshpass -p 123456 ssh-copy-id $net.$i ;done
/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

number of key(s) added: 1

now try logging into the machine, with:   "ssh '192.168.39.7'"  # 本机也要发一个key验证
and check to make sure that only the key(s) you wanted were added.

/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: warning: all keys were skipped because they already exist on the remote system.
        (if you think this is a mistake, you may want to use -f option)

/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: warning: all keys were skipped because they already exist on the remote system.
        (if you think this is a mistake, you may want to use -f option)

/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: warning: all keys were skipped because they already exist on the remote system.
        (if you think this is a mistake, you may want to use -f option)

/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

number of key(s) added: 1

now try logging into the machine, with:   "ssh '192.168.39.57'"
and check to make sure that only the key(s) you wanted were added.

/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

number of key(s) added: 1

now try logging into the machine, with:   "ssh '192.168.39.77'"
and check to make sure that only the key(s) you wanted were added.

/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

number of key(s) added: 1

now try logging into the machine, with:   "ssh '192.168.39.8'"
and check to make sure that only the key(s) you wanted were added.
  • 以上key验证就部署好了(测试一下能否连接)
[root@ansible ~]#ssh 192.168.39.8
activate the web console with: systemctl enable --now cockpit.socket

last login: thu dec  5 03:22:37 2019 from 192.168.39.1
[root@centos8 ~]#exit
logout
connection to 192.168.39.8 closed.

# 不用再输入密码(-p -k 都不用加了)
[root@ansible ~]#ansible websrvs -m ping
192.168.39.47 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.39.37 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.39.27 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
[root@ansible ~]#ansible appsrvs -m ping
192.168.39.8 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.39.57 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.39.77 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

ansible使用

  1. 查看ansible管理所有主机
[root@ansible ~]#ansible all --list-host
  hosts (6):
    192.168.39.57
    192.168.39.77
    192.168.39.8
    192.168.39.27
    192.168.39.37
    192.168.39.47
  1. 使用ansible访问其他用户
[root@ansible ~]#ansible websrvs -u yang -m ping  # 因为yang这个账户没有做过key验证所以无法访问
192.168.39.27 | unreachable! => {
    "changed": false, 
    "msg": "failed to connect to the host via ssh: permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).", 
    "unreachable": true
}
192.168.39.47 | unreachable! => {
    "changed": false, 
    "msg": "failed to connect to the host via ssh: permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).", 
    "unreachable": true
}
192.168.39.37 | unreachable! => {
    "changed": false, 
    "msg": "failed to connect to the host via ssh: permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).", 
    "unreachable": true
}

# 想访问还是加-k来提示输入密码访问
[root@ansible ~]#ansible websrvs -u yang -k -m ping
ssh password: 
192.168.39.37 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.39.47 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.39.27 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
  1. 测试所有主机连接
[root@ansible ~]#ansible all -m ping
192.168.39.57 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
.....(省略)
192.168.39.47 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

[root@ansible ~]#ansible '*' -m ping  # 这个是一样的效果
192.168.39.57 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
.....(省略)
192.168.39.47 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

[root@ansible ~]#ansible "192.168.39.*" -m ping  # 这个是指这个网段的所有主机
192.168.39.57 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
.....(省略)
192.168.39.47 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

# 加-v显示详细信息加的v越多显示越详细最多三个
[root@ansible ~]#ansible websrvs -m ping -v
using /etc/ansible/ansible.cfg as config file
192.168.39.37 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.39.47 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.39.27 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
[root@ansible ~]#ansible websrvs -m ping -vv
ansible 2.9.1
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, oct 30 2018, 23:45:53) [gcc 4.8.5 20150623 (red hat 4.8.5-36)]
using /etc/ansible/ansible.cfg as config file
meta: ran handlers
192.168.39.47 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.39.37 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.39.27 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
meta: ran handlers
meta: ran handlers
  1. ansible颜色显示定义
    ANSIBLE安装和常用模块模块使用详细教程
  • 修改颜色定义文件
[root@ansible ~]#vim /etc/ansible/ansible.cfg
[root@ansible ~]#grep -a 14 '\[colors\]' /etc/ansible/ansible.cfg  # 使用grep查找colors下面的是定义颜色的
[colors]
#highlight = white
#verbose = blue
#warn = bright purple
#error = red
#debug = dark gray
#deprecate = purple
#skip = cyan
#unreachable = red
#ok = green
#changed = yellow
#diff_add = green
#diff_remove = red
#diff_lines = cyan

# 绿色:执行成功并且不需要做改变的操作
# 黄色:执行成功并且对目标主机做变更
# 红色:执行失败

ansible-galaxy工具

此工具会连接 https://galaxy.ansible.com 下载相应的roles
范例:

[root@ansible ~]#ansible-galaxy install geerlingguy.redis
- downloading role 'redis', owned by geerlingguy
- downloading role from https://github.com/geerlingguy/ansible-role-redis/archive/1.6.0.tar.gz
- extracting geerlingguy.redis to /root/.ansible/roles/geerlingguy.redis
- geerlingguy.redis (1.6.0) was installed successfully
[root@ansible ~]#ansible-galaxy list
# /root/.ansible/roles
- geerlingguy.redis, 1.6.0
# /usr/share/ansible/roles
# /etc/ansible/roles
[root@ansible ~]#ansible-galaxy remove geerlingguy.redis
- successfully removed geerlingguy.redis
[root@ansible ~]#ansible-galaxy list
# /root/.ansible/roles
# /usr/share/ansible/roles
# /etc/ansible/roles
#列出所有已安装的galaxy
ansible-galaxy list
#安装galaxy
ansible-galaxy install geerlingguy.redis
#删除galaxy
ansible-galaxy remove geerlingguy.redis

ansible-pull工具

此工具会推送ansible的命令至远程,效率无限提升,对运维要求较高

ansible-playbook

此工具用于执行编写好的playbook任务

范例:

[root@ansible ~]#ansible-playbook hello.yml 
[root@ansible ~]#cat hello.yml
---
#hello world yml file
- hosts: websrvs 
  remote_user: root 
  tasks:
    - name: hello world
      command: /usr/bin/wall hello world

ansible常用模块

command 模块

功能:在远程主机执行命令,此为默认模块,可忽略-m选项
注意:此命令不支持 $varname < > | ; & 等,用shell模块实现
[root@ansible ~]#ansible websrvs -m command -a 'cat /etc/redhat-release'
192.168.39.37 | changed | rc=0 >>
centos linux release 7.6.1810 (core) 

192.168.39.27 | changed | rc=0 >>
centos linux release 7.6.1810 (core) 

192.168.39.47 | changed | rc=0 >>
centos linux release 7.6.1810 (core) 

[root@ansible ~]#ansible websrvs -a 'cat /etc/redhat-release'  # 默认模块为command可以不用写
192.168.39.37 | changed | rc=0 >>
centos linux release 7.6.1810 (core) 

192.168.39.47 | changed | rc=0 >>
centos linux release 7.6.1810 (core) 

192.168.39.27 | changed | rc=0 >>
centos linux release 7.6.1810 (core)


[root@ansible ~]#ansible websrvs -a 'chdir=/etc cat redhat-release' # 指定目录进入,之后不需要写全部路径
192.168.39.37 | changed | rc=0 >>
centos linux release 7.6.1810 (core) 

192.168.39.27 | changed | rc=0 >>
centos linux release 7.6.1810 (core) 

192.168.39.47 | changed | rc=0 >>
centos linux release 7.6.1810 (core) 

# 测试command模块判断执行
# 在两台主机建立两个文件测试
[root@centos27 ~]#touch /data/test.txt
[root@centos37 ~]#touch /data/test.txt

# 目标主机建立过文件的两个主机执行另一个不执行
[root@ansible ~]#ansible websrvs -a 'creates=/data/test.txt ls /data'
192.168.39.27 | success | rc=0 >>
skipped, since /data/test.txt exists     

192.168.39.37 | success | rc=0 >>
skipped, since /data/test.txt exists

192.168.39.47 | changed | rc=0 >>
log.tar.bz2
  • 可以用linux命令执行
[root@ansible ~]#ansible websrvs -a 'useradd jack'   # 利用useradd建立一个用户
192.168.39.47 | changed | rc=0 >>


192.168.39.27 | changed | rc=0 >>


192.168.39.37 | changed | rc=0 >>

[root@ansible ~]#ansible websrvs -a 'getent passwd jack' 
192.168.39.47 | changed | rc=0 >>
jack:x:1001:1001::/home/jack:/bin/bash

192.168.39.27 | changed | rc=0 >>
jack:x:1001:1001::/home/jack:/bin/bash

192.168.39.37 | changed | rc=0 >>
jack:x:1001:1001::/home/jack:/bin/bash


[root@centos27 ~]#grep jack /etc/passwd
jack:x:1001:1001::/home/jack:/bin/bash

[root@centos37 ~]#grep jack /etc/passwd
jack:x:1001:1001::/home/jack:/bin/bash

[root@centos47 ~]#grep jack /etc/passwd
jack:x:1001:1001::/home/jack:/bin/bash
  • 但是这个模块也有的命令不支持
[root@ansible ~]#ansible websrvs -a 'echo centos | passwd --stdin jack'  # 使用管道设置密码
192.168.39.47 | changed | rc=0 >>
centos | passwd --stdin jack

192.168.39.27 | changed | rc=0 >>
centos | passwd --stdin jack

192.168.39.37 | changed | rc=0 >>
centos | passwd --stdin jack

# 没有密码,证明没设置。(不支持管道符“|”)
[root@centos27 ~]#grep jack /etc/shadow
jack:!!:18235:0:99999:7:::


# $也不可以使用
[root@ansible ~]#ansible websrvs -a "echo $hostname"  # 查看的都是本机的变量
192.168.39.37 | changed | rc=0 >>
ansible

192.168.39.47 | changed | rc=0 >>
ansible

192.168.39.27 | changed | rc=0 >>
ansible

[root@ansible ~]#ansible websrvs -a "echo $uid"    
192.168.39.47 | changed | rc=0 >>
0

192.168.39.37 | changed | rc=0 >>
0

192.168.39.27 | changed | rc=0 >>
0
  • 重定向也不支持
    ANSIBLE安装和常用模块模块使用详细教程
    ---

shell模块

  • shell模块简单说明
[root@ansible ~]#ansible-doc -s shell
- name: execute shell commands on targets
  shell:
      chdir:                 # change into this directory before running the command.
      cmd:                   # the command to run followed by optional arguments.
      creates:               # a filename, when it already exists, this step will
                               *not* be run.
      executable:            # change the shell used to execute the command. this
                               expects an absolute
                               path to the executable.
      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.
      removes:               # a filename, when it does not exist, this step will
                               *not* be run.
      stdin:                 # set the stdin of the command directly to the specified
                               value.
      stdin_add_newline:     # whether to append a newline to stdin data.
      warn:                  # whether to enable task warnings.
  • 使用shell查看主机名
[root@ansible ~]#ansible websrvs -m shell -a "echo $hostname"  # 不可以加双引号
192.168.39.27 | changed | rc=0 >>
ansible

192.168.39.37 | changed | rc=0 >>
ansible

192.168.39.47 | changed | rc=0 >>
ansible

[root@ansible ~]#ansible websrvs -m shell -a 'echo $hostname'  # 必须单引号
192.168.39.47 | changed | rc=0 >>
centos47

192.168.39.37 | changed | rc=0 >>
centos37

192.168.39.27 | changed | rc=0 >>
centos27
  • 查看文件
[root@ansible ~]#ansible websrvs -m shell -a 'cat /data/test.txt'
192.168.39.27 | changed | rc=0 >>


192.168.39.47 | failed | rc=1 >>
cat: /data/test.txt: no such file or directorynon-zero return code   # 这条信息是因为这个主机上没有这个文件

192.168.39.37 | changed | rc=0 >>
  • 设置用户密码
[root@ansible ~]#ansible websrvs -m shell -a 'echo centos | passwd --stdin jack'
192.168.39.27 | changed | rc=0 >>
changing password for user jack.
passwd: all authentication tokens updated successfully.

192.168.39.37 | changed | rc=0 >>
changing password for user jack.
passwd: all authentication tokens updated successfully.

192.168.39.47 | changed | rc=0 >>
changing password for user jack.
passwd: all authentication tokens updated successfully.

[root@centos27 ~]#grep jack /etc/shadow  # 显示加密,密码设置成功
jack:$6$je4qxqod$9qcguklhk/vzpphaos3lvaavclwiexnlaitngif6kkl/hupf4rbeet9w8o9u7d2o/yb391ys4s5u.y6fcoype1:18235:0:99999:7:::
  • 使用shell模块修改selinux状态
[root@centos27 ~]#cat /etc/selinux/config 

# this file controls the state of selinux on the system.
# selinux= can take one of these three values:
#     enforcing - selinux security policy is enforced.
#     permissive - selinux prints warnings instead of enforcing.
#     disabled - no selinux policy is loaded.
selinux=disabled  # 现在是禁用状态
# selinuxtype= can take one of three values:
#     targeted - targeted processes are protected,
#     minimum - modification of targeted policy. only selected processes are protected. 
#     mls - multi level security protection.
selinuxtype=targeted 

[root@ansible ~]#ansible websrvs -m shell -a "sed -i 's/selinux=disabled/selinux=enforcing/' /etc/selinux/config"
[warning]: consider using the replace, lineinfile or template module rather than
running 'sed'.  if you need to use command because replace, lineinfile or template 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.39.47 | changed | rc=0 >>


192.168.39.27 | changed | rc=0 >>


192.168.39.37 | changed | rc=0 >>


[root@centos27 ~]#cat /etc/selinux/config 

# this file controls the state of selinux on the system.
# selinux= can take one of these three values:
#     enforcing - selinux security policy is enforced.
#     permissive - selinux prints warnings instead of enforcing.
#     disabled - no selinux policy is loaded.
selinux=enforcing  # 修改为启用了
# selinuxtype= can take one of three values:
#     targeted - targeted processes are protected,
#     minimum - modification of targeted policy. only selected processes are protected. 
#     mls - multi level security protection.
selinuxtype=targeted 
  • 修改shell为默认模块
[root@ansible ~]#grep '^[#]module' /etc/ansible/ansible.cfg
#module_utils   = /usr/share/my_module_utils/
#module_lang    = c
#module_set_locale = false
module_name = shell   # 找到这一行删掉注释 把后面修改为shell就可以了
#module_compression = 'zip_deflated'


# 使用的时候可以不加shell模块了
[root@ansible ~]#ansible websrvs -a 'echo linux | passwd --stdin jack'
192.168.39.27 | changed | rc=0 >>
changing password for user jack.
passwd: all authentication tokens updated successfully.

192.168.39.47 | changed | rc=0 >>
changing password for user jack.
passwd: all authentication tokens updated successfully.

192.168.39.37 | changed | rc=0 >>
changing password for user jack.
passwd: all authentication tokens updated successfully.

几乎可以使用系统里的所有命令,但是有的命令有更专业的模块,最好对应使用。

script模块

功能::在远程主机上运行ansible服务器上的脚本
  • 模块简单介绍
[root@ansible ~]#ansible-doc -s script
- name: runs a local script on a remote node after transferring it
  script:
      chdir:                 # change into this directory on the remote node before
                               running the script.
      cmd:                   # path to the local script to run followed by optional
                               arguments.
      creates:               # a filename on the remote node, when it already exists,
                               this step will *not* be
                               run.
      decrypt:               # this option controls the autodecryption of source
                               files using vault.
      executable:            # name or path of a executable to invoke the script
                               with.
      free_form:             # path to the local script file followed by optional
                               arguments.
      removes:               # a filename on the remote node, when it does not exist,
                               this step will *not* be
                               run.
  • 在ansible主机写一个脚本来测试
[root@ansible ~]#cat test.sh
#!/bin/bash
touch /data/host.txt   # 测试使用没写多
  • 开始使用script模块执行脚本在远程实现
[root@ansible ~]#ansible websrvs -m script -a '/root/test.sh'
192.168.39.27 | changed => {
    "changed": true, 
    "rc": 0, 
    "stderr": "shared connection to 192.168.39.27 closed.\r\n", 
    "stderr_lines": [
        "shared connection to 192.168.39.27 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}
192.168.39.47 | changed => {
    "changed": true, 
    "rc": 0, 
    "stderr": "shared connection to 192.168.39.47 closed.\r\n", 
    "stderr_lines": [
        "shared connection to 192.168.39.47 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}
192.168.39.37 | changed => {
    "changed": true, 
    "rc": 0, 
    "stderr": "shared connection to 192.168.39.37 closed.\r\n", 
    "stderr_lines": [
        "shared connection to 192.168.39.37 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}
[root@ansible ~]#ansible websrvs -a 'ls /data'
192.168.39.27 | changed | rc=0 >>
host.txt   # 创建成功
log.tar.bz2
mysql-20191130-1445.tar.gz
test.txt

192.168.39.47 | changed | rc=0 >>
host.txt
log.tar.bz2

192.168.39.37 | changed | rc=0 >>
host.txt
log.tar.bz2
test.txt

copy模块

功能:从ansible服务器主控端复制文件到远程主机
  • 模块简单介绍
[root@ansible ~]#ansible-doc -s copy
- name: copy files to remote locations
  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
  • 修改path变量并修改所有者所属组和权限
profile.d/mysql.sh owner=yang group=bin mode=700"
192.168.39.47 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "224051367fc65d418858652f7766065a65a46b83", 
    "dest": "/etc/profile.d/mysql.sh", 
    "gid": 1, 
    "group": "bin", 
    "md5sum": "4272eaf1388c674a434242136cd65beb", 
    "mode": "0700", 
    "owner": "yang", 
    "size": 81, 
    "src": "/root/.ansible/tmp/ansible-tmp-1575536571.04-31281855976552/source", 
    "state": "file", 
    "uid": 1000
}
192.168.39.27 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "224051367fc65d418858652f7766065a65a46b83", 
    "dest": "/etc/profile.d/mysql.sh", 
    "gid": 1, 
    "group": "bin", 
    "md5sum": "4272eaf1388c674a434242136cd65beb", 
    "mode": "0700", 
    "owner": "yang", 
    "size": 81, 
    "src": "/root/.ansible/tmp/ansible-tmp-1575536571.02-85433210657540/source", 
    "state": "file", 
    "uid": 1000
}
192.168.39.37 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "224051367fc65d418858652f7766065a65a46b83", 
    "dest": "/etc/profile.d/mysql.sh", 
    "gid": 1, 
    "group": "bin", 
    "md5sum": "4272eaf1388c674a434242136cd65beb", 
    "mode": "0700", 
    "owner": "yang", 
    "size": 81, 
    "src": "/root/.ansible/tmp/ansible-tmp-1575536571.05-107810656824997/source", 
    "state": "file", 
    "uid": 1000
}
  • 查看修改结果
[root@ansible ~]#ansible websrvs -a 'ls -l /etc/profile.d/mysql.sh'
192.168.39.47 | changed | rc=0 >>
-rwx------ 1 yang bin 81 dec  5 17:02 /etc/profile.d/mysql.sh

192.168.39.37 | changed | rc=0 >>
-rwx------ 1 yang bin 81 dec  5 17:02 /etc/profile.d/mysql.sh

192.168.39.27 | changed | rc=0 >>
-rwx------ 1 yang bin 81 dec  5 17:02 /etc/profile.d/mysql.sh
  • 拷贝文件到目标主机
[root@ansible ~]#ansible websrvs -m copy -a "src=/etc/selinux/config dest=/data"
192.168.39.37 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "086428e2a122b0fec18cd17858f334ca65116f69", 
    "dest": "/data/config", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "8a7e44af619a4538054b458dfa31941d", 
    "mode": "0644", 
    "owner": "root", 
    "size": 542, 
    "src": "/root/.ansible/tmp/ansible-tmp-1575536783.04-173190751129047/source", 
    "state": "file", 
    "uid": 0
}
192.168.39.47 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "086428e2a122b0fec18cd17858f334ca65116f69", 
    "dest": "/data/config", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "8a7e44af619a4538054b458dfa31941d", 
    "mode": "0644", 
    "owner": "root", 
    "size": 542, 
    "src": "/root/.ansible/tmp/ansible-tmp-1575536783.03-90703232115071/source", 
    "state": "file", 
    "uid": 0
}
192.168.39.27 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "086428e2a122b0fec18cd17858f334ca65116f69", 
    "dest": "/data/config", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "8a7e44af619a4538054b458dfa31941d", 
    "mode": "0644", 
    "owner": "root", 
    "size": 542, 
    "src": "/root/.ansible/tmp/ansible-tmp-1575536783.02-59216625108124/source", 
    "state": "file", 
    "uid": 0
}

# 查看结果

[root@ansible ~]#ansible websrvs -a 'll /data'  # 不要使用别名  ll类似于别名识别不了
192.168.39.37 | failed | rc=127 >>
/bin/sh: ll: command not foundnon-zero return code

192.168.39.27 | failed | rc=127 >>
/bin/sh: ll: command not foundnon-zero return code

192.168.39.47 | failed | rc=127 >>
/bin/sh: ll: command not foundnon-zero return code

[root@ansible ~]#ansible websrvs -a 'ls -l /data'  
192.168.39.37 | changed | rc=0 >>
total 640
-rw-r--r-- 1 root root    542 dec  5 17:06 config   # 拷贝成功
-rw-r--r-- 1 root root      0 dec  5 15:58 host.txt
-rw-r--r-- 1 root root 647441 dec  4 21:27 log.tar.bz2
-rw-r--r-- 1 root root      0 dec  5 14:54 test.txt

192.168.39.27 | changed | rc=0 >>
total 1204
-rw-r--r-- 1 root root    542 dec  5 17:06 config
-rw-r--r-- 1 root root      0 dec  5 15:58 host.txt
-rw-r--r-- 1 root root 640288 dec  4 21:27 log.tar.bz2
-rw-r--r-- 1 root root 585133 nov 30 14:47 mysql-20191130-1445.tar.gz
-rw-r--r-- 1 root root      0 dec  5 14:54 test.txt

192.168.39.47 | changed | rc=0 >>
total 624
-rw-r--r-- 1 root root    542 dec  5 17:06 config
-rw-r--r-- 1 root root      0 dec  5 15:58 host.txt
-rw-r--r-- 1 root root 634270 dec  4 21:27 log.tar.bz2
  • 判断拷贝目标主机有这个文件先备份再覆盖
[root@ansible ~]#ansible websrvs -m copy -a "src=/etc/issue dest=/data/config backup=yes"
192.168.39.47 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "backup_file": "/data/config.13745.2019-12-05@17:12:29~", 
    "changed": true, 
    "checksum": "5c76e3b565c91e21bee303f15c728c71e6b39540", 
    "dest": "/data/config", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "f078fe086dfc22f64b5dca2e1b95de2c", 
    "mode": "0644", 
    "owner": "root", 
    "size": 23, 
    "src": "/root/.ansible/tmp/ansible-tmp-1575537147.78-218002224821544/source", 
    "state": "file", 
    "uid": 0
}
192.168.39.27 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "backup_file": "/data/config.13680.2019-12-05@17:12:29~", 
    "changed": true, 
    "checksum": "5c76e3b565c91e21bee303f15c728c71e6b39540", 
    "dest": "/data/config", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "f078fe086dfc22f64b5dca2e1b95de2c", 
    "mode": "0644", 
    "owner": "root", 
    "size": 23, 
    "src": "/root/.ansible/tmp/ansible-tmp-1575537147.76-127133770301032/source", 
    "state": "file", 
    "uid": 0
}
192.168.39.37 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "backup_file": "/data/config.13707.2019-12-05@17:12:29~", 
    "changed": true, 
    "checksum": "5c76e3b565c91e21bee303f15c728c71e6b39540", 
    "dest": "/data/config", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "f078fe086dfc22f64b5dca2e1b95de2c", 
    "mode": "0644", 
    "owner": "root", 
    "size": 23, 
    "src": "/root/.ansible/tmp/ansible-tmp-1575537147.79-135304360989753/source", 
    "state": "file", 
    "uid": 0
}

# 查看结果

[root@ansible ~]#ansible websrvs -a 'ls -l /data'
192.168.39.47 | changed | rc=0 >>
total 628
-rw-r--r-- 1 root root     23 dec  5 17:12 config  # 这个是拷贝过去的文件
-rw-r--r-- 1 root root    542 dec  5 17:06 config.13745.2019-12-05@17:12:29~  # 这是备份的,这个文件名每个服务器是不一样的
-rw-r--r-- 1 root root      0 dec  5 15:58 host.txt
-rw-r--r-- 1 root root 634270 dec  4 21:27 log.tar.bz2

192.168.39.27 | changed | rc=0 >>
total 1208
-rw-r--r-- 1 root root     23 dec  5 17:12 config
-rw-r--r-- 1 root root    542 dec  5 17:06 config.13680.2019-12-05@17:12:29~
-rw-r--r-- 1 root root      0 dec  5 15:58 host.txt
-rw-r--r-- 1 root root 640288 dec  4 21:27 log.tar.bz2
-rw-r--r-- 1 root root 585133 nov 30 14:47 mysql-20191130-1445.tar.gz
-rw-r--r-- 1 root root      0 dec  5 14:54 test.txt

192.168.39.37 | changed | rc=0 >>
total 644
-rw-r--r-- 1 root root     23 dec  5 17:12 config
-rw-r--r-- 1 root root    542 dec  5 17:06 config.13707.2019-12-05@17:12:29~
-rw-r--r-- 1 root root      0 dec  5 15:58 host.txt
-rw-r--r-- 1 root root 647441 dec  4 21:27 log.tar.bz2
-rw-r--r-- 1 root root      0 dec  5 14:54 test.txt
  • 拷贝目录到目标主机
# 保证data下有文件做测试使用
[root@ansible ~]#touch /data/test.txt
[root@ansible ~]#ll /data/
total 0
-rw-r--r-- 1 root root 0 dec  5 17:23 test.txt

[root@ansible ~]#ansible websrvs -m copy -a "src=/data dest=/backup"
192.168.39.47 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709", 
    "dest": "/backup/data/test.txt", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "d41d8cd98f00b204e9800998ecf8427e", 
    "mode": "0644", 
    "owner": "root", 
    "size": 0, 
    "src": "/root/.ansible/tmp/ansible-tmp-1575537831.85-231491228827500/source", 
    "state": "file", 
    "uid": 0
}


 查看结果

# 目录和文件都拷贝过去了
[root@ansible ~]#ansible websrvs -a 'ls -l /backup'
192.168.39.37 | changed | rc=0 >>
total 0
drwxr-xr-x 2 root root 22 dec  5 17:23 data

192.168.39.27 | changed | rc=0 >>
total 0
drwxr-xr-x 2 root root 22 dec  5 17:23 data

192.168.39.47 | changed | rc=0 >>
total 0
drwxr-xr-x 2 root root 22 dec  5 17:23 data

[root@ansible ~]#ansible websrvs -a 'ls -l /backup/data'
192.168.39.27 | changed | rc=0 >>
total 0
-rw-r--r-- 1 root root 0 dec  5 17:23 test.txt

192.168.39.47 | changed | rc=0 >>
total 0
-rw-r--r-- 1 root root 0 dec  5 17:23 test.txt

192.168.39.37 | changed | rc=0 >>
total 0
-rw-r--r-- 1 root root 0 dec  5 17:23 test.txt
  • 只拷贝目录下的文件
# 只用在源文件夹后面跟上斜杠就可以了
[root@ansible ~]#ansible websrvs -m copy -a "src=/data/ dest=/backup"
192.168.39.47 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709", 
    "dest": "/backup/test.txt", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "d41d8cd98f00b204e9800998ecf8427e", 
    "mode": "0644", 
    "owner": "root", 
    "size": 0, 
    "src": "/root/.ansible/tmp/ansible-tmp-1575538078.66-3118597090714/source", 
    "state": "file", 
    "uid": 0
}

# 查看结果

[root@ansible ~]#ansible websrvs -a 'ls -l /backup/'  # 只拷贝了文件目录没有拷贝
192.168.39.47 | changed | rc=0 >>
total 0
-rw-r--r-- 1 root root 0 dec  5 17:27 test.txt

192.168.39.37 | changed | rc=0 >>
total 0
-rw-r--r-- 1 root root 0 dec  5 17:27 test.txt

192.168.39.27 | changed | rc=0 >>
total 0
-rw-r--r-- 1 root root 0 dec  5 17:27 test.txt
也可以配置远程主机yum源使用,src是源  dest是目标

fetch模块

功能:从远程主机提取文件至ansible的主控端,copy相反,目前不支持目录,但是可以打包抓取目录。
  • 抓取文件到本机
[root@ansible ~]#ansible websrvs -m fetch -a 'src=/etc/redhat-release dest=/data/os.txt'
192.168.39.37 | changed => {
    "changed": true, 
    "checksum": "dd9a53b0d396d3ab190cfbc08dca572d3e741a03", 
    "dest": "/data/os.txt/192.168.39.37/etc/redhat-release", 
    "md5sum": "712356bf79a10f4c45cc0a1772bbeaf6", 
    "remote_checksum": "dd9a53b0d396d3ab190cfbc08dca572d3e741a03", 
    "remote_md5sum": null
}
192.168.39.47 | changed => {
    "changed": true, 
    "checksum": "dd9a53b0d396d3ab190cfbc08dca572d3e741a03", 
    "dest": "/data/os.txt/192.168.39.47/etc/redhat-release", 
    "md5sum": "712356bf79a10f4c45cc0a1772bbeaf6", 
    "remote_checksum": "dd9a53b0d396d3ab190cfbc08dca572d3e741a03", 
    "remote_md5sum": null
}
192.168.39.27 | changed => {
    "changed": true, 
    "checksum": "dd9a53b0d396d3ab190cfbc08dca572d3e741a03", 
    "dest": "/data/os.txt/192.168.39.27/etc/redhat-release", 
    "md5sum": "712356bf79a10f4c45cc0a1772bbeaf6", 
    "remote_checksum": "dd9a53b0d396d3ab190cfbc08dca572d3e741a03", 
    "remote_md5sum": null
}

# 查看结果

[root@ansible ~]#ll /data/  # 会生成一个文件夹
total 0
drwxr-xr-x 5 root root 69 dec  5 17:50 os.txt
-rw-r--r-- 1 root root  0 dec  5 17:23 test.txt

[root@ansible ~]#tree /data/os.txt/  # 文件夹结构 按照主机ip存放的
/data/os.txt/
├── 192.168.39.27
│   └── etc
│       └── redhat-release
├── 192.168.39.37
│   └── etc
│       └── redhat-release
└── 192.168.39.47
    └── etc
        └── redhat-release

6 directories, 3 files

file模块

功能:管理文件和文件的属性
  state=absent 代表删除的意思
  state=touch  创建空文件
  state=directory  创建空文件夹
  state=link  创建软连接
  state=hard  创建硬链接
  • 更改远程主机文件属性没有这个文件不执行。
[root@ansible ~]#ansible websrvs -m file -a 'path=/data/test.txt owner=yang group=root mode=600'
192.168.39.27 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0600", 
    "owner": "yang", 
    "path": "/data/test.txt", 
    "size": 0, 
    "state": "file", 
    "uid": 1000
}
192.168.39.47 | failed! => {   # 不执行但是会报错
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "msg": "file (/data/test.txt) is absent, cannot continue", 
    "path": "/data/test.txt"
}
192.168.39.37 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0600", 
    "owner": "yang", 
    "path": "/data/test.txt", 
    "size": 0, 
    "state": "file", 
    "uid": 1000
}

# 查看结果

[root@ansible ~]#ansible websrvs -a 'ls -l /data/test.txt'
192.168.39.47 | failed | rc=2 >>
ls: cannot access /data/test.txt: no such file or directorynon-zero return code

192.168.39.27 | changed | rc=0 >>
-rw------- 1 yang root 0 dec  5 14:54 /data/test.txt

192.168.39.37 | changed | rc=0 >>
-rw------- 1 yang root 0 dec  5 14:54 /data/test.txt
  • 也可以删除文件使用
[root@ansible ~]#ansible websrvs -m file -a 'path=/data/test.txt state=absent'
192.168.39.27 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "path": "/data/test.txt", 
    "state": "absent"
}
192.168.39.37 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "path": "/data/test.txt", 
    "state": "absent"
}
192.168.39.47 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "path": "/data/test.txt", 
    "state": "absent"
}

# 查看结果
[root@ansible ~]#ansible websrvs -a 'ls -l /data/'
192.168.39.47 | changed | rc=0 >>
total 628
-rw-r--r-- 1 root root     23 dec  5 17:12 config
-rw-r--r-- 1 root root    542 dec  5 17:06 config.13745.2019-12-05@17:12:29~
-rw-r--r-- 1 root root      0 dec  5 15:58 host.txt
-rw-r--r-- 1 root root 634270 dec  4 21:27 log.tar.bz2

192.168.39.27 | changed | rc=0 >>
total 1208
-rw-r--r-- 1 root root     23 dec  5 17:12 config
-rw-r--r-- 1 root root    542 dec  5 17:06 config.13680.2019-12-05@17:12:29~
-rw-r--r-- 1 root root      0 dec  5 15:58 host.txt
-rw-r--r-- 1 root root 640288 dec  4 21:27 log.tar.bz2
-rw-r--r-- 1 root root 585133 nov 30 14:47 mysql-20191130-1445.tar.gz

192.168.39.37 | changed | rc=0 >>
total 644
-rw-r--r-- 1 root root     23 dec  5 17:12 config
-rw-r--r-- 1 root root    542 dec  5 17:06 config.13707.2019-12-05@17:12:29~
-rw-r--r-- 1 root root      0 dec  5 15:58 host.txt
-rw-r--r-- 1 root root 647441 dec  4 21:27 log.tar.bz2
  • 删除文件夹
[root@ansible ~]#ansible websrvs -m file -a 'path=/backup/ state=absent'  # 
192.168.39.47 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "path": "/backup/", 
    "state": "absent"
}
192.168.39.37 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "path": "/backup/", 
    "state": "absent"
}
192.168.39.27 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "path": "/backup/", 
    "state": "absent"
}

# 查看结果
[root@ansible ~]#ansible websrvs -a 'ls -l /'
192.168.39.27 | changed | rc=0 >>
total 32
lrwxrwxrwx.   1 root root     7 sep  5 16:17 bin -> usr/bin
dr-xr-xr-x.   5 root root  4096 sep  5 16:23 boot
drwxr-xr-x.   2 root root     6 dec  5 18:02 data
drwxr-xr-x   19 root root  3320 dec  5 14:50 dev
drwxr-xr-x. 143 root root 12288 dec  5 15:46 etc
drwxr-xr-x.   4 root root    30 dec  5 15:00 home
lrwxrwxrwx.   1 root root     7 sep  5 16:17 lib -> usr/lib
lrwxrwxrwx.   1 root root     9 sep  5 16:17 lib64 -> usr/lib64
drwxr-xr-x.   2 root root     6 apr 11  2018 media
drwxr-xr-x    3 root root    16 nov 15 20:06 misc
drwxr-xr-x.   2 root root     6 apr 11  2018 mnt
drwxr-xr-x.   3 root root    16 sep  5 16:20 opt
dr-xr-xr-x  190 root root     0 dec  5 14:49 proc
dr-xr-x---.  17 root root  4096 dec  5 14:56 root
drwxr-xr-x   40 root root  1200 dec  5 14:50 run
lrwxrwxrwx.   1 root root     8 sep  5 16:17 sbin -> usr/sbin
drwxr-xr-x.   2 root root     6 apr 11  2018 srv
dr-xr-xr-x   13 root root     0 dec  5 17:20 sys
drwxrwxrwt.  19 root root  4096 dec  5 18:03 tmp
drwxr-xr-x.  13 root root   155 sep  5 16:17 usr
drwxr-xr-x.  21 root root  4096 sep  5 16:25 var

# 还有一种情况,当这个文件夹是挂载点的时候不能直接删除目录只会清空目录下的数据。
[root@ansible ~]#ansible websrvs -m file -a 'path=/data/ state=absent'
192.168.39.37 | failed! => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "msg": "rmtree failed: [errno 16] device or resource busy: '/data/'"
}
192.168.39.27 | failed! => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "msg": "rmtree failed: [errno 16] device or resource busy: '/data/'"
}
192.168.39.47 | failed! => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "msg": "rmtree failed: [errno 16] device or resource busy: '/data/'"
}

[root@ansible ~]#ansible websrvs -a 'ls -l /data'
192.168.39.37 | changed | rc=0 >>
total 0

192.168.39.47 | changed | rc=0 >>
total 0

192.168.39.27 | changed | rc=0 >>
total 0
  • 创建空文件使用
[root@ansible ~]#ansible websrvs -m file -a 'path=/data/fa.txt state=touch'
192.168.39.47 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/data/fa.txt", 
    "gid": 0, 
    "group": "root", 
    "mode": "0644", 
    "owner": "root", 
    "size": 0, 
    "state": "file", 
    "uid": 0
}
[root@ansible ~]#ansible websrvs -a 'ls -l /data'
192.168.39.27 | changed | rc=0 >>
total 0
-rw-r--r-- 1 root root 0 dec  5 18:06 fa.txt

192.168.39.37 | changed | rc=0 >>
total 0
-rw-r--r-- 1 root root 0 dec  5 18:06 fa.txt

192.168.39.47 | changed | rc=0 >>
total 0
-rw-r--r-- 1 root root 0 dec  5 18:06 fa.txt
  • 创建空文件夹
[root@ansible ~]#ansible websrvs -m file -a 'path=/data/dir state=directory'
192.168.39.37 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/data/dir", 
    "size": 6, 
    "state": "directory", 
    "uid": 0
}

[root@ansible ~]#ansible websrvs -a 'ls -l /data'
192.168.39.47 | changed | rc=0 >>
total 0
drwxr-xr-x 2 root root 6 dec  5 18:10 dir
-rw-r--r-- 1 root root 0 dec  5 18:06 fa.txt

192.168.39.37 | changed | rc=0 >>
total 0
drwxr-xr-x 2 root root 6 dec  5 18:10 dir
-rw-r--r-- 1 root root 0 dec  5 18:06 fa.txt

192.168.39.27 | changed | rc=0 >>
total 0
drwxr-xr-x 2 root root 6 dec  5 18:10 dir
-rw-r--r-- 1 root root 0 dec  5 18:06 fa.txt

[root@ansible ~]#ansible websrvs -a 'ls -l /data/dir'
192.168.39.37 | changed | rc=0 >>
total 0

192.168.39.47 | changed | rc=0 >>
total 0

192.168.39.27 | changed | rc=0 >>
total 0
  • 创建软连接
[root@ansible ~]#ansible websrvs -m file -a 'src=/etc/issue path=/data/issue.link state=link' 
192.168.39.27 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/data/issue.link", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "size": 10, 
    "src": "/etc/issue", 
    "state": "link", 
    "uid": 0
}

[root@ansible ~]#ansible websrvs -a 'ls -l /data/'
192.168.39.27 | changed | rc=0 >>
total 0
drwxr-xr-x 2 root root  6 dec  5 18:10 dir
-rw-r--r-- 1 root root  0 dec  5 18:06 fa.txt
lrwxrwxrwx 1 root root 10 dec  5 18:12 issue.link -> /etc/issue

192.168.39.37 | changed | rc=0 >>
total 0
drwxr-xr-x 2 root root  6 dec  5 18:10 dir
-rw-r--r-- 1 root root  0 dec  5 18:06 fa.txt
lrwxrwxrwx 1 root root 10 dec  5 18:12 issue.link -> /etc/issue

192.168.39.47 | changed | rc=0 >>
total 0
drwxr-xr-x 2 root root  6 dec  5 18:10 dir
-rw-r--r-- 1 root root  0 dec  5 18:06 fa.txt
lrwxrwxrwx 1 root root 10 dec  5 18:12 issue.link -> /etc/issue

# 删除软连接
[root@ansible ~]#ansible websrvs -m file -a 'path=/data/issue.link state=absent'
192.168.39.47 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "path": "/data/issue.link", 
    "state": "absent"
}
[root@ansible ~]#ansible websrvs -a 'ls -l /data/'
192.168.39.37 | changed | rc=0 >>
total 0
drwxr-xr-x 2 root root 6 dec  5 18:10 dir
-rw-r--r-- 1 root root 0 dec  5 18:06 fa.txt

192.168.39.27 | changed | rc=0 >>
total 0
drwxr-xr-x 2 root root 6 dec  5 18:10 dir
-rw-r--r-- 1 root root 0 dec  5 18:06 fa.txt

192.168.39.47 | changed | rc=0 >>
total 0
drwxr-xr-x 2 root root 6 dec  5 18:10 dir
-rw-r--r-- 1 root root 0 dec  5 18:06 fa.txt
  • 创建硬链接(不能跨设备创建)
[root@ansible ~]#ansible websrvs -m file -a 'src=/data/fa.txt path=/data/f1.txt.hardlink state=hard'
192.168.39.47 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/data/f1.txt.hardlink", 
    "gid": 0, 
    "group": "root", 
    "mode": "0644", 
    "owner": "root", 
    "size": 0, 
    "src": "/data/fa.txt", 
    "state": "hard", 
    "uid": 0
}

[root@ansible ~]#ansible websrvs -a 'ls -l /data/'
192.168.39.47 | changed | rc=0 >>
total 0
drwxr-xr-x 2 root root 6 dec  5 18:10 dir
-rw-r--r-- 2 root root 0 dec  5 18:06 f1.txt.hardlink
-rw-r--r-- 2 root root 0 dec  5 18:06 fa.txt

192.168.39.37 | changed | rc=0 >>
total 0
drwxr-xr-x 2 root root 6 dec  5 18:10 dir
-rw-r--r-- 2 root root 0 dec  5 18:06 f1.txt.hardlink
-rw-r--r-- 2 root root 0 dec  5 18:06 fa.txt

192.168.39.27 | changed | rc=0 >>
total 0
drwxr-xr-x 2 root root 6 dec  5 18:10 dir
-rw-r--r-- 2 root root 0 dec  5 18:06 f1.txt.hardlink
-rw-r--r-- 2 root root 0 dec  5 18:06 fa.txt

# 删除和软连接一样
[root@ansible ~]#ansible websrvs -m file -a ' path=/data/f1.txt.hardlink state=absent'
192.168.39.47 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "path": "/data/f1.txt.hardlink", 
    "state": "absent"
}

unarchive模块

功能:解包解压缩
实现有两种用法: 
    1、将ansible主机上的压缩包传到远程主机后解压缩至特定目录,设置copy=yes 
    2、将远程主机上的某个压缩包解压缩到指定路径下,设置copy=no    
  • 常见参数:
    • copy:默认为yes,当copy=yes,拷贝的文件是从ansible主机复制到远程主机上,如果设置为copy=no,会在远程主机上寻找src源文件
    • remote_src:和copy功能一样且互斥,yes表示在远程主机,不在ansible主机,no表示文件在ansible主机上
    • src:源路径,可以是ansible主机上的路径,也可以是远程主机上的路径,如果是远程主机上的路径,则需要设置copy=no
    • dest:远程主机上的目标路径
    • mode:设置解压缩后的文件权限
  • 先打包一个文件夹
[root@ansible ~]#tar cvf os2.txt.tar /data/os.txt 
tar: removing leading '/' from member names
/data/os.txt/
/data/os.txt/192.168.39.37/
/data/os.txt/192.168.39.37/etc/
/data/os.txt/192.168.39.37/etc/redhat-release
/data/os.txt/192.168.39.27/
/data/os.txt/192.168.39.27/etc/
/data/os.txt/192.168.39.27/etc/redhat-release
/data/os.txt/192.168.39.47/
/data/os.txt/192.168.39.47/etc/
/data/os.txt/192.168.39.47/etc/redhat-release
[root@ansible ~]#ll os.txt.tar 
-rw-r--r-- 1 root root 10240 dec  5 18:46 os.txt.tar
  • 从本机解压到远程主机
[root@ansible ~]#ansible websrvs -m unarchive -a 'src=/root/data.tar dest=/data mode=700'
192.168.39.37 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/data", 
    "extract_results": {
        "cmd": [
            "/usr/bin/gtar", 
            "--extract", 
            "-c", 
            "/data", 
            "-f", 
            "/root/.ansible/tmp/ansible-tmp-1575543401.67-225423334919338/source"
        ], 
        "err": "", 
        "out": "", 
        "rc": 0
    }, 
    "gid": 0, 
    "group": "root", 
    "handler": "tararchive", 
    "mode": "0755", 
    "owner": "root", 
    "size": 43, 
    "src": "/root/.ansible/tmp/ansible-tmp-1575543401.67-225423334919338/source", 
    "state": "directory", 
    "uid": 0
}

# 查看结果
[root@ansible ~]#ansible websrvs -a 'ls -l /data'  # 权限和目录都是对的
192.168.39.47 | changed | rc=0 >>
total 0
drwxr-xr-x 3 root root 20 dec  5 18:56 data
drwxr-xr-x 2 root root  6 dec  5 18:10 dir
-rw-r--r-- 1 root root  0 dec  5 18:06 fa.txt

192.168.39.37 | changed | rc=0 >>
total 0
drwxr-xr-x 3 root root 20 dec  5 18:56 data
drwxr-xr-x 2 root root  6 dec  5 18:10 dir
-rw-r--r-- 1 root root  0 dec  5 18:06 fa.txt

192.168.39.27 | changed | rc=0 >>
total 0
drwxr-xr-x 3 root root 20 dec  5 18:56 data
drwxr-xr-x 2 root root  6 dec  5 18:10 dir
-rw-r--r-- 1 root root  0 dec  5 18:06 fa.txt

[root@ansible ~]#ansible websrvs -a 'ls -l /data/data/os.txt'
192.168.39.37 | changed | rc=0 >>
total 0
drwx------ 3 root root 17 dec  5 17:50 192.168.39.27
drwx------ 3 root root 17 dec  5 17:50 192.168.39.37
drwx------ 3 root root 17 dec  5 17:50 192.168.39.47

192.168.39.27 | changed | rc=0 >>
total 0
drwx------ 3 root root 17 dec  5 17:50 192.168.39.27
drwx------ 3 root root 17 dec  5 17:50 192.168.39.37
drwx------ 3 root root 17 dec  5 17:50 192.168.39.47

192.168.39.47 | changed | rc=0 >>
total 0
drwx------ 3 root root 17 dec  5 17:50 192.168.39.27
drwx------ 3 root root 17 dec  5 17:50 192.168.39.37
drwx------ 3 root root 17 dec  5 17:50 192.168.39.47
  • 在ansible主机解压远程主机的包,先打包一个目录做实验
[root@centos27 ~]#tar zcvf etc.tar.gz /etc 
[root@centos27 ~]#ll etc.tar.gz 
-rw-r--r-- 1 root root 11091868 dec  5 19:03 etc.tar.gz

# 开始在ansible主机解压(下面报错的是因为另外两台主机没有这个压缩包)
[root@ansible ~]#ansible websrvs -m unarchive -a 'copy=no src=/root/etc.tar.gz dest=/data'
192.168.39.37 | failed! => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "msg": "source '/root/etc.tar.gz' does not exist"
}
192.168.39.47 | failed! => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "msg": "source '/root/etc.tar.gz' does not exist"
}
192.168.39.27 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/data", 
    "extract_results": {
        "cmd": [
            "/usr/bin/gtar", 
            "--extract", 
            "-c", 
            "/data", 
            "-z", 
            "-f", 
            "/root/etc.tar.gz"
        ], 
        "err": "", 
        "out": "", 
        "rc": 0
    }, 
    "gid": 0, 
    "group": "root", 
    "handler": "tgzarchive", 
    "mode": "0755", 
    "owner": "root", 
    "size": 17, 
    "src": "/root/etc.tar.gz", 
    "state": "directory", 
    "uid": 0
}

#在远程主机查看
[root@centos27 ~]#ll /data/
total 12
drwxr-xr-x 143 root root 8192 dec  5 15:46 etc

archive模块

功能:打包压缩
范例:

ansible websrvs -m archive -a 'path=/var/log/ dest=/data/log.tar.bz2 format=bz2 owner=wang mode=0600'

hostname模块

功能:管理主机名
  • 模块简介
[root@ansible ~]#ansible-doc -s hostname
- name: manage hostname
  hostname:
      name:                  # (required) name of the host
      use:                   # which strategy to use to update the hostname. if not set we
                               try to autodetect, but this
                               can be problematic, specially
                               with containers as they can
                               present misleading
                               information.
  • 直接使用的话所有的主机名都会改成一样的了
[root@ansible ~]#ansible websrvs -m hostname -a 'name=node1'
[root@ansible ~]#ansible websrvs -a 'hostname'
192.168.39.27 | changed | rc=0 >>
node1

192.168.39.47 | changed | rc=0 >>
node1

192.168.39.37 | changed | rc=0 >>
node1
  • 指定主机修改主机名
[root@ansible ~]#ansible 192.168.39.47 -m hostname -a 'name=node47.centos.com'
192.168.39.47 | changed => {
    "ansible_facts": {
        "ansible_domain": "centos.com", 
        "ansible_fqdn": "node47.centos.com", 
        "ansible_hostname": "node47", 
        "ansible_nodename": "node47.centos.com", 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "name": "node47.centos.com"
}
[root@ansible ~]#ansible websrvs -a 'hostname'
192.168.39.27 | changed | rc=0 >>
node1

192.168.39.47 | changed | rc=0 >>
node47.centos.com

192.168.39.37 | changed | rc=0 >>
node1

cron模块

功能:计划任务,支持时间:minute,hour,day,month,weekday
  • 模块简介
[root@ansible ~]#ansible-doc -s cron
- name: manage cron.d and crontab entries
  cron:
      backup:                # if set, create a backup of the crontab before it is modified.
                               the location of the backup is
                               returned in the `backup_file'
                               variable by this module.
      cron_file:             # if specified, uses this file instead of an individual user's
                               crontab. if this is a relative
                               path, it is interpreted with
                               respect to `/etc/cron.d'. if
                               it is absolute, it will
                               typically be `/etc/crontab'.
                               many linux distros expect (and
                               some require) the filename
                               portion to consist solely of
                               upper- and lower-case letters,
                               digits, underscores, and
                               hyphens. to use the
                               `cron_file' parameter you must
                               specify the `user' as well.
      day:                   # day of the month the job should run ( 1-31, *, */2, etc )
      disabled:              # if the job should be disabled (commented out) in the crontab.
                               only has effect if
                               `state=present'.
      env:                   # if set, manages a crontab's environment variable. new
                               variables are added on top of
                               crontab. `name' and `value'
                               parameters are the name and
                               the value of environment
                               variable.
      hour:                  # hour when the job should run ( 0-23, *, */2, etc )
      insertafter:           # used with `state=present' and `env'. if specified, the
                               environment variable will be
                               inserted after the declaration
                               of specified environment
                               variable.
      insertbefore:          # used with `state=present' and `env'. if specified, the
                               environment variable will be
                               inserted before the
                               declaration of specified
                               environment variable.
  • 创建计划任务每天晚上备份数据库 把脚本推送到远程,定期调用脚本,实现备份。
[root@ansible ~]#cat mysql_backuo.sh
#!/bin/bash
mysqldump -a -f --single-transaction --master-data=2 -q -uroot |gzip > /data/mysql_`date +%f_%t`.sql.gz

# 加个执行权限
[root@ansible ~]#chmod +x mysql_backuo.sh   

#推送脚本到远程并设置权限
[root@ansible ~]#ansible websrvs -m copy -a 'src=/root/mysql_backuo.sh dest=/data mode=755' 
192.168.39.47 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "5c0da3eb2bfa30920e8bdfb7a4196d8bc31c743f", 
    "dest": "/data/mysql_backuo.sh", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "4c11424f39a5692e47c6d520f31bf586", 
    "mode": "0755", 
    "owner": "root", 
    "size": 116, 
    "src": "/root/.ansible/tmp/ansible-tmp-1575548529.47-40893078198274/source", 
    "state": "file", 
    "uid": 0
}
192.168.39.37 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "5c0da3eb2bfa30920e8bdfb7a4196d8bc31c743f", 
    "dest": "/data/mysql_backuo.sh", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "4c11424f39a5692e47c6d520f31bf586", 
    "mode": "0755", 
    "owner": "root", 
    "size": 116, 
    "src": "/root/.ansible/tmp/ansible-tmp-1575548529.45-67802454244249/source", 
    "state": "file", 
    "uid": 0
}
192.168.39.27 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "5c0da3eb2bfa30920e8bdfb7a4196d8bc31c743f", 
    "dest": "/data/mysql_backuo.sh", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "4c11424f39a5692e47c6d520f31bf586", 
    "mode": "0755", 
    "owner": "root", 
    "size": 116, 
    "src": "/root/.ansible/tmp/ansible-tmp-1575548529.43-261659034922163/source", 
    "state": "file", 
    "uid": 0
}

[root@ansible ~]#ansible websrvs -a 'ls -l /data'
192.168.39.27 | changed | rc=0 >>
total 16
drwxr-xr-x 143 root root 8192 dec  5 15:46 etc
-rwxr-xr-x   1 root root  116 dec  5 20:22 mysql_backuo.sh

192.168.39.37 | changed | rc=0 >>
total 4
-rwxr-xr-x 1 root root 116 dec  5 20:22 mysql_backuo.sh

192.168.39.47 | changed | rc=0 >>
total 4
-rwxr-xr-x 1 root root 116 dec  5 20:22 mysql_backuo.sh
  • 创建计划任务
[root@ansible ~]#ansible 192.168.39.27 -m cron -a 'hour=2 minute=30 weekday=1-5 name="backup mysql" job=/data/mysql_backup.sh'
192.168.39.27 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "backup mysql"
    ]
}
[root@centos27 ~]#crontab -l
#ansible: backup mysql
30 2 * * 1-5 /data/mysql_backup.sh
  • 测试计划任务
# 时间调至计划任务前一点
[root@centos27 ~]#date 120402292019.40
wed dec  4 02:29:40 cst 2019
[root@centos27 ~]#date
wed dec  4 02:29:58 cst 2019
# 执行成功
[root@centos27 ~]#ll /data/
total 16
drwxr-xr-x 143 root root 8192 dec  5  2019 etc
-rwxr-xr-x   1 root root  116 dec  5  2019 mysql_backuo.sh

# 测试成功把计划任务推给所有需要备份数据库的主机
[root@ansible ~]#ansible websrvs -m cron -a 'hour=2 minute=30 weekday=1-5 name="backup mysql" job=/data/mysql_backup.sh'
192.168.39.27 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "envs": [], 
    "jobs": [
        "backup mysql"
    ]
}
192.168.39.37 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "backup mysql"
    ]
}
192.168.39.47 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "backup mysql"
    ]
}
备份数据库二进制日志必须开启
  • 创建计划任务每五分钟同步更新一次时间
[root@ansible ~]#ansible 192.168.39.37 -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1 &>/dev/null' name=synctime"
192.168.39.37 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "backup mysql", 
        "synctime"
    ]
}

[root@centos37 ~]#crontab -l
#ansible: backup mysql
30 2 * * 1-5 /data/mysql_backup.sh
#ansible: synctime
*/5 * * * * /usr/sbin/ntpdate 172.20.0.1 &>/dev/null

[root@centos37 ~]#tail -f /var/log/cron
dec  5 20:01:01 centos7 run-parts(/etc/cron.hourly)[24559]: finished 0anacron
dec  5 20:10:02 centos7 crond[25342]: (root) cmd (/usr/lib64/sa/sa1 1 1)
dec  5 20:20:01 centos7 crond[26004]: (root) cmd (/usr/lib64/sa/sa1 1 1)
dec  5 20:30:01 centos7 crond[26528]: (root) cmd (/usr/lib64/sa/sa1 1 1)
dec  5 20:31:57 centos7 crontab[26680]: (root) list (root)
dec  5 20:31:57 centos7 crontab[26681]: (root) replace (root)
dec  5 20:35:16 centos7 crontab[26850]: (root) list (root)
dec  5 20:35:16 centos7 crontab[26851]: (root) replace (root)
dec  5 20:35:42 centos7 crontab[26877]: (root) list (root)
dec  5 20:36:01 centos7 crond[6536]: (root) reload (/var/spool/cron/root)
dec  5 20:40:01 centos7 crond[26985]: (root) cmd (/usr/sbin/ntpdate 172.20.0.1 &>/dev/null)
dec  5 20:40:01 centos7 crond[26986]: (root) cmd (/usr/lib64/sa/sa1 1 1)  # 执行成功
  • 启用和禁用计划任务
disabled=no  # 启用计划任务
disabled=yes # 禁用计划任务(计划任务的列表里加注释)
[root@ansible ~]#ansible 192.168.39.37 -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1 &>/dev/null' name=synctime disabled=no"
192.168.39.37 | success => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "envs": [], 
    "jobs": [
        "backup mysql", 
        "synctime"
    ]
}
[root@ansible ~]#ansible 192.168.39.37 -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1 &>/dev/null' name=synctime disabled=yes"
192.168.39.37 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "backup mysql", 
        "synctime"
    ]
}

[root@centos37 ~]#crontab -l
#ansible: backup mysql
30 2 * * 1-5 /data/mysql_backup.sh
#ansible: synctime
#*/5 * * * * /usr/sbin/ntpdate 172.20.0.1 &>/dev/null  # 注释禁用
  • 删除计划任务
[root@ansible ~]#ansible 192.168.39.37 -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1 &>/dev/null' name=synctime state=absent"
192.168.39.37 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "backup mysql"
    ]
}

# 指定删除计划任务
[root@ansible ~]#ansible 192.168.39.37 -m cron -a "name=synctime state=absent"
[root@ansible ~]#ansible 192.168.39.37 -m cron -a "name='backup mysql' state=absent" # 如果名字中间有个空格就加单引号

yum模块(ubantu不支持)

功能:管理软件包(yum源提前配置好)可以把写好的yum源用copy传到远程主机
  • 查看已经安装的包
[root@centos7 ~]#ansible websrvs -m yum -a 'list=installed'
  • 使用yum模块安装httpd
[root@node1 ~]#systemctl status httpd   # 是没有这个服务的
unit httpd.service could not be found.

[root@ansible ~]#ansible websrvs -m yum -a 'name=httpd'
192.168.39.27 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "changes": {
        "installed": [
            "httpd"
        ]
    }, 
    "msg": "", 
    "rc": 0, 
    "results": [
...(省略)

last login: wed dec  4 02:33:24 2019 from 192.168.39.7
[root@node1 ~]#systemctl status httpd   # 安装完成之后有了
● httpd.service - the apache http server
   loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
   active: inactive (dead)
     docs: man:httpd(8)
           man:apachectl(8)
  • 卸载httpd
[root@ansible ~]#ansible websrvs -m yum -a 'name=httpd state=absent'
192.168.39.37 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "changes": {
        "removed": [
            "httpd"
        ]
    }, 
    "msg": "", 
    "rc": 0, 
    "results": [
[root@node1 ~]#rpm -qa httpd
[root@node1 ~]#systemctl status httpd
unit httpd.service could not be found.

service模块

功能:管理服务
  • 启动httpd服务
# 查看端口
[root@ansible ~]#ansible websrvs -m shell -a 'ss -ntl'
192.168.39.27 | changed | rc=0 >>
state      recv-q send-q local address:port               peer address:port              
listen     0      128          *:111                      *:*                  
listen     0      128          *:6000                     *:*                  
listen     0      5      192.168.122.1:53                       *:*                  
listen     0      128          *:22                       *:*                  
listen     0      128    127.0.0.1:631                      *:*                  
listen     0      128    127.0.0.1:6010                     *:*                  
listen     0      128         :::111                     :::*                  
listen     0      128         :::6000                    :::*                  
listen     0      128         :::22                      :::*                  
listen     0      128        ::1:631                     :::*                  
listen     0      128        ::1:6010                    :::*                  

# 启动服务并设置为开机启动
[root@ansible ~]#ansible websrvs -m service -a 'name=httpd state=started enabled=yes'
192.168.39.37 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "enabled": true, 
    "name": "httpd", 
    "state": "started", 
    "status": {
        "activeentertimestampmonotonic": "0", 
        "activeexittimestampmonotonic": "0", 
        "activestate": "inactive", 
        "after": "nss-lookup.target basic.target network.target -.mount systemd-journald.socket remote-fs.target tmp.mount system.slice", 
        "allowisolate": "no", 
        "ambientcapabilities": "0", 
        "assertresult": "no", 
        "asserttimestampmonotonic": "0", 
        "before": "shutdown.target", 
        "blockioaccounting": "no", 
        "blockioweight": "18446744073709551615", 
        "cpuaccounting": "no", 
        "cpuquotapersecusec": "infinity", 
        "cpuschedulingpolicy": "0", 
        "cpuschedulingpriority": "0", 
        "cpuschedulingresetonfork": "no", 
        "cpushares": "18446744073709551615", 
        "canisolate": "no", 
        "canreload": "yes", 
        "canstart": "yes", 
        "canstop": "yes", 
    # ....(省略)

# 查看端口
[root@ansible ~]#ansible websrvs -m shell -a 'ss -ntl'
192.168.39.27 | changed | rc=0 >>
state      recv-q send-q local address:port               peer address:port              
listen     0      128          *:111                      *:*                  
listen     0      5      192.168.122.1:53                       *:*                  
listen     0      128          *:22                       *:*                  
listen     0      128          *:4567                     *:*                  
listen     0      128    127.0.0.1:631                      *:*                  
listen     0      128    127.0.0.1:6010                     *:*                  
listen     0      128         :::111                     :::*                  
listen     0      128         :::80                      :::*                 # 监听http80端口以打开   
listen     0      128         :::22                      :::*                  
listen     0      128        ::1:631                     :::*                  
listen     0      128        ::1:6010                    :::*                
  • 更改httpd监听端口为8080,并重启服务
[root@ansible ~]#ansible websrvs -m shell -a "sed -i 's/^listen 80/listen 8080/' /etc/httpd/conf/httpd.conf"
[warning]: consider using the replace, lineinfile or template module rather
than running 'sed'.  if you need to use command because replace, lineinfile or
template 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.39.27 | changed | rc=0 >>


192.168.39.47 | changed | rc=0 >>


192.168.39.37 | changed | rc=0 >>


# 重启服务
[root@ansible ~]#ansible websrvs -m service -a 'name=httpd state=restarted'
192.168.39.37 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "name": "httpd", 
    "state": "started", 
    "status": {
        "activeentertimestamp": "fri 2019-12-06 19:26:56 cst", 
        "activeentertimestampmonotonic": "636072454", 
        "activeexittimestampmonotonic": "0", 
        "activestate": "active", 
        "after": "nss-lookup.target basic.target remote-fs.target -.mount network.target systemd-journald.socket tmp.mount system.slice", 
        "allowisolate": "no", 
        "ambientcapabilities": "0", 
        "assertresult": "yes", 
        "asserttimestamp": "fri 2019-12-06 19:26:56 cst", 
        "asserttimestampmonotonic": "635957067", 
        "before": "multi-user.target shutdown.target", 
        "blockioaccounting": "no", 
        "blockioweight": "18446744073709551615", 
        "cpuaccounting": "no", 
        "cpuquotapersecusec": "infinity", 
        "cpuschedulingpolicy": "0", 
        "cpuschedulingpriority": "0", 
        "cpuschedulingresetonfork": "no", 
        "cpushares": "1844674407370955161
.....(省略)


# 查看端口
[root@ansible ~]#ansible websrvs -m shell -a 'ss -ntl'
192.168.39.37 | changed | rc=0 >>
state      recv-q send-q local address:port               peer address:port              
listen     0      128          *:111                      *:*                  
listen     0      5      192.168.122.1:53                       *:*                  
listen     0      128          *:22                       *:*                  
listen     0      128    127.0.0.1:631                      *:*                  
listen     0      128    127.0.0.1:6010                     *:*                  
listen     0      128         :::111                     :::*                  
listen     0      128         :::8080                    :::*             # 修改成功     
listen     0      128         :::22                      :::*                  
listen     0      128        ::1:631                     :::*                  
listen     0      128        ::1:6010                    :::*                  

user模块

功能:管理用户
  • 针对服务创建用户
[root@ansible ~]#ansible websrvs -m user -a 'name=nginx comment=nginx uid=88 group=root groups="bin,daemon" shell=/sbin/nologin system=yes home=/data/nginx non_unique=yes'
192.168.39.37 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "comment": "nginx", 
    "create_home": true, 
    "group": 0, 
    "groups": "bin,daemon", 
    "home": "/data/nginx", 
    "name": "nginx", 
    "shell": "/sbin/nologin", 
    "state": "present", 
    "system": true, 
    "uid": 88
}
192.168.39.47 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "comment": "nginx", 
    "create_home": true, 
    "group": 0, 
    "groups": "bin,daemon", 
    "home": "/data/nginx", 
    "name": "nginx", 
    "shell": "/sbin/nologin", 
    "state": "present", 
    "system": true, 
    "uid": 88
}
192.168.39.27 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "comment": "nginx", 
    "create_home": true, 
    "group": 0, 
    "groups": "bin,daemon", 
    "home": "/data/nginx", 
    "name": "nginx", 
    "shell": "/sbin/nologin", 
    "state": "present", 
    "system": true, 
    "uid": 88
}
[root@ansible ~]#ansible websrvs -a 'grep nginx /etc/passwd'
192.168.39.47 | changed | rc=0 >>
nginx:x:88:0:nginx:/data/nginx:/sbin/nologin

192.168.39.37 | changed | rc=0 >>
nginx:x:88:0:nginx:/data/nginx:/sbin/nologin

192.168.39.27 | changed | rc=0 >>
nginx:x:88:0:nginx:/data/nginx:/sbin/nologin
  • 删除用户
[root@ansible ~]#ansible websrvs -m user -a 'name=nginx state=absent remove=yes'
192.168.39.27 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "force": false, 
    "name": "nginx", 
    "remove": true, 
    "state": "absent", 
    "stderr": "userdel: nginx mail spool (/var/spool/mail/nginx) not found\n", 
    "stderr_lines": [
        "userdel: nginx mail spool (/var/spool/mail/nginx) not found"
    ]
}
192.168.39.47 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "force": false, 
    "name": "nginx", 
    "remove": true, 
    "state": "absent", 
    "stderr": "userdel: nginx mail spool (/var/spool/mail/nginx) not found\n", 
    "stderr_lines": [
        "userdel: nginx mail spool (/var/spool/mail/nginx) not found"
    ]
}
192.168.39.37 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "force": false, 
    "name": "nginx", 
    "remove": true, 
    "state": "absent", 
    "stderr": "userdel: nginx mail spool (/var/spool/mail/nginx) not found\n", 
    "stderr_lines": [
        "userdel: nginx mail spool (/var/spool/mail/nginx) not found"
    ]
}
[root@ansible ~]#ansible websrvs -a 'grep nginx /etc/passwd'
192.168.39.37 | failed | rc=1 >>
non-zero return code

192.168.39.47 | failed | rc=1 >>
non-zero return code

192.168.39.27 | failed | rc=1 >>
non-zero return code
  • 创建用户不创建家目录(create_home=no)
[root@ansible ~]#ansible websrvs -m user -a 'name=nginx comment=nginx uid=88 group=root groups="bin,daemon" shell=/sbin/nologin system=yes create_home=no home=/data/nginx non_unique=yes'

group模块

功能:管理组
  • 模块简介
[root@ansible ~]#ansible-doc -s group
- name: add or remove groups
  group:
      gid:                   # optional `gid' to set for the group.
      local:                 # forces the use of "local" command alternatives
                               on platforms that
                               implement it.
                               this is useful in
                               environments that
                               use centralized
                               authentication
                               when you want to
                               manipulate the
                               local groups.
                               (e.g. it uses
                               `lgroupadd'
                               instead of
                               `groupadd'). this
                               requires that
                               these commands
                               exist on the
                               targeted host,
                               otherwise it will
                               be a fatal error.
      name:                  # (required) name of the group to manage.
      non_unique:            # this option allows to change the group id to a
                               non-unique value.
                               requires `gid'.
                               not supported on
                               macos or busybox
                               distributions.
      state:                 # whether the group should be present or not on
                               the remote host.
      system:                # if `yes', indicates that the group created is 
                               system group.
  • 创建组
[root@ansible ~]#ansible websrvs -m group -a 'name=nginx gid=88 system=yes'
192.168.39.27 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 88, 
    "name": "nginx", 
    "state": "present", 
    "system": true
}
192.168.39.47 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 88, 
    "name": "nginx", 
    "state": "present", 
    "system": true
}
192.168.39.37 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 88, 
    "name": "nginx", 
    "state": "present", 
    "system": true
}
[root@ansible ~]#ansible websrvs -a 'grep nginx /etc/passwd'
192.168.39.27 | changed | rc=0 >>
nginx:x:88:0:nginx:/data/nginx:/sbin/nologin

192.168.39.47 | changed | rc=0 >>
nginx:x:88:0:nginx:/data/nginx:/sbin/nologin

192.168.39.37 | changed | rc=0 >>
nginx:x:88:0:nginx:/data/nginx:/sbin/nologin
  • 删除组(删除组之前先删除账号)
[root@ansible ~]#ansible websrvs -m user -a 'name=nginx state=absent'
192.168.39.47 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "force": false, 
    "name": "nginx", 
    "remove": false, 
    "state": "absent"
}
192.168.39.27 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "force": false, 
    "name": "nginx", 
    "remove": false, 
    "state": "absent"
}
192.168.39.37 | changed => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "force": false, 
    "name": "nginx", 
    "remove": false, 
    "state": "absent"
}
[root@ansible ~]#ansible websrvs -a 'grep nginx /etc/passwd'  # 如果组和用户同名都会一起删掉
192.168.39.47 | failed | rc=1 >>
non-zero return code

192.168.39.27 | failed | rc=1 >>
non-zero return code

192.168.39.37 | failed | rc=1 >>
non-zero return code

# 组删除命令
[root@ansible ~]#ansible websrvs -m group -a 'name=nginx state=absent'

setup模块

功能:得到远程主机的信息
  • 模块简介
[root@ansible ~]#ansible-doc -s setup
- name: gathers facts about remote hosts
  setup:
      fact_path:             # path used for local ansible facts (`*.fact') -
                               files in this dir
                               will be run (if
                               executable) and
                               their results be
                               added to
                               `ansible_local'
                               facts if a file
                               is not executable
                               it is read. check
                               notes for windows
                               options. (from
                               2.1 on)
                               file/results
                               format can be
                               json or ini-
                               format. the
                               default
                               `fact_path' can
                               be specified in
                               `ansible.cfg' for
                               when setup is
                               automatically
                               called as part of
                               `gather_facts'.
      filter:                # if supplied, only return facts that match this
                               shell-style
                               (fnmatch)
                               wildcard.
      gather_subset:         # if supplied, restrict the additional facts
                               collected to the
                               given subset.
                               possible values:
                               `all', `min',
                               `hardware',
                               `network',
                               `virtual',
  • 查找指定主机信息
[root@ansible ~]#ansible 192.168.39.27 -m setup
192.168.39.27 | success => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "192.168.39.27", 
            "192.168.122.1"
        ], 
        "ansible_all_ipv6_addresses": [
            "fe80::20c:29ff:fe35:12eb"
        ], 
        "ansible_apparmor": {
            "status": "disabled"
        }, 
        "ansible_architecture": "x86_64", 
        "ansible_bios_date": "04/13/2018", 
        "ansible_bios_version": "6.00", 
        "ansible_cmdline": {
            "boot_image": "/vmlinuz-3.10.0-957.el7.x86_64", 
            "lang": "en_us.utf-8", 
            "quiet": true, 
            "rhgb": true, 
            "ro": true, 
            "root": "uuid=71131d8c-e6d0-4104-b270-dcb8d5ae959a"
        }, 
        "ansible_date_time": {
            "date": "2019-12-06", 
            "day": "06", 
            "epoch": "1575633554", 
            "hour": "19", 
            "iso8601": "2019-12-06t11:59:14z", 
            "iso8601_basic": "20191206t195914616794", 
            "iso8601_basic_short": "20191206t195914", 
            "iso8601_micro": "2019-12-06t11:59:14.616858z", 
            "minute": "59", 
            "month": "12", 
            "second": "14", 
            "time": "19:59:14", 
....(省略太多了)
  • 指定信息过略查找
[root@ansible ~]#ansible 192.168.39.27 -m setup -a 'filter="ansible_distribution_file_variety"'
192.168.39.27 | success => {
    "ansible_facts": {
        "ansible_distribution_file_variety": "redhat", 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}
这个模块配合playbook使用

比较有用的几个信息以后可以配合使用
ANSIBLE安装和常用模块模块使用详细教程