ansible——自動化運維工具

Ansible

SSH-based configuration management, deployment, and task execution system

運維工具的分類:

agent:基于專用的agent程序完成管理功能,puppet, func, zabbix, …

agentless:基于ssh服務完成管理,ansible, fabric, …

架構:

Ansible Core

Modules:

         Core Modules

         Customed Modules

Host Iventory

         Files

         CMDB

PlayBooks

         Hosts

         roles

Connection Plugins:

特性:

模塊化:調用特定的模塊,完成特定的任務;

基于Python語言研發,由Paramiko, PyYAML和Jinja2三個核心庫實現

部署簡單:agentless;

支持自定義模塊,使用任意編程語言 

強大的playbook機制

冪等性

安裝及程序環境:

程序:

         ansible

         ansible-playbook

         ansible-doc

配置文件:

    /etc/ansible/ansible.cfg

主機清單:

    /etc/ansible/hosts

插件目錄:

    /usr/share/ansible_plugins/

基本使用:

ansible命令:

         Usage: ansible <host-pattern> [options]

        

         常用選項:

             -m MOD_NAME  -a MOD_ARGS

配置Host Inventory:

         /etc/ansible/hosts

         [group_id]

         HOST_PATTERN1

         HOST_PATTERN2

模塊:

         獲取模塊列表:ansible-doc -l

         獲取指定模塊的使用幫助:ansible-doc -s MOD_NAME

常用模塊:

ping:探測目標主機是否存活

    ansible all -m ping

command:在遠程主機執行命令;

         ansible all -m commond -a "ifconfig"

            

         commond模塊:不能理解管道命令,要調用shell模塊來執行

         ansible all -m commond -a "echo 'gmtest' | passwd –stdin centos"

shell:在遠程主機上調用shell解釋器運行命令,支持shell的各種功能,例如管道等

    ansible all -m shell -a "echo 'gmtest' | passwd –stdin centos"

注意:command和shell模塊的核心參數直接為命令本身;而其它模塊的參數通常為“key=value”格式

copy:Copies files to remote locations.

         用法:

                 (1) 復制文件

                     -a "src=  dest=  "

                 (2) 給定內容生成文件

                     -a "content=  dest=  "

                         dest中不指文件名,默認隨機生成文件名

                

                 其它參數:mode, owner, group, …

        

         ansible all -m copy -a "src=/etc/fstab dest=/tmp/test.gm mode =640"

         ansible all -m copy -a "content='hello\nworld\n' dest=/tmp/test.gm mode =640"

file:Sets attributes of files

         用法:

                 (1) 創建目錄:

                     -a "path=  state=directory"

                 (2) 創建鏈接文件:

                     -a "path=  src=  state=link"

                 (3) 刪除文件:

                     -a "path=  state=absent“

            

         ansible all -m file -a "path=/tmp/gm state=directory"

         ansible all -m file -a "path=/tmp/gm state=absent"

         ansible all -m file -a "path=/tmp/gm src=/etc/fstab state=link"

fetch:Fetches a file from remote nodes

    從遠端主機獲取文件,也可以使用scp命令實現

cron:Manage cron.d and crontab entries

         在遠端主機上設置周期性任務

         -a ""

                 minute=

                 hour=

                 day=

                 month=

                 weekday=

                 job=

                 name=

                 user=

                

                 state={present|absent}

                     state=absent+name="STRING":用于取消此任務計劃

            

         ansible all -mrcont cron -a "minute='*/5' job='/usr/sbin/ntpdate 10.1.0.1 &>/dev/null' name='sync time'"

         ansible all -m cront -a "name='sync time' state='absent'"

hostname:Manage hostname

    name=XXX

yum:Manages packages with the I(yum) package manager

        -a ""

                 (1) name=  state={present|latest}

                 (2) name=  state=absent

            

         ansible all -m yum "name=httpd"

         ansible all -m yum "name=httpd state=absent"

service:Manage services.

        -a ""

                 name=

                 state=

                 started

                 stopped

                 restarted

                 reloaded

                 enabled=  on|true

                     是否開機自啟動

                 runlevel=

            

         ansible websrvs -m yum -a "name=httpd "

         ansible websrvs -m service -a "name=httpd state=start enaled=true"

         ansible websrvs -m service -a "name=httpd state=started"

