1. 程式人生 > >Ansible詳解(一)

Ansible詳解(一)

bash share cau 類型 isp 界面 echo unless try_files

一、運維相關概念介紹
二、ansible介紹
三、ansible命令
四、ansible常用模塊
五、ansible配置文件詳解

一、運維相關概念介紹
運維:Opreations
1.系統安裝:
bare metal:pxe(pre execute enviroment),cobbler
virtual machine:
pxe:依賴於網卡自身的功能(dhcp_client,FS_client),以及網絡中預先提供的服務
FS_client:加載bootloader文件,文件server驅動
但是為CentOS6安裝了PXE的話,只能安裝6的OS
cobbler:可以提供選擇界面,供用戶選擇
將多種pxe環境封裝整合

2.Configuration:應用程序:安裝配置啟動等
puppet(ruby)//應用廣泛,性能廣泛
saltstack(python) //穩定性增強中,後來者
puppet,saltstack都是重量級
ansible//相對輕量級
chef(ruby)
cfenginen
...
3.Command and Control:批量的命令執行,例如創建目錄
fabric(python)
func(相對重量級)
4.程序發布: //不能影響用戶體驗,
人工發布
腳本
發布程序(運維程序)
//發布模型(灰度模型)
發布路徑:
在調度器上下線一批主機(標記為維護模式)-->關閉服務-->部署新版本-->啟動服務-->在調度器上啟動這一批主機

二、ansible介紹
1.ansible能夠實現運維的所有工作
程序發布需要根據需求,自行設置,系統安裝正在開發階段
ansible:輕量化,
Configuration
Command and Control
規模更大時,建議使用puppet
支持:windows,debian系列,redhat系列
2.運維工具分類:
agent:RS上有client專用的監聽服務,更安全,
agentless(ssh):ansible,fabric
//ansible可以借助sshd也可以不使用sshd
管理主機需要管理被管理主機:需要被管理主機的特權權限
可以借助於ssh服務//
ansible:被redhat收購,1.5億美元
3.特性:
模塊化,調用特定模塊,完成特定任務
基於python語言實現,由Paramiko,PyYAML和jinja2三個關鍵模板
部署簡單:agentless;
支持自定義模塊
支持playbook;

冪等性:一個任務執行一遍和執行n遍的結果是一樣的

4.架構:
如圖一:
技術分享圖片---------------------------------------------------------------------
核心:ansible
核心模塊(Core Modules):這些都是ansible自帶的模塊
擴展模塊(Custom Modules):如果核心模塊不足以完成某種功能,可以添加擴展模塊
插件(Plugins):完成模塊功能的補充
劇本(Playbooks):ansible的任務配置文件,將多個任務定義在劇本中,由ansible自動執行。YAML格式
連接插件(Connectior Plugins):ansible基於連接插件連接到各個主機上,雖然ansible是使用ssh連接到各個主機的,但是它還支持其他的連接方法,所以需要有連接插件
Host Inventory:定義了被管理主機,Inventory:清單
Ansible要和管理節點之間ssh隧道打通
Ansible命令行管理主機(Ad-hoc command)
Ansible的“命令”(module)

5.Ansible Tower //商業化軟件
Ansile Tower則是針對企業級用戶的,中心化ansible管理節點。它向管理員提供Web頁面接口,來運行ansible腳本playbook。
管理員在ansible tower上使用和分享主機的ssh key,但是不能查看和拷貝key文件。
登錄ansible tower的所有管理員可以共享playbook腳本,減少重復工作。
此外ansible還可以收集和展現所有主機的playbook的執行狀況,便於統計和分析主機的狀態。

註意:假如被管控主機有例如ubuntu(apt-get,yum,dnf等)等其他的os的話,可以支持變量
條件判斷,判斷目標主機類型等 //puppet可以自動識別不同的OS,進行安裝

三、ansible命令
yum install ansible //epel源
[root@localhost ~]# rpm -ql ansible |egrep -v -i "man|share|lib"

/etc/ansible/ansible.cfg    配置文件:
/etc/ansible/hosts            主機清單
/etc/ansible/roles            
    
/usr/bin/ansible
/usr/bin/ansible-console
/usr/bin/ansible-doc        查看文檔
/usr/bin/ansible-galaxy    
/usr/bin/ansible-playbook
/usr/bin/ansible-pull    
/usr/bin/ansible-vault


