Ansible之系列命令詳解


  ansible系列命令有:ansible、ansible-doc、ansible-playbook、ansible-vault、ansible-console、ansible-galaxy、ansible-pull,這些命令每個命令都有它獨特的作用和用法,接下來我們一一來了解它的用法。

1、ansible-doc:這個命令主要作用是顯示模塊的幫助信息,有點類似Linux里的man命令。

命令用法:

ansible-doc [options] [module...]

 常用選項:

  -a:顯示所有模塊的文檔

[root@localhost ~]# ansible-doc -a ping 
> A10_SERVER    (/usr/lib/python2.7/site-packages/ansible/modules/network/a10/a10_server.py)

        Manage SLB (Server Load Balancer) server objects on A10 Networks devices via aXAPIv2.

OPTIONS (= is mandatory):

= host
        Hostname or IP of the A10 Networks device.
        [Default: None]

- partition
        set active-partition
        [Default: None]
        version_added: 2.3

= password
        Password for the `username' account.
        (Aliases: pass, pwd)[Default: None]

- server_ip
        The SLB server IPv4 address.
        (Aliases: ip, address)[Default: None]

:

  說明:-a選項列出了ping模塊的所有用法,以上只顯示了部分。

  -l,--list列出全部可以模塊

[root@localhost ~]# ansible-doc -l
a10_server                                Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' server object.  
a10_server_axapi3                         Manage A10 Networks AX/SoftAX/Thunder/vThunder devices                  
a10_service_group                         Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' service groups. 
a10_virtual_server                        Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' virtual servers.
accelerate                                Enable accelerated mode on remote node                                  
aci_aep                                   Manage attachable Access Entity Profile (AEP) on Cisco ACI fabrics (infr...
aci_ap                                    Manage top level Application Profile (AP) objects on Cisco ACI fabrics (...
aci_bd                                    Manage Bridge Domains (BD) on Cisco ACI Fabrics (fv:BD)                 
aci_bd_subnet                             Manage Subnets on Cisco ACI fabrics (fv:Subnet)                         
aci_bd_to_l3out                           Bind Bridge Domain to L3 Out on Cisco ACI fabrics (fv:RsBDToOut)        
aci_config_rollback                       Provides rollback and rollback preview functionality for Cisco ACI fabri...
aci_config_snapshot                       Manage Config Snapshots on Cisco ACI fabrics (config:Snapshot, config:Ex...
aci_contract                              Manage contract resources on Cisco ACI fabrics (vz:BrCP)                
aci_contract_subject                      Manage initial Contract Subjects on Cisco ACI fabrics (vz:Subj)         
aci_contract_subject_to_filter            Bind Contract Subjects to Filters on Cisco ACI fabrics (vz:RsSubjFiltAtt...
aci_epg                                   Manage End Point Groups (EPG) on Cisco ACI fabrics (fv:AEPg)            
aci_epg_monitoring_policy                 Manage monitoring policies on Cisco ACI fabrics (mon:EPGPol)            
aci_epg_to_contract                       Bind EPGs to Contracts on Cisco ACI fabrics (fv:RsCons and fv:RsProv)   
aci_epg_to_domain                         Bind EPGs to Domains on Cisco ACI fabrics (fv:RsDomAtt)                 
aci_filter                                Manages top level filter objects on Cisco ACI fabrics (vz:Filter)       
aci_filter_entry                          Manage filter entries on Cisco ACI fabrics (vz:Entry)                   
aci_intf_policy_fc                        Manage Fibre Channel interface policies on Cisco ACI fabrics (fc:IfPol) 
aci_intf_policy_l2                        Manage Layer 2 interface policies on Cisco ACI fabrics (l2:IfPol)       
:

  說明:-l選項列出了所有可用模塊,並簡要說明了模塊主要功能,以上內容只顯示了部分

  -s,--snippet顯示指定模塊的playbook片段

[root@localhost ~]# 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.
[root@localhost ~]# 

  說明:-s這個選項是我們常用的選項,它主要列出模塊的常用參數的使用和參數的作用。

2、ansible:這個命令就是ansible的主程序,我們經常用這個命令來管理主機,它可以調用各種模塊對遠端主機進行配置管理、應用部署、任務執行等功能。前文我們介紹了ansible有兩種方式管理主機,一種是ad-hoc,也就是在命令行用ansible這個命令來管理主機,還有一種方式就是用ansible-playbook。

命令用法:

 ansible <host-pattern> [-m module_name] [-a args]

  說明:它的用法還是很好理解,我們都知道ansible的強大之處是它有很多模塊,ansible命令管理主機就是利用這些模塊去管理主機的,以上用法就是說 用ansible管理哪些主機(我們需要指定主機或主機組),用什么模塊(表現形式 -m指定模塊名稱,若不指定則表示使用默認模塊),讓模塊干什么事(它的表現形式就是-a 指定給模塊傳遞相應的參數)

常用選項:

  --version:顯示版本

[root@localhost ~]# ansible --version
ansible 2.4.2.0
  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, Aug  4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]
[root@localhost ~]#

  -m  module:指定模塊,才安裝好ansible軟件默認的模塊是command

  -v :顯示簡要的執行過程,-vv顯示較為詳細的過程,-vvv顯示更為詳細的執行過程

  --list-hostss:顯示主機列表,可以簡寫 --list

[root@localhost ~]# ansible all --list
  hosts (3):
    192.168.0.99
    192.168.0.218
    192.168.0.128
[root@localhost ~]# ansible websers --list
  hosts (1):
    192.168.0.99
[root@localhost ~]# ansible appsers --list
  hosts (2):
    192.168.0.218
    192.168.0.128
[root@localhost ~]# 

  說明:all 表示匹配主機列表中的所有主機

  -k,--ask-pass:指定輸入ssh連接密碼,默認ansible是基於ssh key驗證的(k是小寫的)

[root@localhost ~]# ansible websers -m ping -k
SSH password: 
192.168.0.99 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
[root@localhost ~]# 

  說明:這個選項一般用於我們主機列表中沒有做ssh key驗證的主機,通常不建議使用。

  -K,--ask-become-pass提示輸入sudo時的口令(k是大寫的)

[root@localhost ~]# ansible websers  -u 'qiuhom' -k -s -K  -a " getent shadow qiuhom"     
[DEPRECATION WARNING]: The sudo command line option has been deprecated in favor of the "become" command line 
arguments. This feature will be removed in version 2.6. Deprecation warnings can be disabled by setting 
deprecation_warnings=False in ansible.cfg.
SSH password: 
SUDO password[defaults to SSH password]: 
192.168.0.99 | SUCCESS | rc=0 >>
qiuhom:$6$5mlfZaKT$YmDjmEnKPoC.xASTVA5JqUrTiIkuXOe1yDm9PCql89e4lGKUS.W1515phi1OgD1W7Zu6Lm9srTBHi9QAigWpz/:18068:0:99999:7:::

[root@localhost ~]# 

  說明:-u是指定遠程以那個用戶執行,-s 表示使用sudo運行后面的操作,-k(小寫)指定用ssh口令驗證,-K(大寫)提示輸入sudo時的口令,-a 指定給模塊傳遞的參數,上面示例沒有寫-m指定的模塊就是用的默認模塊command,當然這個默認模塊我們可以在/etc/ansible/ansible.cfg里指定

  -C,--check 檢查,並不執行,這個參數主要用於檢查playbook是否寫的正確。

  -T,--timeout指定執行命令的超時時間,默認是10S

  -u,指定以那個用戶遠程執行命令,指定的用戶是遠端服務器上存在的。並非本地管理端的用戶

  -b,--become代替舊版的sudo切換

  --become-user-USERNAME指定sudo的runas用戶,默認是root

了解了ansible的基本選項說明,接下來我們來說說匹配主機列表

  1、all:表示匹配所有定義在主機清單中的主機

[root@localhost ~]# ansible all -m ping 
192.168.0.99 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.0.128 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.0.218 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
[root@localhost ~]# ansible all --list
  hosts (3):
    192.168.0.99
    192.168.0.218
    192.168.0.128
[root@localhost ~]# 

  2、“*”:通配符,也可表示匹配所有主機清單中的主機,它的用法和Linux里的通配符類似。

[root@localhost ~]# ansible * -m ping 
192.168.0.128 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.0.218 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.0.99 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
[root@localhost ~]# ansible 192.168.0.1* -m ping 
192.168.0.128 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
[root@localhost ~]# ansible web* -m ping     
192.168.0.99 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
[root@localhost ~]# 

  3、或關系

[root@localhost ~]# tail -6 /etc/ansible/hosts
[websers]
192.168.0.99:41319
192.168.0.218
[appsers]
192.168.0.218
192.168.0.128
[root@localhost ~]# ansible "websers:appsers" --list
  hosts (3):
    192.168.0.99
    192.168.0.218
    192.168.0.128
[root@localhost ~]# ansible "192.168.0.1*:192.168.0.2*" --list
  hosts (2):
    192.168.0.128
    192.168.0.218
[root@localhost ~]# 

  4、邏輯與

[root@localhost ~]# ansible "websers:&appsers" --list 
  hosts (1):
    192.168.0.218
[root@localhost ~]# 

  說明:以上命令的意思是列出在websers組中,並且又在appsers組的主機

  5、邏輯非

[root@localhost ~]# ansible "websers:!appsers" --list 
-bash: !appsers": event not found
[root@localhost ~]# ansible 'websers:!appsers' --list
  hosts (1):
    192.168.0.99
[root@localhost ~]# 

  說明:這里需要注意一點的是邏輯非要用單引號,以上命令表達的意思是列出在websers組中,但是不在appsers組中的主機

  6、綜合邏輯

[root@localhost ~]# tail -13 /etc/ansible/hosts  
[websers]
192.168.0.99:41319
192.168.0.218
[appsers]
192.168.0.218
192.168.0.128
[dbsers]
192.168.0.208
192.168.0.199
[ftpsers]
192.168.0.123
192.168.0.233

[root@localhost ~]#  ansible 'dbsers:websers:&appsers:!ftpsers' --list  
  hosts (1):
    192.168.0.218
[root@localhost ~]# 

  說明:以上命令有邏輯或邏輯與邏輯非,在這種綜合的匹配模式中我們要遵循這樣一個優先級順序來匹配,首先邏輯非的優先級最好,其次是邏輯與,優先級最低是邏輯或,以上命令表示匹配dbsers和websers兩個組中的主機,在appsers中檔不在ftpsers中的主機

  7、正則表達式

[root@localhost ~]# ansible "~(web|db).*" --list
  hosts (4):
    192.168.0.99
    192.168.0.218
    192.168.0.208
    192.168.0.199
[root@localhost ~]# 

  說明:以上命令表示匹配web開頭的組或者db開頭的組中的主機,~表示使用正則匹配

了解了ansible的主機列表匹配,接着我們再說下ansible命令的執行過程,我們在使用ansible執行命令的時候可以用-vvv選項來顯示更為詳細的執行過程

[root@localhost ~]# ansible "websers:&appsers" -m shell -a "getent passwd root" -vvv
ansible 2.4.2.0
  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, Aug  4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]
Using /etc/ansible/ansible.cfg as config file
Parsed /etc/ansible/hosts inventory source with ini plugin
META: ran handlers
Using module file /usr/lib/python2.7/site-packages/ansible/modules/commands/command.py
<192.168.0.218> ESTABLISH SSH CONNECTION FOR USER: None
<192.168.0.218> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/root/.ansible/cp/82e2c5d794 192.168.0.218 '/bin/sh -c '"'"'echo ~ && sleep 0'"'"''
<192.168.0.218> (0, '/root\n', '')
<192.168.0.218> ESTABLISH SSH CONNECTION FOR USER: None
<192.168.0.218> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/root/.ansible/cp/82e2c5d794 192.168.0.218 '/bin/sh -c '"'"'( umask 77 && mkdir -p "` echo /root/.ansible/tmp/ansible-tmp-1573399527.3-188437527440745 `" && echo ansible-tmp-1573399527.3-188437527440745="` echo /root/.ansible/tmp/ansible-tmp-1573399527.3-188437527440745 `" ) && sleep 0'"'"''
<192.168.0.218> (0, 'ansible-tmp-1573399527.3-188437527440745=/root/.ansible/tmp/ansible-tmp-1573399527.3-188437527440745\n', '')
<192.168.0.218> PUT /tmp/tmpPczCAu TO /root/.ansible/tmp/ansible-tmp-1573399527.3-188437527440745/command.py
<192.168.0.218> SSH: EXEC sftp -b - -C -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/root/.ansible/cp/82e2c5d794 '[192.168.0.218]'
<192.168.0.218> (0, 'sftp> put /tmp/tmpPczCAu /root/.ansible/tmp/ansible-tmp-1573399527.3-188437527440745/command.py\n', '')
<192.168.0.218> ESTABLISH SSH CONNECTION FOR USER: None
<192.168.0.218> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/root/.ansible/cp/82e2c5d794 192.168.0.218 '/bin/sh -c '"'"'chmod u+x /root/.ansible/tmp/ansible-tmp-1573399527.3-188437527440745/ /root/.ansible/tmp/ansible-tmp-1573399527.3-188437527440745/command.py && sleep 0'"'"''
<192.168.0.218> (0, '', '')
<192.168.0.218> ESTABLISH SSH CONNECTION FOR USER: None
<192.168.0.218> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/root/.ansible/cp/82e2c5d794 -tt 192.168.0.218 '/bin/sh -c '"'"'/usr/bin/python /root/.ansible/tmp/ansible-tmp-1573399527.3-188437527440745/command.py; rm -rf "/root/.ansible/tmp/ansible-tmp-1573399527.3-188437527440745/" > /dev/null 2>&1 && sleep 0'"'"''
<192.168.0.218> (0, '\r\n{"changed": true, "end": "2019-11-10 23:25:23.100262", "stdout": "root:x:0:0:root:/root:/bin/bash", "cmd": "getent passwd root", "rc": 0, "start": "2019-11-10 23:25:23.082719", "stderr": "", "delta": "0:00:00.017543", "invocation": {"module_args": {"warn": true, "executable": null, "_uses_shell": true, "_raw_params": "getent passwd root", "removes": null, "creates": null, "chdir": null, "stdin": null}}}\r\n', 'Shared connection to 192.168.0.218 closed.\r\n')
192.168.0.218 | SUCCESS | rc=0 >>
root:x:0:0:root:/root:/bin/bash

META: ran handlers
META: ran handlers
[root@localhost ~]#

  說明:通過以上信息的查看,我們可以大概知道ansible的執行命令的過程,如下

  1、首先ansible會加載自己的配置文件,默認是/etc/ansible/ansible.cfg

  2、加載對應模塊文件,如上就是加載的是shell模塊

  3、通過ansible將模塊或命令生成對應的python臨時文件,並將該文件用sftp傳輸至遠端主機的對應執行用戶的家目錄下的.ansible/tmp/ansible-tmp-數字/xxxx.py文件

  4、然后對剛才傳送過去的臨時文件加可執行權限 chmod + x

  5、執行臨時文件,並返回結果

  6、刪除臨時py文件,sleep 0 退出

ansible的返回結果一般會有3種顏色來表示執行結果:紅色,綠色,橘黃色。其中紅色表示執行失敗,或者執行過程中有異常,一般會終止剩余的所有任務。綠色和橘黃色表示執行過程中沒有異常,所有任務均正常執行,但橘黃色表示命令執行結束后目標有狀態變化,而綠色表示命令執行后目標沒有狀態變化,不僅ansible命令執行結果有如此設置,ansible系列命令均有此設置,所以判斷ansible系列命令的執行結果是否正常,我們看顏色即可

3、ansible-galaxy:命令主要作用是連接https://galaxy.ansible.com下載/上傳相應的roles

命令用法:

Usage: ansible-galaxy [delete|import|info|init|install|list|login|remove|search|setup] [--help] [options] ... 

  1、下載安裝角色

[root@localhost ~]# 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 /etc/ansible/roles/geerlingguy.redis
- geerlingguy.redis (1.6.0) was installed successfully
[root@localhost ~]# 

  2、列出所有已經安裝的角色列表

[root@localhost ~]# ansible-galaxy list
- geerlingguy.redis, 1.6.0
[root@localhost ~]# 

  3、刪除已安裝的角色

[root@localhost ~]# ansible-galaxy remove geerlingguy.redis
- successfully removed geerlingguy.redis
[root@localhost ~]# ansible-galaxy list
[root@localhost ~]# 

  說明:galaxy默認下載到/etc/ansible/roles目錄下,我們刪除也可直接刪除該目錄下的角色,當然我們也可把自己寫好的角色放在該目錄下,用ansible-galaxy list 也是可以查看到我們自己寫的角色。

4、ansible-vault:命令主要功能管理機密解密yaml文件

命令用法:

Usage: ansible-vault [create|decrypt|edit|encrypt|encrypt_string|rekey|view] [options] [vaultfile.yml]

  1、加密

[root@localhost ansible]# cat test.yaml 
---
- hosts: websers
  remote_user: root
  
  tasks:
    - name: test
      command: hostname
[root@localhost ansible]# ansible-vault encrypt test.yaml 
New Vault password: 
Confirm New Vault password: 
Encryption successful
[root@localhost ansible]# cat test.yaml
$ANSIBLE_VAULT;1.1;AES256
38653234373532306537633636343038383031613537303437623730626462306665363165363432
6162306332313031326330386136623464346533363164320a353734386632303837393633643932
62656262626265396236646536646231646631363431383261623530626639303132396139633731
6663633466373034320a323161316262653535353361353436353238663836623034366534393265
34663862363938653531346237323265633861663430313839653932633362333865333366353765
38326239386432373665396133346632346336373839386134366335663339363338306138363733
39653462373564383736373063333764653137356237353563396635633862623039373964326531
61626138316239663535346562643436666534333637313363663536393932313565623533666561
6564
[root@localhost ansible]# 

  2、解密

[root@localhost ansible]# cat test.yaml
$ANSIBLE_VAULT;1.1;AES256
38653234373532306537633636343038383031613537303437623730626462306665363165363432
6162306332313031326330386136623464346533363164320a353734386632303837393633643932
62656262626265396236646536646231646631363431383261623530626639303132396139633731
6663633466373034320a323161316262653535353361353436353238663836623034366534393265
34663862363938653531346237323265633861663430313839653932633362333865333366353765
38326239386432373665396133346632346336373839386134366335663339363338306138363733
39653462373564383736373063333764653137356237353563396635633862623039373964326531
61626138316239663535346562643436666534333637313363663536393932313565623533666561
6564
[root@localhost ansible]# ansible-vault decrypt test.yaml 
Vault password: 
Decryption successful
[root@localhost ansible]# cat test.yaml 
---
- hosts: websers
  remote_user: root
  
  tasks:
    - name: test
      command: hostname
[root@localhost ansible]# 

  3、不解密查看

[root@localhost ansible]# cat test.yaml
$ANSIBLE_VAULT;1.1;AES256
63623938346561623733663938396234303933353162326531353230366237373664663662623133
3136653066363866363461666438346531626439346134660a623231326637336464303965366263
38353637633962326233313664353966343663393931393131303361323139646530333566313739
3233336166653038630a626637366661646638376338653261373336373438353639333930363836
32353464313438633632323366323731333830326632313837623131636363393664323863663437
38346131303561373865316666346265653039346333373663383861653737373466356466393439
35386163636234623564353537373264636138636663663531356164313437373164633433303635
63306439633963636136663637643936373337376130616433396561303535313330656337323233
3065
[root@localhost ansible]# ansible-vault view test.yaml 
Vault password: 
---
- hosts: websers
  remote_user: root
  
  tasks:
    - name: test
      command: hostname
[root@localhost ansible]# cat test.yaml 
$ANSIBLE_VAULT;1.1;AES256
63623938346561623733663938396234303933353162326531353230366237373664663662623133
3136653066363866363461666438346531626439346134660a623231326637336464303965366263
38353637633962326233313664353966343663393931393131303361323139646530333566313739
3233336166653038630a626637366661646638376338653261373336373438353639333930363836
32353464313438633632323366323731333830326632313837623131636363393664323863663437
38346131303561373865316666346265653039346333373663383861653737373466356466393439
35386163636234623564353537373264636138636663663531356164313437373164633433303635
63306439633963636136663637643936373337376130616433396561303535313330656337323233
3065
[root@localhost ansible]# 

  4、編輯加密文件

[root@localhost ansible]# cat test.yaml 
$ANSIBLE_VAULT;1.1;AES256
63623938346561623733663938396234303933353162326531353230366237373664663662623133
3136653066363866363461666438346531626439346134660a623231326637336464303965366263
38353637633962326233313664353966343663393931393131303361323139646530333566313739
3233336166653038630a626637366661646638376338653261373336373438353639333930363836
32353464313438633632323366323731333830326632313837623131636363393664323863663437
38346131303561373865316666346265653039346333373663383861653737373466356466393439
35386163636234623564353537373264636138636663663531356164313437373164633433303635
63306439633963636136663637643936373337376130616433396561303535313330656337323233
3065
[root@localhost ansible]# ansible-vault edit test.yaml 
Vault password: 
---
- hosts: websers
  remote_user: root

  tasks:
    - name: test
      command: hostname
    - name: test1
      shell: ls /root/
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
"/tmp/tmpBHavml.yaml" 9L, 135C written
[root@localhost ansible]# cat test.yaml 
$ANSIBLE_VAULT;1.1;AES256
30653764326466326131636362363762356362393334383966303433306331316335373732633463
3430383065336336333232303933356161363861376335630a363837363963386265333866643265
35333133393861646662636261653662313864633866373930306664646563343966366239373432
3661376233383766610a306366633964343434313533333065623739313762326561303837666437
61623136303764326138643362653166633138653237383761323665393132656161663639353631
62333063323135623466386333633835346539653463656239393562616164656664353562316163
36373161326261336338613137386636653431336535376338313165343564616531653439333764
65653834333335346531316137663332643963323966373064653664656532343061326234373563
31636364663737376639336531313937363630306232613561373932306432623835663563643463
66366530396536373031613134326464623939396538383335633764363237653064656135373262
306462316363333863393765323932373737
[root@localhost ansible]# 

  說明:這種編輯好的文件還是處於加密狀態

  5、修改加密口令

[root@localhost ansible]# ansible-vault rekey test.yaml 
Vault password: 
New Vault password: 
Confirm New Vault password: 
Rekey successful
[root@localhost ansible]# 

  說明:修改口令必須先輸入原口令,正確后才可以修改,如果忘記密碼則文件就無法查看,也無法修改口令

  6、創建新加密文件

[root@localhost ansible]# ls
test.yaml
[root@localhost ansible]# ansible-vault create test2.yaml
New Vault password: 
Confirm New Vault password: 
---
- hosts: appsers
  remote_user: root

  tasks:
  - name: test2
    shell: getent passwd
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
~                                                                                                                      
"/tmp/tmpgYTB3x.yaml" 7L, 92C written
[root@localhost ansible]# ls
test2.yaml  test.yaml
[root@localhost ansible]# cat test2.yaml 
$ANSIBLE_VAULT;1.1;AES256
64616164373236646635383539366661646262383936613533363263303136393031633533373638
6261613964636466656439656464336635323337643632620a366133383633633837363432326138
63323331346437636365353866656233363139633364353833623933353732323038336364376539
3963643939383734350a643734356432663063383066313932333837323631636536613834333232
30393464376230633762663364333330343132386132343861636665343831653863653939356536
62333564303934303138356332376634313535373037663866323038363237323438633464623534
61303937313930363230353165346337393462666131303861646262333830333365393737326365
63346431613736303963346130363464313239646361653830303862333236303939613665383261
3230
[root@localhost ansible]

5、ansible-console:可交互式執行ansible命令,支持tab補全,常用於ad-hoc和ansible-playbook之間的場景,常用於集中一批臨時操作或命令。

[root@localhost ansible]# ansible-console
Vault password: 
Welcome to the ansible console.
Type help or ? to list commands.

root@all (7)[f:5]$ list
192.168.0.99
192.168.0.218
192.168.0.123
192.168.0.233
192.168.0.128
192.168.0.208
192.168.0.199
root@all (7)[f:5]$ cd websers
root@websers (2)[f:5]$ list
192.168.0.99
192.168.0.218
root@websers (2)[f:5]$ forks 2
root@websers (2)[f:2]$ shell getent passwd root
192.168.0.218 | SUCCESS | rc=0 >>
root:x:0:0:root:/root:/bin/bash

192.168.0.99 | SUCCESS | rc=0 >>
root:x:0:0:root:/root:/bin/bash

root@websers (2)[f:2]$

  說明:在終端鍵入ansible-console命令后會進入類似shell一樣的交互式終端環境,其中提示符格式是:執行用戶@當前操作的主機組(主機組中的主機數量)[f:並發數]$,設置並發數:forks n,其中n 表示設置的並發數;切換組用cd 主機組,如cd websers;list是列出當前主機組里的主機列表,列出所有的內置命令用?或help

6、ansible-playbook:命令功能是執行playbook文件

命令用法:

Usage: ansible-playbook [options] playbook.yml [playbook2 ...]

常用選項:

  -C,--check:檢查playbook 不執行

  -e,傳遞變量

  -f,設置並發數,默認是5

  -t,指定tags運行

  -l,--limit=subset針對某些主機執行

  --list-hosts:列出匹配的主機列表

  --list-tags:列出所有可用標簽

  --list-tasks:列出所有將被執行的任務

[root@localhost ansible]# cat test.yaml 
---
- hosts: websers
  remote_user: root
  
  tasks:
    - name: test
      command: /usr/bin/wall hello world 
[root@localhost ansible]# ansible-playbook -C test.yaml 

PLAY [websers] ********************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************
ok: [192.168.0.218]
ok: [192.168.0.99]

TASK [test] ***********************************************************************************************************
skipping: [192.168.0.218]
skipping: [192.168.0.99]

PLAY RECAP ************************************************************************************************************
192.168.0.218              : ok=1    changed=0    unreachable=0    failed=0   
192.168.0.99               : ok=1    changed=0    unreachable=0    failed=0   

[root@localhost ansible]# ansible-playbook  test.yaml   

PLAY [websers] ********************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************
ok: [192.168.0.218]
ok: [192.168.0.99]

TASK [test] ***********************************************************************************************************
changed: [192.168.0.218]
changed: [192.168.0.99]

PLAY RECAP ************************************************************************************************************
192.168.0.218              : ok=2    changed=1    unreachable=0    failed=0   
192.168.0.99               : ok=2    changed=1    unreachable=0    failed=0   

[root@localhost ansible]# ansible-playbook  test.yaml --list-hosts

playbook: test.yaml

  play #1 (websers): websers    TAGS: []
    pattern: [u'websers']
    hosts (2):
      192.168.0.99
      192.168.0.218
[root@localhost ansible]# ansible-playbook  test.yaml --list-tags

playbook: test.yaml

  play #1 (websers): websers    TAGS: []
      TASK TAGS: []
[root@localhost ansible]# ansible-playbook  test.yaml --list-tasks

playbook: test.yaml

  play #1 (websers): websers    TAGS: []
    tasks:
      test      TAGS: []
[root@localhost ansible]# ansible-playbook  test.yaml --limit 192.168.0.99

PLAY [websers] ********************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************
ok: [192.168.0.99]

TASK [test] ***********************************************************************************************************
changed: [192.168.0.99]

PLAY RECAP ************************************************************************************************************
192.168.0.99               : ok=2    changed=1    unreachable=0    failed=0   

[root@localhost ansible]# 

7、ansible-pull:命令功能從VCS存儲庫中提取劇本並為本地主機執行,該命令的使用涉及ansible的另一種工作模式:pull模式(ansible默認使用push模式)。這和通常的push模式工作機制剛好相反,其適用於一下場景。1、有數量巨大的機器需要配置,即使使用高並發線程依舊要花費很多時間;2、在剛啟動的、沒有網絡連接的主機上使用運行ansible

命令用法:

ansible-pull -U <repository> [options] [<playbook.yml>]

 常用選項:

-U <URL>, --url <URL>
劇本資料庫的網址
-d <DEST>, --directory <DEST>
檢出存儲庫的目錄
-i, --inventory, --inventory-file
指定清單主機路徑或逗號分隔的主機列表。–不推薦使用庫存文件
-o, --only-if-changed
僅在存儲庫已更新的情況下運行劇本
-u <REMOTE_USER>, --user <REMOTE_USER>
以該用戶身份連接(默認=無)

通常ansible-pull結合git和crontab 一並實現,其原理是通過crontab定期拉取指定的git庫中的playbook到本地,並指定模式自動運行預先制定好的指令。

示例:

*/20 * * * * root /usr/local/bin/ansible-pull -o -C 2.1.0 -d /srv/www/king-gw/ -i /etc/ansible/hosts -U git://git.kingifa.com/king-gw-ansiblepull >> /var/log/ansible-pull.log 2>&1

ansible-pull通常在配置大批量機器的場景會用到,靈活性稍有欠缺,但效率幾乎可以無限提升,對運維人員的技術水平和前瞻性規划有較高要求。

更多的選項說明請參考https://docs.ansible.com/ansible/2.4/ansible-pull.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM