Templates

January 7, 2022 - Reading time: ~1 minute

Ansible uses Jenkins templates to build the playbook.
Templates can use variables from the inventory file, or part of the facts collected.

Variables can also be extracted from the inventory.

Additional variables can be set via the --extra-vars flag.

Set default values with:

    node_file: "node-v{{ node_ver }}-linux-x64.tar.xz"

The following playbook downloads a specific version of nodejs to the webservers group:

root@f12d33c83ada:~# cat playbook.yaml
---
- name: Download nodejs
  gather_facts: no
  hosts: webservers
  vars:
    node_host: 'https://nodejs.org/'
    node_ver: "{{ node_version | default('14.18.2') }}"
    node_file: "node-v{{ node_ver }}-linux-x64.tar.xz"
    node_url: "{{ node_host }}/dist/v{{ node_ver }}/{{ node_file }}"
  tasks:
  - name: download nodejs
    get_url:
      url: "{{ node_url }}"
      dest: "/tmp/{{ node_file }}"
      force: yes

Running it to change the version:

root@f12d33c83ada:~# ansible-playbook -i inventory.yaml playbook.yaml --extra-vars node_version=16.13.1