前面花了不少篇幅在講 Ad-Hoc 指令,是為了讓大家熟悉 Ansible 的一些概念,像是 Inventory, Group, Module ... 等
但 Ad-Hoc 會有什麼問題呢?
沒錯…Ad-Hoc 充其量只是讓你初步知道 Ansible 的威力
在 Ansible 的世界裡,組態的維護檔被稱作 playbook
它記錄了一連串要執行的任務來達到你想要的狀態,就好比籃球場上的戰術執行,是為了得分或是防守成功
Playbook 是以 YAML 的型式撰寫的,而且 playbook 可以再引用 playbook,達到共用的效果
以下是一段再常見不過的 shell script:
# Install apache
yum install --quiet httpd httpd-devel
# Copy configuration files.
cp httpd.conf /etc/httpd/conf/httpd.conf
cp httpd-vhosts.conf /etc/httpd/conf/httpd-vhosts.conf
# Start Apache and configure it to run at boot.
service httpd start
chkconfig httpd on
如果換成 playbook 的型式會是如何呢?
---
- hosts: all
tasks:
- name: Install Apache.
command: yum install --quiet -y httpd httpd-devel
- name: Copy configuration files.
command: cp httpd.conf /etc/httpd/conf/httpd.conf
- command: cp httpd-vhosts.conf /etc/httpd/conf/httpd-vhosts.conf
- name: Start Apache and configure it to run at boot.
command: service httpd start
- command: chkconfig httpd on
呃 ... 這不是只是換了個語言寫而已嗎?
下面我們將透過 Ansible 的 module 來優化這個 playbook,否則就沒必要用了不是嗎? 說好的 Idempotence ?
---
- hosts: all
become: yes
tasks:
- name: Install apache
yum: name={{ item }} state=present
with_items:
- httpd
- httpd-devel
- name: Copy configuration files
copy:
src: "{{ item.src }}"
dest: "{{ item.dest }}"
owner: root
group: root
mode: 0644
with_items:
- src: "httpd.conf"
dest: "/etc/httpd/conf/httpd.conf"
- src: "httpd-vhosts.conf"
dest: "/etc/httpd/conf/httpd-vhosts.conf"
- name: Make sure Apache is started now and at boot.
service: name=httpd state=started enabled=yes
如果我們再執行一次呢?
上面的範例主要有幾個大重點:
以上是第一個 playbook,希望各位可以自行操作看看