1. 程式人生 > >自動化運維之Ansible

自動化運維之Ansible

name -o 所有者 ref random sum passwd 默認 -i

Ansible概述

Ansible基於Python開發,集合了眾多優秀運維工具的特點,實現了批量運行命令、部署程序、配置系統等功能。默認通過SSH協議進行遠程命令執行或下發配置,無需部署任何客戶端代理軟件,從而使得自動化環境部署變得更加簡單。可同時支持多臺主機並行管理,使得管理主機更加便捷。

Ansible核心組件

Ansible可以看作是一種基於模塊進行工作的框架結構,批量部署能力就是由Ansible所運行的模塊實現的。

Ansible基本架構有六個部分組成

  • Ansible core核心引擎
  • Host inventory主機清單:用來定義Ansible所管理的主機,默認是在Ansible的hosts配置文件中定義被管理主機,同時也支持自定義動態主機清單和指定其他配置文件的位置。
  • Connection plugins連接插件:負責和被管理主機實現通信。
  • Playbooks(yaml,jinja2)劇本:用來集中定義Ansible任務的配置文件,即將多個任務定義在一個劇本中由Ansible自動執行,可以由控制主機針對多臺被管理主機同時運行多個任務。
  • Core modules核心模塊:是Ansible自帶的模塊,使用執行模塊將資源分發到被管理主機,使其執行特定任務或匹配特定的狀態。
  • Custom modules自定義模塊:用於完成模塊功能的補充,可借助相關插件完成記錄日誌、發送郵件等功能。

安裝部署Ansible服務

Ansible自動化運維環境由控制主機與被管理主機組成,由於Ansibble是基於SSH協議進行通信的,所以控制主機安裝Ansible軟件後不需要重啟或運行任何程序,被管理主機也不需要安裝和運行任何代理程序。

Ansible環境表

技術分享圖片

實驗步驟

1.安裝Ansible

1)通過YUM方式安裝Ansible,需要依賴第三方的EPEL源,下面配置 epel源作為部署Ansible的yum源。

[root@localhost ~]# yum install epel-release -y

2)使用yum命令安裝ansible

[root@localhost ~]# yum install ansible -y
[root@localhost ~]# ansible --version    #查看版本信息
ansible 2.6.2
  config file = /etc/ansible/ansible.cfg
.....//省略

3)使用樹狀結構展示文件夾

[root@localhost ~]# yum install tree -y
[root@localhost ~]# tree /etc/ansible/  
/etc/ansible/  
├── ansible.cfg      #ansible的配置文件
├── hosts          #ansible的主倉庫,用於存儲需要管理的遠程主機的相關信息  
└── roles         #角色

2.配置主機清單

Ansible通過讀取默認主機清單/etc/ansible/hosts文件,修改主機與組配置後,可同時連接到多個被管理主機上執行任務。

[root@localhost ~]# vim /etc/ansible/hosts 
[webserver]    #被管理主機node2的別名,可自定義。
192.168.126.158

[mysql]       #被管理主機node3的別名,可自定義。
192.168.126.159

3.設置SSH無密碼登錄

為了避免Ansible下發指令時輸入被管理主機的密碼,可以通過證書簽名達到SSH無密碼登錄的效果,使用ssh-keygen產生一對密鑰,使用ssh-copy-id來下發生成的公鑰。

[root@localhost ~]# ssh-keygen -t rsa
Enter file in which to save the key (/root/.ssh/id_rsa):    #Enter
/root/.ssh/id_rsa already exists.
Enter passphrase (empty for no passphrase):   #輸入密碼
Enter same passphrase again:        #確認密碼
SHA256:RRrz8tRs6aW8YHDEVAp+Kfcn139TheaTAu0n8s4+AwU [email protected]
The key‘s randomart image is:
+---[RSA 2048]----+
|        +o+..    |
|       . OE* . . |
|        * @.* + .|
|         @ B.= o.|
|        S =.X B o|
|         ..+ O .o|
|           .o  .o|
|           oo   o|
|           .+o   |
+----[SHA256]-----+