1.ansible 命令
參數:
ansible host-pattern [-f forks] [-m module] [-a args]
ansible 192.168.0.102 -a 'date'
-a 'Arguments', --args='Arguments' 命令行參數
-m NAME, --module-name=NAME 執行模塊的名字,默認使用 command 模塊,所以如果是只執行單一命令可以不用 -m參數
-i PATH, --inventory=PATH 指定庫存主機文件的路徑,默認為/etc/ansible/hosts. //主機清單
-u Username, --user=Username 執行用戶,使用這個遠程用戶名而不是當前用戶
-U --sud-user=SUDO_User sudo到哪個用戶,默認為 root
-k --ask-pass 登錄密碼,提示輸入SSH密碼而不是假設基於密鑰的驗證
-K --ask-sudo-pass 提示密碼使用sudo
-s --sudo sudo運行
-S --su 用 su 命令
-l --list 顯示所支持的所有模塊
-s --snippet 指定模塊顯示劇本片段
-f --forks=NUM 並行任務數。NUM被指定為一個整數,默認是5。 #ansible testhosts -a "/sbin/reboot" -f 10 重啟testhosts組的所有機器,每次重啟10臺
--private-key=PRIVATE_KEY_FILE 私鑰路徑,使用這個文件來驗證連接
-v --verbose 詳細信息
all 針對hosts 定義的所有主機執行
-M MODULE_PATH, --module-path=MODULE_PATH 要執行的模塊的路徑,默認為/usr/share/ansible/
--list-hosts 只打印有哪些主機會執行這個 playbook 文件,不是實際執行該 playbook 文件
-o --one-line 壓縮輸出,摘要輸出.嘗試一切都在一行上輸出。
-t Directory, --tree=Directory 將內容保存在該輸出目錄,結果保存在一個文件中在每臺主機上。
-B 後臺運行超時時間
-P 調查後臺程序時間
-T Seconds, --timeout=Seconds 時間,單位秒s
-P NUM, --poll=NUM 調查背景工作每隔數秒。需要- b
-c Connection, --connection=Connection 連接類型使用。可能的選項是paramiko(SSH),SSH和地方。當地主要是用於crontab或啟動。
--tags=TAGS 只執行指定標簽的任務 例子:ansible-playbook test.yml --tags=copy 只執行標簽為copy的那個任務
--list-hosts 只打印有哪些主機會執行這個 playbook 文件,不是實際執行該 playbook 文件
--list-tasks 列出所有將被執行的任務
-C, --check 只是測試一下會改變什麽內容,不會真正去執行;相反,試圖預測一些可能發生的變化
--syntax-check 執行語法檢查的劇本,但不執行它
-l SUBSET, --limit=SUBSET 進一步限制所選主機/組模式 --limit=192.168.0.15 只對這個ip執行
--skip-tags=SKIP_TAGS 只運行戲劇和任務不匹配這些值的標簽 --skip-tags=copy_start
-e EXTRA_VARS, --extra-vars=EXTRA_VARS 額外的變量設置為鍵=值或YAML / JSON
#cat update.yml
---
- hosts: {{ hosts }}
remote_user: {{ user }}
..............
#ansible-playbook update.yml --extra-vars "hosts=vipers user=admin" 傳遞{{hosts}}、{{user}}變量,hosts可以是 ip或組名
-l,--limit 對指定的 主機/組 執行任務 --limit=192.168.0.10,192.168.0.11 或 -l 192.168.0.10,192.168.0.11 只對這個2個ip執行任務

2.ansible-doc是Ansible模塊文檔說明,
ansible-doc -l //查看所有的模塊
//查看具體某模塊的用法,這裏如查看command模塊
# ansible-doc -s command //查看詳細用法

3.Ansible-galaxy的功能可以簡單理解為GitHub或PIP的功能
https://galaxy.ansible.com/ 類似於github的roles庫
從Ansible-galaxy上,我們可以根據下載量和關註量等信息,查找和安裝優秀的Roles。
ansible-galaxy [init|info|install|list|remove]

init:初始化本地的Roles配置,以備上傳Roles至galaxy。
info:列表指定Role的詳細信息。
install:下載並安裝galaxy指定的Roles到本地。
list:列出本地已下載的Roles。
remove:刪除本地已下載的Roles。
ansible-doc -l //查看ansible支持的所有模塊

ansible-galaxy list --help //查看幫助信息
ansible-galaxy install patrik.uytterhoeven.Zabbix_Server //可以下載他人寫好的roles

4.ansible-lint
ansible-lint是對playbook的語法進行檢查的一個工具。用法是ansible-lint playbook.yml

5.ansible-playbook
該指令是使用最多的指令,其通過讀取playbook 文件後,執行相應的動作,這個後面會做為一個重點來講。

6.ansible-pull
該指令使用需要談到Ansible的另一種工作模式:pull 模式(Ansible默認使用push模式)。
這和通常使用的push模式工作機理剛好相反,其適用於以下場景:
(1)你有數量巨大的機器需要配置,即使使用高並發線程依舊要花費很多時間;
(2)你要在剛啟動的沒有網絡連接的主機上運行Anisble。

通常Ansible-pull結合git和crontab一並實現,其原理如下:通過crontab定期拉取指定的Git 版本到本地,
並以指定模式自動運行預先制訂好的指令。
ansible-pull [options] [playbook.yml]
*/20 * * * * root /usr/local/bin/ansible-pull -o -C 2.1.0 -d /srv/www/king-gw/ -i /etc/ansible/hosts -U git://git.kingifa.com/king-gw-ansiblepull >> /var/log/ansible-pull.log 2>&1

7.Ansible-vault主要用於配置文件加密,如編寫的Playbook配置文件包含敏感信息並且不希望其他人隨意查看,Ansible-vault可加密/解密這個配置文件
ansible-vault encrypt a.yml
ansible-vault decrypt a.yml

8. Ansible-console是Ansible為用戶提供的一款交互式工具

9.ansible-config
list // list all current configs reading lib/constants.py and shows env and config file setting names
dump // Shows the current settings, merges ansible.cfg if specified
--only-changed // Only show configurations that have changed from the default
view // Displays the current config file

ssh-keygen
ssh-copy-id -i .ssh/id_rsa.pub [email protected]
ssh-copy-id -i .ssh/id_rsa.pub [email protected]

ansible all -m ping //使用ping模塊測試主機是否在線
all :可以使用組名,websrvs,或者單個主機

四、ansible常用模塊
vim /etc/ansible/ansible.cfg
forks //多個目標主機的話,一次執行5個
模塊:
ansible-doc -l //列出所有模塊
command|shell|copy|cron|fetch|file|hostname|yum|service|uri|user
-s //snippet:片段,ansible對應的模塊的幫助片段信息,簡要幫助
例如:ansible-doc -s yum
1.command //在遠程主機上執行一個命令
ansible-doc -s command //這是在YAML中可以使用的
chdir:cd 到一個文件夾
creates:創建一個文件
executable:
remove:
warn:
ansible websrvs -m command -a 'ls /var' //-a指定參數
ansible websrvs -a 'ls /var' //-a指定參數, ,可省略
ansible websrvs -a 'cd /root ' -a 'ls'
註:command模塊是不支持管道的,需要調用shell模塊
輸入輸出重定向等,也要使用shell模塊
ansible websrvs -a 'echo test | passwd --stdin wolf' //這個並不能修改密碼,因為command是默認模塊,但是不支持管道
ansible websrvs -m shell -a 'echo test | passwd --stdin wolf'
2.shell模塊,支持shell特性,例如管道等
3.copy 復制本地文件到遠程位置
src :absolute or relative.絕對路徑或者相對路徑
dest= :目標路徑
mode
owner //目標文件的屬主和屬組
content 填充內容,而不是文件
ansible 192.168.4.110 -m copy -a "src=/etc/sysconfig/iptables-config dest=/root owner=root"
ansible 192.168.4.106 -m copy -a "content='test' dest=/root/aab mode=0600"
ansible 192.168.4.106 -m copy -a "src=/var/test dest=/var/ " //目錄復制
註:如果目標文件存在則直接覆蓋
4.cron //計劃任務
day,hour,month,weekday,minute
state={absent|present} //缺席,出席的//是要刪除任務還是添加任務
reboot,
name= //cron的名稱
job=

