自動化運維工具ansible詳細介紹以模塊的使用

ansible

ansible的理論部分

ansible的介紹

 ansible是新出現的自動化運維工具,基於Python開發,集合了衆多運維工具(puppet、chef、func、fabric)的優點,實現了批量系統配置、批量程序部署、批量運行命令等功能。
  ansible是基於 paramiko 開發的,並且基於模塊化工作,本身沒有批量部署的能力。真正具有批量部署的是ansible所運行的模塊,ansible只是提供一種框架。ansible不需要在遠程主機上安裝client/agents,因爲它們是基於ssh來和遠
程主機通訊的。ansible目前已經已經被紅帽官方收購,是自動化運維工具中大家認可度最高的,並且上手容易,學習簡單。是每位運維工程師必須掌握的技能之一。

ansible的特點

  1. 部署簡單,只需在主控端部署Ansible環境,被控端無需做任何操作;
  2. 默認使用SSH協議對設備進行管理;
  3. 有大量常規運維操作模塊,可實現日常絕大部分操作;
  4. 配置簡單、功能強大、擴展性強;
  5. 支持API及自定義模塊,可通過Python輕鬆擴展;
  6. 通過Playbooks來定製強大的配置、狀態管理;
  7. 輕量級,無需在客戶端安裝agent,更新時,只需在操作機上進行一次更新即可;
  8. 提供一個功能強大、操作性強的Web管理界面和REST API接口——AWX平臺。

    ansible的架構圖

    自動化運維工具ansible詳細介紹以模塊的使用
    上圖中我們看到的主要模塊如下:

Ansible:Ansible核心程序。
HostInventory:記錄由Ansible管理的主機信息,包括端口、密碼、ip等。
Playbooks:“劇本”YAML格式文件,多個任務定義在一個文件中,定義主機需要調用哪些模塊來完成的功能。
CoreModules:核心模塊,主要操作是通過調用核心模塊來完成管理任務。
CustomModules:自定義模塊,完成核心模塊無法完成的功能,支持多種語言。
ConnectionPlugins:連接插件,Ansible和Host通信使用

ansible 任務執行

ansible 任務執行模式

Ansible 系統由控制主機對被管節點的操作方式可分爲兩類,即adhoc和playbook:

  • ad-hoc模式(點對點模式)
    使用單個模塊,支持批量執行單條命令。ad-hoc 命令是一種可以快速輸入的命令,而且不需要保存起來的命令。就相當於bash中的一句話shell。
  • playbook模式(劇本模式)
    是Ansible主要管理方式,也是Ansible功能強大的關鍵所在。playbook通過多個task集合完成一類功能,如Web服務的安裝部署、數據庫服務器的批量備份等。可以簡單地把playbook理解爲通過組合多條ad-hoc操作的配置文件。

    ansible 執行流程

    自動化運維工具ansible詳細介紹以模塊的使用
    簡單理解就是Ansible在運行時, 首先讀取ansible.cfg中的配置, 根據規則獲取Inventory中的管理主機列表, 並行的在這些主機中執行配置的任務, 最後等待執行返回的結果。

ansible 命令執行過程

  1. 加載自己的配置文件,默認/etc/ansible/ansible.cfg;
  2. 查找對應的主機配置文件,找到要執行的主機或者組;
  3. 加載自己對應的模塊文件,如 command;
  4. 通過ansible將模塊或命令生成對應的臨時py文件(python腳本), 並將該文件傳輸至遠程服務器;
  5. 對應執行用戶的家目錄的.ansible/tmp/XXX/XXX.PY文件;
  6. 給文件 +x 執行權限;
  7. 執行並返回結果;
  8. 刪除臨時py文件,sleep 0退出;

ansible安裝

實驗說明

服務角色 IP 系統及所需軟件
主控主機 192.168.24.128 centos7  ansible
受控主機 192.168.24.130 centos7

安裝yum源

[root@linfan ~]# cd /etc/yum.repos.d/ 
root@linfan yum.repos.d]# curl -o 163.repo http://mirrors.163.com/.help/CentOS7-Base-163.repo
[root@linfan yum.repos.d]# sed -i 's/\$releasever/7/g' 163.repo
[root@linfan yum.repos.d]# sed -i 's/^enabled=.*/enabled=1/g' 163.repo
[root@linfan yum.repos.d]#  yum -y install epel-release 

安裝ansible

[root@linfan yum.repos.d]# yum -y install ansible ansible-doc 

查看ansible的版本

[root@linfan ~]# ansible --version
ansible 2.6.3
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Aug  4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]

ansible配置

ansible配置文件:

