天天看點

Ansible之入門簡介

Ansible之入門簡介

ansible是一款由python語言編寫的一款自動化運維工具,它集合了衆多運維工具(puppet、cfengine、chef、func、fabric)優點,實作了批量系統配置、批量程式部署、批量運作指令等功能。它的創始人,Michael DeHaan(cobbler與Func軟體的作者),他在2012年3月9日釋出了ansible 0.01版。2015年10月17日被RedHat宣布收購。

  一、ansible簡介

  ansible是一款由python語言編寫的一款自動化運維工具,它集合了衆多運維工具(puppet、cfengine、chef、func、fabric)優點,實作了批量系統配置、批量程式部署、批量運作指令等功能。它的創始人,Michael DeHaan(cobbler與Func軟體的作者),他在2012年3月9日釋出了ansible 0.01版。2015年10月17日被RedHat宣布收購。

  二、ansible的特點

  1、無用戶端,隻需安裝SSH、python即可,其中python建議版本2.6.6以上

  2、基于openssh通信,底層基于ssh協定(Windows基于powershell)

  3、支援密碼和SSH認證,因可以通過系統帳戶密碼認證或公鑰私鑰認證,是以整個過程簡單、友善、安全。

  4、支援Windows,但僅支援被管理端是Windows,管理端必須是Linux系統 

  5、子產品化:調用特定的子產品,完成特定任務

  6、支援playbook編排任務(類似shell中的腳本)

  7、幂等性:一個任務執行一遍和執行N遍的效果一樣,不因重複執行帶來意外情況

  8、可以使用任何程式設計語言編寫子產品(python可以調用其他語言的庫)

  9、YAML格式,編排任務,支援豐富的資料結構

  三、ansible是如何工作的?

  Ansible沒有用戶端,是以底層通信依賴系統軟體,在Linux系統下基于openssh通信,在Windows下基于powershell,管理端必須是Linux系統,使用者認證通過後在管理節點通過ansible工具調用各應用子產品指令推送至被管理端執行,并在執行完畢後自動删除産生的臨時檔案。

  四、ansible的組成

Ansible之入門簡介

ansible主要組成部分有:

  ANSIBLE-PLAYBOOKS:任務劇本(任務集),編排定義ansible任務集的配置檔案,由ansible順序依次執行,通常是json格式的YAML檔案

  INVENTORY:ansible管理主機的清單/etc/ansible/hosts

  MODULES:ansible執行指令的功能子產品,多數為内置核心子產品,當然也可以自定義

  PLUGINS:子產品功能的補充,如連接配接類型插件、循環插件、變量插件、過濾插件等,該功能不常用

  API:供第三方程式調用的應用程式程式設計接口

  ANSIBLE:組合INVENTORY、API、MODULES、PLUGINS的綠框,可以了解為ansible指令工具,其為核心執行工具

ansible指令執行來源:

  user,普通使用者,即system administrator

  cmdb(配置管理資料庫)API調用

  public/private cloud api 調用

  user--->ansible-playbook---->ansible

利用ansible實作管理的方式有以下兩種:

  ad-hoc即ansible指令,主要用于臨時指令使用場景

  ansible-playbook主要用于長期規劃好的,大型項目的場景,需要有前提的規劃

ansible-playbook(劇本)執行過程:

  将已有編排好的任務集寫入Ansible-Playbook

  通過ansible-playbook指令分拆任務集至逐條ansible指令,按預定規則逐條執行

ansible主要操作對象:

  HOSTS主機

  NETWORKING網絡裝置

  五、ansible的安裝

  1、rpm包安裝:epel源

yum install ansible -y
      

  2、編譯安裝

    2.1、安裝編譯需要的依賴檔案

yum -y install python-jinja2 PyYAML python-paramiko python-babel python-crypto
      

    2.2、下載下傳源碼包,解壓源碼包

wget https://releases.ansible.com/ansible/ansible-latest.tar.gz
tar xf ansible-latest.tar.gz
      

    2.3、進入到解壓後的目錄,運作setup.py 編譯并安裝

cd ansible-2.9.0
python setup.py build
python setup.py install
      

    2.4建立ansible配置檔案目錄,并拷貝配置檔案到相應目錄下