ansible all -m cron -a "minute=*/10 job='/usr/sbin/ntpdate 202.120.2.101 &> /dev/null' name=Synctime"
ansible all -m cron -a "state=absent name=Synctime"
//刪除任務,只需要指定state和name即可
5.fetch //拉取文件
dest=
src=
6.file //設置文件屬性
path= //目標文件
src //源,
state {directory,link,}
mode='u=rw,g=r,o=r' //或者mode=0644
owner
group
recurse //遞歸修改

ansible all -m file -a "src=/tmp/fstab path=/tmp/fstab.link state=link"
//為fstab創建鏈接文件為fstab.link
ansible all -m file -a "path=/tmp/dd state=directory"
創建目錄
ansible all -m file -a "path=/tmp/dd owner=wolf recurse=yes"
修改屬性
7.hostname //管理主機名
8.yum
disablerepo
enablerepo
list
name= //包名,可以指明版本號,name-1.0即可以
state={present|latest|absent} //latest最新版本
update_cache
config_file //指定yum配置文件
ansible all -m yum -a "name=httpd state=latest"
9.service //管理服務的
enabled=1/0 ,yes/no
named=
runlevel //默認2345
sleep
state={started,stopped,restarted}

ansible all -m service -a "name=httpd state=started"
//啟動服務
ansible all -m shell -a "ss -tnl |grep 80"
//查看狀態信息
10.uri
url=(http|https)://hosts.domain[:port]/path
passwd
use
r

tiemout
method //請求的方法

