Ansible系列(一):基本配置和使用


我寫了更完善的Ansible專欄文章:一步到位玩兒透Ansible

Ansible系列文章:http://www.cnblogs.com/f-ck-need-u/p/7576137.html


Ansible是一種批量、自動部署工具,不僅可以批量,還可以自動。它主要基於ssh進行通信,不要求客戶端(被控制端)安裝ansible。

1.1 安裝Ansible

安裝方法有多種,可以下載源碼后編譯安裝,可以從git上獲取資源安裝,也可以rpm包安裝。rpm安裝需要配置epel源。

cat <<eof>>/etc/yum.repos.d/my.repo
[epel]
name=epel
baseurl=http://mirrors.aliyun.com/epel/7Server/x86_64/
enable=1
gpgcheck=0
eof

后面幾篇文章用到的環境。

主機描述 IP地址 主機名 操作系統
ansible6_server1 192.168.100.150 server1.longshuai.com CentOS 6.6
ansible6_node1 192.168.100.59 node1.longshuai.com CentOS 6.6
ansible6_node2 192.168.100.60 node2.longshuai.com CentOS 6.6
ansible6_node3 192.168.100.61 node3.longshuai.com CentOS 6.6
ansible7_server2 192.168.100.62 server2.longshuai.com CentOS 7.2
ansible7_node1 192.168.100.63 anode1.longshuai.com CentOS 7.2
ansible7_node2 192.168.100.64 anode2.longshuai.com CentOS 7.2
ansible7_node3 192.168.100.65 anode3.longshuai.com CentOS 7.2

經多次測試,CentOS 6上安裝ansible 2.3版本有可能會非常慢,需要將ansible執行的結果使用重定向或者-t選項保存到文件中,下次執行才會快。

shell> yum -y install ansible
/etc/ansible/ansible.cfg
/etc/ansible/hosts
/etc/ansible/roles
/usr/bin/ansible
/usr/bin/ansible-2
/usr/bin/ansible-2.6
/usr/bin/ansible-connection
/usr/bin/ansible-console
/usr/bin/ansible-console-2
/usr/bin/ansible-console-2.6
/usr/bin/ansible-doc
/usr/bin/ansible-doc-2
/usr/bin/ansible-doc-2.6
/usr/bin/ansible-galaxy
/usr/bin/ansible-galaxy-2
/usr/bin/ansible-galaxy-2.6
/usr/bin/ansible-playbook
/usr/bin/ansible-playbook-2
/usr/bin/ansible-playbook-2.6
/usr/bin/ansible-pull
/usr/bin/ansible-pull-2
/usr/bin/ansible-pull-2.6
/usr/bin/ansible-vault
/usr/bin/ansible-vault-2
/usr/bin/ansible-vault-2.6

使用ansible-doc可以列出相關的幫助。

ansible-doc -h
Usage: ansible-doc [options] [module...]

Options:
  -a, --all             Show documentation for all modules
  -h, --help            show this help message and exit
  -l, --list            List available modules
  -M MODULE_PATH, --module-path=MODULE_PATH
                        specify path(s) to module library (default=None)
  -s, --snippet         Show playbook snippet for specified module(s)
  -v, --verbose         verbose mode (-vvv for more, -vvvv to enable
                        connection debugging)
  --version             show program's version number and exit

其中"-l"選項用於列出ansible的模塊,通常結合grep來篩選。例如找出和yum相關的可用模塊。

ansible-doc -l | grep yum
yum                                Manages packages with the `yum' package manager yum_repository Add or remove YUM repositories

再使用"-s"選項可以獲取指定模塊的使用幫助。例如,獲取yum模塊的使用語法。

ansible-doc -s yum
- name: Manages packages with the `yum' package manager
  action: yum
      conf_file           # The remote yum configuration file to use for the transaction. disable_gpg_check # Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if state is `present' or `latest'. disablerepo # `Repoid' of repositories to disable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a ",". enablerepo # `Repoid' of repositories to enable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a ",". exclude # Package name(s) to exclude when state=present, or latest installroot # Specifies an alternative installroot, relative to which all packages will be installed. list # Package name to run the equivalent of yum list <package> against. name= # Package name, or package specifier with version, like `name-1.0'. When using state=latest, this can be '*' which means run: yum -y update. You can also pass a url or a local path to a rpm file(using state=present). To operate on several packages this can accept a comma separated list of packages or (as of 2.0) a list of packages. skip_broken # Resolve depsolve problems by removing packages that are causing problems from the trans‐ action. state # Whether to install (`present' or `installed', `latest'), or remove (`absent' or `removed') a package. update_cache # Force yum to check if cache is out of date and redownload if needed. Has an effect only if state is `present' or `latest'. validate_certs # This only applies if using a https url as the source of the rpm. e.g. for localinstall. If set to `no', the SSL certificates will not be validated. This should only set to `no' used on personally controlled sites using self-signed certificates as it avoids verifying the source site. Prior to 2.1 the code worked as if this was set to `yes'.

例如使用yum安裝unix2dos包。

ansible 192.168.100.60 -m yum -a "name=unix2dos state=present"