[root@localhost ~]# ssh-copy-id [email protected]
Are you sure you want to continue connecting (yes/no)? yes
[email protected]‘s password:    #被管理主機的root登錄密碼

[root@localhost ~]# ssh-copy-id [email protected]
Are you sure you want to continue connecting (yes/no)? yes
[email protected]‘s password:    #被管理主機的root登錄密碼

免交互代理:
[root@localhost ~]# ssh-agent bash
[root@localhost ~]# ssh-add
Enter passphrase for /root/.ssh/id_rsa:   #免交互的密碼
Identity added: /root/.ssh/id_rsa (/root/.ssh/id_rsa)

到此Ansible的環境部署完成

Ansible基礎命令應用

1.command模塊

Ansible管理工具使用-m選項來指定使用模塊。默認使用command模塊,即-m選項省略時會運行此模塊,用於在被管理主機上運行命令。分別有三種執行命令的方式去管理寫入之際清單中的主機。如下所示:

[root@localhost ~]# ansible all -m command -a ‘date‘  #顯示所有被管理主機的時間
192.168.126.159 | SUCCESS | rc=0 >>
2018年 08月 02日 星期四 06:41:55 CST

192.168.126.158 | SUCCESS | rc=0 >>
2018年 08月 02日 星期四 06:41:55 CST

[root@localhost ~]# ansible 192.168.126.158 -m command -a ‘date‘  #指定ip執行date
192.168.126.158 | SUCCESS | rc=0 >>
2018年 08月 02日 星期四 06:44:46 CST

[root@localhost ~]# ansible webserver -m command -a ‘date‘    #/指定分類執行date
192.168.126.158 | SUCCESS | rc=0 >>
2018年 08月 02日 星期四 06:45:45 CST

2.cron模塊

cron模塊用於定義任務計劃。其中有兩種狀態(state):present表示添加(省略狀態時使用默認),absent表示移除。

[root@localhost ~]# ansible mysql -m cron -a ‘minute="*/1" job="/bin/echo haha" name="test cron job"‘     #添加任務計劃
192.168.126.159 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "test cron job"
    ]
}
[root@localhost ~]# ansible mysql -a ‘crontab -l‘   #查看任務計劃
192.168.126.159 | SUCCESS | rc=0 >>
#Ansible: test cron job
*/1 * * * * /bin/echo haha

[root@localhost ~]# ansible mysql -m cron -a ‘name="test cron job" state=absent‘  #移除計劃任務,假如該計劃任務沒有取名字,name=None即可
192.168.126.159 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": []
}
[root@localhost ~]# ansible mysql -a ‘crontab -l‘
192.168.126.159 | SUCCESS | rc=0 >>

3.user模塊

user用於創建新的用戶和更改、刪除已存在的用戶。其中name選項用來指明創建用戶的名稱。

[root@localhost ~]# ansible webserver -m user -a ‘name=zhangsan‘   #創建用戶
192.168.126.158 | SUCCESS => {
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 1001, 
    "home": "/home/zhangsan", 
    "name": "zhangsan", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 1001
}

被管理主機上查看是否有用戶zhangsan:
[root@localhost ~]# id zhangsan        #創建用戶成功
uid=1001(zhangsan) gid=1001(zhangsan) 組=1001(zhangsan)

[root@localhost ~]# ansible webserver -m user -a ‘name=zhangsan state=absent‘ #刪除用戶
192.168.126.158 | SUCCESS => {
    "changed": true, 
    "force": false, 
    "name": "zhangsan", 
    "remove": false, 
    "state": "absent"
}

查看:
[root@localhost ~]# id zhangsan   #刪除成功
id: zhangsan: no such user

4.group模塊

group模塊用於用戶組進行管理

