Ansible-基礎配置及常用模塊


一、Ansible介紹

1.1、什么是ansible?

Ansible是一個配置管理系統configuration management system, python 語言是運維人員必須會的語言, ansible 是一個基於python 開發的自動化運維工具, 其功能實現基於ssh遠程連接服務, ansible 可以實現批量系統配置,批量軟件部署,批量文件拷貝,批量運行命令等功能, 除了ansible之外,還有saltstack 等批量管理軟件.

1.2、軟件特點

1)ansible不需要單獨安裝客戶端,SSH相當於ansible客戶端。

2)ansible不需要啟動任何服務,僅需安裝對應工具即可。

3)ansible依賴大量的python模塊來實現批量管理。

4)ansible配置文件/etc/ansible/ansible.cfg

5)Ansible是一種agentless(基於ssh),可實現批量配置、命令執行和控制,基於Python實現的自動化運維工具。Ansible的兩個特性:

  • 模塊化:通過調用相關模塊,完成指定任務,且支持任何語言編寫的自定義模塊;
  • playbook:劇本,可根據需要一次執行完劇本中的所有任務或某些任務;

1.3、架構特點

15365930348150

1)連接插件(connectior plugins) :用於連接主機 用來連接被管理端。

2)核心模塊(core modules) :連接主機實現操作, 它依賴於具體的模塊來做具體的事情。

3)自定義模塊(custom modules): 根據自己的需求編寫具體的模塊。

4)插件(plugins): 完成模塊功能的補充。

5)劇本(playbooks):ansible的配置文件,將多個任務定義在劇本中,由ansible自動執行。

6)主機清單(host inventory):定義ansible需要操作主機的范圍。

1.4、任務執行模式

1.4.1、ad-hoc模式(點對點模式)

使用單個模塊,支持批量執行單條命令。ad-hoc 命令是一種可以快速輸入的命令,而且不需要保存起來的命令。就相當於bash中的一句話shell

1.4.2、playbook模式(劇本模式)

是Ansible主要管理方式,也是Ansible功能強大的關鍵所在。playbook通過多個task集合完成一類功能,如Web服務的安裝部署、數據庫服務器的批量備份等。可以簡單地把playbook理解為通過組合多條ad-hoc操作的配置文件

1.5、命令執行流程

  1. 加載自己的配置文件,默認/etc/ansible/ansible.cfg

  2. 查找對應的主機配置文件,找到要執行的主機或者組;

  3. 加載自己對應的模塊文件,如 command;

  4. 通過ansible將模塊或命令生成對應的臨時py文件(python腳本), 並將該文件傳輸至遠程服務器;

  5. 對應執行用戶的家目錄的.ansible/tmp/XXX/XXX.PY文件;

  6. 給文件 +x 執行權限;

  7. 執行並返回結果;

  8. 刪除臨時py文件,sleep 0退出;

二、Ansible安裝配置

2.1、ansible安裝

1)yum安裝

yum install epel-release -y
yum install ansible –y

2)pip安裝

yum install python-pip
pip install ansible

2.2、程序結構及配置文件

2.2.1、安裝目錄

配置文件目錄:/etc/ansible/
執行文件目錄:/usr/bin/
Lib庫依賴目錄:/usr/lib/pythonX.X/site-packages/ansible/
Help文檔目錄:/usr/share/doc/ansible-X.X.X/
Man文檔目錄:/usr/share/man/man1/

2.2.2、配置文件:/etc/ansible/ansible.cfg

ansible 的配置文件為/etc/ansible/ansible.cfg,ansible 有許多參數,下面我們列出一些常見的參數:

inventory = /etc/ansible/hosts      #這個參數表示資源清單inventory文件的位置
library = /usr/share/ansible        #指向存放Ansible模塊的目錄,支持多個目錄方式,只要用冒號(:)隔開就可以
forks = 5       #並發連接數,默認為5
sudo_user = root        #設置默認執行命令的用戶
remote_port = 22        #指定連接被管節點的管理端口,默認為22端口,建議修改,能夠更加安全
host_key_checking = False       #設置是否檢查SSH主機的密鑰,值為True/False。關閉后第一次連接不會提示配置實例
timeout = 60        #設置SSH連接的超時時間,單位為秒
log_path = /var/log/ansible.log     #指定一個存儲ansible日志的文件(默認不記錄日志)

補充如下:

host_key_checking  
host_key_checking=False 禁用驗證host_key_checking
 
inventory 
定義庫文件位置,腳本,或者存放可通信主機的目錄
inventory = /etc/ansible/hosts
 
library
ansible默認搜尋模塊的位置
library = /usr/share/ansible
Ansible知道如何搜尋多個用冒號隔開的路徑,同時也會搜索在playbook中的"./library"。
 
log_path
日志存放位置
默認不開啟,ansible將會吧模塊加載紀錄在系統日志系統中.不包含用密碼.
log_path=/var/log/ansible.log
 
module_name
這個是/usr/bin/ansible的默認模塊名(-m). 默認是'command'模塊。command模塊不支持shell變量,管道,配額。所以最好把這個參數改為'shell'。
module_name = command
 
nocolor
默認ansible會為輸出結果加上顏色,用來更好的區分狀態信息和失敗信息。如果你想關閉這一功能,可以把'nocolor'設置為'1'。
nocolor=0
 
nocows 
默認ansible可以調用一些cowsay的特性,使得/usr/bin/ansible-playbook運行起來更加愉快。
如果不喜歡cows,可以通通過將'nocows'設置為'1'來禁用這一選項:
nocows=0
 
poll_interval
對於Ansible中的異步任務,這個是設置定義,當具體的poll interval 沒有定義時,多少時間回查一下這些任務的狀態, 默認值是一個折中選擇15秒鍾.這個時間是個回查頻率和任務完成叫回頻率和當任務完成時的回轉頻率的這種:
poll_interval=15
 
private_key_file
如果你是用pem密鑰文件而不是SSH客戶端或秘密啊認證的話, 你可以設置這里的默認值, 來避免每一次提醒設置密鑰文件位置"--ansible-private-keyfile":
private_key_file=/path/to/file.pem
 
remote_port
這個設置是你系統默認的遠程SSH端口, 如果不指定,默認為22號端口:(建議修改成別的端口)
remote_port = 22
 
remote_user
這是個ansible使用/usr/bin/ansible-playbook連接的默認用戶名。注意如果不指定, /usr/bin/ansible默認使用當前用戶名稱:
remote_user = root
 
timeout
這個事默認SSH鏈接嘗試超市時間:
timeout = 10
 
transport
如果"-c <transport_name>" 選項沒有在使用/usr/bin/ansible 或者 /usr/bin/ansible-playbook 特指的話, 這個參數提供了默認通信機制。默認值為'smart'。
如果本地系統支持ControlPersist技術的話, 將會使用(基於OpenSSH)'ssh', 如果不支持該技術,將使用'paramiko'庫,其他傳輸選項包括'local', 'chroot','jail'等等。
用戶通常可以這個設置為'smart',讓playbook在需要的條件自己選擇'connectin:'參數.
 
record_host_keys
默認設置會記錄並驗證通過在用戶hostfile中新發現的的主機(如果host key checking 被激活的話)。這個選項在有很多主機的時候將會性能很差!!
在這種情況下,建議使用SSH傳輸代替。當設置為False時, 性能將會提升,在hostkey checking 被禁用時候, 建議使用!!!
record_host_keys=True
 
scp_if_ssh
又是用戶操控一個一個沒有開啟SFTP協議的遠程系統.如果這個設置為True, scp將代替用來為遠程主機傳輸文件:
scp_if_ssh=False   
如果沒有遇到這樣的問題沒有必要來修改這個設置。當然修改這個設置也沒有什么明顯的弊端。大部分的系統環境都默認支持SFTP, 通常情況下不需要修改。
 
pipelining
在不通過實際文件傳輸的情況下執行ansible模塊來使用管道特性, 從而減少執行遠程模塊SSH操作次數。如果開啟這個設置,將顯著提高性能!!
然而當使用"sudo:"操作的時候, 你必須在所有管理的主機的/etc/sudoers中禁用'requiretty'。
默認這個選項為了保證與sudoers requiretty的設置(在很多發行版中時默認的設置)的兼容性是禁用的。但是為了提高性能強烈建議開啟這個設置。
pipelining=False
 
accelerate_port
在急速模式下使用的端口。
accelerate_port = 5099
 
accelerate_timeout
這個設置時用來控制從客戶機獲取數據的超時時間.如果在這段時間內沒有數據傳輸,套接字連接會被關閉. 一個保持連接(keepalive)數據包通常每15秒回發回給控制台,所以這個超時時間不應該低於15秒(默認值為30秒):
accelerate_timeout = 30
 
accelerate_connect_timeout
這個設置空着套接字調用的超時時間。這個應該設置相對比較短。
這個和'accelerate_port'連接在回滾到ssh或者paramiko(受限於你默認的連接設置)連接方式之前會嘗試三次開始遠程加速daemon守護進程。默認設置為1.0秒!
accelerate_connect_timeout = 1.0
需要注意: 這個選項值可以設置為小於1秒鍾,但是除非你擁有一個速度很快而且很可靠的網絡,否則也許這樣並不是一個很好的選擇。
如果你使用英特網訪問你的系統,最好提高這個值!!!
 
accelerate_daemon_timeout
這個控制加速daemon守護進程的超時時間,用分鍾來衡量.默認為30分鍾!
accelerate_daemon_timeout = 30
注意, 在1.6版本之前,daemon發起的超時時間是硬編碼的.對於1.6以后的版本,超時時間是根據daemon上一次活動信息和這個可設置的選項。
 
accelerate_multi_key
如果這個選項開啟,這個設置將允許多個私鑰被加載到daemon。任何客戶端要想連接daemon都需要開啟這個選項!!!
accelerate_multi_key = yes
通過本地套接字文件連接的通過SSH上傳密鑰文件到目標節點的新客戶端, 必須在登陸daemon時使用原始的登陸密鑰登陸。

2.2.3、主機清單:/etc/ansible/hosts

/etc/ansible/hosts是ansible默認主機資產清單文件,用於定義被管理主機的認證信息, 例如ssh登錄用戶名、密碼以及key相關信息

1)基於密碼連接

[root@m ~]# cat /etc/ansible/hosts

#方式一、主機+端口+密碼
[webservers]
10.0.0.31 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass='123456'
10.0.0.41 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass='123456'

#方式二、主機+端口+密碼
[webservers]
web[1:2].oldboy.com ansible_ssh_pass='123456'

#方式三、主機+端口+密碼
[webservers]
web[1:2].oldboy.com
[webservers:vars]
ansible_ssh_pass='123456'

2)基於密鑰連接,需要先創建公鑰和私鑰,並下發公鑰至被控端

[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.16.1.41
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.16.1.31

#方式一、主機+端口+密鑰
[group_name]
10.0.0.31:22
10.0.0.41

#方式二、別名+主機+端口+密鑰
[group_name]
nfs-node1 ansible_ssh_host=10.0.0.31 ansible_ssh_port=22

3)主機組使用方式

#方式一、主機組變量+主機+密碼
[group_name1]
10.0.0.31
10.0.0.41
[group_name1:vars]
ansible_ssh_pass='123456'

#方式二、主機組變量+主機+密鑰
[group_name2]
10.0.0.7
10.0.0.8

#定義多組,多組匯總整合
# webservers組包括兩個子組[apache,nginx]
[webservers:children]
[group_name1]
[group_name2]

三、Ansible常用命令

/usr/bin/ansible        Ansibe AD-Hoc 臨時命令執行工具,常用於臨時命令的執行
/usr/bin/ansible-doc   Ansible 模塊功能查看工具
/usr/bin/ansible-galaxy  下載/上傳優秀代碼或Roles模塊 的官網平台,基於網絡的
/usr/bin/ansible-playbook  Ansible 定制自動化的任務集編排工具
/usr/bin/ansible-pull  Ansible遠程執行命令的工具,拉取配置而非推送配置(使用較少,海量機器時使用,對運維的架構能力要求較高)
/usr/bin/ansible-vault  Ansible 文件加密工具
/usr/bin/ansible-console  Ansible基於Linux Consoble界面可與用戶交互的命令執行工具

常用的是/usr/bin/ansible/usr/bin/ansible-playbook

3.1、ansible-doc命令

ansible-doc 命令常用於獲取模塊信息及其使用幫助,一般用法如下:

ansible-doc -l              #獲取全部模塊的信息
ansible-doc -s MOD_NAME     #獲取指定模塊的使用幫助

示例:

[root@Manager ~]#ansible-doc -l|grep mysql
azure_rm_mysqlfirewallrule_info                               Get Azure MySQL Firewall Rule facts                     
azure_rm_mysqlconfiguration_info                              Get Azure MySQL Configuration facts                     
mysql_info                                                    Gather information about MySQL servers                  
mysql_db                                                      Add or remove MySQL databases from a remote host        
azure_rm_mysqlserver_info                                     Get Azure MySQL Server facts                            
azure_rm_mysqldatabase_info                                   Get Azure MySQL Database facts                          
mysql_variables                                               Manage MySQL global variables                           
mysql_user                                                    Adds or removes a user from a MySQL database            
proxysql_backend_servers                                      Adds or removes mysql hosts from proxysql admin interfac...
azure_rm_mysqlconfiguration                                   Manage Configuration instance                           
azure_rm_mysqlfirewallrule                                    Manage MySQL firewall rule instance                     
azure_rm_mysqlserver                                          Manage MySQL Server instance                            
mysql_replication                                             Manage MySQL replication                                
proxysql_mysql_users                                          Adds or removes mysql users from proxysql admin interfac...
azure_rm_mysqldatabase                                        Manage MySQL Database instance                          
[root@Manager ~]#ansible-doc -s mysql_user
- name: Adds or removes a user from a MySQL database
  mysql_user:
      append_privs:          # Append the privileges defined by priv to the existing ones for this user instead of
                               overwriting existing ones.
      ca_cert:               # The path to a Certificate Authority (CA) certificate. This option, if used, must specify
                               the same certificate as used by the server.
      check_implicit_admin:   # Check if mysql allows login as root/nopassword before trying supplied credentials.
      client_cert:           # The path to a client public key certificate.
      client_key:            # The path to the client private key.
      config_file:           # Specify a config file from which user and password are to be read.
      connect_timeout:       # The connection timeout when connecting to the MySQL server.
      encrypted:             # Indicate that the 'password' field is a `mysql_native_password` hash.
      host:                  # The 'host' part of the MySQL username.
      host_all:              # Override the host option, making ansible apply changes to all hostnames for a given user.
                               This option cannot be used when creating users.
      login_host:            # Host running the database.
      login_password:        # The password used to authenticate with.
      login_port:            # Port of the MySQL server. Requires `login_host' be defined as other than localhost if
                               login_port is used.
      login_unix_socket:     # The path to a Unix domain socket for local connections.
      login_user:            # The username used to authenticate with.
      name:                  # (required) Name of the user (role) to add or remove.
      password:              # Set the user's password..
      priv:                  # MySQL privileges string in the format: `db.table:priv1,priv2'. Multiple privileges can be
                               specified by separating each one using a forward slash:
                               `db.table:priv/db.table:priv'. The format is based on MySQL
                               `GRANT' statement. Database and table names can be quoted,
                               MySQL-style. If column privileges are used, the
                               `priv1,priv2' part must be exactly as returned by a `SHOW
                               GRANT' statement. If not followed, the module will always
                               report changes. It includes grouping columns by permission
                               (`SELECT(col1,col2') instead of
                               `SELECT(col1',SELECT(col2))).
      sql_log_bin:           # Whether binary logging should be enabled or disabled for the connection.
      state:                 # Whether the user should exist. When `absent', removes the user.
      update_password:       # `always' will update passwords if they differ. `on_create' will only set the password for
                               newly created users.

3.2、ansible命令

15444333387910

語法格式:
ansible <pattern_goes_here> -m <module_name> -a <arguments>
ansible  匹配模式   -m  模塊  -a  '需要執行的內容'

解釋說明:
匹配模式:即哪些機器生效 (可以是某一台, 或某一組, 或all) , 默認模塊為command , 執行常規的shell命令.
-m name, --module-name=name:  指定執行使用的模塊。
-u username, --user=username:  指定遠程主機以username運行命令。
-s, --sudo:  相當於linux系統下的sudo命令。
-u sudo_username, --sudo-user=sudo_username:  使用sudo, 相當於linux系統下的sudo命令。
-C, --check:  只檢查不實際執行。
-e, 即extra_vars:  引用外部參數。
-i, 即inventory:  指定倉庫列表, 默認/etc/ansible/hosts。
--list-host:  列出執行主機列。

詳細說明:

語法:ansible <host-pattern> [options]
 
使用ansible --help可以查看到命令參數,
常用選項參數:
--version               #顯示版本
-m module               #指定使用的模塊,默認為command
-v                      #查看執行的詳細過程(-vv、-vvvv更詳細)
--list-hosts            #顯示主機列表(可以簡寫為--list)
-k,--ask-pass           #提示輸入ssh連接密碼,默認使用key驗證
-K,--ask-become-pass    #提示執行輸入sudo的密碼
-C,--check              #檢查,並不執行
-T,--timeout=TIMEOUT    #執行命令的超時時間,默認10s
-u,--user=REMOTE_USER   #指定遠程執行的執行用戶
-b,--become             #代替舊版本的sudo切換
-h,--help               #顯示使用幫助
-u                      #指定遠程主機運行此命令的用戶
-s                      #相當於sudo
-S                      #使用sudo
 
======================================================
[普通選項]
-a MODULE_ARGS
--args=MODULE_ARGS
傳遞參數給模塊
  
--ask-vault-pass
詢問vault的密碼
  
-B SECONDS
--background=SECONDS
異步后台⽅式執⾏任務,並在指定的秒數后超時,超時會殺掉任務的進程。默認是同步,即保持長連接,它會等待
所有執⾏完畢(即阻塞模式)。但有時候是沒必要這樣的,⽐如某些命令的執⾏時間⽐ssh的超時時間還長。如果
不指定超時秒數,將以同步⽅式運⾏任務
  
-P POLL_INTERVAL
--poll=POLL_INTERVAL
異步模式下輪詢任務的時間間隔,默認60秒
  
-C
--check
不對遠程主機做一些改變,而是預測某些可能發生的改變(檢查功能)
  
-e EXTRA_VARS
--extra-vars=EXTRA_VARS
配置額外的配置變量(key=value或者YAML/JSON格式)
  
-f FORKS
--forks=FORKS
指定並行處理的進程數量,默認5個
  
-h
--help
顯示幫助信息
  
-i INVENTORY
--inventory-file=INVENTORY
指定inventory⽂件,多個⽂件使⽤逗號分隔。默認為/etc/ansible/hosts
  
-l SUBSET
--limit=SECONDS
使⽤額外的匹配模式來篩選⽬標主機列表。
此處的匹配模式是在已有匹配模式下進⾏的,所以是更嚴格的篩選。例如指定了主機組的情況下,使⽤-l選項從中只選⼀台主機進⾏控制
  
--list-hosts
不會執行任何操作,而是列出匹配到的主機列表
  
-m MODULE_NAME
--module-name=MODULE_NAME
指定要執行的模塊名,默認的模塊為"command"
  
--new-vault-password-file=NEW_VAULT_PASSWORD_FILE
new vault password f ile f or rekey
  
-o
--one-line
簡化輸出(一行輸出模式)
  
--output-OUTPUT_FILE
output f ile name f or encrypt or decrypt; use - f or stdout
  
--syntax-check
檢查playbook的語法,不會執行
  
-t TREE
--tree=TREE
記錄輸出到此⽬錄中(測試時以每個host名如IP地址為⽂件名記錄,結果記錄到對應的⽂件中)。
此選項在ansible巨慢的時候(如瞬間應該返回的命令還需要10多秒才完成)有奇⽤,或者將ansible的結果重
定向到某個⽂件中也能解決,為什么如此,我也不明⽩(表⾯看來和輸出⽅式有關系),多次親測有效。
  
--vault-password-file=VAULT_PASSWORD_FILE
指定vault密碼文件
  
-v
--verbose
輸出詳細信息,-vvv和-vvvv輸出更詳細的信息
  
--version
顯示ansbile的版本
  
======================================================
[以下是連接選項,⽤於控制誰以及如何連接主機]
-k
--ask-pass
詢問連接時的密碼
  
--private-key=KEY_FILE
--key-file=KEY_FILE
使用文件來認證SSH連接的過程
  
-u REMOTE_USER
--user=REMOTE_USER
使用指定的用戶名進行連接
  
-c CINNECTION
--connection=CINNECTION
連接類型,默認為ssh。paramiko (SSH), ssh, winrm and local. local is mostly usef ul f or crontab or kickstarts.
  
-T TIMEOUT
--time=TIMEOUT
連接的超時時間,單位為秒,默認10秒
  
--ssh-common-args=SSH_COMMON_ARGS
指定傳遞給sftp/scp/ssh等⼯具的通⽤額外參數
  
--sftp-extra-args=SFTP_EXTRA_ARGS
指定只傳遞給sftp的額外參數,如-f
  
--scp-extra-args=SCP_EXTRA_ARGS
指定只傳遞給scp的額外參數,如-l
  
--ssh-extra-args=SSH_EXTRA_ARGS
指定只傳遞給ssh的額外參數,如-R
  
======================================================
[以下是權限控制選項:控制在⽬標主機上以什么⾝份和權限運⾏任務]
-s
--sudo
為運行ansible命令的用戶提升權限為sudo_user的權限,此命令已經報廢,使用become代替
  
-u SUDO_USER
--sudo-user=SUDO_USER
期望的sudo_user,默認為root,已報廢,使用become代替
  
-S
--su
使⽤su的⽅式執⾏操作,已廢棄,使⽤become替代
  
-R SU_USER
--su-user=SU_USER
使⽤此user的su執⾏操作,默認為root,已廢棄,使⽤become替代
  
-b
--become
使用become的方式升級權限
  
--become-method=BECOME_METHOD
指定提升權限的方式,可選以下⼏種:sudo/su/pbrun/pf exec/doas/dzdo/ksu/runas值
  
--become-user=BECOME_USER
要提升為哪個user的權限,默認為root
  
--ask-sudo-pass
詢問sudo密碼,已廢棄,使⽤become替代
  
--ask-su-pass
詢問su的密碼,已廢棄,使⽤become替代
  
-K
--ask-become-pass
詢問become提升權限時的密碼

3.3、ansible-playbook命令

ansible-playbook是日常用的最多的命令,其工作機制是:通過讀取預先編寫好的playbook文件實現批量管理,要實現的功能與命令ansbile一樣,可以理解為按一定的條件組成ansible的任務集ansible-playbook命令后跟YML格式的playbook文件,執行事先編排好的任務集

#使用ansible-playbook執行一個yaml文件
[root@ansible ~]# ansible-playbook -C /opt/ansible-playbook/test.yaml

3.4、ansible-console(交互終端)

Ansible-console是ansible為用戶提供的一款交互式工具,用戶可在ansible-console虛擬出的終端上使用ansible內置的各種命令。所有的操作與shell類似,並支持tab補全.

#對所有受控端進行操作
[root@Manager ~]#ansible-console 
Welcome to the ansible console.
Type help or ? to list commands.

root@all (2)[f:5]$ uptime
172.16.93.165 | CHANGED | rc=0 >>
 14:43:10 up 140 days, 23 min,  3 users,  load average: 0.44, 0.23, 0.12

172.16.93.167 | CHANGED | rc=0 >>
 14:43:10 up 140 days, 23 min,  1 user,  load average: 0.00, 0.01, 0.05

#對web組操作
[root@Manager ~]#ansible-console web
Welcome to the ansible console.
Type help or ? to list commands.

root@web (1)[f:5]$ list
172.16.93.165
root@web (1)[f:5]$ cat /etc/passwd|grep root
172.16.93.165 | CHANGED | rc=0 >>
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

root@web (1)[f:5]$ exit

#-------------------------------------------------
在終端可做的操作
設置並發數: forks n  例如:forks 10
切換組: cd 組名      例如:cd web
列出當前組主機列表   例如:list
列出所有的內置命令(其實就是內置的模塊)   例如:?或者help
exit命令退出終端

3.5、ansible-inventory命令

查看被控制端主機清單的詳細信息默認情況下它使用庫存腳本,返回JSON格式:

[root@Manager ~]#ansible-inventory --list
{
    "_meta": {
        "hostvars": {
            "172.16.93.165": {
                "ansible_port": 2812
            }, 
            "172.16.93.167": {
                "ansible_port": 2812
            }
        }
    }, 
    "all": {
        "children": [
            "db", 
            "ungrouped", 
            "web"
        ]
    }, 
    "db": {
        "hosts": [
            "172.16.93.167"
        ]
    }, 
    "web": {
        "hosts": [
            "172.16.93.165"
        ]
    }
}

3.6、ansible-vault命令

ansible-vault主要用於配置文件的加密,如編寫的playbook配置文件中包含敏感的信息,不希望其他人隨便的看,ansible-vault可加密/解密這個配置文件:

語法:ansible-vault [create|decrypt|edit|encrypt|encrypt_string|rekey|view] [options] [vaultfile.yml]
參數:
--ask-vault-pass      ask for vault password
-h, --help                                          #查看幫助信息
--new-vault-id=NEW_VAULT_ID                         #設置用於rekey的新vault標識
--new-vault-password-file=NEW_VAULT_PASSWORD_FILE   #新的保險庫密碼文件為rekey
--vault-id=VAULT_IDS                                #要使用的保險庫標識
--vault-password-file=VAULT_PASSWORD_FILES          #庫密碼文件
-v, --verbose                                       #查看執行的詳細過程(-vv、-vvvv更詳細)
--version                                           #查看版本
  
使用參數:
encrypt (加密)
decrypt (解密)
create (創建)
view (查看)
edit (編輯)
rekey (修改密碼)

示例如下:

[root@Manager ~]#echo lawrence > bo.yaml

#加密
[root@Manager ~]#ansible-vault encrypt bo.yaml 
New Vault password: 
Confirm New Vault password: 
Encryption successful
[root@Manager ~]#cat bo.yaml 
$ANSIBLE_VAULT;1.1;AES256
36356635383935353964353133343530643163373437643736356139653031333639323332666534
6439326336616430393936636235386637333663623864300a393563626536396134643564346635
35386339653263613961363937643934663331613931623362396432363833343037303832333862
3538383633653335340a386530343566653439646338663666316438613465616262356264333762
6537

#解密查看
[root@Manager ~]#ansible-vault decrypt bo.yaml 
Vault password: 
Decryption successful
[root@Manager ~]#cat bo.yaml 
lawrence

#直接查看
[root@Manager ~]#ansible-vault encrypt bo.yaml
New Vault password: 
Confirm New Vault password: 
Encryption successful
[root@Manager ~]#ansible-vault view bo.yaml 
Vault password: 
lawrence

#編輯
[root@Manager ~]#ansible-vault edit bo.yaml
Vault password: 
[root@Manager ~]#ansible-vault view bo.yaml 
Vault password: 
lawrence
test

#創建加密文件
[root@Manager ~]#ansible-vault create grace.yaml
New Vault password: 
Confirm New Vault password: 
[root@Manager ~]#ansible-vault view grace.yaml 
Vault password: 
test

四、Ansible常用模塊

4.1、ping模塊

#查看受控端
[root@Manager ~]#ansible all --list-hosts
  hosts (2):
    172.16.93.165
    172.16.93.167
[root@Manager ~]#ansible web --list-hosts
  hosts (1):
    172.16.93.165
[root@Manager ~]#ansible db --list-hosts
  hosts (1):
    172.16.93.167

#ping 模塊
[root@Manager ~]#ansible all -m ping
172.16.93.167 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
172.16.93.165 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
[root@Manager ~]#ansible web -m ping
172.16.93.165 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
[root@Manager ~]#ansible db -m ping
172.16.93.167 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
[root@Manager ~]#ansible -i /etc/ansible/hosts all -m ping
172.16.93.167 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
172.16.93.165 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

#查看幫助說明
[root@Manager ~]#ansible-doc -v ping

4.2、command模塊

command 是ansible的默認模塊, 即不指定模塊的時候默認使用的模塊就是command !  使用ansible自帶模塊執行命令 如果要用 > < | & ‘ ‘ ,最好使用shell 模塊, command是不支持管道符之類的。

image

[root@Manager ~]#ansible all -a "date"
172.16.93.167 | CHANGED | rc=0 >>
Mon Jan  6 16:46:04 CST 2020

172.16.93.165 | CHANGED | rc=0 >>
Mon Jan  6 16:46:04 CST 2020

[root@Manager ~]#ansible all -m command -a "date"
172.16.93.167 | CHANGED | rc=0 >>
Mon Jan  6 16:46:43 CST 2020

172.16.93.165 | CHANGED | rc=0 >>
Mon Jan  6 16:46:43 CST 2020

#在命令執行之前, 先切換到指定的目錄路徑下
[root@Manager ~]#ansible web -m command -a "chdir=/tmp pwd"
172.16.93.165 | CHANGED | rc=0 >>
/tmp

#文件是否存在,存在就不執行,不存在就執行
[root@Manager ~]#ansible web -m command -a "creates=/etc/hosts date"
172.16.93.165 | SUCCESS | rc=0 >>
skipped, since /etc/hosts exists

[root@Manager ~]#ansible web -m command -a "creates=/etc/hosts123 date"
172.16.93.165 | CHANGED | rc=0 >>
Mon Jan  6 16:48:15 CST 2020

#removes 文件是否存在,存在就執行,不存在就執行
[root@Manager ~]#ansible web -m command -a "removes=/etc/hosts uptime"
172.16.93.165 | CHANGED | rc=0 >>
 16:48:57 up 138 days,  2:29,  2 users,  load average: 0.00, 0.04, 0.05

[root@Manager ~]#ansible web -m command -a "removes=/etc/hosts123 uptime"
172.16.93.165 | SUCCESS | rc=0 >>
skipped, since /etc/hosts123 does not exist

4.3、shell模塊

shell模塊可以在遠程主機上調用shell解釋器運行命令,支持shell的各種功能,例如管道等

[root@Manager ~]#ansible web -m shell -a "cat /etc/passwd|grep root"
172.16.93.165 | CHANGED | rc=0 >>
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

#shell 模塊在遠程執行腳本時,遠程主機上一定要有相應的腳本
[root@Manager ~]#ansible web -m shell -a "/bin/bash /tmp/test.sh"
172.16.93.165 | FAILED | rc=127 >>
/bin/bash: /tmp/test.sh: No such file or directorynon-zero return code

4.4、copy模塊

把主控節點本地的文件上傳同步到遠程受控節點上, 該模塊不支持從遠程受控節點拉取文件到主控節點上。 參數選項如下:

src:指定源文件路徑,可以是相對路徑,也可以是絕對路徑,可以是目錄(並非是必須的,可以使用content,直接生成文件內容). src即是要復制到遠程主機的文件在本地的地址,可以是絕對路徑,也可以是相對路徑。如果路徑是一個目錄,它將遞歸復制。在這種情況下,如果路徑使用”/”來結尾,則只復制目錄里的內容,如果沒有使用”/”來結尾,則包含目錄在內的整個內容全部復制,類似於rsync。
dest:指定目標文件路徑,只能是絕對路徑,如果src是目錄,此項必須是目錄. 這個是必選項!
owner:指定屬主;
group:指定屬組;
mode:指定權限,可以以數字指定比如0644;
content:代替src,直接往dest文件中寫內容,可以引用變量,也可以直接使用inventory中的主機變量. 寫后會覆蓋原文件內容!
backup:在覆蓋之前將原文件備份,備份文件包含時間信息。有兩個選項:yes|no
force: 如果目標主機包含該文件,但內容不同,如果設置為yes,則強制覆蓋,如果為no,則只有當目標主機的目標位置不存在該文件時,才復制。默認為yes ;
directory_mode:遞歸的設定目錄的權限,默認為系統默認權限;
others:所有的file模塊里的選項都可以在這里使用;

測試:

[root@Manager ~]#ansible web -m copy -a "src=~/script dest=/tmp/ backup=yes"
[root@Manager ~]#ansible web -m copy -a "src=/etc/hosts dest=/tmp/ owner=root group=root mode=0644"
[root@Manager ~]#ansible web -m copy -a 'src=/etc/hosts dest=/tmp/ owner=root group=root mode="u=rw,g=rw,o=rw"'

#向遠程受控節點文件寫入內容, 把原內容覆蓋掉,並備份
[root@Manager ~]#ansible web -m copy -a 'content="hello,test" dest=/tmp/hosts backup=yes'
172.16.93.165 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "backup_file": "/tmp/hosts.19520.2020-01-06@17:14:48~", 
    "changed": true, 
    "checksum": "5f677f1dc185b643d6f436491f1e165d4151103c", 
    "dest": "/tmp/hosts", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "bf2fcd5a98ca557c37106f400c2954be", 
    "mode": "0666", 
    "owner": "root", 
    "size": 10, 
    "src": "/root/.ansible/tmp/ansible-tmp-1578302087.54-20280675092284/source", 
    "state": "file", 
    "uid": 0
}

4.5、file模塊

file模塊主要用於遠程主機上的文件操作,file模塊包含如下選項:

force: 需要在兩種情況下強制創建軟鏈接,一種是源文件不存在但之后會建立的情況下;另一種是目標軟鏈接已存在,需要先取消之前的軟鏈,然后創建新的軟鏈,有兩個選項: yes|no
group: 定義文件/目錄的屬組
mode: 定義文件/目錄的權限
owner: 定義文件/目錄的屬主
path: 必選項,定義文件/目錄的路徑
recurse: 遞歸的設置文件的屬性,只對目錄有效
src: 要被鏈接的源文件的路徑,只應用於state=link的情況
dest: 被鏈接到的路徑,只應用於state=link的情況
state: 表示file的狀態, 主要分為:
      directory: 如果目錄不存在,創建目錄;
     file: 即使文件不存在,也不會被創建;
     link: 創建軟鏈接;
     hard: 創建硬鏈接;
     touch: 如果文件不存在,則會創建一個新的文件,如果文件或目錄已存在,則更新其最后修改時間;
     absent: 刪除目錄、文件或者取消鏈接文件;

測試:

#創建文件
[root@Manager ~]#ansible web -m file -a "path=/tmp/testfile state=touch mode=600 owner=root group=root"
[root@Manager ~]#ansible web -m file -a "path=/tmp/filetest state=touch mode="u+rw,g-wx,o-rwx" owner=root group=root"

#創建目錄
[root@Manager ~]#ansible web -m file -a "path=/tmp/testdir state=directory mode=755 owner=root group=root"
#刪除文件或目錄
[root@Manager ~]#ansible web -m file -a "path=/tmp/testdir state=absent"

文件的軟鏈接和硬鏈接
[root@Manager ~]# ansible web -m file -a "src=/data/test dest=/opt/heihei state=link"
[root@Manager ~]# ansible web -m file -a "src=/data/test dest=/mnt/hh state=hard" 
[root@Manager ~]# ansible web -m file -a "src=/etc/passwd dest=/opt/heihei state=link force=yes"
 
目錄做軟鏈接
[root@Manager ~]# ansible web -m file -a "src=/data/haha/ dest=/root/aaa state=link"

4.6、fetch模塊

用於從遠程機器獲取文件,並將其本地存儲在由主機名組織的文件樹中。
src:  指定從遠程控制節點上要拉取的文件, 記住: 這個只能拉取文件!!  不能拉取目錄!!!  后續版本可能會支持遞歸提取。
dest:  將遠程節點拉取的文件保存到本地的目錄路徑. 例如,如果dest目錄是/backup,在主機host.example.com上命名為/ etc/profile的src文件將被保存到/backup/host.example.com/etc/profile。
flat: 允許覆蓋將目標文件添加到主機名/path/to/file的默認行為。默認為no!!   如果設置為yes, 將不會顯示類似172.16.60.221/root/信息. (即在dest的本機存放目錄下不會創建遠程節點ip命名的目錄)

#從受控點拉取文件到主控點
[root@Manager ~]#ansible web -m fetch -a "dest=/tmp/ src=/root/appctl.sh"
172.16.93.165 | CHANGED => {
    "changed": true, 
    "checksum": "b4760b1944b8039e79e39a6e90b9c55af7f59dda", 
    "dest": "/tmp/172.16.93.165/root/appctl.sh", 
    "md5sum": "c461a6b1b11858bbe6258ff0b9885a89", 
    "remote_checksum": "b4760b1944b8039e79e39a6e90b9c55af7f59dda", 
    "remote_md5sum": null
}

#發現dest定義的文件存放目錄下會有以遠程節點ip命名的目錄
[root@Manager ~]#ll /tmp/172.16.93.165/root/appctl.sh 
-rwxr-xr-x 1 root root 2763 Jan  6 17:52 /tmp/172.16.93.165/root/appctl.sh

#如果不想要從遠程節點拉取過來的文件在本機存放目錄里已遠程節點ip命名的目錄里面
[root@Manager ~]#ansible web -m fetch -a "dest=/tmp/ src=/root/appctl.sh flat=yes"
172.16.93.165 | CHANGED => {
    "changed": true, 
    "checksum": "b4760b1944b8039e79e39a6e90b9c55af7f59dda", 
    "dest": "/tmp/appctl.sh", 
    "md5sum": "c461a6b1b11858bbe6258ff0b9885a89", 
    "remote_checksum": "b4760b1944b8039e79e39a6e90b9c55af7f59dda", 
    "remote_md5sum": null
}    
[root@Manager ~]#ll /tmp/appctl.sh 
-rwxr-xr-x 1 root root 2763 Jan  6 17:58 /tmp/appctl.sh

4.7、cron模塊

遠程受控節點的crontab配置

day=         #日應該運行的工作( 1-31, , /2, )
hour=        # 小時 ( 0-23, , /2, )
minute=      #分鍾( 0-59, , /2, )
month=       # 月( 1-12, *, /2, )
weekday=     # 周 ( 0-6 for Sunday-Saturday,, )
job=         #指明運行的命令是什么
name=        #定時任務描述
reboot       # 任務在重啟時運行,不建議使用,建議使用special_time
special_time #特殊的時間范圍,參數:reboot(重啟時),annually(每年),monthly(每月),weekly(每周),daily(每天),hourly(每小時)
state        #指定狀態,present表示添加定時任務,也是默認設置,absent表示刪除定時任務
user         # 以哪個用戶的身份執行

示例如下:

#創建定時任務
[root@Manager ~]#ansible web -m cron -a "name='test' hour='2-5' minute='*/5' day='1' month='3,4' weekday='1' job='ls -l' user=root"
[root@Manager ~]#ansible web -m shell -a "crontab -l"
172.16.93.165 | CHANGED | rc=0 >>
#Ansible: test
*/5 2-5 1 3,4 1 ls -l

#根據name刪除定時任務
[root@Manager ~]#ansible web -m cron -a "name=test state=absent"

#--------------------------------------------------------------

#沒有指定name時
[root@Manager ~]#ansible web -m cron -a "minute=* hour=* day=* month=* weekday=*  job='/bin/sh /server/scripts/test.sh'"
[root@Manager ~]#ansible web -m shell -a "crontab -l"
172.16.93.165 | CHANGED | rc=0 >>
#Ansible: None
* * * * * /bin/sh /server/scripts/test.sh

#添加name
[root@Manager ~]#ansible web -m cron -a "name='cron01' job='/bin/sh /server/scripts/test.sh'"
[root@Manager ~]#ansible web -m shell -a "crontab -l"
172.16.93.165 | CHANGED | rc=0 >>
#Ansible: cron01
* * * * * /bin/sh /server/scripts/test.sh

#刪除指定定時任務
[root@Manager ~]#ansible web -m cron -a "name=cron01 state=absent"

#注釋相應定時任務,使定時任務失效 (disabled=yes 表示注釋掉, 即無效; disabled=no 表示去掉注釋, 即有效)
[root@Manager ~]#ansible web -m cron -a "name=cron01 minute=* hour=* day=* month=* weekday=*  job='/bin/sh /server/scripts/test.sh' disabled=no"
[root@Manager ~]#ansible web -m shell -a "crontab -l"
172.16.93.165 | CHANGED | rc=0 >>
#Ansible: cron01
* * * * * /bin/sh /server/scripts/test.sh
[root@Manager ~]#ansible web -m cron -a "name=cron01 disabled=yes"
172.16.93.165 | FAILED! => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "msg": "You must specify 'job' to install a new cron job or variable"
}
[root@Manager ~]#ansible web -m cron -a "name=cron01 job='/bin/sh /server/scripts/test.sh' disabled=yes"
[root@Manager ~]#ansible web -m shell -a "crontab -l"
172.16.93.165 | CHANGED | rc=0 >>
#Ansible: cron01
#* * * * * /bin/sh /server/scripts/test.sh