mkdir /etc/ansible
cp -r examples/* /etc/ansible      

  3、git方式

git clone git://github.com/ansible/ansible.git --recursive
cd ./ansible
source ./hacking/env-setu
      

  4、pip安裝

    4.1、安裝python包管理工具pip,以及python開發庫,以及ansible依賴包

yum install python-pip python-devel
yum install gcc glibc-devel zibl-devel rpm-bulid openssl-devel
      

  說明:pip是安裝python包的管理器,類似yum

    4.2、pip安裝ansible

pip install --upgrade pip
pip install ansible --upgrade
      

   說明:yum安裝的pip預設不是最新版本,是以要先更新pip

以上四種安裝選擇自己喜歡的方式安裝即可,安裝好了,我們用ansible --version來确定是否安裝成功

  六、ansible相關檔案

    1、配置檔案

      /etc/ansible/ansible.cfg主配置檔案,配置ansible工作特性

      /etc/ansible/hosts主機清單

      /etc/ansible/roles/存放角色的目錄

    2、ansible程式相關檔案

      /usr/bin/ansible 主程式,臨時指令執行工具

      /usr/bin/ansible-doc 檢視配置文檔,子產品功能的工具

      /usr/bin/ansible-galaxy 下載下傳/上傳優秀代碼或角色子產品的官網平台

      /usr/bin/ansiable-playbook定制自動化任務,編排劇本工具

      /usr/bin/ansible-pull遠端執行指令的工具

      /usr/bin/ansible-vault檔案加密工具

      /usr/bin/ansible-console基于終端界面與使用者互動的執行工具

  七、主機清單inventory

  ansible的主要功能用于批量主機操作,為了便捷地使用其中的部分主機,可以在主機清單檔案中将其分組命名,預設的主機清單為/etc/ansible/hosts檔案。

# This is the default ansible 'hosts' file.
#
# It should live in /etc/ansible/hosts
#
#   - Comments begin with the '#' character
#   - Blank lines are ignored
#   - Groups of hosts are delimited by [header] elements
#   - You can enter hostnames or ip addresses
#   - A hostname/ip can be a member of multiple groups

# Ex 1: Ungrouped hosts, specify before any group headers.

## green.example.com
## blue.example.com
## 192.168.100.1
## 192.168.100.10

# Ex 2: A collection of hosts belonging to the 'webservers' group

## [webservers]
## alpha.example.org
## beta.example.org
## 192.168.1.100
## 192.168.1.110

# If you have multiple hosts following a pattern you can specify
# them like this:

## www[001:006].example.com

# Ex 3: A collection of database servers in the 'dbservers' group

## [dbservers]
## 
## db01.intranet.mydomain.net
## db02.intranet.mydomain.net
## 10.25.1.56
## 10.25.1.57

# Here's another example of host ranges, this time there are no
# leading 0s:

## db-[99:101]-node.example.com
      

  說明:/etc/ansible/hosts檔案給我們了幾個定義主機清單的示例,我們可以參考它給的示例來定義主機清單,/etc/ansible/hosts檔案遵循INI檔案風格,中括号中的字元為組名,可以将一個主機同時歸并到多個不同的組;其中未分組的主機,需要在任何組标題之前指定,也就是在第一個中括号以上來定義。若要分組,需要在中括号裡寫明組名,然後把對應的主機寫在中括号之下,和下一個中括号之間。如果我們有多個主機遵循我們指定的模式,我們可以把多個主機寫成像www[001:006].example.com,它表示www.001.example.com、www.002.example.com....www.006.example.com,相信看了以上給我們的示例樣本,我們可以根據自己的實際情況來定義主機清單。此外,若目标主機使用了非預設的ssh端口,還可以在主機名稱後面使用加冒号加端口号來标明。

  示例:

ntp.magedu.com
[webservers]
www1.magedu.com:2222
www2.magedu.com
[dbservers]
db1.magedu.com
db2.magedu.com
db3.magedu.com


[websrvs]
www[01:100].example.com
[dbsrvs]
db-[a:f].example.com
      

  八、ansible主配置檔案說明

ansible主配置檔案/etc/ansible/ansible.cfg一般情況我們保持預設,不去修改它。

[defaults]
#inventory = /etc/ansible/hosts # 主機清單配置檔案
#library = /usr/share/my_modules/ # 庫檔案存放目錄
#remote_tmp = $HOME/.ansible/tmp #臨時py指令檔案存放在遠端主機目錄
#local_tmp = $HOME/.ansible/tmp # 本機的臨時指令執行目錄
#forks = 5 # 預設并發數
#sudo_user = root # 預設sudo 使用者
#ask_sudo_pass = True #每次執行ansible指令是否詢問ssh密碼
#ask_pass = True
#remote_port = 22
#host_key_checking = False # 檢查對應伺服器的host_key,建議取消注釋
#log_path=/var/log/ansible.log #日志檔案
#module_name = command #預設子產品
      

  了解了ansible的簡介,安裝和基本配置檔案的說明我們接下來配置幾台主機來用一下ansible,感受下這個軟體的魅力

 首先我們要安裝ansible,和配置好主機清單,上面介紹了怎麼安裝和配置主機清單,這裡就不闡述了。

定義主機清單:

[websers]
192.168.0.128
192.168.0.218
[appsers]
192.168.0.217
      

  說明:本人用三個虛拟機分别模拟了三台伺服器,且ssh端口預設的22号端口,是以不用指定其ssh端口

檢視ansible指令用法

[root@docker ~]#ansible --help
Usage: ansible <host-pattern> [options]

Define and run a single task 'playbook' against a set of hosts

Options:
  -a MODULE_ARGS, --args=MODULE_ARGS
                        module arguments
  --ask-vault-pass      ask for vault password
  -B SECONDS, --background=SECONDS
                        run asynchronously, failing after X seconds
                        (default=N/A)
  -C, --check           don't make any changes; instead, try to predict some
                        of the changes that may occur
  -D, --diff            when changing (small) files and templates, show the
                        differences in those files; works great with --check
  -e EXTRA_VARS, --extra-vars=EXTRA_VARS
                        set additional variables as key=value or YAML/JSON, if
                        filename prepend with @
  -f FORKS, --forks=FORKS
                        specify number of parallel processes to use
                        (default=5)
  -h, --help            show this help message and exit
  -i INVENTORY, --inventory=INVENTORY, --inventory-file=INVENTORY
                        specify inventory host path or comma separated host
                        list. --inventory-file is deprecated
  -l SUBSET, --limit=SUBSET
                        further limit selected hosts to an additional pattern
  --list-hosts          outputs a list of matching hosts; does not execute
                        anything else
  -m MODULE_NAME, --module-name=MODULE_NAME
                        module name to execute (default=command)
  -M MODULE_PATH, --module-path=MODULE_PATH
                        prepend colon-separated path(s) to module library
                        (default=[u'/root/.ansible/plugins/modules',
                        u'/usr/share/ansible/plugins/modules'])
  --new-vault-id=NEW_VAULT_ID
                        the new vault identity to use for rekey
  --new-vault-password-file=NEW_VAULT_PASSWORD_FILES
                        new vault password file for rekey
  -o, --one-line        condense output
  -P POLL_INTERVAL, --poll=POLL_INTERVAL
                        set the poll interval if using -B (default=15)
  --syntax-check        perform a syntax check on the playbook, but do not
                        execute it
  -t TREE, --tree=TREE  log output to this directory
  --vault-id=VAULT_IDS  the vault identity to use
  --vault-password-file=VAULT_PASSWORD_FILES
                        vault password file
  -v, --verbose         verbose mode (-vvv for more, -vvvv to enable
                        connection debugging)
  --version             show program's version number and exit

  Connection Options:
    control as whom and how to connect to hosts

    -k, --ask-pass      ask for connection password
    --private-key=PRIVATE_KEY_FILE, --key-file=PRIVATE_KEY_FILE
                        use this file to authenticate the connection
    -u REMOTE_USER, --user=REMOTE_USER
                        connect as this user (default=None)
    -c CONNECTION, --connection=CONNECTION
                        connection type to use (default=smart)
    -T TIMEOUT, --timeout=TIMEOUT
                        override the connection timeout in seconds
                        (default=10)
    --ssh-common-args=SSH_COMMON_ARGS
                        specify common arguments to pass to sftp/scp/ssh (e.g.
                        ProxyCommand)
    --sftp-extra-args=SFTP_EXTRA_ARGS
                        specify extra arguments to pass to sftp only (e.g. -f,
                        -l)
    --scp-extra-args=SCP_EXTRA_ARGS
                        specify extra arguments to pass to scp only (e.g. -l)
    --ssh-extra-args=SSH_EXTRA_ARGS
                        specify extra arguments to pass to ssh only (e.g. -R)

  Privilege Escalation Options:
    control how and which user you become as on target hosts

    -s, --sudo          run operations with sudo (nopasswd) (deprecated, use
                        become)
    -U SUDO_USER, --sudo-user=SUDO_USER
                        desired sudo user (default=root) (deprecated, use
                        become)
    -S, --su            run operations with su (deprecated, use become)
    -R SU_USER, --su-user=SU_USER
                        run operations with su as this user (default=None)
                        (deprecated, use become)
    -b, --become        run operations with become (does not imply password
                        prompting)
    --become-method=BECOME_METHOD
                        privilege escalation method to use (default=sudo),
                        valid choices: [ sudo | su | pbrun | pfexec | doas |
                        dzdo | ksu | runas | pmrun ]
    --become-user=BECOME_USER
                        run operations as this user (default=root)
    --ask-sudo-pass     ask for sudo password (deprecated, use become)
    --ask-su-pass       ask for su password (deprecated, use become)
    -K, --ask-become-pass
                        ask for privilege escalation password

Some modules do not make sense in Ad-Hoc (include, meta, etc)      

  說明:上面幫助,我們了解了ansible指令的基本格式是ansible <host-pattern> [options],其中host-pattern表示比對主機的模式,這裡我們先大概的認為就是指定的主機吧,後續我們在說說比對的模式有哪些。這裡大概說一下常用選項 -a表示子產品的參數,-m表示指定子產品的名稱,ansible指令的基本格式是 ansible +指定主機(當然這個也可以是我們定義的主機清單的組名,指定組名,比對的就是其組名下的所有主機)+子產品的名稱  + 子產品的參數,大概意思就是 用ansible去操作哪些主機,用什麼子產品,幹什麼事(要做的操作就是對子產品傳遞參數)

檢視ping子產品使用方法

root@docker ~]#ansible-doc  ping   
> PING    (/usr/lib/python2.7/site-packages/ansible/modules/system/ping.py)

        A trivial test module, this module always returns `pong' on successful contact. It does
        not make sense in playbooks, but it is useful from `/usr/bin/ansible' to verify the
        ability to login and that a usable python is configured. This is NOT ICMP ping, this is
        just a trivial test module. For Windows targets, use the [win_ping] module instead.

OPTIONS (= is mandatory):

- data
        Data to return for the `ping' return value.
        If this parameter is set to `crash', the module will cause an exception.
        [Default: pong]


NOTES:
      * For Windows targets, use the [win_ping] module instead.

AUTHOR: Ansible Core Team, Michael DeHaan
        METADATA:
          status:
          - stableinterface
          supported_by: core
:
      

  說明:看到以上說明是不是有點像Linux man幫助的界面呀,我們可以了解為ansible-doc 就相當于檢視ansible子產品的man幫助,這個文檔顯示的比較詳細,但通常我們檢視其基本用法有一個選項 -s 可以檢視子產品的簡要說明和主要參數的說明,這個選項有點像我們Linux裡使用指令的 -h選項或--help選項,如下所示

[root@docker ~]#ansible-doc -s ping 
- name: Try to connect to host, verify a usable python and return `pong' on success
  ping:
      data:                  # Data to return for the `ping' return value. If this parameter is set to `crash', the
                               module will cause an exception.
[root@docker ~]#
      

  說明:用-s選項是不是更加快速的了解了ping子產品的基本使用說明,從上面的幫助資訊我們了解到ping子產品的主要功能就是嘗試去連接配接主機,若主機線上則傳回‘pong’

用ping子產品測試遠端主機是否線上

[root@docker ~]#ansible websers -m ping 
192.168.0.128 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.0.218 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
[root@docker ~]#ansible appsers -m ping 
192.168.0.217 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
[root@docker ~]#ansible all -m ping 
192.168.0.128 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.0.218 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.0.217 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
[root@docker ~]#
      

  說明:由于本人測試環境的三台主機,已經做好了ssh基于key驗證,是以沒有執行失敗的資訊傳回,也沒有提示輸入密碼,這裡值得說一下ansible預設就是用的ssh基于key驗證的方式去認證的(有關ssh基于key驗證配置請參考本人部落格https://www.cnblogs.com/qiuhom-1874/p/11783371.html),如果遠端主機未做SSH基于key驗證,則我們需要加選項 -k指定是使用者名密碼的方式認證,如下所示

[root@docker ~]#ansible all -m ping -k
SSH password: 
192.168.0.128 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.0.218 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.0.217 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
[root@docker ~]#
      

  說明:可以看到我們輸入了一個密碼,則三台主機都傳回了結果,這是為什麼呢?ansible認為我們的主機都是同一密碼,是以它會拿我們輸入的密碼去我們指定的主機上認證,如果認證成功,則傳回成功,失敗則傳回失敗,這樣一來不當緊,如果我們三個主機密碼不一樣呢?這樣就會給我們對管控遠端主機帶來諸多不便,是以建議各位在使用ansible之前做好SSH基于key認證。

以上就是ansible軟體的基本使用和介紹,後續本人将持續更新ansible的其他用法,喜歡的朋友可以加加關注。寫的不好,請大家指正,謝謝!!! 

作者:Linux-1874

出處:https://www.cnblogs.com/qiuhom-1874/

本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,否則保留追究法律責任的權利.

繼續閱讀