Ansible之使用角色一鍵部署httpd並檢查部署結果
阿新 • • 發佈:2018-12-30
規劃
角色:webser
任務: 111為ansible主節點,112,113為被控節點。在ansible主節點遠端一鍵安裝部署httpd,要求執行埠為99,根目錄為/var/www
,域名為其節點的IP地址,執行者身份是apache,部署測試頁面(index.html),並檢查是否部署成功要求有返回資訊。
一、安裝ansible並配置各節點互信
Ansible簡單介紹及安裝部署詳解已講解,有詳細步驟這裡不再演示。
二、建立並配置角色
- 建立工作目錄
[[email protected] ~]# mkdir /project/{roles,inventory} -pv
[ [email protected] ~]# mkdir /project/roles/webser/{tasks,files,templates,vars} -pv
[[email protected] /]# tree /project/
/project/
├── inventory
└── roles
└── webser
├── files
├── tasks
├── templates
└── vars
7 directories, 0 files
- 準備模板檔案,即apache的配置檔案
[ [email protected] ~]# cp /etc/httpd/conf/httpd.conf /project/roles/templates/httpd.conf.j2
# 修改配置檔案的內容
[[email protected] ~]# vim /project/roles/webser/templates/httpd.conf.j2
Listen {{ port }}
User {{ user }}
Group {{ user }}
ServerName {{ ansible_eth0.ipv4.address }}
[[email protected] ~]# grep "^[a-zA-Z]" /project/roles/webser/templates/httpd.conf.j2
ServerRoot "/etc/httpd"
Listen {{ port }}
Include conf.modules.d/*.conf
User {{ user }}
Group {{ user }}
ServerAdmin [email protected]
ServerName {{ ansible_eth0.ipv4.address }}
DocumentRoot "{{ root }}"
ErrorLog "logs/error_log"
LogLevel warn
AddDefaultCharset UTF-8
EnableSendfile on
IncludeOptional conf.d/*.conf
- 建立web頁面測試檔案
[[email protected] ~]# echo "<h1> test page</h1>">/project/roles/webser/files/index.html
- 編寫用於做健康檢查的指令碼
[[email protected] ~]# cd /project/roles/webser/files/
[[email protected] files]# vim check.sh
#!/bin/bash
URL=$1
PORT=$2
curl -I http://$1:$2/index.html |grep "200 OK" &>/dev/null
if [ $? -eq 0 ];then
echo "$1 status is ok"
else
echo "$1 status is error"
fi
- 建立job
[[email protected] files]# cd /project/roles/webser/tasks/
[[email protected] tasks]# vim main.yaml
---
- name: install https
yum: name=httpd state=present
- name: make configrantion file
template: src=httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
- name: start httpd
service: name=httpd state=restarted
- name: install test page
copy: src=index.html dest={{ root }}
- name: make health check
shell: sh roles/webser/files/check.sh {{ ansible_eth0.ipv4.address }} {{ port }}
delegate_to: localhost
register: health_status
- debug: msg="{{ health_status }}"
- 建立主機清單列表
[[email protected] tasks]# cd /project/inventory/
[[email protected] inventory]# vim webser
[webser]
10.220.5.112
10.220.5.113
- 建立入口檔案
[[email protected] inventory]# cd /project/
[[email protected] project]# vim webser.yaml <<<該檔案需要和roles目錄同級
---
- host: all
remote_user: root
roles:
- webser
三、執行palybook
[[email protected] files]# cd /project/
[[email protected] project]# ansible-playbook -i ./inventory/webser ./webser.yaml -e port=99 -e user=apache -e root=/var/www
執行結果是成功的,並且到112,113節點檢視也看到httpd安裝部署成功,從瀏覽器訪問後端節點也是能夠訪問到測試頁面的,至此通過ansible使用角色一鍵部署靜態網站就大功告成了。
------做運維之前很矯情的小年輕-----