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

来源:https://www.cnblogs.com/www233ii/archive/2019/12/06/11997368.html
-Advertisement-
Play Games

ANSIBLE安裝和各種模塊應用功能 [toc] 安裝配置ANSIBLE 1. 下載ANSIBLE 2. 確認安裝 3. 修改主機清單文件(添加要管理的主機) 4. ANSIBLE選項使用 bash ansible doc 查看各種模塊幫助 [root@ansible ~] ansible doc ...


目錄

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

安裝配置ANSIBLE

  1. 下載ANSIBLE
[root@ansible ~]#yum install ansible
  1. 確認安裝
[root@ansible ~]#ansible --version
ansible 2.9.1
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Oct 30 2018, 23:45:53) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
  1. 修改主機清單文件(添加要管理的主機)
[root@ansible ~]#vim /etc/ansible/hosts
[websrvs]
192.168.39.27
192.168.39.37
192.168.39.47

[appsrvs]
192.168.39.57
192.168.39.77
192.168.39.8
  1. ANSIBLE選項使用
# ansible-doc 查看各種模塊幫助
[root@ansible ~]#ansible-doc ping 
> PING    (/usr/lib/python2.7/site-packages/ansible/modules/system/ping.py)

        A trivial test module, this module always returns `pong' on
        successful contact. It does not make sense in playbooks, but
        it is useful from `/usr/bin/ansible' to verify the ability to
        login and that a usable Python is configured. This is NOT ICMP
        ping, this is just a trivial test module that requires Python
        on the remote-node. For Windows targets, use the [win_ping]
        module instead. For Network targets, use the [net_ping] module
        instead.

  * This module is maintained by The Ansible Core Team
OPTIONS (= is mandatory):

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


SEE ALSO:
      * Module net_ping
           The official documentation on the net_ping module.
           https://docs.ansible.com/ansible/2.9/modules/net_ping
        _module.html
      * Module win_ping
           The official documentation on the win_ping module.
           https://docs.ansible.com/ansible/2.9/modules/win_ping
        _module.html


AUTHOR: Ansible Core Team, Michael DeHaan
        METADATA:
          status:
          - stableinterface
          supported_by: core

# -s 簡單幫助
[root@ansible ~]#ansible-doc -s ping
- name: Try to connect to host, verify a usable python and return `pong' on success
  ping:
      data:                  # Data to return for the `ping' return value. If this
                               parameter is set to
                               `crash', the module
                               will cause an
                               exception.
# -m 調用指定模塊
[root@ansible ~]#ansible websrvs -m ping   # 這樣調用是鏈接不上的
The authenticity of host '192.168.39.37 (192.168.39.37)' can't be established.
ECDSA key fingerprint is SHA256:vYJfaHhadE2ci7V5WRkZJ6iDUkQFzoZPmny56D9qKfI.
ECDSA key fingerprint is MD5:22:72:17:9a:a8:93:1a:02:d8:09:17:f4:85:fe:b3:f5.
Are you sure you want to continue connecting (yes/no)? The authenticity of host '192.168.39.47 (192.168.39.47)' can't be established.
ECDSA key fingerprint is SHA256:vYJfaHhadE2ci7V5WRkZJ6iDUkQFzoZPmny56D9qKfI.
ECDSA key fingerprint is MD5:22:72:17:9a:a8:93:1a:02:d8:09:17:f4:85:fe:b3:f5.
Are you sure you want to continue connecting (yes/no)? The authenticity of host '192.168.39.27 (192.168.39.27)' can't be established.
ECDSA key fingerprint is SHA256:vYJfaHhadE2ci7V5WRkZJ6iDUkQFzoZPmny56D9qKfI.
ECDSA key fingerprint is MD5:22:72:17:9a:a8:93:1a:02:d8:09:17:f4:85:fe:b3:f5.
Are you sure you want to continue connecting (yes/no)? yes
192.168.39.37 | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: Warning: Permanently added '192.168.39.37' (ECDSA) to the list of known hosts.\r\nPermission denied (publickey,gssapi-keyex,gssapi-with-mic,password).", 
    "unreachable": true
}
yes
192.168.39.47 | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: Warning: Permanently added '192.168.39.47' (ECDSA) to the list of known hosts.\r\nPermission denied (publickey,gssapi-keyex,gssapi-with-mic,password).", 
    "unreachable": true
}
yes
192.168.39.27 | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: Warning: Permanently added '192.168.39.27' (ECDSA) to the list of known hosts.\r\nPermission denied (publickey,gssapi-keyex,gssapi-with-mic,password).", 
    "unreachable": true
}
# -k 提示輸入密碼(密碼都一樣的話這樣鏈接可以都鏈接成功(最好都是基於key驗證))
[root@ansible ~]#ansible websrvs -k  -m ping
SSH password: 
192.168.39.27 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.39.37 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.39.47 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
  1. 做key驗證鏈接
  • 使用sshpass實現key驗證
[root@ansible ~]#yum install sshpass -y  # 使用這個工具批量實現key驗證

# 使用口令提交直接查看遠程主機信息
[root@ansible ~]#sshpass -p 123456 ssh 192.168.39.27 cat /etc/redhat-release 
CentOS Linux release 7.6.1810 (Core) 
[root@ansible ~]#sshpass -p 123456 ssh 192.168.39.37 cat /etc/redhat-release 
CentOS Linux release 7.6.1810 (Core) 
[root@ansible ~]#sshpass -p 123456 ssh 192.168.39.47 cat /etc/redhat-release 
CentOS Linux release 7.6.1810 (Core) 

[root@ansible ~]#ll ~/.ssh/  # 查看一下有生成的key的公鑰私鑰嗎?
total 4
-rw-r--r-- 1 root root 525 Dec  4 19:49 known_hosts
[root@ansible ~]#ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:Xnbwv9kYkG8B9B9q4LbUDT2m8SsJn2K5YfzuYXDiFqk root@ansible
The key's randomart image is:
+---[RSA 2048]----+
|            .    |
|           . ..  |
|          ...o.= |
|          .o+oO.o|
|        S oX=*.o.|
|       . o*.@+o..|
|        .E @ B=. |
|          + *.o* |
|           .o++ .|
+----[SHA256]-----+

[root@ansible ~]#ll ~/.ssh/   # 查看一下公鑰私鑰對生成成功
total 12
-rw------- 1 root root 1675 Dec  4 20:07 id_rsa
-rw-r--r-- 1 root root  394 Dec  4 20:07 id_rsa.pub
-rw-r--r-- 1 root root  525 Dec  4 19:49 known_hosts
  • 使用for迴圈來進行批量部署key驗證
# 因為之前連過三台機子所以連接過的配置成功了
[root@ansible ~]#NET=192.168.39;for i in 7 27 37 47 57 77 8 ;do sshpass -p 123456 ssh-copy-id $NET.$i ;done
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys

Number of key(s) added: 1

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

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys

Number of key(s) added: 1

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

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys

Number of key(s) added: 1

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

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
  • 修改配置文件來進行key驗證
# 在第一次遠程連接的時候都會有一個提示就是輸入yes/no(這個選項會影響第一次連接的伺服器配置key所以在配置文件里修改一個選項來繞過這步)
[root@ansible ~]#vim /etc/ssh/ssh_config 

# Host *
#   ForwardAgent no
#   ForwardX11 no
#   RhostsRSAAuthentication no
#   RSAAuthentication yes
#   PasswordAuthentication yes
#   HostbasedAuthentication no
#   GSSAPIAuthentication no
#   GSSAPIDelegateCredentials no
#   GSSAPIKeyExchange no
#   GSSAPITrustDNS no
#   BatchMode no
#   CheckHostIP yes
#   AddressFamily any
#   ConnectTimeout 0
 StrictHostKeyChecking no  # 這一項本來是註釋掉的,去掉註釋在後面改為no就可以了
#   IdentityFile ~/.ssh/identity
#   IdentityFile ~/.ssh/id_rsa
#   IdentityFile ~/.ssh/id_dsa
#   IdentityFile ~/.ssh/id_ecdsa
#   IdentityFile ~/.ssh/id_ed25519
#   Port 22
  • 再次進行配置(之前配置好的不會在配置)
[root@ansible ~]#NET=192.168.39;for i in 7 27 37 47 57 77 8 ;do sshpass -p 123456 ssh-copy-id $NET.$i ;done
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '192.168.39.7'"  # 本機也要發一個key驗證
and check to make sure that only the key(s) you wanted were added.

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed

/usr/bin/ssh-copy-id: WARNING: All keys were skipped because they already exist on the remote system.
        (if you think this is a mistake, you may want to use -f option)

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed

/usr/bin/ssh-copy-id: WARNING: All keys were skipped because they already exist on the remote system.
        (if you think this is a mistake, you may want to use -f option)

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed

/usr/bin/ssh-copy-id: WARNING: All keys were skipped because they already exist on the remote system.
        (if you think this is a mistake, you may want to use -f option)

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys

Number of key(s) added: 1

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

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys

Number of key(s) added: 1

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

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys

Number of key(s) added: 1

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

Last login: Thu Dec  5 03:22:37 2019 from 192.168.39.1
[root@centos8 ~]#exit
logout
Connection to 192.168.39.8 closed.

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

ANSIBLE使用

  1. 查看ansible管理所有主機
[root@ansible ~]#ansible all --list-host
  hosts (6):
    192.168.39.57
    192.168.39.77
    192.168.39.8
    192.168.39.27
    192.168.39.37
    192.168.39.47
  1. 使用ansible訪問其他用戶
[root@ansible ~]#ansible websrvs -u yang -m ping  # 因為yang這個賬戶沒有做過key驗證所以無法訪問
192.168.39.27 | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).", 
    "unreachable": true
}
192.168.39.47 | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).", 
    "unreachable": true
}
192.168.39.37 | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).", 
    "unreachable": true
}

# 想訪問還是加-k來提示輸入密碼訪問
[root@ansible ~]#ansible websrvs -u yang -k -m ping
SSH password: 
192.168.39.37 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.39.47 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.39.27 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
  1. 測試所有主機連接
[root@ansible ~]#ansible all -m ping
192.168.39.57 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
.....(省略)
192.168.39.47 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

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

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

# 加-v顯示詳細信息加的v越多顯示越詳細最多三個
[root@ansible ~]#ansible websrvs -m ping -v
Using /etc/ansible/ansible.cfg as config file
192.168.39.37 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.39.47 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.39.27 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
[root@ansible ~]#ansible websrvs -m ping -vv
ansible 2.9.1
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Oct 30 2018, 23:45:53) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
Using /etc/ansible/ansible.cfg as config file
META: ran handlers
192.168.39.47 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.39.37 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.39.27 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
META: ran handlers
META: ran handlers
  1. ansible顏色顯示定義
    在這裡插入圖片描述
  • 修改顏色定義文件
[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=/etc/selinux/config dest=/data"
192.168.39.37 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "086428e2a122b0fec18cd17858f334ca65116f69", 
    "dest": "/data/config", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "8a7e44af619a4538054b458dfa31941d", 
    "mode": "0644", 
    "owner": "root", 
    "size": 542, 
    "src": "/root/.ansible/tmp/ansible-tmp-1575536783.04-173190751129047/source", 
    "state": "file", 
    "uid": 0
}
192.168.39.47 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "086428e2a122b0fec18cd17858f334ca65116f69", 
    "dest": "/data/config", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "8a7e44af619a4538054b458dfa31941d", 
    "mode": "0644", 
    "owner": "root", 
    "size": 542, 
    "src": "/root/.ansible/tmp/ansible-tmp-1575536783.03-90703232115071/source", 
    "state": "file", 
    "uid": 0
}
192.168.39.27 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "086428e2a122b0fec18cd17858f334ca65116f69", 
    "dest": "/data/config", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "8a7e44af619a4538054b458dfa31941d", 
    "mode": "0644", 
    "owner": "root", 
    "size": 542, 
    "src": "/root/.ansible/tmp/ansible-tmp-1575536783.02-59216625108124/source", 
    "state": "file", 
    "uid": 0
}

# 查看結果

[root@ansible ~]#ansible websrvs -a 'll /data'  # 不要使用別名  ll類似於別名識別不了
192.168.39.37 | FAILED | rc=127 >>
/bin/sh: ll: command not foundnon-zero return code

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

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

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

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

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

# 查看結果

[root@ansible ~]#ansible websrvs -a 'ls -l /data'
192.168.39.47 | CHANGED | rc=0 >>
total 628
-rw-r--r-- 1 root root     23 Dec  5 17:12 config  # 這個是拷貝過去的文件
-rw-r--r-- 1 root root    542 Dec  5 17:06 config.13745.2019-12-05@17:12:29~  # 這是備份的,這個文件名每個伺服器是不一樣的
-rw-r--r-- 1 root root      0 Dec  5 15:58 host.txt
-rw-r--r-- 1 root root 634270 Dec  4 21:27 log.tar.bz2

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

192.168.39.37 | CHANGED | rc=0 >>
total 644
-rw-r--r-- 1 root root     23 Dec  5 17:12 config
-rw-r--r-- 1 root root    542 Dec  5 17:06 config.13707.2019-12-05@17:12:29~
-rw-r--r-- 1 root root      0 Dec  5 15:58 host.txt
-rw-r--r-- 1 root root 647441 Dec  4 21:27 log.tar.bz2
-rw-r--r-- 1 root root      0 Dec  5 14:54 test.txt
  • 拷貝目錄到目標主機
# 保證data下有文件做測試使用
[root@ansible ~]#touch /data/test.txt
[root@ansible ~]#ll /data/
total 0
-rw-r--r-- 1 root root 0 Dec  5 17:23 test.txt

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


 查看結果

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

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

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

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

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

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

# 查看結果

[root@ansible ~]#ansible websrvs -a 'ls -l /backup/'  # 只拷貝了文件目錄沒有拷貝
192.168.39.47 | CHANGED | rc=0 >>
total 0
-rw-r--r-- 1 root root 0 Dec  5 17:27 test.txt

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

192.168.39.27 | CHANGED | rc=0 >>
total 0
-rw-r--r-- 1 root root 0 Dec  5 17:27 test.txt
也可以配置遠程主機yum源使用,src是源  dest是目標

Fetch模塊

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

# 查看結果

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

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

6 directories, 3 files

File模塊

功能:管理文件和文件的屬性
  state=absent 代表刪除的意思
  state=touch  創建空文件
  state=directory  創建空文件夾
  state=link  創建軟連接
  state=hard  創建硬鏈接
  • 更改遠程主機文件屬性沒有這個文件不執行。
[root@ansible ~]#ansible websrvs -m file -a 'path=/data/test.txt owner=yang group=root mode=600'
192.168.39.27 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0600", 
    "owner": "yang", 
    "path": "/data/test.txt", 
    "size": 0, 
    "state": "file", 
    "uid": 1000
}
192.168.39.47 | FAILED! => {   # 不執行但是會報錯
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "msg": "file (/data/test.txt) is absent, cannot continue", 
    "path": "/data/test.txt"
}
192.168.39.37 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0600", 
    "owner": "yang", 
    "path": "/data/test.txt", 
    "size": 0, 
    "state": "file", 
    "uid": 1000
}

# 查看結果

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

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

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

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

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

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

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

# 還有一種情況,當這個文件夾是掛載點的時候不能直接刪除目錄只會清空目錄下的數據。
[root@ansible ~]#ansible websrvs -m file -a 'path=/data/ state=absent'
192.168.39.37 | FAILED! => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "msg": "rmtree failed: [Errno 16] Device or resource busy: '/data/'"
}
192.168.39.27 | FAILED! => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "msg": "rmtree failed: [Errno 16] Device or resource busy: '/data/'"
}
192.168.39.47 | FAILED! => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "msg": "rmtree failed: [Errno 16] Device or resource busy: '/data/'"
}

[root@ansible ~]#a

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 概述 Spire.Cloud.Word提供了watermarksApi介面可用於添加水印,包括添加文本水印(SetTextWatermark)、圖片水印(SetImageWatermark),本文將對此做詳細介紹。 關於Spire.Cloud Spire.Cloud是雲端 Office 文檔處理軟體 ...
  • 它可以將字串內的字元替換為別的字元,可以嵌套使用,如下: 需要註意的是,它可以把字元替換為空,但不可以替換空字元,當不確定字元串是否為空時,可以進行以下判斷,再替換: 示例的完整代碼: string aa="d"; if (aa=="d") { Console.WriteLine(aa.Replac ...
  • 我有2個方法 代碼相同 都是執行上傳文件IO操作 一個同步 一個非同步 接著我用POSTMAN 分別用200個線程 去同時測試2個介面 結果很意外 2個介面 同時執行完成的速度 非同步更慢 之前經常看別人博主說 儘量用非同步來優化自己的代碼 但是經過自己測試後 發現使用非同步的效率結果更差,後面仔細想了下 ...
  • 一、描述問題 當托管代碼調用非托管代碼的時候,經常會出現如下報錯:“嘗試讀取或寫入受保護的記憶體。這通常指示其他記憶體已損壞”。 二、原因分析 由於非托管代碼的記憶體指針的回收是由非托管代碼自身手動完成的,而不是像托管代碼一樣有統一的垃圾回收機制,比如.NET的GC。 所以對於托管代碼的調用方來說無法控制 ...
  • 一丶什麼是Win32 API? 簡單來說,就是微軟為了保護操作系統的安全性和穩定性,不允許運行在用戶層的進程隨意操控系統內核,而是必須按照一定方式。我們用戶層要與系統內核層交互(比如對記憶體、進程操作),只能通過調用Windows內核層提供的介面函數,也就是Win32API來操控。這些API以DLL( ...
  • 在嵌入式領域,常用到開發板和宿主機的文件傳輸,tftp傳輸會很方便 ...
  • 原文鏈接:https://blog.csdn.net/u014585564/article/details/68063269 最近項目中出現了一個問題,伺服器端程式會突然崩潰退出,我們採取了coredump技術以找到崩潰原因,即確定進程退出時正在執行的函數是哪個,其狀態如何。 如果系統開啟了core ...
  • 原文鏈接:https://blog.csdn.net/jctian000/article/details/79695006 當我們配置好自動生成core文件的環境後,若不想寫導致崩潰的程式驗證,那要怎麼快速產生core呢?先看下產生core文件的條件:當程式接收到以下UNIX信號會產生core文件: ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...