主頁 > 作業系統 > ANSIBLE安裝和常用模塊模塊使用詳細教程

ANSIBLE安裝和常用模塊模塊使用詳細教程

2020-10-02 15:55:07 作業系統

ANSIBLE安裝和各種模塊應用功能

目錄
  • ANSIBLE安裝和各種模塊應用功能
    • 安裝配置ANSIBLE
    • ANSIBLE使用
    • ansible-galaxy工具
    • ansible-pull工具
    • ansible-playbook
    • ansible常用模塊
      • Command 模塊
      • shell模塊
      • script模塊
      • copy模塊
      • Fetch模塊
      • File模塊
      • unarchive模塊
      • Archive模塊
      • Hostname模塊
      • Cron模塊
      • Yum模塊(ubantu不支持)
      • Service模塊
      • User模塊
      • Group模塊
      • setup模塊

安裝配置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顏色顯示定義
    在這里插入圖片描述
  • 修改顏色定義檔案
[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

  • 重定向也不支持
    在這里插入圖片描述

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=https://www.cnblogs.com/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=https://www.cnblogs.com/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=https://www.cnblogs.com/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=https://www.cnblogs.com/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=https://www.cnblogs.com/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=https://www.cnblogs.com/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=https://www.cnblogs.com/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=https://www.cnblogs.com/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=https://www.cnblogs.com/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=https://www.cnblogs.com/www233ii/p/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=https://www.cnblogs.com/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使用

比較有用的幾個資訊以后可以配合使用
在這里插入圖片描述

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/148718.html

標籤:Linux

上一篇:求助 藍牙問題

下一篇:Linux下快速手動產生core檔案

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • CA和證書

    1、在 CentOS7 中使用 gpg 創建 RSA 非對稱密鑰對 gpg --gen-key #Centos上生成公鑰/密鑰對(存放在家目錄.gnupg/) 2、將 CentOS7 匯出的公鑰,拷貝到 CentOS8 中,在 CentOS8 中使用 CentOS7 的公鑰加密一個檔案 gpg -a ......

    uj5u.com 2020-09-10 00:09:53 more
  • Kubernetes K8S之資源控制器Job和CronJob詳解

    Kubernetes的資源控制器Job和CronJob詳解與示例 ......

    uj5u.com 2020-09-10 00:10:45 more
  • VMware下安裝CentOS

    VMware下安裝CentOS 一、軟硬體準備 1 Centos鏡像準備 1.1 CentOS鏡像下載地址 下載地址 1.2 CentOS鏡像下載程序 點擊下載地址進入如下圖的網站,選擇需要下載的版本,這里選擇的是Centos8,點擊如圖所示。 決定選擇Centos8后,選擇想要的鏡像源進行下載,此 ......

    uj5u.com 2020-09-10 00:12:10 more
  • 如何使用Grep命令查找多個字串

    如何使用Grep 命令查找多個字串 大家好,我是良許! 今天向大家介紹一個非常有用的技巧,那就是使用 grep 命令查找多個字串。 簡單介紹一下,grep 命令可以理解為是一個功能強大的命令列工具,可以用它在一個或多個輸入檔案中搜索與正則運算式相匹配的文本,然后再將每個匹配的文本用標準輸出的格式 ......

    uj5u.com 2020-09-10 00:12:28 more
  • git配置http代理

    git配置http代理 經常遇到克隆 github 慢的問題,這里記錄一下幾種配置 git 代理的方法,解決 clone github 過慢。 目錄 git配置代理 git單獨配置github代理 git配置全域代理 配置終端環境變數 git配置代理 主要使用 git config 命令 git單獨 ......

    uj5u.com 2020-09-10 00:12:33 more
  • Linux npm install 裝包時提示Error EACCES permission denied解

    npm install 裝包時提示Error EACCES permission denied解決辦法 ......

    uj5u.com 2020-09-10 00:12:53 more
  • Centos 7下安裝nginx,使用yum install nginx,提示沒有可用的軟體包

    Centos 7下安裝nginx,使用yum install nginx,提示沒有可用的軟體包。 18 (flaskApi) [root@67 flaskDemo]# yum -y install nginx 19 已加載插件:fastestmirror, langpacks 20 Loading ......

    uj5u.com 2020-09-10 00:13:13 more
  • Linux查看服務器暴力破解ssh IP

    在公網的服務器上經常遇到別人爆破你服務器的22埠,用來挖礦或者干其他嘿嘿嘿的事情~ 這種情況下正確的做法是: 修改默認ssh的22埠 使用設定密鑰登錄或者白名單ip登錄 建議服務器密碼為復雜密碼 創建普通用戶登錄服務器(root權限過大) 建立堡壘機,實作統一管理服務器 統計爆破IP [root ......

    uj5u.com 2020-09-10 00:13:17 more
  • CentOS 7系統常見快捷鍵操作方式

    Linux系統中一些常見的快捷方式,可有效提高操作效率,在某些時刻也能避免操作失誤帶來的問題。 ......

    uj5u.com 2020-09-10 00:13:31 more
  • CentOS 7作業系統目錄結構介紹

    作業系統存在著大量的資料檔案資訊,相應檔案資訊會存在于系統相應目錄中,為了更好的管理資料資訊,會將系統進行一些目錄規劃,不同目錄存放不同的資源。 ......

    uj5u.com 2020-09-10 00:13:35 more
最新发布
  • vim的常用命令

    Vim的6種基本模式 1. 普通模式在普通模式中,用的編輯器命令,比如移動游標,洗掉文本等等。這也是Vim啟動后的默認模式。這正好和許多新用戶期待的操作方式相反(大多數編輯器默認模式為插入模式)。 2. 插入模式在這個模式中,大多數按鍵都會向文本緩沖中插入文本。大多數新用戶希望文本編輯器編輯程序中一 ......

    uj5u.com 2023-04-20 08:43:21 more
  • vim的常用命令

    Vim的6種基本模式 1. 普通模式在普通模式中,用的編輯器命令,比如移動游標,洗掉文本等等。這也是Vim啟動后的默認模式。這正好和許多新用戶期待的操作方式相反(大多數編輯器默認模式為插入模式)。 2. 插入模式在這個模式中,大多數按鍵都會向文本緩沖中插入文本。大多數新用戶希望文本編輯器編輯程序中一 ......

    uj5u.com 2023-04-20 08:42:36 more
  • docker學習

    ###Docker概述 真實專案部署環境可能非常復雜,傳統發布專案一個只需要一個jar包,運行環境需要單獨部署。而通過Docker可將jar包和相關環境(如jdk,redis,Hadoop...)等打包到docker鏡像里,將鏡像發布到Docker倉庫,部署時下載發布的鏡像,直接運行發布的鏡像即可。 ......

    uj5u.com 2023-04-19 09:26:53 more
  • 設定Windows主機的瀏覽器為wls2的默認瀏覽器

    這里以Chrome為例。 1. 準備作業 wsl是可以使用Windows主機上安裝的exe程式,出于安全考慮,默認情況下改功能是無法使用。要使用的話,終端需要以管理員權限啟動。 我這里以Windows Terminal為例,介紹如何默認使用管理員權限打開終端,具體操作如下圖所示: 2. 操作 wsl ......

    uj5u.com 2023-04-19 09:25:49 more
  • docker學習

    ###Docker概述 真實專案部署環境可能非常復雜,傳統發布專案一個只需要一個jar包,運行環境需要單獨部署。而通過Docker可將jar包和相關環境(如jdk,redis,Hadoop...)等打包到docker鏡像里,將鏡像發布到Docker倉庫,部署時下載發布的鏡像,直接運行發布的鏡像即可。 ......

    uj5u.com 2023-04-19 09:19:04 more
  • Linux學習筆記

    IP地址和主機名 IP地址 ifconfig可以用來查詢本機的IP地址,如果不能使用,可以通過install net-tools安裝。 Centos系統下ens33表示主網卡;inet后表示IP地址;lo表示本地回環網卡; 127.0.0.1表示代指本機;0.0.0.0可以用于代指本機,同時在放行設 ......

    uj5u.com 2023-04-18 06:52:01 more
  • 解決linux系統的kdump服務無法啟動的問題

    問題:專案麒麟系統服務器的kdump服務無法啟動,沒有相關日志無法定位問題。 1、查看服務狀態是關閉的,重啟系統也無法啟動 systemctl status kdump 2、修改grub引數,修改“crashkernel”為“512M(有的機器數值太大太小都會導致報錯,建議從128M開始試,或者加個 ......

    uj5u.com 2023-04-12 09:59:50 more
  • 解決linux系統的kdump服務無法啟動的問題

    問題:專案麒麟系統服務器的kdump服務無法啟動,沒有相關日志無法定位問題。 1、查看服務狀態是關閉的,重啟系統也無法啟動 systemctl status kdump 2、修改grub引數,修改“crashkernel”為“512M(有的機器數值太大太小都會導致報錯,建議從128M開始試,或者加個 ......

    uj5u.com 2023-04-12 09:59:01 more
  • 你是不是暴露了?

    作者:袁首京 原創文章,轉載時請保留此宣告,并給出原文連接。 如果您是計算機相關從業人員,那么應該經歷不止一次網路安全專項檢查了,你肯定是收到過資訊系統技術檢測報告,要求你加強風險監測,確保你提供的系統服務堅實可靠了。 沒檢測到問題還好,檢測到問題的話,有些處理起來還是挺麻煩的,尤其是線上正在運行的 ......

    uj5u.com 2023-04-05 16:52:56 more
  • 細節拉滿,80 張圖帶你一步一步推演 slab 記憶體池的設計與實作

    1. 前文回顧 在之前的幾篇記憶體管理系列文章中,筆者帶大家從宏觀角度完整地梳理了一遍 Linux 記憶體分配的整個鏈路,本文的主題依然是記憶體分配,這一次我們會從微觀的角度來探秘一下 Linux 內核中用于零散小記憶體塊分配的記憶體池 —— slab 分配器。 在本小節中,筆者還是按照以往的風格先帶大家簡單 ......

    uj5u.com 2023-04-05 16:44:11 more