script:Runs a local script on a remote node after transferring it

         在遠端主機上運行一個本地的shell腳本

         -a ""

                 creates # 一個文件名,當這個文件存在,則該命令不執行

                 free_form= # 本地腳本路徑

                 removes # 一個文件名,這個文件不存在,則該命令不執行

                    

         ansible test -m script -a ‘/root/local.sh’

             主控端/root/下必須有local.sh腳本

group: Add or remove groups

         -a ""

                 name=

                 state= # Whether the group should be present or not on the remote host

                 system=

                 gid=

            

         ansible all -m group -a "name=gm state=present system=fails gid=2000"

user:Manage user accounts

        -a ""

                 name=

                 group=

                 groups=

                 comment=

                 uid=

                 system=

                 shell=

                 expires=

                 home=

        

         ansible all -m user -a "name=gm group=gm groups=tom uid=2000"

setup:Gathers facts about remote hosts

         獲取遠端主機關于ansible的變量

        

         ansible 10.1.0.68 -m setup

YAML:

YAML is a data serialization format designed for human readability and  interaction with scripting languages.

數據結構:

         key:value

        

         – item1

         – item2

         – item3

        

         {name:jerry, age:21}

PlayBook:

核心元素:

         Tasks:任務,由模塊定義的操作的列表

         Variables:變量

         Templates:模板,即使用了模板語法的文本文件

         Handlers:由特定條件觸發的Tasks

         Roles:角色

playbook的基礎組件:

         Hosts:運行指定任務的目標主機

         remote_user:在遠程主機以哪個用戶身份執行

             sudo_user:非管理員需要擁有sudo權限

         tasks:任務列表

                 模塊,模塊參數:

                         格式:

                         (1) action: module arguments

                         (2) module: arguments

示例1:<一下內容寫入一個.yaml的文件中即可>

- hosts: all
 remote_user: root
 tasks:
 - name: install a group
   group: name=mygrp system=true
 - name: install a user
   user: name=user1 group=mygrp system=true
    
- hosts: websrvs
 remote_user: root
 tasks:
 - name: install httpd package
   yum: name=httpd
 - name: start httpd service
   service: name=httpd state=started
    
- hosts: all
 remote_user: root
 tasks:
 - name: create group
   group: name=hlr gid=3000 state=presend
 - name: create user
   user: name=hlr uid=2500 group=hlr

運行playbook,使用ansible-playbook命令

         (1) 檢測語法

             ansible-playbook –syntax-check /path/to/playbook.yaml

         (2) 測試運行

                 ansible-playbook -C /path/to/playbook.yaml

                         –list-hosts

                         –list-tasks

                         –list-tags

         (3) 運行

                 ansible-playbook  /path/to/playbook.yaml

                         -t TAGS, –tags=TAGS :只運行某個標記的tasks

                         –skip-tags=SKIP_TAGS

                         –start-at-task=START_AT

handlers:由特定條件觸發的Tasks;

         調用及定義方式:

         tasks:

         – name: TASK_NAME

           module: arguments

          notify: HANDLER_NAME

          handlers:

         – name: HANDLER_NAME

          module: arguments

示例2:

- hosts: websrvs
 remote_user: root
  tasks:
  - name: install httpd package
   yum: name=httpd state=latest
  - name: install conf file
   copy: src=/root/httpd.conf dest=/etc/httpd/conf/httpd.conf
   notify: restart httpd service
 - name: start httpd service
   service: name=httpd state=started
 handlers:
 - name: restart httpd service
   service: name=httpd state=restarted

tags:給指定的任務定義一個調用標識

         – name: NAME

           module: arguments

           tags: TAG_ID

示例3:

- hosts: websrvs
 remote_user: root
 tasks:
 - name: install httpd package
   yum: name=httpd
 - name: create httpd-conf file
   copy: src=/etc/httpd/conf/httpd.conf dest=/etc/httpd/conf/httpd.conf
   tags: file_change
   notify: reload httpd server
 - name: create httpd index.html file
   copy: src=/var/www/html/index.html dest=/var/www/html/index.html
   tags: file_change
   notify: reload httpd server
 - name: start httpd server
   service: name=httpd state=started enabled=on
 handlers:
 - name: reload httpd server
   shell: service httpd restart
    
ansible-playbook -t file_change web.yaml
    -t TAG_ID1,TAG_ID2可以一次調用多個標簽

Variables:

類型:

    內建:

      (1) facts

    自定義:

        (1) 命令行傳遞

            -e VAR=VALUE

示例4:

- hosts: websrvs
  remote_user: root
  tasks:
  - name: remove a server package
   yum: name={{ pkgname }} state=absent
    
使用:ansible-playbook -e pkgname=vsftpd XXX.yaml

         (2) 在hosts Inventory中為每個主機定義專用變量值

                 (a) 向不同的主機傳遞不同的變量 

                     IP/HOSTNAME variable_name=value

示例5:

/etc/ansible/hosts文件中定義
[websrvs]
10.1.43.2 pkgname=httpd
10.1.43.3 pkgname=nginx
    
腳本中:
- hosts: websrvs
  remote_user: root
  vars:
  - name: remove a server package
   yum: name={{ pkgname }} state=absent

                 (b) 向組內的所有主機傳遞相同的變量 

                         [groupname:vars]

                         variable_name=value

示例6:

/etc/ansible/hosts文件中定義
[websrvs]
10.1.43.2
10.1.43.3
    
[websrvs:vars]
pkgname=vsftpd
    
腳本中:
- hosts: websrvs
  remote_user: root
  vars:
  - name: remove a server package
   yum: name={{ pkgname }} state=absent

         (3) 在playbook中定義<添加在remote_user后面,tasks前面>

                 vars:

                 – var_name: value

                 – var_name: value

示例7:

- hosts: websrvs
  remote_user: root
  vars:
  - pkgname: vsftpd
  tasks:
  - name: remove a server package
   yum: name={{ pkgname }} state=absent
    
注意:對此配置文件而言,或命令行以-e給出了變量名的值,命令行的優先級更高

         (4) Inventory還可以使用參數:

                 用于定義ansible遠程連接目標主機時使用的屬性,而非傳遞給playbook的變量

                 ansible_ssh_host

                 ansible_ssh_port

                 ansible_ssh_user

                 ansible_ssh_pass

                 ansible_sudo_pass

                

        

         (5) 在角色調用時傳遞

                 roles:

                 – { role: ROLE_NAME, var: value, …}

變量調用:

    {{ var_name }}

Templates:模板

         文本文件,內部嵌套有模板語言腳本(使用模板語言編寫)

        

         Jinja2 is a template engine written in pure Python.  It provides a  Django inspired non-XML syntax but supports inline expressions and an optional sandboxed environment.

        

         語法:

                 字面量:

                         字符串:使用單引號或雙引號;

                         數字:整數、浮點數;

                         列表:[item1, item2, …]

                         元組:(item1, item2, …)

                         字典:{key1:value1, key2:value2, …}

                         布爾型:true/false

                

                 算術運算:

                     +, -, *, /, //, %, **

                

                 比較操作:

                     ==, !=, >, <, >=, <=

                

                 邏輯運算:and, or, not

        

         執行模板文件中的腳本,并生成結果數據流,需要使用template模塊;

                 template:

                         -a ""

                                 src=

                                 dest=

                                 mode=

                                 onwer=

                                 group=

        

         注意:此模板不能在命令行使用,而只能用于playbook

示例8:

/root/nginx.conf.j2文件:
worker_processes  {{ ansible_processor_vcpus }};
ansible_processor_vcpus:此參數可以使用ansible IP -m setup 獲取
    
腳本
- hosts: ngxsrvs
 remote_user: root
 tasks:
 - name: install nginx package
    yum: name=nginx state=latest
 - name: install conf file
    template: src=/root/nginx.conf.j2 dest=/etc/nginx/nginx.conf
    tags: ngxconf
    notify: reload nginx service
 - nyuame: start nginx service
    service: name=nginx state=started enabled=true
 handlers:
 - name: reload nginx service
    shell: /usr/sbin/nginx -s reload

條件測試:

    when語句:在tasks中使用,Jinja2的語法格式

示例9:

- hosts: all
  remote_user: root
  tasks:
  - name: install nginx package
    yum: name=nginx state=latest
  - name: start nginx service on CentOS6
    shell: service nginx start
    when: ansible_distribution == "CentOS" and ansible_distribution_major_version == "6"
  - name: start nginx service
    shell: systemctl start nginx.service
    when: ansible_distribution == "CentOS" and ansible_distribution_major_version == "7"
    