[root@localhost ~]# ansible mysql -m group -a ‘name=mysql gid=406 system=yes‘ #創建mysql組,將mysql用戶添加到mysql組中。
192.168.126.159 | SUCCESS => {
    "changed": true, 
    "gid": 406, 
    "name": "mysql", 
    "state": "present", 
    "system": true
}
[root@localhost ~]# ansible mysql -a ‘tail /etc/group‘
192.168.126.159 | SUCCESS | rc=0 >>
slocate:x:21:
postdrop:x:90:
postfix:x:89:
stapusr:x:156:
stapsys:x:157:
stapdev:x:158:
tcpdump:x:72:
mysql:x:406:        #添加成功

[root@localhost ~]# ansible mysql -m user -a ‘name=lisi uid=304 system=yes group=mysql‘   #把用戶lisi添加到mysql組中
[root@localhost ~]# ansible mysql -a ‘id lisi‘   #查看用戶李四信息
192.168.126.159 | SUCCESS | rc=0 >>
uid=304(lisi) gid=406(mysql) 組=406(mysql),10(wheel)

5.copy模塊

copy模塊用於實現文件復制和批量下發文件。其中使用src來定義本地源文件路徑,使用dest定義被管理主機的文件路徑,使用content則是通過指定信息內容來生成目標文件。

1)將本地文件/etc/fstab復制到被管理主機上的/opt/fstab.back,將所有者設置為root,權限設置為604.

[root@localhost ~]# ansible mysql -m copy -a ‘src=/etc/fstab dest=/opt/fstab.back owner=root mode=640‘
192.168.126.159 | SUCCESS => {
    "changed": true, 
    "checksum": "242f00a74b3d3b43a062c02d905cdbeb9300677d", 
    "dest": "/opt/fstab.back", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "742b16b5d70b86faa48211e3b92b1a07", 
    "mode": "0640", 
    "owner": "root", 
    "secontext": "system_u:object_r:usr_t:s0", 
    "size": 465, 
    "src": "/root/.ansible/tmp/ansible-tmp-1533165452.1-274964488903006/source", 
    "state": "file", 
    "uid": 0
}
[root@localhost ~]# ansible mysql -a ‘ls -l /opt‘
192.168.126.159 | SUCCESS | rc=0 >>
lrwxrwxrwx. 1 root root  15 8月   1 21:22 fstab.link -> /opt/fstab.back

[root@localhost ~]# ansible mysql -a ‘cat /opt/fstab.back‘  #查看被管理主機/opt/目錄下的fstab.back
#
# /etc/fstab
# Created by anaconda on Thu May 31 18:13:32 2018
#
# Accessible filesystems, by reference, are maintained under ‘/dev/disk‘
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/centos-root /                       xfs     defaults        0 0
UUID=1a66bd48-697c-4fca-9822-1f2ada9250e3 /boot                   xfs     defaults        0 0
/dev/mapper/centos-swap swap                    swap    defaults        0 0

2)將hello wangwu寫入/opt/fstab.back

[root@localhost ~]# ansible mysql -m copy -a ‘content="hello wangwu!" dest=/opt/fstab.back‘
.....//省略
[root@localhost ~]# ansible mysql -a ‘cat /opt/fstab.back‘ 
192.168.126.159 | SUCCESS | rc=0 >>
hello wangwu!         #寫入成功
註意:
如果出現報錯,是因為被管理主機開啟了SELinux,需要在被管理主機上安裝libselinux-python軟件包,才可以使用Ansible中與copy、file相關函數。

6.file模塊

設置文件屬性,其中使用path指定文件路徑,使用src定義源文件路徑,使用name或dest來替換創建文件的符號鏈接。

1)設置文件/opt/fstab.back的屬主和屬組為mysql,權限為644.

[root@localhost ~]# ansible mysql -m file -a ‘owner=mysql group=mysql mode=644 path=/opt/fstab.back‘ 

查看:
[root@localhost ~]# ls -l /opt/fstab.back 
-rw-r--r--. 1 mysql mysql 465 8月   2 07:31 /opt/fstab.back

2)設置文件/opt/fstab.link為/opt/fstab.back的鏈接文件