4.8、yum模塊

用於軟件安裝

config_file:yum的配置文件 (optional)
disable_gpg_check:關閉gpg_check (optional)
disablerepo:不啟用某個源 (optional)
enablerepo:啟用某個源(optional)
name:要進行操作的軟件包的名字,默認最新的程序包,指明要安裝的程序包,可以帶上版本號,也可以傳遞一個url或者一個本地的rpm包的路徑
state:表示是安裝還是卸載的狀態, 其中present、installed、latest 表示安裝,  absent 、removed表示卸載刪除;  present默認狀態, laster表示安裝最新版本.

示例如下:

安裝httpd
[root@ansible-server ~]# ansible web-nodes -m yum -a 'name=httpd state=latest'
[root@ansible-server ~]# ansible web-nodes -m yum -a 'name=httpd state=present'
[root@ansible-server ~]# ansible web-nodes -m yum -a 'name=httpd state=installed'
 
[root@ansible-server ~]# ansible web-nodes -m yum -a 'name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present'
[root@ansible-server ~]# ansible web-nodes -m yum -a 'name="@Development tools" state=present'
 
卸載httpd
[root@ansible-server ~]# ansible web-nodes -m yum -a 'name=httpd state=absent'
[root@ansible-server ~]# ansible web-nodes -m yum -a 'name=httpd state=removed'

