Ansible之入門簡介

  1、ansible簡介html

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

  2、ansible的特色python

  一、無客戶端,只需安裝SSH、python便可,其中python建議版本2.6.6以上git

  二、基於openssh通訊,底層基於ssh協議(Windows基於powershell)github

  三、支持密碼和SSH認證,因能夠經過系統賬戶密碼認證或公鑰私鑰認證,因此整個過程簡單、方便、安全。web

  四、支持Windows,但僅支持被管理端是Windows,管理端必須是Linux系統 docker

  五、模塊化:調用特定的模塊,完成特定任務shell

  六、支持playbook編排任務(相似shell中的腳本)數據庫

  七、冪等性:一個任務執行一遍和執行N遍的效果同樣,不因重複執行帶來意外狀況編程

  八、可使用任何編程語言編寫模塊(python能夠調用其餘語言的庫)

  九、YAML格式,編排任務,支持豐富的數據結構

  3、ansible是如何工做的?

  Ansible沒有客戶端,所以底層通訊依賴系統軟件,在Linux系統下基於openssh通訊,在Windows下基於powershell,管理端必須是Linux系統,使用者認證經過後在管理節點經過ansible工具調用各應用模塊指令推送至被管理端執行,並在執行完畢後自動刪除產生的臨時文件。

  4、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網絡設備

  5、ansible的安裝

  一、rpm包安裝:epel源

yum install ansible -y

  二、編譯安裝

    2.一、安裝編譯須要的依賴文件

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

    2.二、下載源碼包,解壓源碼包

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

    2.三、進入到解壓後的目錄,運行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

  三、git方式

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

  四、pip安裝

    4.一、安裝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.二、pip安裝ansible

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

   說明:yum安裝的pip默認不是最新版本,因此要先更新pip

以上四種安裝選擇本身喜歡的方式安裝便可,安裝好了,咱們用ansible --version來肯定是否安裝成功

  6、ansible相關文件

    一、配置文件

      /etc/ansible/ansible.cfg主配置文件,配置ansible工做特性

      /etc/ansible/hosts主機清單

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

    二、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基於終端界面與用戶交互的執行工具

  7、主機清單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

  8、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驗證配置請參考本人博客http://www.javashuo.com/article/p-rjibahxc-bk.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的其餘用法,喜歡的朋友能夠加加關注。寫的很差,請你們指正,謝謝!!! 

相關文章
相關標籤/搜索