Linux下使用Ansible處理批量操作

上古南城發表於2021-07-14

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臺伺服器上。
  • 比如:每當有新伺服器加入工作環境時,運維人員都要為新伺服器部署某個服務。

其他詳情見官方文件https://docs.ansible.com/ansible/2.9/index.html

 環境準備:

屬性 管理機 伺服器-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常用引數及語法。使用詳情見官方模組文件:https://docs.ansible.com/ansible/2.9/modules

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命令. 

情景一: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_ssh_user='root' 
ansible_ssh_pass='centos' 
ansible_ssh_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的金鑰檢查

# 新建yaml檔案
[root@wenCheng ~]# cat /root/ssh_key.yaml
---
  - 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.yaml

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

情景二:管理機批量安裝軟體。

  • 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中顯示的上下文行數
 
 
 
 
 
 

相關文章