配置文件 說明
/etc/ansible/ansible.cfg ansible主配置文件
/etc/ansible/hosts 受控主機清單

受控主機清單配置方式:

  • 分組配置
  • ip配置
  • 域名配置
  • 通配符配置

    ansible通過ssh來控制遠程主機,所以要配置ssh互信,否則將會提示你輸入密碼

[root@linfan ~]#  ssh-keygen -t rsa //使用ssh-keygen 創建公鑰-私鑰對
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:4gPocSR66cSXzSqpFIw+2MA8xbnpdtwWdCeDomGlTJo root@linfan
The key's randomart image is:
+---[RSA 2048]----+
|   . .           |
|  * +   .        |
| E.O.. o + .     |
|=oo==+o . +      |
|+*B+= +.S        |
|oB+=.+...        |
|.+*o.ooo         |
|..o.. ..         |
|.                |
+----[SHA256]-----+
[root@linfan ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
//使用 ssh-copy-id 將公鑰複製到受控上的正確位置
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.24.130 (192.168.24.130)' can't be established.
ECDSA key fingerprint is SHA256:w+sgREnQRuhBiqS0qL9wlAImCSmvSQ6KnNqW6N3znJ0.
ECDSA key fingerprint is MD5:f0:fd:ea:c7:97:83:f0:b0:03:84:d2:a6:0a:23:12:e0.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
[email protected]'s password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '[email protected]'"
and check to make sure that only the key(s) you wanted were added.

將受控主機信息加入清單配置文件中

[root@linfan ~]# vim /etc/ansible/hosts
//添加以下內容
[webservers] //組名
192.168.24.130 //受控主機IP

ansible使用

ansible webservers組名或受控主機IP -m 模塊名 -a ‘命令’

ansible獲取幫助信息

ansible通過ansible-doc命令來獲取幫助信息,可以使用此命令的-s選擇來獲取指定模塊的幫助信息

//查詢service模塊的幫助文檔
[root@linfan ~]# ansible-doc -s service
- name: Manage services
  service:
      arguments:             # Additional arguments provided on the command line
      enabled:               # Whether the service should start on boot. *At least one of state and enabled are
                               required.*
      name:                  # (required) Name of the service.
      pattern:               # If the service does not respond to the status command, name a substring to look for as
                               would be found in the output of the `ps' command as a
                               stand-in for a status result.  If the string is found, the
                               service will be assumed to be running.
      runlevel:              # For OpenRC init scripts (ex: Gentoo) only.  The runlevel that this service belongs to.
      sleep:                 # If the service is being `restarted' then sleep this many seconds between the stop and
                               start command. This helps to workaround badly behaving init
                               scripts that exit immediately after signaling a process to
                               stop.
      state:                 # `started'/`stopped' are idempotent actions that will not run commands unless necessary.
                               `restarted' will always bounce the service.  `reloaded'
                               will always reload. *At least one of state and enabled are
                               required.* Note that reloaded will start the service if it
                               is not already started, even if your chosen init system
                               wouldn't normally.
      use:                   # The service module actually uses system specific modules, normally through auto detection,
                               this setting can force a specific module. Normally it uses
                               the value of the 'ansible_service_mgr' fact and falls back
                               to the old 'service' module when none matching is found.

ansible 常用模塊使用詳解

ansible常用模塊有:

  • ping
  • yum
  • template
  • copy
  • user
  • group
  • service
  • raw
  • command
  • shell
  • script

ansible常用模塊 raw、command、shell的區別

  • shell模塊調用的/bin/sh指令執行
  • command模塊不是調用的shell的指令,所以沒有bash的環境變量
  • raw很多地方和shell類似,更多的地方建議使用command和shell模塊。但是如果是使用老版本python,需要用到raw,又或是客戶端是路由器,因爲沒有安裝pyhton模塊,那就需要使用raw模塊了

ansible常用模塊之command

ansible模塊用於在遠程主機上執行命令,ansible默認使用command模塊
command模塊有一個缺陷就是不能使用管道符號和重定向功能

查看受控主機的/tmp目錄內容

[root@linfan ~]# ansible 192.168.24.130 -a 'ls /tmp'
192.168.24.130 | SUCCESS | rc=0 >>
ansible_aUrss8
systemd-private-105010548bc14e73826a57bb46c41172-chronyd.service-8duX7C
systemd-private-105010548bc14e73826a57bb46c41172-vgauthd.service-qpo65h
systemd-private-105010548bc14e73826a57bb46c41172-vmtoolsd.service-cQZm7W

在受控主機的/tmp目錄下新建一個文件test

[root@linfan ~]# ansible 192.168.24.130 -a 'touch /tmp/test'
 [WARNING]: Consider using the file module with state=touch rather than running touch.  If you need to use command
because file is insufficient you can add warn=False to this command task or set command_warnings=False in ansible.cfg to
get rid of this message.

192.168.24.130 | SUCCESS | rc=0 >>

[root@linfan ~]# ansible 192.168.24.130 -a 'ls /tmp'
192.168.24.130 | SUCCESS | rc=0 >>
ansible_sgtAwO
systemd-private-105010548bc14e73826a57bb46c41172-chronyd.service-8duX7C
systemd-private-105010548bc14e73826a57bb46c41172-vgauthd.service-qpo65h
systemd-private-105010548bc14e73826a57bb46c41172-vmtoolsd.service-cQZm7W
test

command模板不支持管道符,不支持重定向

[root@linfan ~]# ansible 192.168.24.130 -a "echo 'hello world' > /tmp/test"
192.168.24.130 | SUCCESS | rc=0 >>
hello world > /tmp/test

[root@linfan ~]# ansible 192.168.24.130 -a 'cat /tmp/test'
192.168.24.130 | SUCCESS | rc=0 >>

[root@linfan ~]# ansible 192.168.24.130 -a 'ps -ef | grep vsftpd'
192.168.24.130 | FAILED | rc=1 >>
error: garbage option

Usage:
 ps [options]

 Try 'ps --help <simple|list|output|threads|misc|all>'
  or 'ps --help <s|l|o|t|m|a>'
 for additional help text.

For more details see ps(1).non-zero return code

ansible常用模塊之raw

raw模塊用於在受控主機上執行命令,其支持管道符與重定向

支持重定向

[root@linfan ~]# ansible 192.168.24.130 -m raw -a 'echo "hello world" > /tmp/test'

192.168.24.130 | SUCCESS | rc=0 >>
Shared connection to 192.168.24.130 closed.

[root@linfan ~]#
[root@linfan ~]# ansible 192.168.24.130 -a 'cat /tmp/test'
192.168.24.130 | SUCCESS | rc=0 >>
hello world

支持管道符

[root@linfan ~]# ansible 192.168.24.130 -m raw -a 'cat /tmp/test |grep -Eo hello'
192.168.24.130 | SUCCESS | rc=0 >>
hello
Shared connection to 192.168.24.130 closed.

ansible常用模塊之shell

shell模塊用於在受控主機上執行受控主機上的腳本,也可以直接在受控主機上執行命令
shell模塊也支持管道與重定向

查看受控主機上的腳本

[root@linfan ~]# ansible 192.168.24.130 -a 'ls -l /scripts/'
192.168.24.130 | SUCCESS | rc=0 >>
total 4
-rw-r--r--. 1 root root 23 Sep  9 10:37 test.sh

使用shell模塊在受控主機上執行受控主機上的腳本

[root@linfan ~]# ansible 192.168.24.130 -m shell -a '/bin/bash /scripts/test.sh'
192.168.24.130 | SUCCESS | rc=0 >>
8

ansible常用模塊之script

script模塊用於在受控主機上執行主控主機上的腳本

[root@linfan ~]# ll /etc/ansible/scripts/
total 4
-rw-r--r-- 1 root root 26 Sep  9 10:55 boss.sh 
[root@linfan ~]# ansible 192.168.24.130 -m script -a '/etc/ansible/scripts/boss.sh &>/tmp/boss'
192.168.24.130 | SUCCESS => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 192.168.24.130 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 192.168.24.130 closed."
    ],
    "stdout": "",
    "stdout_lines": []
}