4.9、service服務

管理服務的模塊, service管理的服務必須是yum安裝的服務, 即默認的系統服務腳本。編譯安裝的服務不好使用service模塊管理.

name: 服務名稱;
state:  started/stopped/restarted/reloaded;
enabled: true/false;
runlevel: 運行級別;
sleep: 如果執行了restarted,在stop和start之間沉睡幾秒;
arguments: 給命令行提供一些選項;

示例如下:

[root@ansible-server ~]# ansible web-nodes -m service -a "name=sshd state=restarted"
[root@ansible-server ~]# ansible web-nodes -m service -a "enabled=on name=httpd state=started"
[root@ansible-server ~]# ansible web-nodes -m service -a "enabled=yes name=httpd state=started"
[root@ansible-server ~]# ansible web-nodes -m service -a "name=httpd state=reloaded"   
[root@ansible-server ~]# ansible web-nodes -m service -a "name=httpd state=stopped"

4.10、systemd模塊

service模塊適用於service管理程序的情況,如果是centos7系統,使用systemctl管理程序的話,可以使用systemd模塊。systemctl可以控制程序啟/停,reload,開機啟動,觀察程序狀態(status)等。systemd模塊的主要參數如下:

name:  服務名稱,例如crond.service,最好帶上后綴 .service
state:  需要的操作,started/stopped/restarted/reloaded
enabled:是否需要開機啟動
daemon_reload:systemd 讀取配置文件,每次修改了文件,最好都運行一次,確保應用了

使用systemd前,如果是自己生成的配置文件,需要先放到/etc/systemd/system/ 目錄中,然后使用daemon_reload 中就可以了,注意不要和系統之前自帶的配置沖突,例如之前已經用yum安裝過redis或haproxy 之類的,已經存在相應的服務了,需要自行判斷要使用哪個文件。也可以使用.include 引用其他文件,具體參考systemd文檔 (查看命令"ansible-doc systemd")。systemd模塊在ansible的yml文件中配置示例如下:

- name: Make sure a service is running
  systemd: state=started name=httpd
 
- name: stop service cron on debian, if running
  systemd: name=cron state=stopped
 
- name: restart service cron on centos, in all cases, also issue daemon-reload to pick up config changes
  systemd:
    state: restarted
    daemon_reload: yes
    name: crond
 
- name: reload service httpd, in all cases
  systemd:
    name: httpd
    state: reloaded
 
- name: enable service httpd and ensure it is not masked
  systemd:
    name: httpd
    enabled: yes
    masked: no
 
- name: enable a timer for dnf-automatic
  systemd:
    name: dnf-automatic.timer
    state: started
    enabled: True
 
- name: just force systemd to reread configs (2.4 and above)
  systemd: daemon_reload=yes

4.11、user模塊

用來管理用戶賬號,參數如下:

home: 指定用戶的家目錄, 需要與createhome配合使用。
groups: 指定用戶的屬組。
uid: 指定用的uid。
password: 設定用戶密碼, password參數需要接受md5加密后的值. 特別注意: 指定password參數時, 不能使用明文密碼, 因為后面這一串密碼會被直接傳送到被管理主機的/etc/shadow文件中, 所以需要先將密碼字符串進行加密處理, 然后將得到的字符串放到password中即可。
name: 指定用戶名。
system: 是否為系統用戶。 表示默認創建為普通用戶, 而非系統用戶, 指定是用yes. 也就是說yes是默認創建為普通用戶, 而非系統用戶;
update_password: 修改用戶密碼, 其中always: 新密碼和舊密碼不同時進行修改; on_create: 為新創建的用戶指定密碼.
create_home: 創建家目錄, 其中yes表示默認項, 即創建用戶默認是有家目錄的; no表示創建用戶時不創建家目錄.
remove: 其中yes是刪除用戶家目錄, 需要指定此參數; no是默認項, 刪除用戶時默認不刪除用戶的家目錄. 當state=absent時, remove=yes則表示連同家目錄一起刪除, 等價於userdel -r。
state: 用戶狀態是創建還是刪除. (present, absent) ;默認為present; 其中present表示添加用戶; absent表示刪除用戶
shell: 指定用戶的shell環境。
generate_ssh_key: 是否為相關用戶生成SSH密鑰。 這不會覆蓋現有的SSH密鑰。
ssh_key_bits: 可選擇指定要創建的SSH密鑰中的位數。
ssh_key_passphrase: 設置SSH密鑰的密碼。 如果沒有提供密碼, SSH密鑰將默認沒有密碼。
ssh_key_file: 指定SSH密鑰文件名(可選). 如果這是一個相對的文件名, 那么它將是相對於用戶的主目錄。
ssh_key_type: 指定要生成的SSH密鑰的類型(可選). 可用的SSH密鑰類型將取決於目標主機上的實現。

示例如下:

使用bash shell添加用戶haha,將組"管理員"和"開發人員"附加到用戶組
[root@ansible-server ~]# ansible web-nodes -m user -a "name=haha shell=/bin/bash groups=admins,developers append=yes"
  
增加用戶anhui (先對密碼做明文到密文的處理)
[root@ansible-server ~]# echo "anhui@123" | openssl passwd -1 -stdin
$1$rj74jCVy$NDW80bgY0DUTuHUlSunVv1
[root@ansible-server ~]# ansible web-nodes -m user -a 'name=anhui system=yes password=$1$rj74jCVy$NDW80bgY0DUTuHUlSunVv1 state=present'
  
刪除用戶anhui
[root@ansible-server ~]# ansible web-nodes -m user -a 'name=anhui remove=yes state=absent' 
  
更新用戶kevin的密碼 (先對新密碼kevin@bj123做明文到密文的處理)
[root@ansible-server ~]# echo "kevin@bj123"| openssl passwd -1 -stdin 
$1$5X5bH5.J$RwE6o6g6bX953W7vAaizv/
[root@ansible-server ~]# ansible web-nodes -m user -a 'name=kevin update_password=always password=$1$5X5bH5.J$RwE6o6g6bX953W7vAaizv/'
  
在~/.ssh/id_rsa中為用戶bobo創建一個2048位的SSH密鑰
[root@ansible-server ~]# ansible web-nodes -m user -a 'name=bobo generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa'
 
[root@ansible-server ~]# ansible web-nodes -m group -a "name=yang gid=888"
[root@ansible-server ~]# ansible web-nodes -m user -a "name=yang uid=888 group=888 shell=/sbin/nologin create_home=no"

可以使用debug模塊將明文密碼進行hash加密,然后進行用戶創建

[root@Manager ~]#ansible localhost -m debug -a "msg={{ 'bgx' | password_hash('sha512', 'salt') }}"
localhost | SUCCESS => {
    "msg": "$6$salt$WP.Kb1hMfqJG7dtlBltkj4Um4rVhch54R5JCi6oP73MXzGhDWqqIY.JkSOnIsBSOeXpKglY7gUhHzY4ZtySm41"
}
[root@Manager ~]# ansible web -m user -a 'name=lawrence password=$6$salt$WP.Kb1hMfqJG7dtlBltkj4Um4rVhch54R5JCi6oP73MXzGhDWqqIY.JkSOnIsBSOeXpKglY7gUhHzY4ZtySm41 create_home=yes shell=/bin/bash'
172.16.93.165 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 1003, 
    "home": "/home/lawrence", 
    "name": "lawrence", 
    "password": "NOT_LOGGING_PASSWORD", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 1003
}

4.12、group模塊

gid: 指定用的gid。
name: 指定用戶名。
state: 是創建還是刪除, (present,absent);
system: 如果是,則表示創建的組是系統組;

示例如下:

[root@ansible-server ~]# ansible web-nodes -m group -a "name=huoqiu state=present"
[root@ansible-server ~]# ansible web-nodes -m group -a "name=chenzun gid=897 state=present" 
[root@ansible-server ~]# ansible web-nodes -m group -a "name=huoqiu state=absent"

4.13、script模塊

將本機的腳本在被管理端的機器上運行。該模塊直接指定腳本的路徑即可

需要注意: 使用scripts模塊,不用將腳本傳輸到遠程節點,腳本本身不用進行授權,即可利用script模塊執行。直接執行腳本即可,不需要使用sh 或者 /bin/bash

[root@Manager ~]#cat /tmp/df.sh 
#!/bin/bash
date >> /tmp/disk_total.log
df -lh >> /tmp/disk_total.log

[root@Manager ~]#ansible web -m script -a "/tmp/df.sh"
172.16.93.165 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 172.16.93.165 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 172.16.93.165 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}
[root@Manager ~]#ansible web -a "cat /tmp/disk_total.log"
172.16.93.165 | CHANGED | rc=0 >>
Wed Jan  8 10:26:22 CST 2020
Filesystem      Size  Used Avail Use% Mounted on
/dev/vda1       197G  5.5G  184G   3% /
devtmpfs         16G     0   16G   0% /dev
tmpfs            16G     0   16G   0% /dev/shm
tmpfs            16G  560K   16G   1% /run
tmpfs            16G     0   16G   0% /sys/fs/cgroup
/dev/vdc1       400G  119G  282G  30% /data/mysql_db
tmpfs           3.2G     0  3.2G   0% /run/user/0

4.14、setup模塊

用於收集遠程受控主機的一些基本信息. 

filter參數:用於進行條件過濾。如果設置,僅返回匹配過濾條件的信息

#打印受控機全部信息
[root@Manager ~]#ansible web -m setup

#獲取ip地址
[root@Manager ~]#ansible web -m setup -a "filter=ansible_all_ipv4_addresses"
172.16.93.165 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "172.16.93.165"
        ], 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}

#獲取內存信息
[root@Manager ~]#ansible web -m setup -a "filter=ansible_memory_mb"
172.16.93.165 | SUCCESS => {
    "ansible_facts": {
        "ansible_memory_mb": {
            "nocache": {
                "free": 27947, 
                "used": 4065
            }, 
            "real": {
                "free": 15806, 
                "total": 32012, 
                "used": 16206
            }, 
            "swap": {
                "cached": 0, 
                "free": 0, 
                "total": 0, 
                "used": 0
            }
        }, 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}

#通過通配符實現模糊匹配,比如以”mb”關鍵字結尾的信息
[root@Manager ~]#ansible web -m setup -a "filter=*mb"
172.16.93.165 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 15806, 
        "ansible_memory_mb": {
            "nocache": {
                "free": 27947, 
                "used": 4065
            }, 
            "real": {
                "free": 15806, 
                "total": 32012, 
                "used": 16206
            }, 
            "swap": {
                "cached": 0, 
                "free": 0, 
                "total": 0, 
                "used": 0
            }
        }, 
        "ansible_memtotal_mb": 32012, 
        "ansible_swapfree_mb": 0, 
        "ansible_swaptotal_mb": 0, 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}

#獲取信息保存至文件
[root@Manager ~]#ansible web -m setup -a 'filter="*mem*"' --tree /tmp/facts
172.16.93.165 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 15806, 
        "ansible_memory_mb": {
            "nocache": {
                "free": 27947, 
                "used": 4065
            }, 
            "real": {
                "free": 15806, 
                "total": 32012, 
                "used": 16206
            }, 
            "swap": {
                "cached": 0, 
                "free": 0, 
                "total": 0, 
                "used": 0
            }
        }, 
        "ansible_memtotal_mb": 32012, 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}
[root@Manager ~]#cd /tmp/facts/
[root@Manager facts]#ls
172.16.93.165
[root@Manager facts]#cat 172.16.93.165   #JSON格式
{"ansible_facts": {"ansible_memfree_mb": 15806, "ansible_memory_mb": {"nocache": {"free": 27947, "used": 4065}, "real": {"free": 15806, "total": 32012, "used": 16206}, "swap": {"cached": 0, "free": 0, "total": 0, "used": 0}}, "ansible_memtotal_mb": 32012, "discovered_interpreter_python": "/usr/bin/python"}, "changed": false}

其他常用信息:

