Skip to main content

Roles, Templates, and Vault

Updated Jan 05, 2021 ·

Overview

Roles package reusable automation. Templates render configuration from variables. Vault encrypts sensitive values that must live with playbooks.

Role Layout

Create a role with ansible-galaxy.

ansible-galaxy init roles/webservers

Common role directories:

DirectoryPurpose
tasksMain task list for the role.
handlersService restarts and notified actions.
defaultsLow-priority default variables.
varsHigher-priority role variables.
filesStatic files copied without rendering.
templatesJinja2 templates rendered before copying.
metaRole metadata and dependencies.

Using a Role

---
- name: Configure web servers
hosts: webservers
become: true
roles:
- webservers

Handlers

Handlers run only when notified by a changed task.

- name: Copy Apache config
ansible.builtin.template:
src: httpd.conf.j2
dest: /etc/httpd/conf/httpd.conf
notify: Restart httpd
- name: Restart httpd
ansible.builtin.service:
name: httpd
state: restarted

Jinja2 Templates

Templates combine static text and variables.

Managed by Ansible.
Host: {{ ansible_hostname }}
OS: {{ ansible_distribution }} {{ ansible_distribution_version }}

Deploy the template.

- name: Deploy motd
ansible.builtin.template:
src: motd.j2
dest: /etc/motd

Ansible Vault

Create an encrypted variable file.

ansible-vault create vars/secrets.yml

Edit it later.

ansible-vault edit vars/secrets.yml

Run a playbook that needs vault values.

ansible-playbook playbooks/setup-app-vault.yml --ask-vault-pass
warning

Do not commit vault password files. Commit encrypted vault files only when the repository is intended to store them.