Ansible

Ansible簡介

  • ansible是一種基于python語言開發的輕量級自動化運維工具,它可以自動化批量完成主機服務配置管理,軟件部署,執行特定命令等工作

  • ansible的核心組件有ansible core(核心代碼),host inventory(要管理的主機),core modules(核心模塊),custom modules(用戶可以自定義模塊),playbook (yaml, jinjia2),connect plugin(paramiko)

Ansible的安裝和基礎配置

Summary     : SSH-based configuration management, deployment, and task execution system
URL         : http://ansible.com
License     : GPLv3+
Description :         需要配置好epelYUM源
            : Ansible is a radically simple model-driven configuration management,
            : multi-node deployment, and remote task execution system. Ansible works
            : over SSH and does not require any software or daemons to be installed
            : on remote nodes. Extension modules can be written in any language and
            : are transferred to managed machines automatically.
[root@centos ~]# yum install ansible -y  自動安裝yaml,jinjia2,paramiko等相關庫
,,,,,,,
Complete!
[root@centos ~]# ansible --version  測試是否安裝成功,提示有ansible版本號
ansible 2.1.2.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = Default w/o overrides
[root@centos ~]# ssh-keygen 基于秘鑰對管理client
[root@centos ~]# ssh-copy-id -i .ssh/id_rsa.pub root@192.168.40.138
[root@centos ~]# ssh root@192.168.40.138  "ifconfig>/dev/null"  測試是否能夠免密碼登錄client,我這里只有一臺client
[root@centos ~]#
[root@centos ansible]# vim /etc/ansible/hosts 定義client
[singleclient]  被管主機的定義方式,該配置文件有詳細范例
192.168.40.138
[root@centos ansible]# ansible all  -m ping   需要關閉client的selinux
192.168.40.138 | SUCCESS => {
    "changed": false, 
    "ping": "pong"     測試能ping通
}

Ansible常用命令的使用

 ansible <host-pattern主機列表> [-m module_name模塊名字] [-a args模塊參數] [options]
 常用[options] 更多參數需要man ansible 或 ansible --help了解
 
 -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 向playbook里傳遞變量
                        set additional variables as key=value or YAML/JSON
 -f FORKS, --forks=FORKS 多少個線程并行執行任務
                        specify number of parallel processes to use
                        
 ansible-doc - show documentation on Ansible modules
 ansible-doc -l 列出所有可用模塊 ansible-doc -s module 查看某個模塊用法
 
 ansible-playbook - run an ansible playbook 運行劇本內的編排任務

Ansible的playbook編寫

  • playbook的主要組成部分Tasks(由多個模塊組成的多個任務),Variables(變量),Template(模版針對服務配置文件),Handler(處理器),Roles(角色)

  • playbook一定要指定Hosts(主機),Users(以哪個用戶身份執行任務)

  • playbook遵循YAML語言語法格式,常用的有序列用“-”表示;key:value鍵值對;{k1:v1,k2:v2}字典等

  • 下面為playbook由tasks,variables,template,handler,roles逐個測試,當然可以組合使用,組合使用才能發揮playbook的任務編排能力

[root@centos ~]# ansible-playbook ./test1.yml  --syntax-check
playbook: ./test1.yml
[root@centos ~]# cat test1.yml 
- hosts: singleclient 指定要在那些主機上運行playbook
  remote_user: root  指定了以那個用戶身份去運行playbook
  tasks:
  - name: install httpd 任務一
    yum: name=httpd state=present
  - name: start the httpd service 任務二
    service: name=httpd state=running
  - name: reporting 任務三
    shell: /bin/echo "httpd installed and running"
  ignore_errors: true  如果在運行任務三時報錯,就忽略掉報錯
[root@centos ~]# ansible-playbook ./test1.yml 
PLAY [singleclient] ************************************************************
其中- host是頂級層是個大列表,remote_user,tasks和ignore_errors是頂級層的元素,
remote_user和tasks都是鍵值對,tasks的值比較特殊,為三個列表;playbook中可以有多個- host
ansible的變量分為fact變量就是ansible all -m setup獲得的變量
通過--extra-var 參數傳進playbook的變量,playbook 中通過{{}}引用變量 例如:
yum: name={{software}} state=present 也可以在playbook中通過var關鍵字來定義并引用
ansible-doc --extra-var "sotfware=nginx" test1.yml 則會安裝nginx
inventory的主機變量和組變量,在主機后面加上k=v ,playbook通過{{k}}來引用,模版則會針對不同的主機得到不同的值
[root@centos ~]# cat index.txt /template/index.j2 
just test port for {{ port }} 源文件
just test a port {{ port }} 模版文件
[root@centos ~]# cat test3.yml 
- hosts: singleclient
  remote_user: root
  tasks: 此處為簡單測試,實際生產環境會針對服務的配置文件來操作
  - name: copy configuration file
    copy: src=/root/index.txt dest=/tmp/index.txt 復制源文檔到client
  - name: modify configuration file
    template: src=/template/index.j2 dest=/tmp/index.txt 根據模版修改client的index.txt文檔
[root@centos ~]# grep "port" /etc/ansible/hosts 
192.168.40.138 port=888  主機變量 port
#port=888
[root@centos ~]# ssh root@192.168.40.138 "cat /tmp/index.txt"
just test a port 888
[root@centos ~]# grep  -C2 "singleclient" /etc/ansible/hosts 
## 192.168.100.1
## 192.168.100.10
[singleclient]采用組變量方式,40.138,40.200都會相同的變量,其值也相同
192.168.40.138 
192.168.40.200
[singleclient:vars]
port=888
# Ex 2: A collection of hosts belonging to the 'webservers' group
[root@centos ~]# ansible-playbook test3.yml  test3.yml仍能正常執行
PLAY [singleclient] ************************************************************
[root@centos ~]# ssh root@192.168.40.138 "cat /tmp/index.txt"
just test a port 888   測試結果和主機變量測試結果相同
ansible的條件,迭代和處理器測試
tasks: 當client主機發行版為CentOS時,才會關機
  - name: "shut down CentOS 6 systems"   
    command: /sbin/shutdown -t now  
    when:
    - ansible_distribution == "CentOS"
