Low Orbit Flux Logo 2 F

Ansible - Playbooks

Launch a playbook with commands like these:



ansible-playbook my_playbook.yaml          # run a playbook
ansible-playbook test.yaml -kK             # prompt for SSH pass and sudo pass

ansible-playbook playbook.yml --list-hosts  # show hosts that would be effected
ansible-playbook test.yaml --limit host1    # limit to specified host
ansible-playbook playbook.yml -f 10         # with more options ( 10 forks )

Basic playbook example:

test-task1.yaml
--- - name: A Test Playbook hosts: all tasks: - name: First Test command: "uname -a"

Playbook to install an NGINX web server and deploy a web page from a template:

web_deploy.yaml
--- - name: A Test Playbook hosts: webservers become: yes vars: var1: "TEST STRING 123ABC" tasks: - name: Update repo cache and install nginx package ansible.builtin.apt: name: nginx update_cache: yes - name: Make sure a service is started, enabled, and not masked ansible.builtin.systemd: state: started name: nginx enabled: true masked: no - template: src: templates/index.html.j2 dest: /var/www/html/index.html mode: a+r

Big example showing multiple different options and different ways to define and import variables:

db_deploy.yaml
- name: Update db servers hosts: databases remote_user: admin become: yes vars: trigger_task: true supported_os: - RedHat - Fedora vars_files: - my_variables.yaml - db_params.yaml gather_facts: false tasks: - name: Include Variables include_vars: "my_variables2.yaml" - name: Ensure postgresql is at the latest version ansible.builtin.yum: name: postgresql state: latest - name: Ensure that postgresql is started ansible.builtin.service: name: postgresql state: started

Sections

Playbooks can be broken into different sections. They are run in this order:

Handlers run after each of those stages. ( more on handlers and roles in later sections )

Here is an example of how this can be split up:

test_sections.yaml
--- - name: A Test Playbook hosts: webservers become: yes pre_tasks: - name: Test task command: "import_data" tasks: - name: Test task command: "process_data" - name: Test task command: "move_data" post_tasks: - name: Test task command: "export_data" - name: Test task command: "cleanup_data"

Ansible - Multiple Plays

Breaking a playbook into multiple plays allows you to specify differnt sets of hosts and a different remote_user for each play.

test_multi.yaml
--- - hosts: webservers remote_user: user1 tasks: - name: ensure nginx is at the latest version apt: name: nginx state: latest - hosts: databases remote_user: admin tasks: - name: ensure postgresql is at the latest version apt: name: postgresql state: latest

Verify

Verify playbooks ( I rarely use this but you might want to ):



ansible-playbook test.yaml --check
ansible-playbook test.yaml --diff
ansible-playbook test.yaml --list-hosts
ansible-playbook test.yaml --list-tasks
ansible-playbook test.yaml --syntax-check