[root@localhost ~]# ansible mysql -m file -a ‘path=/opt/fstab.link src=/opt/fstab.back state=link‘ 

3)文件的添加和刪除

[root@localhost ~]# ansible mysql -m file -a "path=/opt/test state=touch" #添加文件

查看被管理主機node3:
[root@localhost ~]# ls /opt/
apache-tomcat-8.5.16  fstab.back  fstab.link  jdk1.8.0_91  rh  script.txt  test

[root@localhost ~]# ansible mysql -m file -a "path=/opt/fstab.back state=absent" #刪除文件
[root@localhost ~]# ls /opt/
apache-tomcat-8.5.16  fstab.link  jdk1.8.0_91  rh  script.txt  test

7.ping模塊檢測指定主機的連通性

[root@localhost ~]# ansible all -m ping
192.168.126.159 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.126.158 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

8.yum模塊

yum模塊負責在被管理主機上安裝與卸載軟件包,但是需要提前在每個節點配置自己的YUM倉庫。其中使用name指定要安裝的軟件包,還需要帶上軟件包的版本號,否則安裝最新的軟件包;使用state指定安裝軟件包的狀態,present、latest用來表示安裝,absent表示卸載。

1)安裝httpd軟件包

[root@localhost ~]# ansible webserver -m yum -a ‘name=httpd‘

[root@localhost ~]# rpm -q httpd
httpd-2.4.6-80.el7.centos.1.x86_64

2)卸載httpd服務

[root@localhost ~]# ansible webserver -m yum -a ‘name=httpd state=absent‘

9.service模塊

控制服務的運行狀態,使用enable表示開機自啟動,取值為true或false;使用name定義服務名稱;使用state指定服務狀態,取值分別為started、stoped、restarted。

1)查看被管理主機node3的httpd服務狀態

[root@localhost ~]# ansible mysql -a ‘systemctl status httpd‘
192.168.126.159 | FAILED | rc=3 >>
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
   Active: inactive (dead)
     Docs: man:httpd(8)
           man:apachectl(8)non-zero return code

2)啟動httpd服務並設置為開機自啟動

[root@localhost ~]# ansible mysql -m service -a ‘enabled=true name=httpd state=started‘
192.168.126.159 | SUCCESS => {
    "changed": true, 
    "enabled": true, 
    "name": "httpd", 
    "state": "started", 
.....//省略

node3:
[root@localhost ~]# netstat -ntap | grep 80
tcp        0      0 192.168.126.159:22      192.168.126.10:55807    ESTABLISHED 2613/sshd: root@pts 
tcp6       0      0 :::80                   :::*                    LISTEN      6893/httpd    

10.shell模塊

shell模塊可以在被管理主機上運行命令,並支持像管道符號等功能的復雜命令。

[root@localhost ~]# ansible mysql -m shell -a ‘echo abc123|passwd --stdin lisi‘ #無交互模式給用戶設置密碼
192.168.126.159 | SUCCESS | rc=0 >>
更改用戶 lisi 的密碼 。
passwd:所有的身份驗證令牌已經成功更新。

11.script模塊

script模塊可以將本地腳本復制到被管理主機上進行運行。需要註意的是,使用相對路徑來指定腳本。

[root@localhost opt]# vim test.sh    #編輯本地腳本

#!/bin/bash
echo "hello ansible from script" > /opt/script.txt
[root@localhost opt]# chmod +x test.sh 

[root@localhost opt]# ansible webserver -m script -a ‘test.sh‘  #復制到被管理主機上運行
192.168.126.158 | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.126.158 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.126.158 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}

node3:
[root@localhost ~]# cat /opt/script.txt   
hello ansible from script

12.setup模塊

setup模塊收集、查看被管理主機的設備信息的一個功能。每個被管理主機在接收並運行管理命令之前,都會將自己的相關消息發送給控制主機。

[root@localhost ~]# ansible mysql -m setup   #輸出信息太多,這裏省略

自動化運維之Ansible