[root@centos ~]# ansible-playbook test4.yml 
PLAY [singleclient] ************************************************************
TASK [setup] *******************************************************************
ok: [192.168.40.138]
TASK [copy wrong file to test when] ********************************************
fatal: [192.168.40.138]: FAILED! => {"failed": true, "msg": "the file_name 
...ignoring
TASK [ping test] ***************************************************************
ok: [192.168.40.138]
PLAY RECAP *********************************************************************
192.168.40.138             : ok=3    changed=0    unreachable=0    failed=0   
[root@centos ~]# cat test4.yml 
- hosts: singleclient
  remote_user: root
  tasks:
  - name: copy wrong file to test when
    copy: src=/root/index dest=/tmp/index.txt
    register: result
    ignore_errors: True 為了不影響下一條任務執行和when條件判斷
  - name: ping test
    ping: 
    when: result|failed  上一條命令執行失敗時,才執行ping
,,,,,,,,,,,,,,,,,
- name: add several users  user: name={{ item }} state=present groups=wheel 迭代測試 
 with_items: 
     - testuser1 
     - testuser2
,,,,,,,,,,,,,,,,,    
tasks:處理器測試
  - name: ensure apache is at the latest version
    yum: name=httpd state=latest
  - name: write the apache config file
    template: src=/srv/httpd.j2 dest=/etc/httpd.conf
    notify:  表明觸發條件
    - restart apache
  - name: ensure apache is running (and enable it at boot)
    service: name=httpd state=started enabled=yes
  handlers:  執行相應動作
    - name: restart apache
      service: name=httpd state=restarted
ansible的roles使用
roles是變量,任務,文件,模版,處理器,分別放在單獨的目錄并都是role目錄的子目錄
role目錄會有site.yml為ansible-playbook的執行入口,需要相應的文件是會自動導入
適用場景當有大量主機要安裝配置不同的服務時,比如20臺主機需要安裝配置nginx,
其他20臺需要安裝配置mysql,則可以新建nginx和mysql的role來執行安裝配置nginx和mysql服務

role內各目錄中可用的文件

tasks目錄:至少應該包含一個名為main.yml(只寫任務列表)的文件,其定義了此角色的任務列表

files目錄:存放由copy或script等模塊調用的文件; 

templates目錄:template模塊會自動在此目錄中尋找Jinja2模板文件; 

handlers目錄:此目錄中應當包含一個main.yml(只寫handler)文件,用于定義此角色用到的各handler;

vars目錄:應當包含一個main.yml(只寫變量),用于定義此角色用到的變量;

meta目錄:應當包含一個main.yml文件,用于定義此角色的特殊設定及其依賴關系;

default目錄:為當前角色設定默認變量時使用此目錄;應當包含一個main.yml文件;

roles目錄的同級目錄下需要新建site.yml 來作為ansible-playbook的執行入口,定義Hosts和Users
使用roles關鍵字來指定執行roles目錄下的哪個role中的編排任務

通過以上總結可以對ansible的簡單使用加深理解,ansible的其他用法需要參考官網或其他文檔

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

(0)
SnooSnoo
上一篇 2016-11-14
下一篇 2016-11-14

相關推薦

  • 文件權限

     本篇博客是對文件權限的簡單介紹,將會簡述下權限的數字表現形式,還有字母表現形式,還有一些特殊的suid、sgid、sticky的權限介紹,還有對ACL權限的簡述。  一、權限的定義     關于權限,百度百科的解釋如下:權限(privilege)是指某個特定的用戶具有特定的系統資源使用權力,像是文…

    Linux干貨 2017-07-29
  • LVM2 邏輯卷管理工具

    LVM2:  LVM: Logical Volume Manager, Version: 2  dm: device mapper,將一個或多個底層塊設備組織成一個邏輯設備的模塊; /dev/dm-#  /dev/mapper/VG_NAME-LV_NAME /dev/mapper/vol0-root /dev/VG_NAME/…

    Linux干貨 2015-09-19
  • redis主從復制(1)— 慢查詢導致復制中斷

    redis的異常行為是一件令人頭疼的問題。redis提供的錯誤日志只提供了一些server的運行狀態信息,而沒有server在故障現場的操作日志,比如執行了什么命令,命令操作對象的數據結構信息。如果redis也有mysql的slow-log,那么很多性能和故障問題也很容易處理。1、redis rdb在redis2.8版本以前,redis主從數據復制在生產上存…

    Linux干貨 2016-04-12
  • ssh基于密鑰的認證及實現

    ssh登錄認證方式介紹 大致有以下兩種 基于口令的認證這種認證方式就是通過ssh指令以指定用戶名、指定端口等信息后,待連接建立完成,需要輸入用戶名對應的口令來完成認證。一般形如: [root@localhost ~]# ssh -l lantian 192.168.1.201  &nbsp…

    Linux干貨 2017-01-05
  • 從Linux小白到大牛——與狼共舞的日子5

    馬哥教育網絡班21期+第5周課程練習 1、顯示/boot/grub/grub.conf中以至少一個空白字符開頭的行。 [root@localhost ~]# grep '^[[:space:]]\+' /boot/grub/grub.conf 2、顯示/etc/rc.d/rc.sysinit文件中以…

    Linux干貨 2016-08-31
  • linux 學習筆記

    第一周

    Linux干貨 2018-03-16
欧美性久久久久