文章目錄
自動化運維的含義
1.手動運維時代
2.自動化運維時代
3.自動化運維工具給運維帶來的好處
Ansible 基礎及安裝
1.什麼是Ansible
Ansible是一個自動化統一配置管理工具
2.同類型軟件對比
1.puppet 學習難,安裝ruby環境難,沒有遠程執行功能 2.ansible 輕量級,大規模環境下只通過ssh會很慢,串行的 3.saltstack 一般選擇salt會使用C/S
結構的模式,salt-master
和salt-minion
,並行的,大規模批量操作的情況下,會比Ansible速度快一些,底層使用的是zero-MQ
消協隊列
Ansible使用的是python2
saltstack即有python2也有python3
*Ansible的功能及優點*
1.遠程執行 批量執行遠程命令,可以對多臺主機進行遠程操作
2.配置管理 批量配置軟件服務,可以進行自動化方式配置,服務的統一配置管理,和啓停
3.事件驅動 通過Ansible的模塊,對服務進行不同的事件驅動 比如: 1)修改配置後重啓 2)只修改配置文件,不重啓 3)修改配置文件後,重新加載 4)遠程啓停服務管理
4.管理公有云 通過API接口的方式管理公有云,不過這方面做的不如saltstack
. saltstack本身可以通過saltcloud管理各大雲廠商的雲平臺。
5.二次開發 因爲語法是Python,所以便於運維進行二次開發。
6.任務編排 可以通過playbook的方式來統一管理服務,並且可以使用一條命令,實現一套架構的部署
7.跨平臺,跨系統 幾乎不受到平臺和系統的限制,比如安裝apache
和啓動服務
在Ubuntu上安裝apache服務名字叫apache2 在CentOS上安裝apache服務名字叫httpd
在CentOS6上啓動服務器使用命令:/etc/init.d/nginx start 在CentOS7上啓動服務器使用命令:systemctl start nginx
Ansible的架構
1、連接插件connectior plugins用於連接主機 用來連接被管理端
2、核心模塊 core modules 連接主機實現操作, 它依賴於具體的模塊來做具體的事情
3、自定義模塊 custom modules,根據自己的需求編寫具體的模塊
4、插件 plugins,完成模塊功能的補充
5、劇本 playbooks,ansible的配置文件,將多個任務定義在劇本中,由ansible自動執行
6、主機清單 inventor,定義ansible需要操作主機的範圍最重要的一點是 ansible是模塊化的 它所有的操作都依賴於模塊
Ansible的執行流程
1.Ansible讀取playbook劇本,劇本中會記錄對哪些主機執行哪些任務。 2.首先Ansible通過主機清單找到要執行的主機,然後調用具體的模塊。 3.其次Ansible會通過連接插件連接對應的主機並推送對應的任務列表。 4.最後被管理的主機會將Ansible發送過來的任務解析爲本地Shell命令執行。
*安裝Ansible*
1.環境準備
主機名 | wanIP | lanIP | 角色 |
---|---|---|---|
m01 | 10.0.0.61 | 172.16.1.61 | Ansible控制端 |
web01 | 10.0.0.7 | 172.16.1.7 | Ansible被控端 |
web02 | 10.0.0.8 | 172.16.1.8 | Ansible被控端 |
2.安裝ansible
[root@m01 ~]# yum install -y ansible
3.查看ansible模塊及版本
[root@m01 ~]# ansible --version
ansible 2.8.4
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, Oct 30 2018, 23:45:53) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
4.ansible參數
# ansible <host-pattern> [options]
--version #ansible版本信息
-v #顯示詳細信息
-i #主機清單文件路徑,默認是在/etc/ansible/hosts
-m #使用的模塊名稱,默認使用command模塊
-a #使用的模塊參數,模塊的具體動作
-k #提示輸入ssh密碼,而不使用基於ssh的密鑰認證
-C #模擬執行測試,但不會真的執行
-T #執行命令的超時
5.ansible配置文件讀取順序
[root@m01 ~]# vim /etc/ansible/ansible.cfg
# nearly all parameters can be overridden in ansible-playbook
# or with command line flags. ansible will read ANSIBLE_CONFIG,
# ansible.cfg in the current working directory, .ansible.cfg in
# the home directory or /etc/ansible/ansible.cfg, whichever it
# finds first
1、$ANSIBLE_CONFIG
2、./ansible.cfg
3、~/.ansible.cfg
4、/etc/ansible/ansible.cfg
ansible配置文件
#inventory = /etc/ansible/hosts #主機列表配置文件
#library = /usr/share/my_modules/ #庫文件存放目錄
#remote_tmp = ~/.ansible/tmp #臨時py文件存放在遠程主機目錄
#local_tmp = ~/.ansible/tmp #本機的臨時執行目錄
#forks = 5 #默認併發數
#sudo_user = root #默認sudo用戶
#ask_sudo_pass = True #每次執行是否詢問sudo的ssh密碼
#ask_pass = True #每次執行是否詢問ssh密碼
#remote_port = 22 #遠程主機端口
host_key_checking = False #跳過檢查主機指紋
log_path = /var/log/ansible.log #ansible日誌
#普通用戶提權操作
[privilege_escalation]
#become=True
#become_method=sudo
#become_user=root
#become_ask_pass=False
ansible Inventory(主機清單文件)
/etc/ansible/hosts
是ansible 默認主機資產清單文件,用於定義被管理機的認證信息,例如ssh登錄用戶名、密碼、以及key相關信息。Inventory文件中填寫需要被管理的主機與主機組信息。還可以自定義Inventory 主機清單的位置,使用-i 指定文件位置即可。
場景一:密碼方式連接
[root@m01 ~]# cat /etc/ansible/hosts
#方式一、IP+端口+用戶+密碼
[webs]
10.0.0.7 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass='1'
10.0.0.8 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass='1'
#方式二、主機名+密碼
[webs]
web0[1:2] ansible_ssh_pass='123456'
#方式三、主機+密碼
[webs]
web0[1:2]
[webs:vars]
ansible_ssh_pass='123456'
注意:方式二和方式三,都需要做hosts解析
場景二:密鑰方式連接,需要先創建公鑰和私鑰,並下發公鑰至被控端
#創建密鑰對
[root@m01 ~]# ssh-keygen
#推送公鑰
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
#方式一:主機+端口+密鑰
[web_group]
172.16.1.7
172.16.1.8
#方式二:別名+主機+端口+密鑰
[webs]
web01 ansible_ssh_host=172.16.1.7
web02 ansible_ssh_host=172.16.1.8
場景三:主機組定義方式
[root@m01 ~]# vim hosts
[web_group]
web01 ansible_ssh_host=172.16.1.7
web02 ansible_ssh_host=172.16.1.8
[db_group]
db01 ansible_ssh_host=172.16.1.51
lb01 ansible_ssh_host=172.16.1.5
[db_group:vars]
ansible_ssh_pass='1'
[nfs_group]
nfs ansible_ssh_host=172.16.1.31
#定義多組,多組彙總整合
[nfs_server:children]
web_group
nfs_group
[lnmp:children]
web_group
db_group
#查看所有主機數量
[root@m01 ~]# ansible 'all' --list-host
hosts (5):
nfs
web01
web02
db01
lb01
[root@m01 ~]# ansible 'web_group' --list-host
hosts (2):
web01
web02
[root@m01 ~]# ansible 'db_group' --list-host
hosts (2):
db01
lb01
[root@m01 ~]# ansible 'lnmp' --list-host
hosts (4):
web01
web02
db01
lb01
Ansible ad-hoc
1.什麼是AD-HOC
ad-hoc 簡而言之就是臨時命令,執行完即結束,並不會保存
2.ad-hoc模式的使用場景
比如在多臺機器上查看某個進程是否啓動,或拷貝指定文件到本地,等等。
3.ad-hoc模式的命令使用
ad-hoc 執行結果返回顏色說明
綠色: 代表被管理端主機沒有被修改,或者只是對遠程節點信息進行查看
黃色: 代表被管理端主機發現變更
紅色: 代表出現了故障,注意查看提示
紫色:表示對命令執行發出警告信息(可能存在的問題,給你一下建議)
ansible常用模塊
*1.command命令模塊*
# 默認模塊, 執行命令
[root@m01 ~]# ansible 'web_group' -a "hostname"
# 如果需要一些管道操作,則使用shell
[root@m01 ~]# ansible 'web_group' -m shell -a "ifconfig|grep eth0" -f 50
# -f =forks /etc/ansible/ansible.cfg #結果返回的數量
[root@m01 ~]# ansible 'web_group' -m command -a 'free -m'
web02 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 972 140 489 7 342 658
Swap: 1023 0 1023
web01 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 972 113 412 13 446 669
Swap: 1023 0 1023
*2.shell*
[root@m01 ~]# ansible 'web_group' -m shell -a 'ps -ef|grep nginx'
web02 | CHANGED | rc=0 >>
root 12584 12583 0 20:16 pts/1 00:00:00 /bin/sh -c ps -ef|grep nginx
root 12586 12584 0 20:16 pts/1 00:00:00 grep nginx
web01 | CHANGED | rc=0 >>
root 14575 14570 0 12:16 pts/1 00:00:00 /bin/sh -c ps -ef|grep nginx
root 14577 14575 0 12:16 pts/1 00:00:00 grep nginx
注意:
1)command不支持特殊符號
2)shell模塊支持特殊符號
3)不指定-m 默認使用的是command模塊
*3.script腳本模塊*
#編寫腳本
[root@m01 ~]# vim vsftpd.sh
#!/usr/bin/bash
mkdir /tmp/zls
#在本地運行模塊,等同於在遠程執行,不需要將腳本文件進行推送目標主機執行
[root@m01 ~]# ansible 'web01' -m script -a '/root/vsftpd.sh'
[root@m01 ~]# ansible 'web01' -m shell -a 'ls -l /tmp'
*4.yum安裝軟件模塊*
[root@m01 ~]# ansible 'web_group' -m yum -a 'name=vsftpd state=present'
#相當於:yum install -y vsftpd
[root@m01 ~]# ansible 'web_group' -m yum -a 'name=https://mirrors.aliyun.com/zabbix/zabbix/4.0/rhel/7/x86_64/zabbix-agent-4.0.0-2.el7.x86_64.rpm state=present'
#相當於:yum install -y https://mirrors.aliyun.com/zabbix/zabbix/4.0/rhel/7/x86_64/zabbix-agent-4.0.0-2.el7.x86_64.rpm
[root@m01 ~]# ansible 'web_group' -m yum -a 'name=file:///root/nagios-4.4.3-1.el7.x86_64.rpm state=present'
#相當於:yum localinstall -y nagios-4.4.3-1.el7.x86_64.rpm
[root@m01 ~]# ansible 'web_group' -m yum -a 'name=vsftpd state=absent'
#相當於:yum remove -y vsftpd
name
httpd #指定要安裝的軟件包名稱
file:// #指定本地安裝路徑(yum localinstall 本地rpm包)
http:// #指定yum源(從遠程倉庫獲取rpm包)
state #指定使用yum的方法
installed,present #安裝軟件包
removed,absent #移除軟件包
latest #安裝最新軟件包
*5.yum_repository*
- name: Add repository
yum_repository:
name: epel
description: EPEL YUM repo
baseurl: https://download.fedoraproject.org/pub/epel/$releasever/$basearch/
#添加yum倉庫
ansible 'web_group' -m yum_repository -a 'name=zls_epel description=EPEL baseurl=https://download.fedoraproject.org/pub/epel/$releasever/$basearch/ gpgcheck=no enabled=yes file=zls_epel'
#添加mirrorlist
ansible 'web_group' -m yum_repository -a 'name=zls_epel description=EPEL baseurl=https://download.fedoraproject.org/pub/epel/$releasever/$basearch/ gpgcheck=no enabled=yes file=epel mirrorlist=http://mirrorlist.repoforge.org/el7/mirrors-rpmforge'
#刪除yum倉庫
ansible 'web_group' -m yum_repository -a 'name=zls_epel,zls_base file=zls_epel state=absent'
#修改yum倉庫
ansible 'web_group' -m yum_repository -a 'name=epel description=EPEL baseurl=https://download.fedoraproject.org/pub/epel/$releasever/$basearch/ gpgcheck=no enabled=no file=epel'
name #指定倉庫名字
description #添加描述(repo文件中的name)
baseurl #指定yum倉庫的地址
gpgcheck #是否開啓校驗
yes
no
enabled #是否啓用yum倉庫
yes
no
file #指定倉庫文件名
state
absent #刪除yum倉庫
present #創建yum倉庫
ansible 'web_group' -m yum_repository -a 'name=zls_yum description=EPEL baseurl=http://www.driverzeng.com gpgcheck=no enabled=no file=zls'
*ansible文件管理模塊*
*1.copy*
- name: Copy file with owner and permissions
copy:
src: /srv/myfiles/foo.conf
dest: /etc/foo.conf
owner: foo
group: foo
mode: '0644'
#推送文件
[root@m01 ~]# ansible 'web_group' -m copy -a 'src=/root/index.html dest=/var/www/html owner=root group=root mode=0644'
#推送文件並備份
[root@m01 ~]# ansible 'web_group' -m copy -a 'src=/root/index.html dest=/var/www/html owner=root group=root mode=0644 backup=yes'
#編輯nfs配置文件
[root@m01 ~]# ansible 'web_group' -m copy -a 'content="/data 172.16.1.0/24(rw,sync,all_squash,anonuid=666,anongid=666)" dest=/etc/exports'
src #指定推送的源文件
dest #指定推送的目標位置
owner #指定屬主
group #指定屬組
mode #指定權限(數字方式)
content #在指定文件中添加內容
backup #是否備份(注意:控制端和被控端,內容不一致纔會備份)
yes
no
*2.file文件配置模塊*
- name: Create an insecure file
file:
path: /work
owner: root
group: root
mode: 0755
#創建目錄 mkdir
[root@m01 ~]# ansible 'web_group' -m file -a 'path=/backup state=directory owner=adm group=adm mode=0700'
#遞歸創建目錄並授權chown -R chmod -R
[root@m01 ~]# ansible 'web_group' -m file -a 'path=/zls/mysql/db01 state=directory owner=adm group=adm mode=0700 recurse=yes'
#創建文件(前提條件,上級目錄必須存在) touch
[root@m01 ~]# ansible 'web_group' -m file -a 'path=/root/zls.txt state=touch'
#刪除目錄 rm -fr
[root@m01 ~]# ansible 'web_group' -m file -a 'path=/backup state=absent'
#做軟鏈接 ln -s
[root@m01 ~]# ansible 'web_group' -m file -a 'src=/root/zls.txt dest=/root/zls.txt.ori state=link'
src #指定軟鏈接的源文件
dest #指定軟連接的目標文件
path #指定創建目錄或文件
state
touch #創建文件
directory #創建目錄
absent #刪除目錄或文件
link #做軟鏈接
owner #指定屬主
group #指定屬組
mode #指定權限
recurse #遞歸授權
yes
no
*3.get_url服務模塊*
- name: Download foo.conf
get_url:
url: http://example.com/path/file.conf
dest: /etc/foo.conf
mode: '0440'
#下載worldpress代碼
[root@m01 ~]# ansible 'web_group' -m get_url -a 'url=http://test.driverzeng.com/Nginx_Code/wordpress-5.0.3-zh_CN.tar.gz dest=/root mode=0777'
#下載並校驗MD5
[root@m01 ~]# ansible 'web_group' -m get_url -a 'url=http://test.driverzeng.com/Nginx_Code/test.txt dest=/root mode=0777 checksum=md5:ba1f2511fc30423bdbb183fe33f3dd0f'
url #指定下載文件的url
dest #指定下載的位置
mode #指定下載後的權限
checksum #校驗
md5 #md5校驗
sha256 #sha256校驗
*ansible服務管理模塊*
*1.service,systemd*
[root@m01 ~]# ansible 'web_group' -m systemd -a 'name=httpd state=stopped enabled=yes'
[root@m01 ~]# ansible 'web_group' -m systemd -a 'name=httpd state=started enabled=yes'
[root@m01 ~]# ansible 'web_group' -m systemd -a 'name=httpd state=restarted enabled=yes'
[root@m01 ~]# ansible 'web_group' -m systemd -a 'name=httpd state=reloaded enabled=yes'
name #指定服務名稱
state
started #啓動
stopped #停止
restarted #重啓
reloaded #重載
enabled #是否開機自啓
yes
no
*ansible用戶管理模塊*
*1.group*
- name: Ensure group "somegroup" exists
group:
name: somegroup
state: present
#創建組
[root@m01 ~]# ansible 'web_group' -m group -a 'name=www gid=666 state=present'
#刪除組
[root@m01 ~]# ansible 'web_group' -m group -a 'name=www gid=666 state=absent'
name #指定組名
gid #指定gid
state
present #創建
absent #刪除
*2.user*
- name: Create a 2048-bit SSH key for user jsmith in ~jsmith/.ssh/id_rsa
user:
name: jsmith
generate_ssh_key: yes
ssh_key_bits: 2048
ssh_key_file: .ssh/id_rsa
#創建用戶
[root@m01 ~]# ansible 'web_group' -m user -a 'name=www uid=666 group=www state=present shell=/sbin/nologin create_home=false'
#刪除用戶
[root@m01 ~]# ansible 'web_group' -m user -a 'name=www uid=666 state=absent'
#創建用戶的同時創建密鑰對
[root@m01 ~]# ansible 'web_group' -m user -a 'name=zls generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa'
name #指定用戶名
uid #指定uid
group #指定屬組
groups #指定附加組
state
present #創建用戶
absent #刪除用戶
shell #指定用戶登錄的shell
/bin/bash
/sbin/nologin
create_home #是否創建家目錄
true
false
comment #添加註釋
generate_ssh_key #創建密鑰對
ssh_key_bits #指定密鑰對長度
ssh_key_file #指定密鑰文件
實戰
寫主機清單,一鍵部署rsync,nfs,nginx,httpd,上傳作業代碼
1.配置主機
[root@m01 ~]# yum install -y ansible
#創建密鑰對
[root@m01 ~]# ssh-keygen
#推送公鑰
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
2.編寫主機清單
[web_group]
gjy_web01 ansible_ssh_host=172.16.1.7
gjy_web02 ansible_ssh_host=172.16.1.8
gjy_web03 ansible_ssh_host=172.16.1.9
[db_group]
gjy_db01 ansible_ssh_host=172.16.1.51
gjy_db02 ansible_ssh_host=172.16.1.52
[nfs_group]
gjy_nfs ansible_ssh_host=172.16.1.31
[backup_group]
gjy_backup ansible_ssh_host=172.16.1.41
[daili_group]
gjy_lb01 ansible_ssh_host=172.16.1.5
gjy_lb02 ansible_ssh_host=172.16.1.6
[m01]
gjy_m01 ansible_ssh_host=172.16.1.61
[rsync_server:children]
nfs_group
backup_group
[nfs_server:children]
web_group
nfs_group
[lnmp_server:children]
web_group
daili_group
3.先編寫一個比較low的腳本測試下
#!/bin/bash
#創建用戶及組
ansible 'all' -m group -a 'name=www gid=666 state=present' &&\
ansible 'all' -m user -a 'name=www uid=666 group=www state=present shell=/sbin/nologin create_home=false' &&\
#部署httpd服務
ansible 'web_group' -m yum -a 'name=httpd,php state=present' &&\
#替換http服務啓動用戶及組
ansible 'web_group' -m shell -a "sed -i '/^User/c User www' /etc/httpd/conf/httpd.conf" &&\
ansible 'web_group' -m shell -a "sed -i '/^Group/c Group www' /etc/httpd/conf/httpd.conf" &&\
#啓動httpd服務
ansible 'web_group' -m systemd -a 'name=httpd state=started enabled=yes' &&\
#上傳代碼,並修改圖片路徑
ansible 'web_group' -m copy -a 'src=/root/httpd_file/ dest=/var/www/html/ owner=www group=www '
#遠程推送作業代碼
ansible 'web_group' -m file -a 'path=/var/www/html/uploads state=directory owner=www group=www' &&\
#部署nfs服務
ansible 'nfs_server' -m yum -a 'name=nfs-utils state=present' &&\
#推送nfs服務配置文件
ansible 'nfs_group' -m copy -a 'content="/data 172.16.1.0/24(rw,sync,all_squash,anonuid=666,anongid=666)" dest=/etc/exports' &&\
#啓動nfs服務並開機自啓
ansible 'nfs_server' -m systemd -a 'name=nfs-server state=started enabled=yes' &&\
#遠程下載rsync服務
ansible 'rsync_server' -m yum -a 'name=rsync state=present' &&\
#推送rsync配置文件
ansible 'backup_group' -m copy -a 'src=/root/rsync_file dest=/etc/rsyncd.conf' &&\
#推送密碼文件至rsync服務端
ansible 'backup_group' -m copy -a 'content=rsync_backup:123 dest=/etc/rsync.passwd mode=0600' &&\
#推送密碼文件至rsync客戶端
ansible 'nfs_group' -m copy -a 'content=123 dest=/etc/rsync.pass mode=0600' &&\
#啓動rsync服務,並加入開機自啓
ansible 'rsync_server' -m systemd -a 'name=rsyncd state=started enabled=yes' &&\
#遠程下載mariadb服務
ansible 'db_group' -m yum -a 'name=mariadb-server state=present' &&\
#啓動並加入開機自啓
ansible 'db_group' -m systemd -a 'name=mariadb state=started enabled=yes' &&\
#推送nginx 官方源
ansible 'lnmp_server' -m copy -a 'src=/etc/yum.repos.d/nginx.repo dest=/etc/yum.repos.d/' &&\
#遠程下載nginx
ansible 'lnmp_server' -m yum -a 'name=nginx state=present' &&\
#遠程修改nginx配置文件
ansible 'lnmp_server' -m shell -a "sed -i '/^user/c user www;' /etc/nginx/nginx.conf" &&\
#啓動nginx
ansible 'lnmp_server' -m systemd -a 'name=nginx state=started enabled=yes'
4.寫與腳本對應的配置文件
[root@m01 ~]# vim /root/rsync_file
uid = www
gid = www
port = 873
fake super = yes
use chroot = no
max connections = 200
timeout = 600
ignore errors
read only = false
list = false
auth users = rsync_backup
secrets file = /etc/rsync.passwd
log file = /var/log/rsyncd.log
#####################################
[backup]
comment = welcome to oldboyedu backup!
path = /backup
[data]
comment = welcome to oldboyedu nfs!
path = /data
#傳作業壓縮包到目錄裏,並解壓修改上傳圖片路徑
[root@m01 ~]# cd httpd_file
#編寫nginx官方源
[root@m01 ~]# vim /etc/yum.repos.d/nginx.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1
5.執行腳本 測試:1.web上http服務,上傳作業代碼
2.lb_group,nginx服務
3.測試db_group ,mysql服務
4.測試nfs配置
5.測試rsync服務
ansible 流程控制
playbook 條件語句
不管是 shell
還是各大編程預言中,流程控制,條件判斷都是必不可少的,在我們使用 Ansible
的過程中,條件判斷的使用頻率都非常高。
例如:
1. 我們使用不同的系統的時候,可以通過判斷系統 來對軟件包進行安裝。
2. 在 nfs和 rsync 安裝過程中,客戶端服務器不需要推送配置文件,之前我們都是寫多個play,會影響效率。
3. 我們在源碼安裝nginx 的時候,執行第二遍就無法執行了,此時我們就可以進行判斷是否安裝過。
根據不同的操作系統安裝apache
官方示例:
tasks:
- name: "shut down Debian flavored systems"
command: /sbin/shutdown -t now
when: ansible_facts['os_family'] == "Debian"
# note that all variables can be used directly in conditionals without double curly braces
示例: 根據不同的 系統安裝不同的服務
- hosts: web_group
tasks:
- name: Install CentOS Htt
state: present
#官方
when: ansible_facts['os_family'] == "CentOS"
#非官方
when: ansible_distribution == "CentOS"
- name: Install Ubuntu Httpd
yum:
name: apache2
state: present
when: ansible_facts['os_family'] == "Ubuntu"
可以使用括號對條件進行分組
tasks:
- name: "shut down CentOS 6 and Debian 7 systems"
command: /sbin/shutdown -t now
when: (ansible_facts['distribution'] == "CentOS" and ansible_facts['distribution_major_version'] == "6") or
(ansible_facts['distribution'] == "Debian" and ansible_facts['distribution_major_version'] == "7")
可以指定多條件爲列表
tasks:
- name: "shut down CentOS 6 systems"
command: /sbin/shutdown -t now
when:
- ansible_facts['distribution'] == "CentOS"
- ansible_facts['distribution_major_version'] == "6"
條件運算
tasks:
- shell: echo "only on Red Hat 6, derivatives, and later"
when: ansible_facts['os_family'] == "RedHat" and ansible_facts['lsb']['major_release']|int >= 6
rsync服務端推送配置文件
[root@m01 ~]# cat rsyncd/rsyncd.yml
- hosts: rsync_server
tasks:
- name: Install Rsyncd Server
yum:
name: rsync
state: present
- name: Create www Group
group:
name: www
gid: 666
- name: Create www User
user:
name: www
group: www
uid: 666
create_home: false
shell: /sbin/nologin
- name: Scp Rsync Config
copy:
src: ./rsyncd.j2
dest: /etc/rsyncd.conf
owner: root
group: root
mode: 0644
when: ansible_hostname == "backup"
- name: Create Passwd File
copy:
content: 'rsync_backup:123'
dest: /etc/rsync.passwd
owner: root
group: root
mode: 0600
when: ansible_hostname == "backup"
- name: Create backup Directory
file:
path: /backup
state: directory
mode: 0755
owner: www
name: rsyncd
state: started
when: ansible_hostname == "backup"
rsync客戶端推送腳本
[root@m01 ~]# vim rsync.yml
- hosts: rsync_server
tasks:
- name: SCP Backup Shell
copy:
src: ./backup.sh
dest: /root/backup.sh
when: ansible_hostname is match "web*"
#執行結果
PLAY [rsync_server] **************************************************************************************************************************************************************************************************************************
TASK [Gathering Facts] ***********************************************************************************************************************************************************************************************************************
ok: [web02]
ok: [backup]
ok: [web01]
TASK [SCP Backup Shell] **********************************************************************************************************************************************************************************************************************
skipping: [backup]
changed: [web01]
changed: [web02]
PLAY RECAP ***********************************************************************************************************************************************************************************************************************************
backup : ok=1 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0
web01 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
web02 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
通過register將命令執行結果保存至變量,然後通過when 語句進行判斷
- hosts: web_group
tasks:
- name: Check Httpd Server
command: systemctl is-active httpd
ignore_errors: yes
register: check_httpd
- name: debug outprint
debug: var=check_httpd
- name: Httpd Restart
service:
name: httpd
state: restarted
when: check_httpd.rc == 0
使用when判斷主機名
- hosts: rsync_server
tasks:
- name: Install rsyncd Server
yum:
name: rsync
state: present
- name: Config rsyncd Conf
copy:
src: ./rsyncd.j2
dest: /etc/rsyncd.conf
owner: root
group: root
mode: 0644
when: ansible_fqdn == 'backup'
- name: Create dir
file:
path: /backup
state: directory
owner: www
group: www
mode: 0755
recurse: yes
when: ansible_fqdn == 'backup'
- name: Create passwd file
copy:
content: "rsync_backup:123"
dest: /etc/rsync.passwd
owner: root
group: root
mode: 0600
when: ansible_fqdn == 'backup'
#單條件判斷
- name: Start rsyncd
systemd:
name: rsyncd
state: started
enabled: yes
when: ansible_fqdn == 'backup'
#多條件判斷,使用小括號分組
- name: copy shell
template:
src: ./backup.sh
dest: /root
when: (ansible_fqdn == 'web01') or (ansible_fqdn == 'web02')
#多條件判斷,使用list列表形式
- name: copy shell
template:
src: ./backup.sh
dest: /root
when:
- ansible_fqdn == 'web01'
- ansible_fqdn == 'web02'
#多條件判斷,使用is match 支持通配符
- name: Add Crontab
cron:
name: "backup"
minute: "00"
hour: "01"
job: "/bin/sh /root/backup.sh &>/dev/null"
when: ansible_fqdn is match 'web*'
2.使用when判斷系統
- hosts: webs
tasks:
- name: Install CentOS Apache
yum:
name: httpd
state: present
when: ansible_distribution == 'CentOS'
- name: Install Ubuntu Apache
apt:
name: apache2
state: present
when: ansible_distribution == 'Ubuntu'
3.使用when判斷系統版本
- hosts: webs
tasks:
- name: Start CentOS6 Httpd
shell: "/etc/init.d/httpd start"
when: ansible_distribution_major_version == '6'
- name: Start CentOS7 Httpd
shell: "systemctl start httpd"
when: ansible_distribution_major_version == '7'
4.使用註冊變量對返回值進行判斷
- name: pan duan rpm bao
shell: "rpm -qa|grep php"
register: check_php
- name: Install php
shell: "cd /usr/local/src && rpm -Uvh *rpm"
when: check_php.rc != 0
playbook 循環語句
創建目錄之類的操作,2個目錄就要寫兩個file 模塊來創建,如果有循環,可以減少重複性代碼。
1.啓動多個服務
- hosts: web_group
tasks:
- name: start service
systemd:
name: "{{ item }}"
state: started
with_items:
- httpd
- php-fpm
- mariadb
2.定義變量循環
- name: ensure a list of packages installed
yum:
name: "{{ packages }}"
vars:
packages:
- httpd
- httpd-tools
- hosts: web_group
tasks:
- name: ensure a list of packages installed
yum: name= "{{ item }}" state=present
with_items:
- httpd
- httpd-tools
3.字典循環
拷貝文件
- hosts: web_group
tasks:
- name: copy conf and code
copy:
src: "{{ item.src }}"
dest: "{{ item.dest }}"
mode: "{{ item.mode }}"
with_items:
- { src: "./httpd.conf", dest: "/etc/httpd/conf/", mode: "0644" }
- { src: "./upload_file.php", dest: "/var/www/html/", mode: "0600" }
- name: tar php and nginx and wordpress
unarchive:
src: "{{ item.src }}"
dest: "{{ item.dest }}"
owner: "{{ item.user }}"
group: "{{ item.user }}"
copy: yes
with_items:
- { src: "./php.tgz", dest: "/usr/local/src", user: "root" }
- { src: "./nginx-1.16.0.tar.gz", dest: "/root", user: "root" }
- { src: "./wordpress.tgz", dest: "/code", user: "www" }
ansible handlers(觸發器)
handler 用來執行某些條件下的任務,比如當配置文件發生變化的時候,通過notify 觸發 handler去重啓服務。
在saltstack中也有類似的觸發器,寫法相對Ansible簡單,只需要watch,配置文件即可。
實踐案例:
- name: scp nginx shell conf
copy:
src: "{{ item.src }}"
dest: "{{ item.dest }}"
with_items:
- { src: "./nginx.service", dest: "/usr/lib/systemd/system" }
- { src: "./nginx.conf", dest: "/usr/local/nginx/conf/" }
- { src: "./www.drz.com.conf", dest: "/usr/local/nginx/conf/conf.d" }
#添加觸發器
notify: reload nginx
handlers:
- name: reload nginx
systemd:
name: nginx
state: reloaded
注意:
1.無論多少個task通知了相同的handlers,handlers僅會在所有tasks結束後運行一次。
2.Handlers只有在其所在的任務被執行時,纔會被運行;如果一個任務中定義了notify調用Handlers,但是由於條件判斷等原因,該任務未被執行,那麼Handlers同樣不會被執行。
3.Handlers只會在每一個play的末尾運行一次;如果想在一個playbook中間運行Handlers,則需要使用meta模塊來實現。例如: -meta: flush_handlers。
4.如果一個play在運行到調用Handlers的語句之前失敗了,那麼這個Handlers將不會被執行。我們可以使用meta模塊的–force-handlers選項來強制執行Handlers,即使Handlers所在的play中途運行失敗也能執行。
5.不能使用handlers替代tasks
playbook任務標籤
默認情 況下,Ansible 在執行一個playbook 時,會執行playbook中定義的所有任務,Ansible的標籤 (tag)功能可以給單獨任務甚至整個playbook 打上標籤,然後利用這些標籤來指定要運行playbook中的個別任務,或不執行制定的任務。
打標籤的方式
- 對一個task打一個標籤
- 對一個task打多個標籤
- 對多個task打一個標籤
打完標籤如何使用
-t : 指定的tag標籤任務
–skip-tags : 執行–skip-tags之外的標籤任務
使用 - t 指定 tag
[root@m01 m01]# cat tag.yml
- hosts: web_group
vars:
- http_port: 8080
tasks:
- name: Install Http Server
yum:
name: httpd
state: present
tags:
- install_httpd
- httpd_server
- name: configure httpd server
template:
src: ./httpd.j2
dest: /etc/httpd/conf/httpd.conf
notify: Restart Httpd Server
tags:
- config_httpd
- httpd_server
- name: start httpd server
service:
name: httpd
state: started
enabled: yes
tags: service_httpd
handlers:
- name: Restart Httpd Server
systemd:
name: httpd
state: restarted
[root@m01 m01]# ansible-playbook tag.yml --list-tags
[root@m01 m01]# ansible-playbook tag.yml -t httpd_server
[root@m01 m01]# ansible-playbook tag.yml -t install_httpd,confiure_httpd
[root@m01 m01]# ansible-playbook tag.yml --skip-tags httpd_server
playbo ok複用include
在之前寫playbook的過程中,寫多個playbook沒有辦法一鍵執行,所以playbook 中有一個功能,叫做 include
用來動態調用task任務列表。
只調用task include_tasks
調用整個task 文件: include
(新版本: import_playbook)
在saltstack中,叫做 top file
入口文件。
示例:
[root@m01 web]# vim install_nginx.yml
- name: Install nginx
yum:
name: nginx
state: present
[root@m01 web]# vim conf_nginx.yml
- name: conf nginx
copy:
src: ./www.drz.com.conf
dest: /etc/nginx/conf.d
notify: reload nginx
[root@m01 web]# vim main.yml
- hosts:
tasks:
- include_tasks: ./install_nginx.yml
- include_tasks: ./conf_nginx.yml
handlers:
- name: reload nginx
systemd:
name: nginx
state: reloaded
2.直接複用寫好的yml文件
- 舊版:
include
- 新版:
import_playbook
- import_playbook: ./lnmp.yml
- import_playbook: ../mariadb/mysql.yml
playbook 忽略錯誤
默認playbook會監測task 執行的返回狀態,如果遇到錯誤則會立即中止playbook 的後續task執行,然而有些時候playbook 即使執行錯誤了也要讓其繼續執行。
加入參數: ignore_errors:yes 忽略錯誤
[root@m01 ~]# cat ignore.yml
---
- hosts: web_group
tasks:
- name: Ignore False
command: /bin/false
ignore_errors: yes
- name: touch new file
file:
path: /tmp/zls.txt
state: touch
playbook 錯誤處理
如上所述,當 task 執行失敗時,playbook 將不再繼續執行,包括如果在task中設置了handler 也不會被執行。
但是我們可以採取強制措施…
強制調用handler
[root@m01 ~]# cat handler.yml
- hosts: web_group
vars:
- http_port: 8080
force_handlers: yes
tasks:
- name: config httpd server
template:
src: ./httpd.j2
dest: /etc/httpd/conf
notify:
- Restart Httpd Server
- Restart PHP Server
- name: Install Http Server
yum:
name: htttpd
state: present
- name: start httpd server
service:
name:httpd
state: started
enabled: yes
handlers:
- name: Restart Httpd Server
systemd:
name: httpd
state: restarted
- name: Restart PHP Server
systemd:
name: php-fpm
state: restarted
抑制changed
被管理主機沒有發生變化,可以使用參數將change狀態改爲ok
[root@m01 ~]# cat handler.yml
- hosts: web_group
vars:
- http_port: 8080
force_handlers: yes
tasks:
- name: shell
shell: netstat -lntup|grep httpd
register: check_httpd
changed_when: false
- name: debug
debug: msg={{ check_httpd.stdout.lines }}
[root@m01 project2]# cat changed_when.yml
- hosts: webservers
vars:
- http_port: 8080
tasks:
- name: configure httpd server
template:
src: ./httpd.j2
dest: /etc/httpd/conf/httpd.conf
notify: Restart Httpd Server
- name: Check HTTPD
shell: /usr/sbin/httpd -t
register: httpd_check
changed_when:
- httpd_check.stdout.find('OK')
- false
- name: start httpd server
service:
name: httpd
state: started
enabled: yes
handlers:
- name: Restart Httpd Server
systemd:
name: httpd
state: restarted
Ansible 變量
變量概述
變量提供了便捷的方式來管理Ansible playbook 的每一個項目中的動態值,比如nginx -1.6.3
這個軟件包的版本,在其他地方或許會反覆使用,那麼如果將此值設置爲變量,然後在其他的playbook
中調用,會方便很多,方便維護,減少維護的成本。
定義變量的方式
- 通過命令行進行變量定義
- playbook,在play文件中進行變量定義
- 主機清單,通過主機信息文件中進行變量定義
如何定義變量
1.在playbook中定義變量
#方法一:
- hosts: db02
vars:
pkg:
- MySQL-python
- mariadb-server
tasks:
- name:
yum:
name: "{{ pkg }}"
state: present
#方法二:
- hosts: db01
vars:
web_pkg: httpd
db_pkg:
- unzip
- vsftpd
php_pkg:
- php-fpm
- php
- php-mysql
2.使用vars_file定義變量
#定義階段
[root@m01 project]# vim vars_file.yml
web_pkg: httpd
db_pkg: mariadb-server
php_pkg: php
#調用階段
[root@m01 project]# vim httpd.yml
- hosts: web_group
vars_files: ./vars_file.yml
tasks:
- name: Install httpd
yum:
name: "{{ db_pkg }}"
state: present
3.使用Ansible內置變量
vim mkdri.yml
- hosts: web_group
tasks:
- name: MKDIR
file:
path: /backup/{{ ansible_fqdn }}_{{ ansible_default_ipv4['address'] }}_{{ ansible_date_time['date'] }}
state: directory
recurse: yes
4.使用主機清單定義變量 ,
注意: 主機的變量高於主機組的變量,所以該方法不推薦使用,容易將環境弄亂
#定義階段
[web_group]
zls_web01 ansible_ssh_host=172.16.1.7
zls_web02 ansible_ssh_host=172.16.1.8
[web_group:vars]
web_pkg=nginx
[backup_group]
backup ansible_ssh_host=172.16.1.41
[db_group]
db01 ansible_ssh_host=172.16.1.51
db02 ansible_ssh_host=172.16.1.52
[nfs_group]
nfs ansible_ssh_host=172.16.1.31
[rsync_server:children]
web_group
backup_group
[rsync_server:vars]
web_pkg=httpd
[nfs_server:children]
web_group
nfs_group
#調用階段
- hosts: zls_web01
tasks:
- name: Install web server
yum:
name: "{{ web_pkg }}"
state: present
5.官方推薦變量定義方式
值錢的幾種變量定義都不是很好用,比較好用的是在Ansible 項目目錄下創建兩個變量目錄:
host_vars
group_hosts
切記,目錄名字一定要一致,不能做任何修改。
1.主機組定義變量
#定義階段
#創建主機組變量定義目錄
mkdir group_vars
[root@m01 ~]# vim group_vars/webs
web_pkg: httpd
#定義階段
[root@m01 ~]# cat group_vars/webs
web_pkg: httpd
#定義階段
[root@m01 ~]# cat host_vars/zls_web01
web_pkg: nginx
[root@m01 ~]# vim web.yml
- hosts: webs
tasks:
- name: Install web server
yum:
name: "{{ web_pkg }}"
state: present
6.命令行定義變量
通過命令行覆蓋變量,Inventory的變量會被playbook文件中覆蓋,這兩種方式的變量都會被命令行直接指定變量所覆蓋,使用 --extra-vars
或者-e
設置變量
#調用階段
[root@m01 ~]# !vim
vim web.yml
- hosts: webs
tasks:
- name: Install httpd Server
yum:
name:
- "{{ web_pkg }}"
- name: Install mariadb Server
yum:
name:
- "{{ db_pkg }}"
#定義階段
[root@m01 ~]# ansible-playbook web.yml -e "web_pkg=vsftpd" -e "db_pkg=unzip"
Ansible變量優先級測試
定義階段:
#定義playbook
[root@m01 ~]# vim test.yml
- hosts: webs
vars:
dir: playbook_vars
vars_files: ./vars_file.yml
tasks:
- name: Create Dir
file:
path: /opt/{{ dir }}
state: directory
#定義vars_files
[root@m01 ~]# vim vars_file.yml
dir: vars_file
#定義host_vars中的web01
[root@m01 ~]# vim host_vars/zls_web01
dir: host_vars
#定義group_vars
[root@m01 ~]# vim group_vars/webs
dir: group_vars
測試階段:
#1.命令行測試
[root@m01 ~]# ansible-playbook test.yml -e "dir=command_vars"
#查看到命令行定義的文件
[root@web01 ~]# ll /opt/
total 0
drwxr-xr-x 2 root root 6 Sep 19 16:48 command_vars
#2.正常執行playbook
[root@m01 ~]# ansible-playbook test.yml
#再次出現的是vars_files 定義的內容
[root@web01 ~]# ll /opt/
total 0
drwxr-xr-x 2 root root 6 Sep 19 16:48 command_vars
drwxr-xr-x 2 root root 6 Sep 19 16:50 vars_file
#3.取消調用vars_files
[root@m01 ~]# vim test.yml
- hosts: webs
vars:
dir: playbook_vars
tasks:
- name: Create Dir
file:
path: /opt/{{ dir }}
state: directory
[root@m01 ~]# ansible-playbook test.yml
#再次出現的是playbook調用的
[root@web01 ~]# ll /opt/
total 0
drwxr-xr-x 2 root root 6 Sep 19 16:48 command_vars
drwxr-xr-x 2 root root 6 Sep 19 16:52 playbook_vars
drwxr-xr-x 2 root root 6 Sep 19 16:50 vars_file
#4.取消playbook調用的
- hosts: webs
tasks:
- name: Create Dir
file:
path: /opt/{{ dir }}
state: directory
[root@m01 ~]# ansible-playbook test.yml
結論:
命令行 > vars_file > playbook vars > host_vars > group_vars
變量註冊
當ansible
的模塊在運行之後,其實都會返回一些result
結果,就像是執行腳本,我們有的時候需要腳本給我們一些return
返回值,我們才知道,上一步是否可以執行成功,但是,在默認情況下, ansible
的 result
並不會顯示出來,所以,我們可以把這些返回值存儲到變量中,這樣就可以調用對應的變量名,從而得到這些result
,這種將模塊的返回值,寫入到變量中的方法被稱爲變量註冊。
debug模塊常用參數:
msg : 調試輸出的消息
var : 將某個任務執行的輸出作爲變量傳遞給debug模塊,debug會直接將其打印輸出verbosity: debug的級別(默認是0級,全部顯示)
示例:
變量註冊"{{ list_dir }}"
#編寫劇本
[root@m01 vars]# cat register.yml
- hosts: gjy_web01
tasks:
- name: test vars
shell: "ls -l /root"
register: list_dir
- name: return result
debug:
msg: "{{ list_dir }}"
#查看執行結果
[root@m01 vars]# ansible-playbook register.yml
PLAY [gjy_web01] ********************************************************************************************************************************************
TASK [Gathering Facts] **************************************************************************************************************************************
ok: [gjy_web01]
TASK [test vars] ********************************************************************************************************************************************
changed: [gjy_web01]
TASK [return result] ****************************************************************************************************************************************
ok: [gjy_web01] => {
"msg": {
"changed": true,
"cmd": "ls -l /root",
"delta": "0:00:00.008826",
"end": "2019-09-20 03:36:38.313543",
"failed": false,
"rc": 0,
"start": "2019-09-20 03:36:38.304717",
"stderr": "",
"stderr_lines": [],
"stdout": "total 8\n-rw-------. 1 root root 1430 Aug 2 04:57 anaconda-ks.cfg\n-rwxr-xr-x. 1 root root 473 Aug 1 20:44 host_ip.sh\ndrwxr-xr-x 9 1001 1001 186 Sep 19 18:40 nginx-1.16.0",
"stdout_lines": [
"total 8",
"-rw-------. 1 root root 1430 Aug 2 04:57 anaconda-ks.cfg",
"-rwxr-xr-x. 1 root root 473 Aug 1 20:44 host_ip.sh",
"drwxr-xr-x 9 1001 1001 186 Sep 19 18:40 nginx-1.16.0"
]
}
}
PLAY RECAP **************************************************************************************************************************************************
gjy_web01 : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
###############################################################################################
注意:rc就想當於命令行執行完命令,echo $? 的返回值,返回值爲0 的時候證明執行成功
##############################################################################################
優化版,只輸出自己想要的內容 "{{ list_dir[‘stdout_lines’] }}"
#調用stdout_lines ,只顯示想要的內容
[root@m01 vars]# cat register.yml
- hosts: gjy_web01
tasks:
- name: test vars
shell: "ls -l /root"
register: list_dir
- name: return result
debug:
msg: "{{ list_dir['stdout_lines'] }}"
#查看結果
[root@m01 vars]# ansible-playbook register.yml
PLAY [gjy_web01] ********************************************************************************************************************************************
TASK [Gathering Facts] **************************************************************************************************************************************
ok: [gjy_web01]
TASK [test vars] ********************************************************************************************************************************************
changed: [gjy_web01]
TASK [return result] ****************************************************************************************************************************************
ok: [gjy_web01] => {
"msg": [
"total 8",
"-rw-------. 1 root root 1430 Aug 2 04:57 anaconda-ks.cfg",
"-rwxr-xr-x. 1 root root 473 Aug 1 20:44 host_ip.sh",
"drwxr-xr-x 9 1001 1001 186 Sep 19 18:40 nginx-1.16.0"
]
}
PLAY RECAP **************************************************************************************************************************************************
gjy_web01 : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
ansibl e層級定義變量
#編輯變量文件
[root@m01 ~]# vim vars_file.yml
lamp:
framework:
web_package: httpd
db_package: mariadb-server
php_package: php
lnmp:
framework:
web_package: nginx
db_package: mysql
php_package: php
lnmt:
framework:
web_package: nginx
db_package: mysql
java_package: tomcat
#編輯playbook文件
[root@m01 ~]# vim test.yml
- hosts: web_group
vars_files: ./vars_file.yml
tasks:
- name: Install LAMP httpd
yum:
name: "{{ lamp.framework.web_package }}"
- name: Install LAMP mariadb-server
yum:
name: "{{ lamp.framework.db_package }}"
- name: Install LAMP php
yum:
name: "{{ lamp.framework.php_package }}"
#官方推薦寫法
[root@m01 ~]# vim test.yml
- hosts: web_group
vars_files: ./vars_file.yml
tasks:
- name: Install LAMP httpd
yum:
name: "{{ lamp['framework']['web_package'] }}"
- name: Install LAMP mariadb-server
yum:
name: "{{ lamp['framework']['db_package'] }}"
- name: Install LAMP php
yum:
name: "{{ lamp['framework']['php_package'] }}"
#執行playbook
[root@m01 ~]# ansible-playbook test.yml
PLAY [web_group] *****************************************************************************************************************************************************************************************************************************
TASK [Gathering Facts] ***********************************************************************************************************************************************************************************************************************
ok: [web01]
ok: [web02]
TASK [Install LAMP httpd] ********************************************************************************************************************************************************************************************************************
ok: [web02]
ok: [web01]
TASK [Install LAMP mariadb-server] ***********************************************************************************************************************************************************************************************************
ok: [web02]
ok: [web01]
TASK [Install LAMP php] **********************************************************************************************************************************************************************************************************************
ok: [web02]
ok: [web01]
PLAY RECAP ***********************************************************************************************************************************************************************************************************************************
web01 : ok=4 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
web02 : ok=4 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
- hosts: webs
tasks:
- name: mem
file:
path: /opt/{{ ansible_facts['fqdn'] }}
#path: /root/{{ ansible_fqdn }}
state: directory
facts緩存
Ansible facts是在被管理追擊上通過Ansible 自動採集發現的變量, facts 包含每臺特定的主機信息。
比如:被控端的主機名,IP 地址,系統版本,CPU數量,內存狀態,次盤狀態等等。
facts使用場景 :
1.通過 facts 緩存檢查CPU,來省城對應的nginx配置文件
2.通過 facts 緩存主機名,生成不同的zabbix 配置文件
3. 通過 facts 緩存檢查物理機的內存大小來生成不同的mysql配置文件
綜上所述的Ansible facts 類似於saltstack 中的 grains 對於做自動化非常有用的
facts 基本用法
#編輯
[root@m01 ~]# vim facts.yml
- hosts: web_group
tasks:
- name: Get Host Info
debug:
msg: >
Hostname "{{ ansible_fqdn }}" and IP "{{ ansible_default_ipv4.address }}"
#執行
[root@m01 ~]# ansible-playbook facts.yml
[root@m01 ~]# ansible-playbook facts.yml
PLAY [web_group] *****************************************************************************************************************************************************************************************************************************
TASK [Gathering Facts] ***********************************************************************************************************************************************************************************************************************
ok: [web02]
ok: [web01]
TASK [Get Host Info] *************************************************************************************************************************************************************************************************************************
ok: [web01] => {
"msg": "Hostname \"web01\" and IP \"10.0.0.7\"\n"
}
ok: [web02] => {
"msg": "Hostname \"web02\" and IP \"10.0.0.8\"\n"
}
PLAY RECAP ***********************************************************************************************************************************************************************************************************************************
web01 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
web02 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
關閉facts
[root@m01 ~]# vim facts.yml
- hosts: web_group
gather_facts: no #關閉信息採集
tasks:
facts 生成zabbix配置文件
- hosts: web_group
vars:
- zabbix_server: 172.16.1.71
tasks:
- name: copy zabbix agent conf
template:
src: ./zabbix_agentd.conf
dest: /tmp/zabbix_agentd.conf
facts 生成mysqld 配置文件
- hosts: db_group
tasks:
- name: Install mysql server
yum:
name: mariadb-server
state: present
- name: copy mysql conf
template:
src: ./my.cnf
dest: /etc/my.cnf
[root@m01 ~]# vim /etc/my.cnf
[mysqld]
basedir=/usr
datadir=/var/lib/mysql/
socket=/var/lib/mysql/mysql.sock
log_error=/var/log/mariadb/mariadb.log
innodb_buffer_pool_size={{ ansible_memtotal_mb * 0.8 }}