- hosts: mysqlsrvs
  remote_user: root
  tasks:
  - name: install DB package
   yum: name=mysql-server
   when: ansible_distribution == 'CentOS' and ansible_distribution_major_version == '6'
  - name: install DB package
   yum: name=mariadb-server
   when: ansible_distribution == 'CentOS' and ansible_distribution_major_version == '7'
  - name: start DB service
   service: name=mysqld state=started enabled=on
   when: ansible_distribution == 'CentOS' and ansible_distribution_major_version == '6'
  - name: start DB service
   service: name=mariadb state=started enabled=on
   when: ansible_distribution == 'CentOS' and ansible_distribution_major_version == '7'

循環:迭代,需要重復執行的任務;

         對迭代項的引用,固定變量名為"item”,使用with_item屬性給定要迭代的元素;

                 元素:列表

                         字符串

                         字典

基于字符串列表給出元素示例10:

- hosts: websrvs
  remote_user: root
  tasks:
  - name: install packages
   yum: name={{ item }} state=latest
   with_items:
   - httpd
   - php
   - php-mysql
   - php-mbstring
   - php-gd

基于字典列表給元素示例11:

- hosts: all
  remote_user: root
  tasks:
  - name: create groups
    group: name={{ item }} state=present
   with_items:
   - groupx1
   - groupx2
   - groupx3
  - name: create users
    user: name={{ item.name }} group={{ item.group }} state=present
   with_items:
   - {name: 'userx1', group: 'groupx1'}
   - {name: 'userx2', group: 'groupx2'}
   - {name: 'userx3', group: 'groupx3'}

角色:roles

         以特定的層級目錄結構進行組織的tasks、variables、handlers、templates、files等

         role_name/

                 files/:存儲由copy或script等模塊調用的文件

    

                 tasks/:此目錄中至少應該有一個名為main.yml的文件,用于定義各task;其它的文件需要由main.yml進行“包含”調用

    

                 handlers/:此目錄中至少應該有一個名為main.yml的文件,用于定義各handler;其它的文件需要由main.yml進行“包含”調用

    

                 vars/:此目錄中至少應該有一個名為main.yml的文件,用于定義各variable;其它的文件需要由main.yml進行“包含”調用

    

                 templates/:存儲由template模塊調用的模板文本

    

                 meta/:此目錄中至少應該有一個名為main.yml的文件,定義當前角色的特殊設定及其依賴關系;其它的文件需要由main.yml進行“包含”調用

    

                 default/:此目錄中至少應該有一個名為main.yml的文件,用于設定默認變量

    

在playbook中調用角色的方法:

- hosts: HOSTS
  remote_user: USERNAME
  roles:
  - ROLE1
  - ROLE2
  - { role: ROLE3, VARIABLE: VALUE, ...}
  - { role: ROLE4, when: CONDITION }

原創文章,作者:megedugao,如若轉載,請注明出處:http://www.www58058.com/58276

(0)
megedugaomegedugao
上一篇 2016-11-06
下一篇 2016-11-06

相關推薦

  • N26-第四周作業-邢巖

    馬哥門徒-N26-邢巖   精神練習需要深入認真的工作以及熱情的勁頭。當你開始練習,你是在掙扎、在反抗,你需要集中精力,然后慢慢進步。那么,我們就開始吧。   第一題,復制/etc/skel目錄為/home/tuser1,要求/home/tuser1及其內部文件的屬組和其它用戶均沒有任何訪問權限。   ~]# cp -r /et…

    Linux干貨 2017-02-15
  • 程序包管理

    程序包 linux的程序包主要分為兩類;二進制可執行安裝包和源代碼程序文件包     二進制應用程序的組成部分:     二進制文件、庫文件、配置文件、幫助文件   查看二進制程序所依賴的庫文件:     ldd&nbs…

    Linux干貨 2016-05-30
  • linux軟件包管理(開始上正菜了)

    linux程序包管理:     API:數據接口     ABI:應用程序二進制接口        庫級別的虛擬化:             linux:wine    …

    Linux干貨 2017-03-07
  • 面向對象簡單介紹

    面向對象簡單介紹

    Linux干貨 2017-11-12
  • 磁盤陣列(raid),劃分邏輯卷(lvm)

    磁盤陣列(raid),劃分邏輯卷(lvm)       將來我們在生產環境中由于磁盤的來回讀寫量比較大,所以就容易導致磁盤的損壞率比較高。但是,處于生產環境的需求,我們還得保證服務器的正常運行?;蛘哒f我們需要對服務器的讀寫速率進行優化,這樣我們就不得不運用到這個磁盤陣列(raid )。而所謂的磁盤陣列就是使用…

    Linux干貨 2016-08-29
欧美性久久久久