Ansible - Playbook&Role
Playbook: A yaml file that can be excuted by ansible
Before playbook, we need to understand YAML: what is yaml
CMD
ansible-playbook deploy.ymlansible-playbook playbook.yml --verboseansible-playbook playbook.yml --list-hostsansible-playbook playbook.yml -f 10
Basic Playbook Structure
playbook is basically about 3 questions:
- what hosts do we want to run playbook on?
- what tasks do we want to run?
- what aftercare tasks do we want to run?
Q1: what hosts do we want to run playbook on?
- host: IP, hostname or all
- user: remote uses to use
- become: if we want to change user, yes or no
- become_method: sudo, su, pbrun, pfexec, doas
- become_user: root or other usename
we can also use --ask-become-pass to promot password
Q2: what tasks do we want to run?
- task run from top to down, if any task has any failure, the whole playbook will stop.
- each task will call a module
- each task need a name to provide readability
Q3: what aftercare tasks do we want to run?
handler is event of playbook, the exexcutation order of handler is follow the order you define them.
Example:
Logic Control in Playbook
when
-
we use
whento to excute certain task when meet some requirment.e.g.
-
we can also use expressions in
whene.g.
Loop
-
we could use
with_itemsto iterate list.e.g.
1 2 3 4 5 6 7 8 9 10 11 12- name: add several users user: name={{ item }} state=present groups=wheel with_items: - testuser1 - testuser2 # or we can define a list vars: list1: ["user1", "user2"] tasks: - name: add several users user: name={{ item }} state=present groups=wheel with_items: "{{ list1 }}"
Block
we can use block to excute a series of tasks in one block of task
block will make try-cache-finally easily
|
|
Reuse of Playbook
include
-
we could use
includeto use pre-written playbook yaml file. -
we can also use params
-
using
includein the playbook’s global space is not recommonded, sometimes it’s unstable. -
includebecome more and more powerful and also more and more unstable.
Tags
-
basic tags
we can use
tagsto tag a task, and run the tagged task byansible-playbook example.yml --tags "packages" -
special tags
- always
- tagged
- untagged
- all
Best Practice of Writing Playbook
follow below two principles
- use include and role to avoid duplicate code
- seperate big files into small files.