ansible_all_ipv4_addresses:僅顯示ipv4的信息。
ansible_devices:僅顯示磁盤設備信息。
ansible_distribution:顯示是什么系統,例:centos,suse等。
ansible_distribution_major_version:顯示是系統主版本。
ansible_distribution_version:僅顯示系統版本。
ansible_machine:顯示系統類型,例:32位,還是64位。
ansible_eth0:僅顯示eth0的信息。
ansible_hostname:僅顯示主機名。
ansible_kernel:僅顯示內核版本。
ansible_lvm:顯示lvm相關信息。
ansible_memtotal_mb:顯示系統總內存。
ansible_memfree_mb:顯示可用系統內存。
ansible_memory_mb:詳細顯示內存情況。
ansible_swaptotal_mb:顯示總的swap內存。
ansible_swapfree_mb:顯示swap內存的可用內存。
ansible_mounts:顯示系統磁盤掛載情況。
ansible_processor:顯示cpu個數(具體顯示每個cpu的型號)。
ansible_processor_vcpus:顯示cpu個數(只顯示總的個數).

4.15、selinux模塊

管理遠程受控節點的selinux的模塊

[root@Manager ~]#ansible web -m selinux -a "state=disabled"
172.16.93.165 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "configfile": "/etc/selinux/config", 
    "msg": "", 
    "policy": "targeted", 
    "reboot_required": false, 
    "state": "disabled"
}

4.16、find模塊

幫助在被管理的受控主機中查找符合條件的文件,就像 find 命令一樣

paths:  必須參數,指定在哪個目錄中查找文件,可以指定多個路徑,路徑間用逗號隔開,此參數有別名,使用別名 path 或者別名 name 可以代替 paths。
recurse: 默認情況下,只會在指定的目錄中查找文件,也就是說,如果目錄中還包含目錄,ansible 並不會遞歸的進入子目錄查找對應文件,如果想要遞歸的查找文件,需要使用 recurse 參數,當 recurse 參數設置為 yes 時,表示在指定目錄中遞歸的查找文件。
hidden: 默認情況下,隱藏文件會被忽略,當 hidden 參數的值設置為 yes 時,才會查找隱藏文件。
file_type: 默認情況下,ansible 只會根據條件查找”文件”,並不會查找”目錄”或”軟鏈接”等文件類型,如果想要指定查找的文件類型,可以通過 file_type 指定文件類型,可指定的文件類型有 any、directory、file、link 四種。
patterns: 使用此參數指定需要查找的文件名稱,支持使用 shell(比如通配符)或者正則表達式去匹配文件名稱,默認情況下,使用 shell 匹配對應的文件名,如果想要使用 python 的正則去匹配文件名,需要將 use_regex 參數的值設置為 yes。
use_regex:默認情況下,find 模塊不會使用正則表達式去解析 patterns 參數中對應的內容,當 use_regex 設置為 yes 時,表示使用 python 正則解析 patterns 參數中的表達式,否則,使用 glob 通配符解析 patterns 參數中的表達式。
contains:使用此參數可以根據文章內容查找文件,此參數的值為一個正則表達式,find 模塊會根據對應的正則表達式匹配文件內容。
age: 使用此參數可以根據時間范圍查找文件,默認以文件的 mtime 為准與指定的時間進行對比,比如,如果想要查找 mtime 在3天之前的文件,那么可以設置 age=3d,如果想要查找 mtime 在3天以內的文件,可以設置 age=-3d,這里所說的3天是按照當前時間往前推3天,可以使用的單位有秒(s)、分(m)、時(h)、天(d)、星期(w)。
age_stamp: 文件的時間屬性中有三個時間種類,atime、ctime、mtime,當我們根據時間范圍查找文件時,可以指定以哪個時間種類為准,當根據時間查找文件時,默認以 mtime 為准。
size: 使用此參數可以根據文件大小查找文件,比如,如果想要查找大於3M的文件,那么可以設置 size=3m,如果想要查找小於50k的文件,可以設置 size=-50k,可以使用的單位有 t、g、m、k、b。
get_checksum: 當有符合查找條件的文件被找到時,會同時返回對應文件的 sha1校驗碼,如果要查找的文件比較大,那么生成校驗碼的時間會比較長

示例如下:

#在受控主機的 /data目錄中查找文件內容中包含wang字符串的文件,隱藏文件會被忽略,不會進行遞歸查找。
[root@ansible-server ~]# ansible web-nodes -m find -a "paths=/data contains=".*wang.*""
 
#在受控主機的的 /data目錄以及其子目錄中查找文件內容中包含wang字符串的文件,隱藏文件會被忽略。
[root@ansible-server ~]# ansible web-nodes -m find -a "paths=/data contains=".*wang.*" recurse=yes"
 
#在受控主機的的 /data目錄中查找以 .sh 結尾的文件,包括隱藏文件,但是不包括目錄或其他文件類型,不會進行遞歸查找。
[root@ansible-server ~]# ansible web-nodes -m find -a 'paths=/data patterns="*.sh" file_type=any hidden=yes'
 
#在受控主機的的 /data目錄中查找以 .sh 結尾的文件,只不過patterns對應的表達式為正則表達式,查找范圍包括隱藏文件,包括所有文件類型,但是不會進行遞歸查找,不會對/data目錄的子目錄進行查找。
[root@ansible-server ~]# ansible web-nodes -m find -a 'paths=/data patterns=".*\.sh" use_regex=yes file_type=any hidden=yes' 
 
#在受控主機的的 /data目錄中以及其子目錄中查找 mtime 在1天以內的文件,不包含隱藏文件,不包含目錄或軟鏈接文件等文件類型。
[root@ansible-server ~]# ansible web-nodes -m find -a "path=/data age=-1d recurse=yes"
 
在受控主機的的 /data目錄中以及其子目錄中查找大於 2g 的文件,不包含隱藏文件,不包含目錄或軟鏈接文件等文件類型。
[root@ansible-server ~]# ansible web-nodes -m find -a "paths=/data size=2g recurse=yes"
 
在受控主機的的 /data目錄中以及其子目錄中查找以 .sh 結尾的文件,並且返回符合條件文件的 sha1 校驗碼,包括隱藏文件
[root@ansible-server ~]# ansible web-nodes -m find -a "paths=/data patterns=*.sh get_checksum=yes hidden=yes recurse=yes"

4.17、mount模塊

在遠程受控節點上掛載文件系統。可用參數

present: 開機掛載,僅將掛載配置寫入/etc/fstab(不常用)
mounted: 掛載設備,並將配置寫入/etc/fstab
unmounted: 卸載設備,不會清除/etc/fstab寫入的配置
absent: 卸載設備,會清理/etc/fstab寫入的配置

示例如下:

將受控節點的/dev/sd0設備掛載到/mnt/data目錄上, 文件格式為ext4, 只讀屬性
[root@ansible-server ~]# ansible web-nodes -m mount -a "path=/mnt/data src=/dev/sd0 fstype=ext4 ots=ro state=present"
 
僅將掛載的配置寫入/etc/fstab,並不會執行掛載操作
[root@ansible-server ~]# ansible web-nodes -m mount -a "src=172.16.60.220:/data path=/data fstype=nfs opts=defaults state=present"
 
臨時掛載設備,並將掛載信息寫入/etc/fstab
[root@ansible-server ~]# ansible web-nodes -m mount -a "src=172.16.60.220:/data path=/data fstype=nfs opts=defaults state=mounted"
 
臨時卸載,不會清理/etc/fstab
[root@ansible-server ~]# ansible web-nodes -m mount -a "src=172.16.60.220:/data path=/data fstype=nfs opts=defaults state=unmounted"
 
卸載,不僅臨時卸載,同時會清理/etc/fstab
[root@ansible-server ~]# ansible web-nodes -m mount -a "src=172.16.60.220:/data path=/data fstype=nfs opts=defaults state=absent"

[root@m01 ~]# ansible oldboy -m mount -a "src=172.16.1.31:/data path=/data fstype=nfs opts=defaults state=present"
[root@m01 ~]# ansible web -m mount -a "src=172.16.1.31:/data path=/data fstype=nfs opts=defaults state=mounted"
[root@m01 ~]# ansible web -m mount -a "src=172.16.1.31:/data path=/data fstype=nfs opts=defaults state=unmounted"
[root@m01 ~]# ansible web -m mount -a "src=172.16.1.31:/data path=/data fstype=nfs opts=defaults state=absent"

4.18、stat模塊

獲取遠程文件的狀態信息,包括atime,ctime,mtime,md5,uid,gid等信息

[root@Manager ~]#ansible web -m stat -a "path=/tmp/testfile"

4.19、hostname模塊

使用hostname模塊修改遠程節點的主機名時, 最好指明遠程單節點ip地址進行設置主機名了. 因為不同節點的主機名不一樣

[root@ansible-server ~]# ansible 172.16.60.213 -m hostname -a 'name="web-node03"'

4.20、unarchive模塊

解壓文件:

copy: 在解壓文件之前,是否先將文件復制到遠程主機,默認為yes。若為no,則要求目標主機上壓縮包必須存在。
creates: 指定一個文件名,當該文件存在時,則解壓指令不執行
dest: 遠程主機上的一個路徑,即文件解壓的絕對路徑。 必須是一個目錄路徑!
group: 解壓后的目錄或文件的屬組;
list_files: 如果為yes,則會列出壓縮包里的文件,默認為no,2.0版本新增的選項;
mode: 解壓后文件的權限;
src: 如果copy為yes,則需要指定壓縮文件的源路徑;
owner: 解壓后文件或目錄的屬主;

