Ansible - Templates
Templates are an incredibly powerful feature.
Super Simple Example
Most simple template ever:
deployments/test.conf.j2This is a test template. Selected color is {{ color }} That's it.
Playbook, variable defined here:
deployments/test_playbook.yaml- name: Test Playbook hosts: all vars: color: blue tasks: - name: Template test template: src: deployments/test.conf.j2 dest: /data/test.conf
Bigger Example - Features
The template:
deployments/test.conf.j2Selected color is {{ color }} {% if size > 25 %} Large enough {% else %} Too small {% endif %} Here is the list: {% for f in food %} {{ f }} {% endfor %}
The playbook:
deployments/test_playbook.yaml- name: Playbook to test templates hosts: all vars: color: blue size: 30 volume: 12 food: - apple - pizza - rice - taco tasks: - name: Template test template: src: deployments/test.conf.j2 dest: /data/test.conf
Real Example
web_deploy.yaml--- - name: A Test Playbook hosts: webservers 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_service: state: started name: nginx enabled: true masked: no - template: src: templates/index.html.j2 dest: /var/www/html/index.html var1: "TEST STRING" mode: a+r
The actual template:
templates/index.html.j2This is a sample page. Here is the test value: {{ var1 }} That is it.
Another Real Example
Playbook, variable defined here:
deployments/test_playbook.yaml--- - name: Test Playbook hosts: all become: yes vars nameserver: 192.168.3.2 domain: lab.net data: - host: localhost IP: 127.0.0.1 - host: silly-wombat1 IP: 104.131.68.105 - host: sneaky-dingo1 IP: 167.99.9.15 - host: chirpy-bird1 IP: 159.65.234.12 - host: serious-squid1 IP: 68.183.109.62 - host: hyper-snail IP: 159.89.48.164 - host: hairy-hog1 IP: 45.33.72.164 tasks: - name: Resolve File template: src: deployments/resolv.conf.j2 dest: /tmp/etc/resolv.conf - name: Hosts File template: src: deployments/hosts.conf.j2 dest: /tmp/etc/hosts.conf
First template:
deployments/resolv.conf.j2nameserver {{ nameserver }} search {{ domain }}
Second template:
deployments/hosts.conf.j2{% for x in data %} {{ x['IP'] }} {{ x['host'] }} {% endfor %}
More Info
You can also configure permissions and ownership for templated files:
- name: Template a file to /etc/my_settings.conf
ansible.builtin.template:
src: /templates/my_settings.j2
dest: /etc/my_settings.conf
owner: bin
group: wheel
mode: '0644'