Linux下使用Ansible處理批量操作
Ansible介紹
- ansible是一款為類unix系統開發的自由開源的配置和自動化工具。它用python寫成,類似于saltstack和puppet,但是不同點是ansible不需要再節點中安裝任何客戶端。它使用ssh來通信。它基于python的paramiko開發,分布式,無需任何客戶端,輕量級,配置語法使用ymal及jinja2模板語言,更強的遠程命令執行操作。
Ansibe特性
- 部署簡單,只需在主控端部署Ansible環境,被控端無需做任何操作。
- 默認使用SSH協議對設備進行管理。
- 有大量常規運維操作模塊,可實現日常絕大部分操作。
- 配置簡單、功能強大、擴展性強;
- 支持API及自定義模塊,可通過Python輕松擴展。
- 通過Playbooks來定制強大的配置、狀態管理。
- 輕量級,無需在客戶端安裝agent,更新時,只需在操作機上進行一次更新即可。
- 提供一個功能強大、操作性強的Web管理界面和REST API接口——AWX平臺。
- 支持非root用戶管理操作,支持sudo。
Ansible架構


核心組件構成:
- ansible(主體):ansible的核心程序,提供一個命令行接口給用戶對ansible進行管理操作;
- Host Inventory(主機清單):為Ansible定義了管理主機的策略。一般小型環境下我們只需要在host文件中寫入主機的IP地址即可,但是到了中大型環境我們有可能需要使用靜態inventory或者動態主機清單來生成我們所需要執行的目標主機。
- Core Modules(核心模塊):Ansible執行命令的功能模塊,多數為內置的核心模塊。
- Custom Modules(拓展模塊):如何ansible自帶的模塊無法滿足我么你的需求,用戶可自定義相應的模塊來滿足自己的需求。
- Connection Plugins(連接插件):模塊功能的補充,如連接類型插件、循環插件、變量插件、過濾插件等,該功能不常用
- Playbook(任務劇本):編排定義ansible任務集的配置文件,由ansible順序依次執行,通常是JSON格式的* YML文件
- API:供第三方程序調用的應用程序編程接口
Ansible能做什么?
ansible可以幫助運維人員完成一些批量任務,或者完成一些需要經常重復的工作。
- 比如:同時在100臺服務器上安裝nginx服務,并在安裝后啟動服務。
- 比如:將某個文件一次性拷貝到100臺服務器上。
- 比如:每當有新服務器加入工作環境時,運維人員都要為新服務器部署某個服務。
ansible的配置文件可以存放在任何位置,但配置文件有讀取順序。
- 最先查找$ANSIBLE_CONFIG變量對應的位置和文件
- 其次查找當前目錄下ansible.cfg
- 然后查找用戶家目錄下的.ansible.cfg
- 最后查找/etc/ansible/ansible.cfg(默認)
ansible 命令執行過程。
- 加載自己的配置文件,默認路徑為 /etc/ansible/ansible.cfg;
- 查找對應的主機配置文件,找到要執行的主機或者組;
- 加載自己對應的模塊文件,如 command;
- 通過ansible將模塊或命令生成對應的臨時py文件(python腳本), 并將該文件傳輸至遠程服務器;
- 對應執行用戶的家目錄的.ansible/tmp/XXX/XXX.py文件;
- 給文件 +x 執行權限;
- 執行并返回結果;
- 刪除臨時py文件,sleep 0退出;
其他詳情見官方文檔:【傳送門】
環境準備:
| 屬性 | 管理機 | 服務器-01 | 服務器-02 |
| 節點 | wenCheng | Server-01 | Server-02 |
| 系統 | CentOS Linux release 7.5.1804 (Minimal) | CentOS Linux release 7.5.1804 (Minimal) | CentOS Linux release 7.5.1804 (Minimal) |
| 內核 | 3.10.0-862.el7.x86_64 | 3.10.0-862.el7.x86_64 | 3.10.0-862.el7.x86_64 |
| SELinux | setenforce 0 | disabled | setenforce 0 | disabled | setenforce 0 | disabled |
| Firewlld | systemctl stop/disable firewalld | systemctl stop/disable firewalld | systemctl stop/disable firewalld |
| IP地址 | 172.16.70.37 | 172.16.70.181 | 172.16.70.182 |
Ansible常用參數及語法。
ansible官方模塊文檔:【傳送門】
ansible官方命令參數:【傳送門】
Ansible常用模塊
ping 模塊: 檢查指定節點機器是否還能連通,用法很簡單,不涉及參數,主機如果在線,則回復pong 。
raw 模塊: 執行原始的命令,而不是通過模塊子系統。
yum 模塊: RedHat和CentOS的軟件包安裝和管理工具。
apt 模塊: Ubuntu /Debian 的軟件包安裝和管理工具。
pip 模塊 : 用于管理Python庫依賴項,為了使用pip模塊,必須提供參數name或者requirements。
synchronize 模塊: 使用 rsync 同步文件,將主控方目錄推送到指定節點的目錄下。
template 模塊: 基于模板方式生成一個文件復制到遠程主機(template使用Jinjia2格式作為文件模版,進行文檔內變量的替換的模塊。
copy 模塊: 在遠程主機執行復制操作文件。
user 模塊 與 group 模塊: user模塊是請求的是 useradd , userdel, usermod 三個指令,goup模塊請求的是groupadd, groupdel, groupmod 三個指令。
service 或 systemd 模塊: 用于管理遠程主機的服務。
get_url 模塊: 該模塊主要用于從http、 ftp 、https服務器上下載文件(類似于wget)。
fetch 模塊: 它用于從遠程機器獲取文件,并將其本地存儲在由主機名組織的文件樹中。
file 模塊: 主要用于遠程主機上的文件操作。
lineinfile 模塊: 遠程主機上的文件編輯模塊
unarchive模塊: 用于解壓文件。
command 模塊 和 shell模塊: 用于在各被管理節點運行指定的命令. shell和 command 的區別:shell模塊可以特殊字符,而 command 是不支持
hostname 模塊: 修改遠程主機名的模塊。
script模塊: 在遠程主機上執行主控端的腳本,相當于 scp +shell組合。
stat模塊: 獲取遠程文件的狀態信息,包括atime,ctime,mtime,md5,uid,gid等信息。
cron 模塊: 遠程主機 crontab 配置。
mount 模塊: 掛載文件系統。
find 模塊: 幫助在被管理主機中查找符合條件的文件,就像 find 命令一樣。
selinux模塊:遠程管理受控節點的selinux的模塊
Ansible語法及配置參數
語法格式:
ansible <pattern_goes_here> -m <module_name> -a <arguments>
也就是:
ansible 匹配模式 -m 模塊 -a '需要執行的內容'
解釋說明:
匹配模式:即哪些機器生效 (可以是某一臺, 或某一組, 或all) , 默認模塊為 command , 執行常規的shell命令.
-a MODULE_ARGS #模塊的參數,如果執行默認COMMAND的模塊,即是命令參數,如: “date”,“pwd”等等
-k,--ask-pass #ask for SSH password。登錄密碼,提示輸入SSH密碼而不是假設基于密鑰的驗證
--ask- su -pass #ask for su password。su切換密碼
-K,--ask- sudo -pass #ask for sudo password。提示密碼使用sudo,sudo表示提權操作
--ask-vault-pass #ask for vault password。假設我們設定了加密的密碼,則用該選項進行訪問
-B SECONDS #后臺運行超時時間
-C #模擬運行環境并進行預運行,可以進行查錯測試
-c CONNECTION #連接類型使用
-f FORKS #并行任務數,默認為5
-i INVENTORY #指定主機清單的路徑,默認為/etc/ansible/hosts
--list-hosts #查看有哪些主機組
-m MODULE_NAME #執行模塊的名字,默認使用 command 模塊,所以如果是只執行單一命令可以不用 -m參數
-o #壓縮輸出,嘗試將所有結果在一行輸出,一般針對收集工具使用
-S #用 su 命令
-R SU_USER #指定 su 的用戶,默認為 root 用戶
-s #用 sudo 命令
-U SUDO_USER #指定 sudo 到哪個用戶,默認為 root 用戶
-T TIMEOUT #指定 ssh 默認超時時間,默認為10s,也可在配置文件中修改
-u REMOTE_USER #遠程用戶,默認為 root 用戶
- v #查看詳細信息,同時支持-vvv,-vvvv可查看更詳細信息
ansible-doc 命令常用于獲取模塊信息及其使用幫助,一般用法如下:
ansible-doc -l #獲取全部模塊的信息
ansible-doc -s MOD_NAME #獲取指定模塊的使用幫助
示例
[root@wenCheng ~] # ansible-doc -l | grep authorized_key
authorized_key Adds or removes an SSH authorized key
[root@wenCheng ~] # ansible-doc -s authorized_key
[root@wenCheng ~] # ansible-doc authorized_key
情景一:Ansible安裝部署及首次批量分發公鑰(管理機)。
- command模塊 和 shell模塊: 用于在各被管理節點運行指定的命令.;shell和command的區別:shell模塊可以特殊字符,而command是不支持。
[root@wenCheng ~] # yum install epel-release -y
[root@wenCheng ~] # yum install ansible -y
[root@wenCheng ~] # ansible --version
ansible 2.9.21
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, Apr 11 2018, 07:36:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]
[root@wenCheng ~] # rpm -qa | grep ansible
ansible-2.9.21-1.el7.noarch
[root@wenCheng ~] # rpm -ql ansible-2.9.21-1.el7.noarch | less
/etc/ansible/ansible .cfg #主配置文件,配置ansible工作特性
/etc/ansible/hosts #主機清單
/etc/ansible/roles/ #存放角色的目錄
/usr/bin/ansible #主程序,臨時命令執行工具
/usr/bin/ansible-doc #查看配置文檔,模塊功能查看工具
/usr/bin/ansible-galaxy #下載/上傳優秀代碼或Roles模塊的官網平臺
/usr/bin/ansible-playbook #定制自動化任務,編排劇本工具
/usr/bin/ansible-pull #遠程執行命令的工具
/usr/bin/ansible-vault #文件加密工具
/usr/bin/ansible-console #基于Console界面與用戶交互的執行工具
......
# 備份配置
[root@wenCheng ~] # cp /etc/ansible/hosts{,.bak}
[root@wenCheng ~] # cp /etc/ansible/ansible.cfg{,.bak}
[root@wenCheng ~] # vim /etc/ansible/hosts
......
# 末行添加內容
# 遠程主機(根據實際情況):單IP/IP段 用戶名 密碼 端口;下面舉例2類形式
[type1]
172.16.70.181
172.16.70.182
[type1:vars]
ansible_user= 'root'
ansible_pass= 'centos'
ansible_port= '22'
[type2]
172.16.70.[181:182] ansible_user= 'root' ansible_pass= 'centos' ansible_port= '22'
[root@wenCheng ~] # vim /etc/ansible/ansible.cfg
......
host_key_checking = False # 首次連接是否需要檢查key認證,取消注釋以禁用主機的ssh的密鑰檢查
......
/var/log/ansible .log # 取消注釋以記錄日志信息
# 新建yaml文件
[root@wenCheng ~] # cat /root/ssh_key.yml
---
- hosts: all # 遠程主機組
tasks:
- name: send id_rsa.pub
authorized_key: user=root key= "{{ lookup('file', '/root/.ssh/id_rsa.pub') }}" # 被控制的遠程服務上的用戶名 本機的公鑰地址
# 執行批量公鑰分發
[root@wenCheng ~] # ansible-playbook ssh_key.yml
PLAY [all] ********************************************************************************************************************************
TASK [Gathering Facts] ********************************************************************************************************************
ok: [172.16.70.182]
ok: [172.16.70.181]
TASK [send id_rsa.pub] ********************************************************************************************************************
ok: [172.16.70.181]
ok: [172.16.70.182]
PLAY RECAP ********************************************************************************************************************************
172.16.70.181 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
172.16.70.182 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
# 驗證結果
[root@wenCheng ~] # ansible all -m command -a "hostname"
172.16.70.182 | CHANGED | rc=0 >>
Server-02
172.16.70.181 | CHANGED | rc=0 >>
Server-01
[root@wenCheng ~] # ansible all -m shell -a "hostname"
172.16.70.182 | CHANGED | rc=0 >>
Server-02
172.16.70.181 | CHANGED | rc=0 >>
Server-01
# command模塊不支持管道
[root@wenCheng ~] # ansible all -m command -a "cat /etc/passwd| grep centos"
172.16.70.181 | FAILED | rc=1 >>
cat : /etc/passwd |: No such file or directory
cat : grep : No such file or directory
cat : centos: No such file or directorynon-zero return code
172.16.70.182 | FAILED | rc=1 >>
cat : /etc/passwd |: No such file or directory
cat : grep : No such file or directory
cat : centos: No such file or directorynon-zero return code
[root@wenCheng ~] # ansible all -m shell -a "cat /etc/passwd| grep centos"
172.16.70.182 | CHANGED | rc=0 >>
centos:x:1000:1000:: /home/centos : /bin/bash
172.16.70.181 | CHANGED | rc=0 >>
centos:x:1000:1000:: /home/centos : /bin/bash
# 修改sshd_config文件,禁止使用密碼登錄
[root@wenCheng ~] # ansible all -m shell -a "sed -i.bak 's/^PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config"
[root@wenCheng ~] # ansible all -m shell -a "systemctl restart sshd"
情景二:管理機批量安裝軟件。
- yum 模塊: RedHat和CentOS的軟件包安裝和管理工具。
參數:
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表示安裝最新版本.
安裝 rsync :
[root@wenCheng ~] # ansible all -m yum -a "name=rsync state=present"
或
[root@wenCheng ~] # ansible all -m yum -a "name=http://mirror.centos.org/centos/7/os/x86_64/Packages/rsync-3.1.2-10.el7.x86_64.rpm state=present"
卸載 rsync :
[root@wenCheng ~] # ansible all -m yum -a "name=rsync state=removed"
情景三:管理機批量分發文件/目錄。
- synchronize 模塊: 使用rsync同步文件,將主控方目錄推送到指定節點的目錄下。
參數:
delete: 刪除不存在的文件,delete= yes 使兩邊的內容一樣(即以推送方為主),默認no
src: 要同步到目的地的源主機上的路徑; 路徑可以是絕對的或相對的。如果路徑使用”/”來結尾,則只復制目錄里的內容,如果沒有使用”/”來結尾,則包含目錄在內的整個內容全部復制
dest:目的地主機上將與源同步的路徑; 路徑可以是絕對的或相對的。
dest_port:默認目錄主機上的端口 ,默認是22,走的 ssh 協議。
mode: push或pull,默認push,一般用于從本機向遠程主機上傳文件,pull 模式用于從遠程主機上取文件。
rsync_opts:通過傳遞數組來指定其他 rsync 選項。
# 接情景二環境,并創建所需文件/目錄
[root@wenCheng ~] # tree /tmp/
/tmp/
├── dir_ansible1
│ └── 1
├── dir_ansible2
│ └── 2
├── dir_ansible3
│ └── 3
├── dir_ansible4
│ └── 4
├── file_ansible1
├── file_ansible2
├── file_ansible3
└── file_ansible4
4 directories, 8 files
# 推送文件/tmp/file_ansible1到遠程主機目錄/tmp下
[root@wenCheng ~] # ansible all -m synchronize -a 'src=/tmp/file_ansible1 dest=/tmp'
# 推送文件/tmp/file_ansible2到遠程主機目錄并覆蓋原文件/tmp/file_ansible1
[root@wenCheng ~] # ansible all -m synchronize -a 'src=/tmp/file_ansible2 dest=/tmp/file_ansible1'
# 推送目錄/tmp/dir_ansible1到遠程主機目錄/tmp下(保留遠程主機原/tmp內容不變再新增dir_ansible1目錄)
[root@wenCheng ~] # ansible all -m synchronize -a 'src=/tmp/dir_ansible1 dest=/tmp'
# 推送目錄/tmp/的所有文件或目錄到遠程主機目錄/tmp下,使內容一致,默認delete=no(刪除遠程主機原/tmp內容再同步推送的目錄)
[root@wenCheng ~] # ansible all -m synchronize -a "src=/tmp/ dest=/tmp delete=yes"
# 拉取遠程主機文件/etc/hostname到本地目錄/tmp
[root@wenCheng ~] # ansible all -m synchronize -a "src=/etc/hostname dest=/tmp rsync_opts='-a' mode=pull"
- 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 模塊里的選項都可以在這里使用;
特別注意: src和content不能同時使用。
# 拷貝本地目錄/tmp/dir_ansible1至遠程主機目錄/tmp
[root@wenCheng ~] # ansible all -m copy -a 'src=/tmp/dir_ansible1 dest=/tmp backup=yes'
# 拷貝本地文件/tmp/file_ansible1至遠程主機目錄/tmp,并修改屬組為centos,權限為400
[root@wenCheng ~] # ansible all -m copy -a 'src=/tmp/file_ansible1 dest=/tmp group=centos mode=400'
synchronize模塊與copy模塊區別:
- copy 模塊不支持從遠端到本地的拉去操作,fetch 模塊支持,但是 src 參數不支持目錄遞歸,只能回傳具體文件;
- copy 模塊的 remote_src 參數是指定從遠端服務器上往遠端服務器上復制,相當于在 shell 模塊中執行 copy 命令;
- synchronize 則支持文件下發和回傳,分別對應的 push 和 pull 模式。synchronize 模塊的功能依賴于 rsync,但是功能不依賴于 rsync 配置文件中定義的模塊;
- copy 模塊適用于小規模文件操作,synchronize 支持大規模文件操作
附: Ansible默認配置解析:
[root@wenCheng ~] # cat /etc/ansible/ansible.cfg
......
[defaults]
# some basic default values...
#inventory = /etc/ansible/hosts # 資源清單inventory文件的位置,腳本或連接管理主機列表
#library = /usr/share/my_modules/ # 庫文件存放目錄
#module_utils = /usr/share/my_module_utils/ # 模塊存放目錄
#remote_tmp = ~/.ansible/tmp # 臨時文件遠程主機存放目錄
#local_tmp = ~/.ansible/tmp # 臨時文件本地存放目錄
#plugin_filters_cfg = /etc/ansible/plugin_filters.yml # 拒絕模塊的配置文件
#forks = 5 # 默認開啟的并發數
#poll_interval = 15 # 默認輪詢的時間間隔
#sudo_user = root # 默認sudo用戶
#ask_sudo_pass = True # 是否需要sudo密碼
#ask_pass = True # 是否需要密碼
#transport = smart # 默認執行智能模式
#remote_port = 22 # 默認ssh遠程端口
#module_lang = C # 默認模塊和系統之間通信的計算機語言,默認為'C'語言
#module_set_locale = False # 默認設置本地環境變量
# plays will gather facts by default, which contain information about
# the remote system.
#
# smart - gather by default, but don't regather if already gathered
# implicit - gather by default, turn off with gather_facts: False
# explicit - do not gather by default, must say gather_facts: True
#gathering = implicit
# This only affects the gathering done by a play's gather_facts directive,
# by default gathering retrieves all facts subsets
# all - gather all subsets
# network - gather min and network facts
# hardware - gather hardware facts (longest facts to retrieve)
# virtual - gather min and virtual facts
# facter - import facts from facter
# ohai - import facts from ohai
# You can combine them using comma (ex: network,virtual)
# You can negate them using ! (ex: !hardware,!facter,!ohai)
# A minimal set of facts is always gathered.
#gather_subset = all
# some hardware related facts are collected
# with a maximum timeout of 10 seconds. This
# option lets you increase or decrease that
# timeout to something more suitable for the
# environment.
# gather_timeout = 10 # 收集一些與硬件相關的信息,允許根據系統情況來設置超時時間
# Ansible facts are available inside the ansible_facts.* dictionary
# namespace. This setting maintains the behaviour which was the default prior
# to 2.5, duplicating these variables into the main namespace, each with a
# prefix of 'ansible_'.
# This variable is set to True by default for backwards compatibility. It
# will be changed to a default of 'False' in a future release.
# ansible_facts.
# inject_facts_as_vars = True # 設置為True是為了向后兼容,為了維護2.5之前的默認行為
# additional paths to search for roles in, colon separated
#roles_path = /etc/ansible/roles # 搜索角色的其它路徑,冒號分隔
# uncomment this to disable SSH key host checking
#host_key_checking = False # 首次連接是否需要檢查key認證,取消注釋以禁用主機的ssh的密鑰檢查
# change the default callback, you can only have one 'stdout' type enabled at a time.
#stdout_callback = skippy # 更改默認回調的類型
## Ansible ships with some plugins that require whitelisting,
## this is done to avoid running all of a type by default.
## These setting lists those that you want enabled for your system.
## Custom plugins should not need this unless plugin author specifies it.
# enable callback plugins, they can output to stdout but cannot be 'stdout' type.
#callback_whitelist = timer, mail # 回調插件白名單,限制默認插件自動調用。如果是自定義插件則不需要
# Determine whether includes in tasks and handlers are "static" by
# default. As of 2.0, includes are dynamic by default. Setting these
# values to True will make includes behave more like they did in the
# 1.x versions. # 默認情況下,tasks和handlers是靜態。從2.0開始默認是動態
#task_includes_static = False
#handler_includes_static = False
# Controls if a missing handler for a notification event is an error or a warning
#error_on_missing_handler = True # 如果處理程序丟失是錯誤還是警告
# change this for alternative sudo implementations
#sudo_exe = sudo
# What flags to pass to sudo
# WARNING: leaving out the defaults might create unexpected behaviours
#sudo_flags = -H -S -n # 傳遞給sudo的標志,這里如果省略默認值可能會報錯
# SSH timeout
#timeout = 10 # 默認SSH超時時間
# default user to use for playbooks if user is not specified
# (/usr/bin/ansible will use current user as default)
#remote_user = root # /usr/bin/Ansible屬于哪個用戶,如果沒有給定,那么屬于playbook
# logging is off by default unless this path is defined
# if so defined, consider logrotate
#log_path = /var/log/ansible.log # 執行日志存放目錄
# default module name for /usr/bin/ansible
#module_name = command # 默認執行的模塊
# use this shell for commands executed under sudo
# you may need to change this to bin/bash in rare instances
# if sudo is constrained
#executable = /bin/sh
# if inventory variables overlap, does the higher precedence one win
# or are hash values merged together? The default is 'replace' but
# this can also be set to 'merge'.
#hash_behaviour = replace # 如果inventory變量重疊,優先級越高的會被使用
# by default, variables from roles will be visible in the global variable
# scope. To prevent this, the following option can be enabled, and only
# tasks and handlers within the role will see the variables there
#private_role_vars = yes # 默認情況下,角色中的變量將在全局變量中可見
# list any Jinja2 extensions to enable here:
#jinja2_extensions = jinja2.ext.do,jinja2.ext.i18n # Jinjia2所有可用的擴展名
# if set, always use this private key file for authentication, same as
# if passing --private-key to ansible or ansible-playbook
#private_key_file = /path/to/file # 使用私鑰文件進行身份驗證,私鑰的存儲位置
# If set, configures the path to the Vault password file as an alternative to
# specifying --vault-password-file on the command line.
#vault_password_file = /path/to/vault_password_file # 如果設置,則配置Vault密碼文件的路徑,以替代在命令行上指定--vault-password-file
# format of string {{ ansible_managed }} available within Jinja2
# templates indicates to users editing templates files will be replaced.
# replacing {file}, {host} and {uid} and strftime codes with proper values.
#ansible_managed = Ansible managed: {file} modified on %Y-%m-%d %H:%M:%S by {uid} on {host}
# {file}, {host}, {uid}, and the timestamp can all interfere with idempotence
# in some situations so the default is a static string:
#ansible_managed = Ansible managed
# by default, ansible-playbook will display "Skipping [host]" if it determines a task
# should not be run on a host. Set this to "False" if you don't want to see these "Skipping"
# messages. NOTE: the task header will still be shown regardless of whether or not the
# task is skipped.
#display_skipped_hosts = True
# 默認情況下,如果確定不應該在主機上運行任務,則ansible-playbook將顯示Skipping [host],如果你不想看到這條消息,將其設置為False
# by default, if a task in a playbook does not include a name: field then
# ansible-playbook will construct a header that includes the task's action but
# not the task's args. This is a security feature because ansible cannot know
# if the *module* considers an argument to be no_log at the time that the
# header is printed. If your environment doesn't have a problem securing
# stdout from ansible-playbook (or you have manually specified no_log in your
# playbook on all of the tasks where you have secret information) then you can
# safely set this to True to get more informative messages.
#display_args_to_stdout = False
# by default (as of 1.3), Ansible will raise errors when attempting to dereference
# Jinja2 variables that are not set in templates or action lines. Uncomment this line
# to revert the behavior to pre-1.3.
#error_on_undefined_vars = False
# by default (as of 1.6), Ansible may display warnings based on the configuration of the
# system running ansible itself. This may include warnings about 3rd party packages or
# other conditions that should be resolved if possible.
# to disable these warnings, set the following value to False:
#system_warnings = True
# by default (as of 1.4), Ansible may display deprecation warnings for language
# features that should no longer be used and will be removed in future versions.
# to disable these warnings, set the following value to False:
#deprecation_warnings = True
# (as of 1.8), Ansible can optionally warn when usage of the shell and
# command module appear to be simplified by using a default Ansible module
# instead. These warnings can be silenced by adjusting the following
# setting or adding warn=yes or warn=no to the end of the command line
# parameter string. This will for example suggest using the git module
# instead of shelling out to the git command.
# command_warnings = False
# set plugin path directories here, separate with colons # 插件的存儲位置,ansible將會自動執行下面的插件
#action_plugins = /usr/share/ansible/plugins/action
#become_plugins = /usr/share/ansible/plugins/become
#cache_plugins = /usr/share/ansible/plugins/cache
#callback_plugins = /usr/share/ansible/plugins/callback
#connection_plugins = /usr/share/ansible/plugins/connection
#lookup_plugins = /usr/share/ansible/plugins/lookup
#inventory_plugins = /usr/share/ansible/plugins/inventory
#vars_plugins = /usr/share/ansible/plugins/vars
#filter_plugins = /usr/share/ansible/plugins/filter
#test_plugins = /usr/share/ansible/plugins/test
#terminal_plugins = /usr/share/ansible/plugins/terminal
#strategy_plugins = /usr/share/ansible/plugins/strategy
# by default, ansible will use the 'linear' strategy but you may want to try
# another one
#strategy = free # 默認情況下,ansible將使用“linear”策略
# by default callbacks are not loaded for /bin/ansible, enable this if you
# want, for example, a notification or logging callback to also apply to
# /bin/ansible runs
#bin_ansible_callbacks = False
# 默認情況下沒有為/bin/ansible加載回調,如果你想要啟用它將其設置為True
# don't like cows? that's unfortunate.
# set to 1 if you don't want cowsay support or export ANSIBLE_NOCOWS=1
#nocows = 1 # 如果您不想要cowsay支持或導出ANSIBLE_NOCOWS = 1,則設置為1
# set which cowsay stencil you'd like to use by default. When set to 'random',
# a random stencil will be selected for each task. The selection will be filtered
# against the `cow_whitelist` option below.
#cow_selection = default
#cow_selection = random
# when using the 'random' option for cowsay, stencils will be restricted to this list.
# it should be formatted as a comma-separated list with no spaces between names.
# NOTE: line continuations here are for formatting purposes only, as the INI parser
# in python does not support them.
#cow_whitelist=bud-frogs,bunny,cheese,daemon,default,dragon,elephant-in-snake,elephant,eyes,\
# hellokitty,kitty,luke-koala,meow,milk,moofasa,moose,ren,sheep,small,stegosaurus,\
# stimpy,supermilker,three-eyes,turkey,turtle,tux,udder,vader-koala,vader,www
# don't like colors either?
# set to 1 if you don't want colors, or export ANSIBLE_NOCOLOR=1
#nocolor = 1
# if set to a persistent type (not 'memory', for example 'redis') fact values
# from previous runs in Ansible will be stored. This may be useful when
# wanting to use, for example, IP information from one group of servers
# without having to talk to them in the same playbook run to get their
# current IP information.
#fact_caching = memory # fact緩存的存儲類型。如果存儲在memory那么只是暫時的,你可以將其存儲在文件或者數據庫中
#This option tells Ansible where to cache facts. The value is plugin dependent.
#For the jsonfile plugin, it should be a path to a local directory.
#For the redis plugin, the value is a host:port:database triplet: fact_caching_connection = localhost:6379:0
#fact_caching_connection=/tmp # fact緩存的存儲路徑
# retry files
# When a playbook fails a .retry file can be created that will be placed in ~/
# You can enable this feature by setting retry_files_enabled to True
# and you can change the location of the files by setting retry_files_save_path
#retry_files_enabled = False
#retry_files_save_path = ~/.ansible-retry # 默認情況下,當playbook執行失敗時,將在~/創建.retry文件
# squash actions
# Ansible can optimise actions that call modules with list parameters
# when looping. Instead of calling the module once per with_ item, the
# module is called once with all items at once. Currently this only works
# under limited circumstances, and only with parameters named 'name'.
#squash_actions = apk,apt,dnf,homebrew,pacman,pkgng,yum,zypper
# prevents logging of task data, off by default
#no_log = False # Ansible可以優化在循環時使用列表參數調用模塊的操作
# prevents logging of tasks, but only on the targets, data is still logged on the master/controller
#no_target_syslog = False # 防止記錄任務,但僅在目標上,數據仍記錄在主/控制器上
# controls whether Ansible will raise an error or warning if a task has no
# choice but to create world readable temporary files to execute a module on
# the remote machine. This option is False by default for security. Users may
# turn this on to have behaviour more like Ansible prior to 2.1.x. See
# https://docs.ansible.com/ansible/become.html#becoming-an-unprivileged-user
# for more secure ways to fix this than enabling this option.
#allow_world_readable_tmpfiles = False
# 控制Ansible是否會引發錯誤或警告,如果任務別無選擇,只能創建可讀的臨時文件來執行遠程計算機上的模塊。對于安全性,默認情況下此選項為False
# controls the compression level of variables sent to
# worker processes. At the default of 0, no compression
# is used. This value must be an integer from 0 to 9.
#var_compression_level = 9 # 控制發送到工作進程的變量的壓縮級別。 默認值為0時,不使用壓縮。 該值必須是0到9之間的整數
# controls what compression method is used for new-style ansible modules when
# they are sent to the remote system. The compression types depend on having
# support compiled into both the controller's python and the client's python.
# The names should match with the python Zipfile compression types:
# * ZIP_STORED (no compression. available everywhere)
# * ZIP_DEFLATED (uses zlib, the default)
# These values may be set per host via the ansible_module_compression inventory
# variable
#module_compression = 'ZIP_DEFLATED' # 控制將ansible模塊發送到遠程系統時使用的壓縮方法
# This controls the cutoff point (in bytes) on --diff for files
# set to 0 for unlimited (RAM may suffer!).
#max_diff_size = 1048576
# 這將控制文件的--diff的截止點(以字節為單位),設置為0表示無限制(RAM可能會受損!)
# This controls how ansible handles multiple --tags and --skip-tags arguments
# on the CLI. If this is True then multiple arguments are merged together. If
# it is False, then the last specified argument is used and the others are ignored.
# This option will be removed in 2.8.
#merge_multiple_cli_flags = True
# 這將控制ansible如何在CLI上處理多個--tags和--skip-tags參數。如果這是True,則將多個參數合并在一起。如果為False,則使用最后指定的參數,并忽略其他參數
# Controls showing custom stats at the end, off by default
#show_custom_stats = True # 最后顯示自定義統計信息的控件,默認情況下已關閉
# Controls which files to ignore when using a directory as inventory with
# possibly multiple sources (both static and dynamic)
#inventory_ignore_extensions = ~, .orig, .bak, .ini, .cfg, .retry, .pyc, .pyo
# 控制將目錄用作具有可能多個源(靜態和動態)的庫存時要忽略的文件
# This family of modules use an alternative execution path optimized for network appliances
# only update this setting if you know how this works, otherwise it can break module execution
#network_group_modules=eos, nxos, ios, iosxr, junos, vyos
# 此系列模塊使用針對網絡設備優化的替代執行路徑,只有在您了解其工作原理的情況下才更新此設置,否則會破壞模塊執行
# When enabled, this option allows lookups (via variables like {{lookup('foo')}} or when used as
# a loop with `with_foo`) to return data that is not marked "unsafe". This means the data may contain
# jinja2 templating language which will be run through the templating engine.
# ENABLING THIS COULD BE A SECURITY RISK
#allow_unsafe_lookups = False
#啟用時,此選項允許查找(通過{{lookup('foo')}}之類的變量或當用作帶有“with_foo”的循環時)返回未標記為“不安全”的數據
# set default errors for all plays
#any_errors_fatal = False # 為所有的操作設置默認錯誤
[inventory]
# enable inventory plugins, default: 'host_list', 'script', 'auto', 'yaml', 'ini', 'toml'
#enable_plugins = host_list, virtualbox, yaml, constructed # 默認啟動的插件
# ignore these extensions when parsing a directory as inventory source
#ignore_extensions = .pyc, .pyo, .swp, .bak, ~, .rpm, .md, .txt, ~, .orig, .ini, .cfg, .retry # 在將目錄解析為庫存源時忽略這些擴展
# ignore files matching these patterns when parsing a directory as inventory source
#ignore_patterns= # 在將目錄解析為庫存源時忽略與這些模式匹配的文件
# If 'true' unparsed inventory sources become fatal errors, they are warnings otherwise.
#unparsed_is_failed=False # 如果'true'未解析的庫存來源成為致命錯誤,則會發出警告
[privilege_escalation] # 權限提升設置
#become=True
#become_method=sudo
#become_user=root
#become_ask_pass=False
[paramiko_connection] # 該部分功能不常用,了解即可。
# uncomment this line to cause the paramiko connection plugin to not record new host
# keys encountered. Increases performance on new host additions. Setting works independently of the
# host key checking setting above.
#record_host_keys=False # 不記錄新主機的Key,以提示效率
# by default, Ansible requests a pseudo-terminal for commands executed under sudo. Uncomment this
# line to disable this behaviour.
#pty=False # 禁用sudo功能, 取消注釋此行以禁用此行為
# paramiko will default to looking for SSH keys initially when trying to
# authenticate to remote devices. This is a problem for some network devices
# that close the connection after a key failure. Uncomment this line to
# disable the Paramiko look for keys function
#look_for_keys = False # 默認初始查找SSH密鑰,取消注釋此行以禁用Paramiko查找鍵功能
# When using persistent connections with Paramiko, the connection runs in a
# background process. If the host doesn't already have a valid SSH key, by
# default Ansible will prompt to add the host key. This will cause connections
# running in background processes to fail. Uncomment this line to have
# Paramiko automatically add host keys.
#host_key_auto_add = True # 默認提示首次添加主機密鑰,取消注釋此行以使Paramiko自動添加主機密鑰
[ssh_connection] # Ansible默認使用SSH協議連接對端主機,該部署是主要是SSH連接的一些配置,但配置項較少,多數默認即可。
# ssh arguments to use
# Leaving off ControlPersist will result in poor performance, so use
# paramiko on older platforms rather than removing it, -C controls compression use
#ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s
# 要使用的ssh參數離開ControlPersist會導致性能不佳,所以在較舊的平臺上使用paramiko而不是刪除它,-C控制壓縮使用
# The base directory for the ControlPath sockets.
# This is the "%(directory)s" in the control_path option
#
# Example:
# control_path_dir = /tmp/.ansible/cp
#control_path_dir = ~/.ansible/cp
# The path to use for the ControlPath sockets. This defaults to a hashed string of the hostname,
# port and username (empty string in the config). The hash mitigates a common problem users
# found with long hostnames and the conventional %(directory)s/ansible-ssh-%%h-%%p-%%r format.
# In those cases, a "too long for Unix domain socket" ssh error would occur.
#
# Example:
# control_path = %(directory)s/%%h-%%r # 用于ControlPath套接字的路徑。 默認為主機名,端口和用戶名的散列字符串(配置中為空字符串)
#control_path =
# Enabling pipelining reduces the number of SSH operations required to
# execute a module on the remote server. This can result in a significant
# performance improvement when enabled, however when using "sudo:" you must
# first disable 'requiretty' in /etc/sudoers
#
# By default, this option is disabled to preserve compatibility with
# sudoers configurations that have requiretty (the default on many distros).
#
#pipelining = False # 默認情況下,禁用此選項以保持兼容性,sudoers配置requiretty(許多發行版的默認設置)。
# Control the mechanism for transferring files (old)
# * smart = try sftp and then try scp [default]
# * True = use scp only
# * False = use sftp only
#scp_if_ssh = smart # 控制傳輸文件的機制(舊)smart|True|False
# Control the mechanism for transferring files (new)
# If set, this will override the scp_if_ssh option
# * sftp = use sftp to transfer files
# * scp = use scp to transfer files
# * piped = use 'dd' over SSH to transfer files
# * smart = try sftp, scp, and piped, in that order [default]
#transfer_method = smart # 控制傳輸文件的機制(新) sftp|scp|piped|smart
# if False, sftp will not use batch mode to transfer files. This may cause some
# types of file transfer failures impossible to catch however, and should
# only be disabled if your sftp version has problems with batch mode
#sftp_batch_mode = False # False為sftp將不使用批處理模式傳輸文件,并且只有在sftp版本的批處理模式出現問題時才應禁用
# The -tt argument is passed to ssh when pipelining is not enabled because sudo
# requires a tty by default.
#usetty = True # 未啟用管道傳輸時,-tt參數將傳遞給ssh,因為默認情況下sudo需要tty
# Number of times to retry an SSH connection to a host, in case of UNREACHABLE.
# For each retry attempt, there is an exponential backoff,
# so after the first attempt there is 1s wait, then 2s, 4s etc. up to 30s (max).
#retries = 3 # 重試與主機的SSH連接的次數
[persistent_connection]
# Configures the persistent connection timeout value in seconds. This value is
# how long the persistent connection will remain idle before it is destroyed.
# If the connection doesn't receive a request before the timeout value
# expires, the connection is shutdown. The default value is 30 seconds.
#connect_timeout = 30 # 持久連接超時時間,單位秒
# The command timeout value defines the amount of time to wait for a command
# or RPC call before timing out. The value for the command timeout must
# be less than the value of the persistent connection idle timeout (connect_timeout)
# The default value is 30 second.
#command_timeout = 30 # 命令超時時間,必須小持于久連接空閑超時的時間,單位秒
[accelerate] # 該配置項在提升Ansibile連接速度時會涉及,多數保持默認即可。
#accelerate_port = 5099 # 加速連接端口
#accelerate_timeout = 30 # 命令執行超時時間,單位秒
#accelerate_connect_timeout = 5.0 # 連接超時時間,單位秒
# The daemon timeout is measured in minutes. This time is measured
# from the last activity to the accelerate daemon.
#accelerate_daemon_timeout = 30 # 上一個活動連接的時間,單位分鐘
# If set to yes, accelerate_multi_key will allow multiple
# private keys to be uploaded to it, though each user must
# have access to the system via SSH to add a new key. The default
# is "no".
#accelerate_multi_key = yes # 允許通過SSH使用多個私鑰
[selinux] # 關于selinux的相關配置幾乎不會涉及,保持默認配置即可。
# file systems that require special treatment when dealing with security context
# the default behaviour that copies the existing context or uses the user default
# needs to be changed to use the file system dependent context.
#special_context_filesystems=nfs,vboxsf,fuse,ramfs,9p,vfat
# Set this to yes to allow libvirt_lxc connections to work without SELinux.
#libvirt_lxc_noseclabel = yes
[colors] # Ansible對于輸出結果的顏色也進行了詳盡的定義且可配置,該選項對日常功能應用影響不大,幾乎不用修改
#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
[ diff ]
# Always print diff when running ( same as always running with -D/--diff )
# always = no # 在運行時始終打印diff(與使用-D / - diff 運行相同)
# Set how many context lines to show in diff
# context = 3 # 設置要在diff中顯示的上下文行數
********** 如果您認為這篇文章還不錯或者有所收獲,請點擊右下角的【推薦】/【贊助】按鈕,因為您的支持是我繼續創作分享的最大動力! **********
作者:講文張字
出處:http://www.rzrgm.cn/zhangwencheng
版權:本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出 原文鏈接
出處:http://www.rzrgm.cn/zhangwencheng
版權:本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出 原文鏈接
浙公網安備 33010602011771號