1. 程式人生 > >ansible工作原理以及使用詳解

ansible工作原理以及使用詳解

內容:
1、ansible的作用以及工作結構
2、ansible的安裝以及使用
3、ansible的playbook使用

一、ansible的作用以及工作結構
        1、ansible簡介:
        ansible是新出現的自動化運維工具,基於Python開發,集合了眾多運維工具(puppet、cfengine、chef、func、fabric)的優點,實現了批量系統配置、批量程式部署、批量執行命令等功能。ansible是基於模組工作的,本身沒有批量部署的能力。真正具有批量部署的是ansible所執行的模組,ansible只是提供一種框架。主要包括:
        (1)、連線外掛connection plugins:負責和被監控端實現通訊;
        (2)、host inventory:指定操作的主機,是一個配置檔案裡面定義監控的主機;
        (3)、各種模組核心模組、command模組、自定義模組;
        (4)、藉助於外掛完成記錄日誌郵件等功能;
        (5)、playbook:劇本執行多個任務時,非必需可以讓節點一次性執行多個任務。
        2、ansible的架構:連線其他主機預設使用ssh協議


二、ansible的安裝以及常用模組使用
        1、ansible無伺服器端,使用時直接執行命令即可,同時不需要在被管控主機上安裝任何客戶端,因此ansible是一個十分輕量級的工具,可以在epel源進行安裝,ansible已經被紅帽收購,相信不久會被收入base源
        配置好epel源後直接yum安裝ansible

  •   1 
      2 [[email protected] ~]# yum info ansible
      3
    Loaded plugins: fastestmirror, refresh-packagekit, security 4 Loading mirror speeds from cached hostfile 5 base | 4.0 kB 00:00 ... 6 epel | 4.3 kB 00:00 7 epel/primary_db | 5.7 MB 00:00 8 Available Packages 9 Name : ansible 10
    Arch : noarch 11 Version : 1.9.2 12 Release : 1.el6 13 Size : 1.7 M 14 Repo : epel 15 Summary : SSH-based configuration management, deployment, and task execution system 16 URL : http://ansible.com 17 License : GPLv3 18 Description : 19 : Ansible is a radically simple model-driven configuration management, 20 : multi-node deployment, and remote task execution system. Ansible works 21 : over SSH and does not require any software or daemons to be installed 22 : on remote nodes. Extension modules can be written in any language and 23 : are transferred to managed machines automatically. 24 [[email protected] ~]# yum install ansible

 

檢視生成的主要檔案:

  1 /etc/ansible
  2 /etc/ansible/ansible.cfg   #配置檔案
  3 /etc/ansible/hosts   #主機庫(host inventory)
  4 /usr/bin/ansible   #主程式
  5 /usr/bin/ansible-doc   #文件
  6 /usr/bin/ansible-playbook   #劇本


ansible命令的使用方法也比較簡單:
        語法:
        ansible <host-pattern> [-f forks] [-m module_name] [-a args]
        host-pattern:host inventory檔案的一個組名,可以為all
            -f forks:並行處理的個數,預設為5
            -m module_name:模組名,預設為command
            -a args:引數
        ansible-doc:
            -l:檢視模組列表
            -s:檢視相關模組引數
        我們可以看到ansible支援非常多的模組:

  1 [21:20 [email protected]/var/ftp/pub/files]# ansible-doc -l
  2 less 436
  3 Copyright (C) 1984-2009 Mark Nudelman
  4 less comes with NO WARRANTY, to the extent permitted by law.
  5 For information about the terms of redistribution,
  6 see the file named README in the less distribution.
  7 Homepage: http://www.greenwoodsoftware.com/less
  8 a10_server                    Manage A10 Networks AX/SoftAX/Thunder/vThunder devices
  9 a10_service_group             Manage A10 Networks AX/SoftAX/Thunder/vThunder devices
 10 a10_virtual_server            Manage A10 Networks AX/SoftAX/Thunder/vThunder devices
 11 acl                           Sets and retrieves file ACL information.
 12 add_host                      add a host (and alternatively a group) to the ansible-playbook in-memory inventory
 13 airbrake_deployment           Notify airbrake about app deployments
 14 alternatives                  Manages alternative programs for common commands
 15 apache2_module                enables/disables a module of the Apache2 webserver
 16 apt                           Manages apt-packages
 17 apt_key                       Add or remove an apt key
 18 apt_repository                Add and remove APT repositories
 19 apt_rpm                       apt_rpm package manager
 20 assemble                      Assembles a configuration file from fragments
 21 assert                        Fail with custom message
 22 at                            Schedule the execution of a command or script file via the at command.
 23 authorized_key                Adds or removes an SSH authorized key
 24 azure                         create or terminate a virtual machine in azure
 25 bigip_facts                   Collect facts from F5 BIG-IP devices
 26 bigip_monitor_http            Manages F5 BIG-IP LTM http monitors
 27 bigip_monitor_tcp             Manages F5 BIG-IP LTM tcp monitors
 28 bigip_node                    Manages F5 BIG-IP LTM nodes
 29 bigip_pool                    Manages F5 BIG-IP LTM pools
 30 bigip_pool_member             Manages F5 BIG-IP LTM pool members
 31 bigpanda                      Notify BigPanda about deployments
 32 boundary_meter                Manage boundary meters
 33 