查看受控機上的/tmp/boss文件內容

[root@linfan ~]# ansible 192.168.24.130 -m shell -a 'cat /tmp/boss'
192.168.24.130 | SUCCESS | rc=0 >>
999

ansible常用模塊之template

template模塊用於生成一個模塊,並將其傳輸到受控主機上

下載一個163源文件並開啓此源

[root@linfan ~]# cd /etc/yum.repos.d/ 
root@linfan yum.repos.d]# curl -o 163.repo http://mirrors.163.com/.help/CentOS7-Base-163.repo
[root@linfan yum.repos.d]# sed -i 's/\$releasever/7/g' 163.repo
[root@linfan yum.repos.d]# sed -i 's/^enabled=.*/enabled=1/g' 163.repo

將設置好的163源傳到受控主機上

[root@linfan ~]# ansible 192.168.24.130 -m template -a 'src=/etc/yum.repos.d/163.repo dest=/etc/yum.repos.d/163.repo'
192.168.24.130 | SUCCESS => {
    "changed": true,
    "checksum": "60b8868e0599489038710c45025fc11cbccf35f2",
    "dest": "/etc/yum.repos.d/163.repo",
    "gid": 0,
    "group": "root",
    "md5sum": "5a3e688854d9ceccf327b953dab55b21",
    "mode": "0644",
    "owner": "root",
    "secontext": "system_u:object_r:system_conf_t:s0",
    "size": 1462,
    "src": "/root/.ansible/tmp/ansible-tmp-1536505977.96-30562591219464/source",
    "state": "file",
    "uid": 0
}