其中192.168.100.60是被ansible遠程控制的機器,即要在此機器上安裝unix2dos,下一小節將說明如何指定待控制主機。"-m"指定模塊名稱,"-a"用於為模塊指定各模塊參數,例如name和state。

ansible命令選項和各模塊的使用方法見:Ansible系列(二):選項和常用模塊

1.2 配置ansible

1.2.1 環境配置

Ansible配置以ini格式存儲配置數據,在Ansible中幾乎所有配置都可以通過Ansible的Playbook或環境變量來重新賦值。在運行Ansible命令時,命令將會按照以下順序查找配置文件。

  • ANSIBLE_CONFIG:首先,Ansible命令會檢查環境變量,及這個環境變量指向的配置文件。
  • ./ansible.cfg:其次,將會檢查當前目錄下的ansible.cfg配置文件。
  • ~/.ansible.cfg:再次,將會檢查當前用戶home目錄下的.ansible.cfg配置文件。
  • /etc/ansible/ansible.cfg:最后,將會檢查在用軟件包管理工具安裝Ansible時自動產生的配置文件。

1、使用化境變量方式來配置

大多數的Ansible參數可以通過設置帶有ANSIBLE_開頭的環境變量進行配置,參數名稱必須都是大寫字母,如下配置:

export ANSIBLE_SUDO_USER=root

設置了環境變量之后,ANSIBLE_SUDO_USER就可以在后續操作中直接引用。

2、設置ansible.cfg配置參數

Ansible有很多配置參數,以下是幾個默認的配置參數:

inventory = /etc/ansible/hosts
library = /usr/share/my_modules/
forks = 5
sudo_user = root
remote_port = 22
host_key_checking = False
timeout = 20
log_path = /var/log/ansible.log

inventory:該參數表示inventory文件的位置,資源清單(inventory)就是Ansible需要連接管理的一些主機列表。
library:Ansible的所有操作都使用模塊來執行實現,這個library參數就是指向存放Ansible模塊的目錄。
forks:設置默認情況下Ansible最多能有多少個進程同時工作,默認5個進程並行處理。具體需要設置多少個,可以根據控制端性能和被管理節點的數量來確定。
sudo_user:設置默認執行命令的用戶,也可以在playbook中重新設置這個參數。
remote_port:指定連接被管理節點的管理端口,默認是22,除非設置了特殊的SSH端口,否則不需要修改此參數。
host_key_checking:設置是否檢查SSH主機的密鑰。可以設置為True或False。即ssh的主機再次驗證。
timeout:設置SSH連接的超時間隔,單位是秒。
log_path:Ansible默認不記錄日志,如果想把Ansible系統的輸出記錄到日志文件中,需要設置log_path。需要注意,模塊將會調用被管節點的(r)syslog來記錄,執行Ansible的用戶需要有寫入日志的權限。

1.2.2 SSH互信配置

將ansible server的ssh公鑰分發到各被管節點上。

在ansible6_server1和ansible_server2上:

ssh-keygen -t rsa -f ~/.ssh/id_rsa -N ''
ssh-copy-id root@192.168.100.59
ssh-copy-id root@192.168.100.60
ssh-copy-id root@192.168.100.61
ssh-copy-id root@192.168.100.62
ssh-copy-id root@192.168.100.63
ssh-copy-id root@192.168.100.64
ssh-copy-id root@192.168.100.65
ssh-copy-id root@192.168.100.150

也可以使用ansible自身來批量添加密鑰到被控節點上。使用ansible的authorized_key模塊即可。見后文常見模塊介紹部分。

以下是借助expect工具實現非交互式的ssh-copy-id,免得總是詢問遠程用戶的登錄密碼。

# 安裝expect
[root@server2 ~]# yum -y install expect

# expect腳本
[root@server2 ~]# cat auto_sshcopyid.exp 
#!/usr/bin/expect

set timeout 10
set user_hostname [lindex $argv 0]
set password [lindex $argv 1]

spawn ssh-copy-id $user_hostname
expect {
        "(yes/no)?"
        {
                send "yes\n"
                expect "*password: " { send "$password\n" }
        }
        "*password: " { send "$password\n" }
}

expect eof

# 批量調用expect的shell腳本
[root@server2 ~]# cat sshkey.sh 
#!/bin/bash 
ip=`echo -n "$(seq -s "," 59 65),150" | xargs -d "," -i echo 192.168.100.{}`
password="123456"
#user_host=`awk '{print $3}' /root/.ssh/id_rsa.pub`

for i in $ip;do
        /root/auto_sshcopyid.exp root@$i $password &>>/tmp/a.log
        ssh root@$i "echo $i ok"
done

# 執行shell腳本配置互信
[root@server2 ~]# chmod +x /root/{sshkey.sh,auto_sshcopyid.exp}
[root@server2 ~]# ./sshkey.sh

1.2.3 簡單測試

向默認的inventory文件/etc/ansible/hosts中添加上幾個被管節點清單。

在ansible6_server1上:

cat >>/etc/ansible/hosts<<eof
192.168.100.59
192.168.100.60
192.168.100.61
192.168.100.62
192.168.100.63
192.168.100.64
192.168.100.65
[centos6]
192.168.100.59
192.168.100.60
192.168.100.61
[centos7]
192.168.100.63
192.168.100.64
192.168.100.65
[centos:children]
centos6
centos7
eof

在ansible7_server2上:

cat >>/etc/ansible/hosts<<eof
192.168.100.150
192.168.100.59
192.168.100.60
192.168.100.61
192.168.100.63
192.168.100.64
192.168.100.65
[centos6]
192.168.100.59
192.168.100.60
192.168.100.61
[centos7]
192.168.100.63
192.168.100.64
192.168.100.65
[centos:children]
centos6
centos7
eof

使用ping模塊測試被管節點。能成功,說明ansible能控制該節點。

ansible 192.168.100.59 -m ping
ansible centos6 -m ping
192.168.100.59 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.100.60 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.100.61 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

如果要指定非root用戶運行ansible命令,則加上"--sudo"或"-s"來提升為sudo_user配置項所指定用戶的權限。

ansible webservers -m ping -u ansible --sudo

或者使用become提升權限。

ansible webservers -m ping -b --become-user=root --become-method=sudo

1.3 inventory

inventory用於定義ansible要管理的主機列表,可以定義單個主機和主機組。上面的/etc/ansible/hosts就是默認的inventory。下面展示了inventory常用的定義規則。

cat -n /etc/ansible/hosts
1 192.168.100.59:22
2 192.168.100.60 ansible_ssh_pass='123456' ansible_ssh_port=22
3 [nginx]
4 192.168.100.5[7:9]
5 [nginx:vars]
6 ansible_ssh_pass='123456'
7 [webservers:children]
8 nginx

第一行和第二行單獨定義主機,第一行帶上了連接被管節點的端口,第二行帶上了單獨傳遞給ssh的參數,分別是ssh連接時的登錄遠程用戶的密碼參數和ssh的連接端口。
第三行和第四行定義的是nginx主機組,該組中包含了192.168.100.57到59這3台主機。還支持字母的擴展,如"web[a-d]"。
第五行和第六行定義了要傳遞給nginx主機組的變量。若定義為"[all:vars]"或"[*:vars]"則表示傳遞給所有主機的變量。
第七和第八行定義了一個新的主機組webservers,該組的組成員有nginx組。

可以指定多個inventory配置文件,只需在ansible的配置文件如/etc/ansible/ansible.cfg中將inventory指令設置為對應的文件或目錄即可,如果是目錄,那么此目錄下的所有文件都是inventory文件。

inventory文件中可以使用一些內置變量,絕大多數ansible的連接和權限變量都可以在此使用,見ansible命令解釋。常見的有:

  • ansible_ssh_host: ansible使用ssh要連接的主機。
  • ansible_ssh_port: ssh的端口。默認為22。
  • ansible_ssh_user: ssh登錄的用戶名。默認為root。
  • ansible_ssh_pass: ssh登錄遠程用戶時的認證密碼。
  • ansible_ssh_private_key_file: ssh登錄遠程用戶時的認證私鑰。(?)
  • ansible_connection: 使用何種模式連接到遠程主機。默認值為smart(智能),表示當本地ssh支持持久連接(controlpersist)時采用ssh連接,否則采用python的paramiko ssh連接。
  • ansible_shell_type: 指定遠程主機執行命令時的shell解析器,默認為sh(不是bash,它們是有區別的,也不是全路徑)。
  • ansible_python_interpreter: 遠程主機上的python解釋器路徑。默認為/usr/bin/python。
  • ansible_*_interpreter:使用什么解釋器。例如,sh、bash、awk、sed、expect、ruby等等。

其中有幾個參數可以在配置文件ansible.cfg中指定,但指定的指令不太一樣,以下是對應的配置項:

  • remote_port: 對應於ansible_ssh_port。
  • remote_user: 對應於ansible_ssh_user。
  • private_key_file: 對應於ansible_ssh_private_key_file。
  • excutable: 對應於ansible_shell_type。但有一點不一樣,excutable必須指定全路徑,而后者只需指定basename。

如果定義了"ansible_ssh_host",那么其前面的主機名就稱為別名。例如,以下inventory文件中nginx就是一個別名,真正連接的對象是192.168.100.65。

nginx ansible_ssh_host=192.168.100.65 ansible_ssh_port=22

當inventory中有任何一台有效主機時,ansible就默認隱式地可以使用"localhost"作為本機,但inventory中沒有任何主機時是不允許使用它的,且"all"或"*"所代表的所有主機也不會包含localhost。例如:

ansible localhost -i /path/to/inventory_file -m MODULE -a "ARGS"
ansible all -i /path/to/inventory_file -m MODULE -a "ARGS"
ansible * -i /path/to/inventory_file -m MODULE -a "ARGS"

inventory_hostname是ansible中可以使用的一個變量,該變量代表的是每個主機在inventory中的主機名稱。例如"192.168.100.59"。這是目前遇到的第一個變量。


免責聲明!

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



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