經測試, 該模塊解壓時識別zip, tgz , tar.gz, tar.bz2 格式的壓縮包, gzip格式的測試時不支持.

示例如下:

#將控制機上/usr/local/src/nginx.tgz解壓縮到/data/www中
[root@ansible-server ~]# ansible web-nodes -m unarchive -a "src=/usr/local/src/nginx.tgz dest=/data/www/"
 
#解壓遠程受控節點上已存在的文件
[root@ansible-server ~]# ansible web-nodes -m unarchive -a "src=/root/file.zip dest=/usr/local remote_src=yes"
 
#解壓文檔需要下載的文件(2.0中添加)
[root@ansible-server ~]# ansible web-nodes -m unarchive -a "src=https://example.com/example.zip dest=/usr/local/bin remote_src=yes"

4.21、lineinfile模塊

用於對遠程受控節點的文件編輯模塊. 主要選項有:

path: 指定要修改的配置文件, 包括:
         regexp:匹配要修改的內容
         line:要增加或者修改的內容
state: 狀態, 包括:
         absent:表示刪除,當匹配到時進行刪除
         present:表示增加,當匹配到時進行修改,當沒有匹配到時在最后增加一行,默認為此項
backrefs: 該參數值包括:
         no:表示如果沒有匹配到,則增加line;如果匹配成功,則替換line;
         yes:表示如果沒有匹配到,則不變line;如果匹配成功,則替換line;
backup: 該參數值包括:
         no:表示如果沒有匹配到,則增加line;如果匹配成功,則替換line;不備份原文件
         yes:表示如果沒有匹配到,則增加line;如果匹配成功,則替換line;備份原文件
insertafter(匹配的是此行): 在匹配到的行之后添加一行.  (經測試, 發現是匹配到的行的最后一行的后面添加一行)
insertbefore(匹配的是此行): 在匹配到的行之前添加一行.  (經測試, 發現是匹配到的行的最后一行的前面添加一行)

示例如下:

#將遠程受控節點的/data/test文件中的"123"字段修改為"lawrence"
[root@Manager ~]#ansible web -m lineinfile -a "path=/tmp/testfile regexp="123" line="lawrence" backrefs=no"

#匹配到的行后增加一行
[root@Manager ~]#ansible web -m lineinfile -a "path=/tmp/testfile insertafter="lawrence" line="huihui""

#匹配到的行前增加一行
[root@Manager ~]#ansible web -m lineinfile -a "path=/tmp/testfile insertbefore="lawrence" line="test""

#刪除匹配到的行並備份原文件
[root@Manager ~]#ansible web -m lineinfile -a "path=/tmp/testfile regexp="lawrence" state=absent backup=yes"

4.22、get_url模塊

該模塊主要用於從http、ftp、https服務器上下載文件(類似於wget), 主要有如下選項:

sha256sum: 下載完成后進行sha256 check;
timeout: 下載超時時間, 默認10s
url: 下載的URL
url_password、url_username: 主要用於需要用戶名密碼進行驗證的情況
dest: 將文件下載到哪里的絕對路徑。如果dest是目錄, 則使用服務器提供的文件名, 或者如果沒有提供, 將使用遠程服務器上的URL的基本名稱。
headers: 以格式“key: value, key: value”為請求添加自定義HTTP標頭

示例如下:

[root@ansible-server ~]# ansible web-nodes -m get_url -a "url=http://lan.Okay686.com/RDPWrap-v1.6.1.zip dest=/usr/local/src/"
[root@ansible-server ~]# ansible web-nodes -m get_url -a "url=http://10.0.8.50/ops.sh  dest=/opt/shell.sh mode=0440"
[root@ansible-server ~]# ansible web-nodes -m get_url -a 'url=http://10.0.8.50/ops.sh dest=/opt/shell.sh headers="key:value,key:value"' 
[root@ansible-server ~]# ansible web-nodes -m get_url -a 'url=http://10.0.8.50/ops.sh dest=/opt/shell.sh checksum=sha256:b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c'

[root@Manager ~]#ansible web -m get_url -a "url=http://XXX:81/sc/service/about/rc-service.log dest=/tmp url_username=username url_password=password"

4.21、template模塊

基於模板方式生成一個文件復制到遠程主機(template使用Jinjia2格式作為文件模版,進行文檔內變量的替換的模塊。它的每次使用都會被ansible標記為”changed”狀態。)

backup: 如果原目標文件存在,則先備份目標文件
src: 在ansible控制器上的Jinja2格式化模板的路徑。 這可以是相對或絕對的路徑。
dest: 將模板渲染到遠程機器上的位置。
force: 是否強制覆蓋,默認為yes
owner: 目標文件屬主
group: 目標文件屬組
mode: 目標文件的權限模式,模式可以被指定為符號模式(例如,u + rwx或u = rw,g = r,o = r)

示例如下:

[root@ansible-server ~]# ansible web-nodes -m template -a "src=/mytemplates/foo.j2 dest=/etc/file.conf owner=bin group=wheel  mode=0644"
 
#同樣的例子,但使用等效於0644的符號模式
[root@ansible-server ~]# ansible web-nodes -m template -a "src=/mytemplates/foo.j2 dest=/etc/file.conf owner=bin group=wheel mode="u=rw,g=r,o=r""

4.22、synchronize模塊

這個模塊是使用rsync同步文件,將主控方目錄推送到指定受控節點的目錄下。其參數如下:

delete: 刪除不存在的文件,delete=yes 使兩邊的內容一樣(即以推送方為主),默認no
src: 要同步到目的地的源主機上的路徑; 路徑可以是絕對的或相對的。如果路徑使用”/”來結尾,則只復制目錄里的內容,如果沒有使用”/”來結尾,則包含目錄在內的整個內容全部復制
dest:目的地主機上將與源同步的路徑; 路徑可以是絕對的或相對的。
dest_port:默認目錄主機上的端口 ,默認是22,走的ssh協議。
mode: push或pull,默認push,一般用於從本機向遠程主機上傳文件,pull 模式用於從遠程主機上取文件。
rsync_opts:通過傳遞數組來指定其他rsync選項。

示例如下:

將主控節點上/data/kevin目錄同步到受控節點的/home目錄下
[root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/data/kevin dest=/home'
 
將主控節點上/data/kevin/test.file文件同步到受控節點的/opt目錄下
[root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/data/kevin/test.file dest=/opt'
 
將主控節點上/data/kevin/test.file文件同步到受控節點的/root/bobo.file文件
[root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/data/kevin/test.file dest=/root/bobo.file'
 
將主控節點上/opt/同步到受控節點的/opt/目錄, 使受控節點保持和主控節點的opt目錄一致, 不一樣的就刪除! 默認delete=no
[root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/opt/ dest=/opt/ delete=yes'
 
注意命令中要加"/", 如果不加"/", 則主控節點的opt目錄就同步到受控節點的/opt目錄下即, 即/opt/opt
[root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/opt dest=/opt delete=yes' 
 
將主控節點上/data/kevin目錄同步到受控節點的/mnt/www目錄下. 但是bobo目錄排除在外!  rsync_opts可以進行多次傳遞.
[root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/data/kevin/ dest=/mnt/www/ rsync_opts="--no-motd" rsync_opts="--exclude=bobo"'
 
強制兩邊同步保持一致! 跟主控節點源目錄保持一致!
[root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/data/kevin/ dest=/mnt/www/ rsync_opts="--no-motd" rsync_opts="--exclude=bobo" delete=yes'
 
從遠程受控節點上將/usr/local/src/grace.file文件拉取到主控節點的/root目錄下
[root@ansible-server ~]# ansible web-nodes -m synchronize -a 'src=/usr/local/src/grace.file dest=/root/ rsync_opts="-avpgolr" mode=pull '

#指定sshd端口
[root@Manager ~]#ansible web -m synchronize -a "src=/root/script dest=/tmp dest_port=2812"
172.16.93.165 | CHANGED => {
    "changed": true, 
    "cmd": "/usr/bin/rsync --delay-updates -F --compress --archive --rsh=/usr/bin/ssh -S none -o Port=2812 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null --out-format=<<CHANGED>>%i %n%L /root/script 172.16.93.165:/tmp", 
    "msg": ".d..t...... script/\n", 
    "rc": 0, 
    "stdout_lines": [
        ".d..t...... script/"
    ]
}
synchronize 模塊相比copy模塊來說, 同步速度增加很多.

4.23、raw模塊

raw, shell, command三個模塊都能調用對象機器上的某條指令或者某個可執行文件。raw和shell模塊很像, 都支持管道; command模塊不支持管道.raw模塊執行的是系統原始命令, 執行后會主動關閉到被控制節點的連接!

[root@Manager ~]#ansible web -m raw -a "hostname"
172.16.93.165 | CHANGED | rc=0 >>
test-mysqldb
Shared connection to 172.16.93.165 closed.

[root@Manager ~]#ansible web -m raw -a "cat /etc/passwd|grep root"
172.16.93.165 | CHANGED | rc=0 >>
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
Shared connection to 172.16.93.165 closed.


免責聲明!

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



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