11.user //管理用戶賬號的
name=
password
append
remove //當state=absent的時候,同時刪除用戶的家目錄
expires
system=yes 系統用戶
uid,shell,group,groups,
state={absent|present
comment,
home,move_home
ansible all -m user -a "name=user2 system=yes uid=306 state=present"

五、ansible配置文件詳解
ansible.cfg //hosts會在後面解釋

ansible配置的優先級:
ANSIBLE_CONFIG(環境變量)-->current 目錄ansible.cfg --->家目錄 .ansible.cfg-->/etc/ansible/ansible.cfg
http://docs.ansible.com/ansible/intro_configuration.html#explanation-of-values-by-section
https://raw.githubusercontent.com/ansible/ansible/devel/examples/ansible.cfg

[defaults]   --->通用默認配置
# some basic default values...
inventory      = /etc/ansible/hosts     這個是默認庫文件位置,腳本,或者存放可通信主機的目錄
#library        = /usr/share/my_modules/   Ansible默認搜尋模塊的位置
remote_tmp     = $HOME/.ansible/tmp   Ansible 通過遠程傳輸模塊到遠程主機,然後遠程執行,執行後在清理現場.在有些場景下,你也許想使用默認路徑希望像更換補丁一樣使用
pattern        = *    如果沒有提供“hosts”節點,這是playbook要通信的默認主機組.默認值是對所有主機通信
forks          = 5    在與主機通信時的默認並行進程數 ,默認是5d
poll_interval  = 15    當具體的poll interval 沒有定義時,多少時間回查一下這些任務的狀態, 默認值是5秒
sudo_user      = root   sudo使用的默認用戶 ,默認是root
#ask_sudo_pass = True   用來控制Ansible playbook 在執行sudo之前是否詢問sudo密碼.默認為no
#ask_pass      = True    控制Ansible playbook 是否會自動默認彈出密碼
transport      = smart   通信機制.默認 值為’smart’。如果本地系統支持 ControlPersist技術的話,將會使用(基於OpenSSH)‘ssh’,如果不支持講使用‘paramiko’.其他傳輸選項包括‘local’, ‘chroot’,’jail’等等
#remote_port    = 22    遠程SSH端口。 默認是22
module_lang    = C   模塊和系統之間通信的計算機語言,默認是C語言
# 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   控制默認facts收集(遠程系統變量). 默認值為’implicit’, 每一次play,facts都會被收集
# additional paths to search for roles in, colon separated
#roles_path    = /etc/ansible/roles   roles 路徑指的是’roles/’下的額外目錄,用於playbook搜索Ansible roles
# uncomment this to disable SSH key host checking
#host_key_checking = False    //關閉第一次使用ansible連接客戶端是輸入命令提示
# change this for alternative sudo implementations
sudo_exe = sudo     如果在其他遠程主機上使用另一種方式執sudu操作.可以使用該參數進行更換
#what flags to pass to sudo   傳遞sudo之外的參數
#sudo_flags = -H
# SSH timeout    SSH超時時間
timeout = 10
# 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     ansible命令執行默認的模塊
# 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     在sudo環境下產生一個shell交互接口. 用戶只在/bin/bash的或者sudo限制的一些場景中需要修改
# 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    特定的優先級覆蓋變量
# list any Jinja2 extensions to enable here:
#jinja2_extensions = jinja2.ext.do,jinja2.ext.i18n      允許開啟Jinja2拓展模塊
# 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         私鑰文件存儲位置
# 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}   這個設置可以告知用戶,Ansible修改了一個文件,並且手動寫入的內容可能已經被覆蓋.
# 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     顯示任何跳過任務的狀態 ,默認是顯示
# 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      如果所引用的變量名稱錯誤的話, 將會導致ansible在執行步驟上失敗
# 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    允許禁用系統運行ansible相關的潛在問題警告
# 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     允許在ansible-playbook輸出結果中禁用“不建議使用”警告
# (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    當shell和命令行模塊被默認模塊簡化的時,Ansible 將默認發出警告
# set plugin path directories here, separate with colons
action_plugins     = /usr/share/ansible_plugins/action_plugins  
callback_plugins   = /usr/share/ansible_plugins/callback_plugins
connection_plugins = /usr/share/ansible_plugins/connection_plugins
lookup_plugins     = /usr/share/ansible_plugins/lookup_plugins
vars_plugins       = /usr/share/ansible_plugins/vars_plugins
filter_plugins     = /usr/share/ansible_plugins/filter_plugins
# 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    用來控制callback插件是否在運行 /usr/bin/ansible 的時候被加載. 這個模塊將用於命令行的日誌系統,發出通知等特性
# don't like cows?  that's unfortunate.
# set to 1 if you don't want cowsay support or export ANSIBLE_NOCOWS=1 
#nocows = 1    默認ansible可以調用一些cowsay的特性   開啟/禁用:0/1
# don't like colors either?
# set to 1 if you don't want colors, or export ANSIBLE_NOCOLOR=1
#nocolor = 1  輸出帶上顏色區別, 開啟/關閉:0/1
# the CA certificate path used for validating SSL certs. This path 
# should exist on the controlling node, not the target nodes
# common locations:
# RHEL/CentOS: /etc/pki/tls/certs/ca-bundle.crt
# Fedora     : /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
# Ubuntu     : /usr/share/ca-certificates/cacert.org/cacert.org.crt
#ca_file_path =    
# the http user-agent string to use when fetching urls. Some web server
# operators block the default urllib user agent as it is frequently used
# by malicious attacks/scripts, so we set it to something unique to 
# avoid issues.
#http_user_agent = ansible-agent
# 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
# retry files
#retry_files_enabled = False
#retry_files_save_path = ~/.ansible-retry
[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
# by default, Ansible requests a pseudo-terminal for commands executed under sudo. Uncomment this
# line to disable this behaviour.
#pty=False
[ssh_connection]
# ssh arguments to use
# Leaving off ControlPersist will result in poor performance, so use 
# paramiko on older platforms rather than removing it
#ssh_args = -o ControlMaster=auto -o ControlPersist=60s
    
# The path to use for the ControlPath sockets. This defaults to
# "%(directory)s/ansible-ssh-%%h-%%p-%%r", however on some systems with
# very long hostnames or very long path names (caused by long user names or 
# deeply nested home directories) this can exceed the character limit on
# file socket names (108 characters for most platforms). In that case, you 
# may wish to shorten the string below.
# 
# Example: 
# control_path = %(directory)s/%%h-%%r
#control_path = %(directory)s/ansible-ssh-%%h-%%p-%%r
# 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
# if True, make ansible use scp if the connection type is ssh 
# (default is sftp)
#scp_if_ssh = True
[accelerate]
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
[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 dependant context.
#special_context_filesystems=nfs,vboxsf,fuse
簡易配置:
[defaults]
inventory      = /etc/ansible/hosts
sudo_user=root
remote_port=22
host_key_checking=False
remote_user=root
log_path=/var/log/ansible.log
module_name=command
private_key_file=/root/.ssh/id_rsa
no_log:True


Ansible詳解(一)