查看受控主機上是否有163源

[root@linfan ~]# ansible 192.168.24.130  -a 'ls /etc/yum.repos.d/'
192.168.24.130 | SUCCESS | rc=0 >>
163.repo
CentOS-Base.repo
CentOS-CR.repo
CentOS-Debuginfo.repo
CentOS-fasttrack.repo
CentOS-Media.repo
CentOS-Sources.repo
CentOS-Vault.repo

ansible常用模塊之yum

yum模塊用於在指定節點機器上通過yum管理軟件,其支持的參數主要有兩個

  • name:要管理的包名
  • state:要執行的操作
    state常用的值:
  • latest:安裝軟件
  • installd:安裝軟件
  • present :安裝軟件
  • removed:卸載軟件
  • absent:卸載軟件
    如果想使用yum來管理軟件,請確保受控主機上的yum源無異常

在受控主機上查詢vsftpd是否安裝

[root@linfan ~]# rpm -qa|grep vsftpd
[root@linfan ~]#                 

在ansible主機上使用yum模塊在受控主機上安裝vsftpd

[root@linfan ~]# ansible 192.168.24.130 -m yum -a 'name=vsftpd state=present'
192.168.24.130 | SUCCESS => {
    "changed": true,
    "msg": "Repository base is listed more than once in the configuration\nRepository updates is listed more than once in the configuration\nRepository extras is listed more than once in the configuration\nRepository centosplus is listed more than once in the configuration\n",
    "rc": 0,
    "results": [
        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package vsftpd.x86_64 0:3.0.2-22.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package          Arch             Version                 Repository      Size\n================================================================================\nInstalling:\n vsftpd           x86_64           3.0.2-22.el7            base           169 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 169 k\nInstalled size: 348 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : vsftpd-3.0.2-22.el7.x86_64                                   1/1 \n  Verifying  : vsftpd-3.0.2-22.el7.x86_64                                   1/1 \n\nInstalled:\n  vsftpd.x86_64 0:3.0.2-22.el7                                                  \n\nComplete!\n"
    ]
}

在受控主機上查看是否安裝了vsftpd

[root@linfan ~]# rpm -qa|grep vsftpd
vsftpd-3.0.2-22.el7.x86_64

ansible常用模塊之copy

copy模塊用於複製文件到受控機上

[root@linfan ~]# ls /etc/ansible/scripts
boss.sh
[root@linfan ~]# ansible 192.168.24.130 -m copy -a 'src=/etc/ansible/scripts/boss.sh dest=/scripts/'
192.168.24.130 | SUCCESS => {
    "changed": true,
    "checksum": "63432244439a6f90006e644666c8d9ad28f0cf11",
    "dest": "/scripts/boss.sh",
    "gid": 0,
    "group": "root",
    "md5sum": "ed0d4fb8e02362109f20dcb380fb8029",
    "mode": "0644",
    "owner": "root",
    "secontext": "system_u:object_r:default_t:s0",
    "size": 26,
    "src": "/root/.ansible/tmp/ansible-tmp-1536506836.61-157751882602101/source",
    "state": "file",
    "uid": 0
}
[root@linfan ~]# ansible 192.168.24.130 -a 'ls /scripts/'
192.168.24.130 | SUCCESS | rc=0 >>
boss.sh
test.sh

ansible常用模塊之group

group模塊用於受控主機上添加或刪除組

在受控主機上添加一個系統組,gid爲306,組名爲mysql

[root@linfan ~]# ansible 192.168.24.130 -m group -a 'name=mysql gid=306 state=present'
192.168.24.130 | SUCCESS => {
    "changed": true,
    "gid": 306,
    "name": "mysql",
    "state": "present",
    "system": false
}
[root@linfan ~]# ansible 192.168.24.130  -a 'grep mysql /etc/group'
192.168.24.130 | SUCCESS | rc=0 >>
mysql:x:306:

刪除受控主機上的mysql組

