Ansible Role用于维护大型的playbooks,下面为具体一个实际例子。
目录结构
.
└── roles
├── demo
│ ├── tasks
│ │ └── main.yml
│ ├── templates
│ │ └── hello_world.txt.j2
│ └── vars
│ └── main.yml
├── setup.yml
└── version
├── 1.0.yml
└── 2.0.yml
其中demo为创建的role,在role目录下包含tasks/templates/vars子目录, 默认读取tasks和vars中的main.yml文件。
- tasks的main.yml放置需要执行的任务;
- vars的main.yml放置变量集;
- templates为模板文件
- tasks会引用模板文件+vars,执行特定task任务。
Role=demo下的主要文件
roles/demo/tasks/main.yml
---
- name: generation the hello_world.txt file
template:
src: templates/hello_world.txt.j2
dest: /tmp/hello_world.txt
- name: show file context
command: cat /tmp/hello_world.txt
register: result
- name: print stdout
debug: msg={{ result.stdout}}
roles/demo/vars/main.yml
dynamic_word: "main"
roles/demo/templates/hello_world.txt.j2
start
Hello "{{ dynamic_word }}"
version "{{ version_num }}"
end
Ansible主Playbook: roles/setup.yml
---
- name: Play the template module
hosts: localhost
roles:
- demo
附加变量定义文件:roles/version/2.0.yml
version_num: 2.0
检查语法
ansible-playbook setup.yml --syntax-check
执行Playbook
ansible-playbook setup.yml -e @version/2.0.yml
其中-e后的为参数文件,并加上@前缀特殊符号。返回结果。
PLAY [Play the template module] **************************************************************************
TASK [Gathering Facts] ***********************************************************************************
ok: [localhost]
TASK [demo : generation the hello_world.txt file] ********************************************************
ok: [localhost]
TASK [demo : show file context] **************************************************************************
changed: [localhost]
TASK [demo : print stdout] *******************************************************************************
ok: [localhost] => {
"msg": "start\nHello \"main\"\nversion \"2.0\"\nend"
}
PLAY RECAP ***********************************************************************************************
localhost : ok=4 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0