抽出变量和变量文件
4.4节中提到的repo地址和apache主目录路径其实也可以作为参数提出来(其实同时也把sudo:yes提出来作为了公共属性):
---
- hosts: static_page
become_method: sudo
become: yes
vars:
packages:
- git
- apache2
repo_url: https://github.com/Yaowenjie/static_page.git
dest_dir: /var/www/html/static_page
tasks:
- name: Apt update
run_once: true
apt:
update_cache: yes
- name: Ensure packages installed
apt:
name: "{{ item }}"
state: present
with_items: "{{ packages }}"
- name: Git clone remote static page repo
git:
repo={{ repo_url }}
dest={{ dest_dir }}
update=yes
实际情况下,我们可能还会遇到很多需要抽出来的变量,很多时候,把变量从主要文件内抽出来单独管理也是很有必要的,本例中我们将它抽成一个名为variables.yml:
---
packages:
- git
- apache2
repo_url: https://github.com/Yaowenjie/static_page.git
dest_dir: /var/www/html/static_page
同时,需要在setupstaticpage.yml中使用__vars_files引用该变量文件:
---
- hosts: static_page
vars_files:
- "variables.yml"
tasks:
- name: Apt update
sudo: yes
apt:
update_cache: yes
- name: Ensure packages installed
sudo: yes
apt:
name: "{{ item }}"
state: present
with_items: "{{ packages }}"
- name: Git clone remote static page repo
sudo: yes
git:
repo={{ repo_url }}
dest={{ dest_dir }}
update=yes
同样的,记得每次改变后重新执行ansible-playbook。