Skip to content
This repository was archived by the owner on Oct 17, 2024. It is now read-only.

Latest commit

 

History

History
88 lines (62 loc) · 2.06 KB

templating.md

File metadata and controls

88 lines (62 loc) · 2.06 KB

Templating in Ansible

Templating in Ansible

  • Sometimes you need dynamic behaviour in plays/tasks
    • File locations
    • Fill in prompted information
    • Secret info (passwords, API keys)
    • Generally sourced from a variable
  • Ansible uses a template syntax called Jinja2

Jinja2

Variables

  • Simple variables or expressions
    • {{ person_name }}
    • {{ 1 + 1 }}
  • Dictionaries
    • {{ lesson['name'] }}
    • {{ lesson.name }}
    • {{ hostvars['myserver'].ansible_distribution }}
Exercise: Templating in our playbook
  • Edit vars section in static-site.yml to add:
    • static_file_directory
    • nginx_conf_directory
vars:
  .
  static_file_directory: /usr/share/nginx/html
  nginx_available_conf: /etc/nginx/sites-available
tasks:
Exercise: Templating in our playbook
  • Use template syntax to replace path for
    • nginx
    • index.html

 - name: Template in nginx config file
   template:
     .
     dest: "{{ nginx_available_conf }}/mysite.conf"
     .

 - name: Copy up static website html
   template:
     .
     dest: "{{ static_file_directory }}/index.html"
     .

Re-run the ansible playbook

Templates and Quoting

  • Be aware that you will often need to put quotes around templated elements
    dest: "{{ nginx_conf_directory }}/mysite.conf"
    
  • However sometimes you do not need them
    command: ls {{ nginx_conf_directory }}