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

来源:http://www.cnblogs.com/f-ck-need-u/archive/2017/09/19/7553186.html
-Advertisement-
Play Games

本文目錄:1.1 安裝Ansible1.2 配置Ansible 1.2.1 環境配置 1.2.2 SSH互信配置 1.2.3 簡單測試1.3 inventory Ansible是一種批量、自動部署工具,不僅可以批量,還可以自動。它主要基於ssh進行通信,不要求客戶端(被控制端)安裝ansible。 ...


本文目錄:
1.1 安裝Ansible
1.2 配置Ansible
  1.2.1 環境配置
  1.2.2 SSH互信配置
  1.2.3 簡單測試
1.3 inventory


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 = /root/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。例如:

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

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

 

回到系列文章大綱:http://www.cnblogs.com/f-ck-need-u/p/7048359.html

轉載請註明出處:http://www.cnblogs.com/f-ck-need-u/p/7553186.html

註:若您覺得這篇文章還不錯請點擊下右下角的推薦,有了您的支持才能激發作者更大的寫作熱情,非常感謝!


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 之前在使用SQLyog的時候也沒有發現這樣問題,就是在使用NavicatPremium的時候這個問題讓我不能忍受,就是每次執行一條sql語句之後,即使是成功之後,下麵仍然有一條報錯信息,雖然是對總的結果來說沒有什麼影響,但是對於有些強迫症的一些人來說,這樣的報錯還是不能容忍的,我就再網上搜瞭解決方案 ...
  • 本篇文章是介紹的hadoop2.6.0的源碼編譯過程,經過實踐驗證是可以編譯成功的。 ...
  • 五筆碼 五筆碼 select comm.fun_spellcode_wb('資料庫') from dual 結果:ORY 函數 函數 ...
  • 原文發表於cu:2017-02-10 參考文檔: Elasticsearchyum文檔:https://www.elastic.co/guide/en/elasticsearch/reference/current/rpm.html Logstashyum文檔:https://www.elastic ...
  • 一,環境說明 dell vostro 1400筆記本,winxp sp3操作系統,ubuntu-9.10-desktop-i386.iso 寫這篇隨筆的時候我用的已經是ubuntu了。 我是在我的移動硬碟上的I盤中安裝的ubuntu,所以我先把這個盤的內容移到其它盤上了。 二,安裝過程 1,首先進入 ...
  • 用su 獲取root許可權 用yum -y install dhcp命令安裝dhcp服務(yum是基於RPM包管 理,自動下載RPM包並且安裝) 查看安裝後生成的配置文件 rpm -qc dhcp 編輯dhcp的配置文件 vim /etc/dhcp/dhcpd.conf 全局配置詳情: 使用subne ...
  • 版權聲明:本文為博主原創文章,未經博主允許不得轉載。 在上一節分析輸入子系統內的intput_handler軟體處理部分後,接下來我們開始寫input_dev驅動 本節目標: 實現鍵盤驅動,讓開發板的4個按鍵代表鍵盤中的L、S、空格鍵、回車鍵 1.先來介紹以下幾個結構體使用和函數,下麵代碼中會用到 ...
  • 一、前言 Linux操作系統至1991年10月5日誕生以來,就其開源性和自由性得到了很多技術大牛的青睞,每個Linux愛好者都為其貢獻了自己的一份力,不管是在Linux內核還是開源軟體等方面,都為我們後來人提供了一個良好的學習和研究環境。 本文主要通過裁剪現有Linux系統,根據自己的需要,打造一個 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...