[root@linfan ~]# ansible 192.168.24.130 -m group -a 'name=mysql gid=306 state=absent'
192.168.24.130 | SUCCESS => {
    "changed": true,
    "name": "mysql",
    "state": "absent"
}
[root@linfan ~]# ansible 192.168.24.130  -a 'grep mysql /etc/group'
192.168.24.130 | FAILED | rc=1 >>
non-zero return code

ansible 常用模塊之user

user模塊用於管理受控主機上的用戶賬戶

在受控主機上添加一個系統用戶,用戶名爲mysql,uid爲306,設置其shell爲/sbin/nologin 無家目錄

[root@linfan ~]# ansible 192.168.24.130 -m  user -a 'name=mysql uid=306 system=yes create_home=no shell=/sbin/nologin state=present'
192.168.24.130 | SUCCESS => {
    "changed": true,
    "comment": "",
    "create_home": false,
    "group": 306,
    "home": "/home/mysql",
    "name": "mysql",
    "shell": "/sbin/nologin",
    "state": "present",
    "system": true,
    "uid": 306
}
[root@linfan ~]# ansible 192.168.24.130 -a 'grep mysql /etc/passwd'
192.168.24.130 | SUCCESS | rc=0 >>
mysql:x:306:3007::/home/mysql:/sbin/nologin

修改mysql用戶的uid爲366

[root@linfan ~]# ansible 192.168.24.130 -m user -a 'name=mysql uid=366'
192.168.24.130 | SUCCESS => {
    "append": false,
    "changed": true,
    "comment": "",
    "group": 3007,
    "home": "/home/mysql",
    "move_home": false,
    "name": "mysql",
    "shell": "/sbin/nologin",
    "state": "present",
    "uid": 366
}
[root@linfan ~]# ansible 192.168.24.130 -a 'grep mysql /etc/passwd'
192.168.24.130 | SUCCESS | rc=0 >>
mysql:x:366:3007::/home/mysql:/sbin/nologin

刪除受控主機上的mysql用戶

[root@linfan ~]# ansible 192.168.24.130 -m user -a 'name=mysql state=absent'
192.168.24.130 | SUCCESS => {
    "changed": true,
    "force": false,
    "name": "mysql",
    "remove": false,
    "state": "absent"
}
[root@linfan ~]# ansible 192.168.24.130 -a 'grep mysql /etc/passwd'
192.168.24.130 | FAILED | rc=1 >>
non-zero return code

ansible常用模塊之service

service模塊用於管理受控主機上的服務

查看受控主機上的vsftpd服務是否啓動

[root@linfan ~]# ansible 192.168.24.130 -a ' systemctl is-active vsftpd'
192.168.24.130 | FAILED | rc=3 >>
unknownnon-zero return code

啓動受控主機上的vsftpd服務

[root@linfan ~]# ansible 192.168.24.130 -m service -a 'name=vsftpd state=started'
192.168.24.130 | SUCCESS => { 
...
...

查看受控主機上的vsftpd服務是否開啓自啓動

[root@linfan ~]# ansible 192.168.24.130 -a ' systemctl is-enabled vsftpd'
192.168.24.130 | FAILED | rc=1 >>
disablednon-zero return code 

設置受控主機上的vsftpd服務開啓自啓動

[root@linfan ~]# ansible 192.168.24.130 -m service -a 'name=vsftpd enabled=yes'
192.168.24.130 | SUCCESS => {
    "changed": true,
    "enabled": true,
    "name": "vsftpd", 
    ...
    ...

查看受控主機上的vsftpd服務是否開機自啓動

[root@linfan ~]# ansible 192.168.24.130 -a ' systemctl is-enabled vsftpd'
192.168.24.130 | SUCCESS | rc=0 >>
enabled

停止受控主機上的vsftpd服務

[root@linfan ~]#  ansible 192.168.24.130 -m service -a 'name=vsftpd state=stopped'
192.168.24.130 | SUCCESS => {
    "changed": true,
    "name": "vsftpd",
    "state": "stopped",
    "status": { 
    ...
    ...
    [root@linfan ~]# ansible 192.168.24.130 -a 'systemctl is-active vsftpd'
192.168.24.130 | FAILED | rc=3 >>
inactivenon-zero return code

[root@linfan ~]# ansible 192.168.24.130 -m raw -a 'ss -natl'
192.168.24.130 | SUCCESS | rc=0 >>
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port
LISTEN     0      128          *:22                       *:*
LISTEN     0      100    127.0.0.1:25                       *:*
LISTEN     0      128         :::22                      :::*
LISTEN     0      100        ::1:25                      :::*
Shared connection to 192.168.24.130 closed.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章