注意:使用ansible-doc -s檢視幫助是,一般有=號的引數都是必要的引數
        Ansible預設安裝好後有一個配置檔案/etc/ansible/ansible.cfg,該配置檔案中定義了ansible的主機的預設配置部分,如預設是否需要輸入密碼、是否開啟sudo認證、action_plugins外掛的位置、hosts主機組的位置、是否開啟log功能、預設埠、key檔案位置等等。
        具體如下:

  1 [defaults]
  2     # some basic default values...
  3     hostfile       = /etc/ansible/hosts   \\指定預設hosts配置的位置
  4     # library_path = /usr/share/my_modules/
  5     remote_tmp     = $HOME/.ansible/tmp
  6     pattern        = *
  7     forks          = 5
  8     poll_interval  = 15
  9     sudo_user      = root  \\遠端sudo使用者
 10     #ask_sudo_pass = True  \\每次執行ansible命令是否詢問ssh密碼
 11     #ask_pass      = True  \\每次執行ansible命令時是否詢問sudo密碼
 12     transport      = smart
 13     remote_port    = 22
 14     module_lang    = C
 15     gathering = implicit
 16     host_key_checking = False    \\關閉第一次使用ansible連線客戶端是輸入命令提示
 17     log_path    = /var/log/ansible.log \\需要時可以自行新增。chown -R root:root ansible.log
 18     system_warnings = False    \\關閉執行ansible時系統的提示資訊,一般為提示升級
 19     # set plugin path directories here, separate with colons
 20     action_plugins     = /usr/share/ansible_plugins/action_plugins
 21     callback_plugins   = /usr/share/ansible_plugins/callback_plugins
 22     connection_plugins = /usr/share/ansible_plugins/connection_plugins
 23     lookup_plugins     = /usr/share/ansible_plugins/lookup_plugins
 24     vars_plugins       = /usr/share/ansible_plugins/vars_plugins
 25     filter_plugins     = /usr/share/ansible_plugins/filter_plugins
 26     fact_caching = memory
 27     [accelerate]
 28     accelerate_port = 5099
 29     accelerate_timeout = 30
 30     accelerate_connect_timeout = 5.0
 31     # The daemon timeout is measured in minutes. This time is measured
 32     # from the last activity to the accelerate daemon.
 33     accelerate_daemon_timeout = 30


免密登陸

因為ansible是基於ssh工作,所以在使用ansible之前要先給各個伺服器製作ssh免密登陸

ssh免密登陸教程

用法

  1 ansible users1 -m command -a 'ls /etc/rc.local'
  2 # |        |    |    |     |          |
  3 # |        |    |    |     |          |_________________要執行的命令
  4 # |        |    |    |     |
  5 # |        |    |    |     |____________________________接命令
  6 # |        |    |    |
  7 # |        |    |    |__________________________________模組
  8 # |        |    |
  9 # |        |    |_______________________________________接模組
 10 # |        |
 11 # |        |____________________________________________組/IP
 12 # |
 13 # |_____________________________________________________ansible


遠端執行命令模組

shell模組

  1 # 在/tmp/1.txt寫入hello
  2 ansible users1 -m shell -a 'echo "hello" > /tmp/1.txt'
  1 # 檢視/tmp/1.txt檔案內容
  2 ansible users1 -m shell -a 'cat /tmp/1.txt'


command模組

  1 ansible users1 -m command -a 'ls /etc/rc.local'


其他模組

copy模組(將本地檔案拷貝到伺服器)

  1 ansible users1 -m copy -a 'src=/root/passwd dest=/tmp/passwd mode=0777 ownes=user group=youboy'

備註:src本地檔案;dest客戶端目錄;修改許可權mode=0777 ;使用者ownes=user ;使用者組group=youboy

// 指定內容寫入到檔案

  1 ansible users1 -m copy -a 'content="hello word" dest=/tmp/test.txt mode=0777'


fetch模組(將伺服器上的檔案拷貝到本地)

  1 ansible users1 -m fetch -a 'src=/etc/passwd dest=/tmp/passwd'

file模組

  1 //刪除檔案
  2 ansible users1 -m file -a 'past=/tmp/passwd state=adsent'
  3 //建立軟連線
  4 ansible users1 -m file -a 'src=/etc/passwd path=/tmp/passwd.link state=link'
  5 //修改使用者許可權
  6 ansible users1 -m file -a 'path=/tmp/passwd mode=0777 ownes=user group=youboy'

疑問?
///伺服器上的檔案拷貝到其他目錄

  1 ansible users1 -m copy -a 'path=/etc/passwd dest=/tmp/passwd'

cron模組(計劃任務)

  1 ansible users1 -m cron -a 'minute=10 hour=02 day=15 moneth=12 weekday=7 name="test" job="date > /tmp/date.txt"'
  2 //使用shell模組驗證計劃任務
  3 ansible users1 -m shell -a 'crontab -l'
  4 //清除計劃任務(使用ansible users1 -m cron -a name="test" state=absent''可能無效,使用全命令清除即可)
  5 ansible users1 -m cron -a 'minute=10 hour=02 day=15 moneth=12 weekday=7 name="test" job="date > /tmp/date.txt" state=absent'
  6 //使用shell模組驗證清除的計劃任務

hostname模組(臨時修改主機名)

  1 ansible 192.168.1.2 -m hostname -a 'name=jiahui.com'

yum模組

  1 ansible users1 -m yum -a 'name=httpd state=installed'

present 檢視安裝
installed 安裝
latest 升級安裝
absent 解除安裝

service模組(操作服務)

  1 //啟動服務
  2 ansible users1 -m service -a 'name=httpd state=started'

started 啟動服務
stopped 關閉服務

  1 /開機自啟
  2 ansible users1 -m service -a 'name=httpd enabled=yes runlevel=2345'

備註:runlevel 執行級別(0123456 7個級別,如下)

  1 chkconfig --list | grep httpd
  2 httpd           0:關閉  1:關閉  2:關閉  3:關閉  4:關閉  5:關閉  6:關閉