Templatize Tasks with Variables in Ansible

From Knowledge Center
Revision as of 13:24, 21 March 2019 by Ruan (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

We want to substitute data with placeholders using variables on ansibles template module.

Objective

Generate the file /tmp/file from the template file.j2 and replace the placeholder versionz with the defined variable versionz = v1.

Our playbook:

$ cat replace-task.yml
- name: replace variable in template
  hosts: localhost
  vars:
    versionz: v1
  roles:
    - echo

Our role:

$ cat roles/echo/tasks/main.yml
- name: generate file from template
  template:
    src: file.j2
    dest: /tmp/file
    owner: ruan
    group: staff
    mode: 0644

The template:

$ cat roles/echo/templates/file.j2
version: "{{ versionz }}"

Running the playbook:

$ ansible-playbook -i inventory.ini -u ruan replace-task.yml

Verify the output:

$ cat /tmp/file
version: "v1"

We can also override the variable by passing it via the command line:

$ ansible-playbook -i inventory.ini -u ruan replace-task.yml -e versionz=v2

Check the output:

$ cat /tmp/file
version: "v2"

Dealing with unused placeholders

I have not figured out this one, but the way I came around this was to run a shell script.

The output should look like this:

DOMAIN: ruan.dev
text: "{{ .CommonAnnotations.description }}"

But running the example from befores fails:

fatal: [localhost]: 
FAILED! => {"changed": false, "msg": "AnsibleError: template error while templating string: unexpected '.'. String: version: \"{{ versionz }}\"\ntext: \"{{ .CommonAnnotations.description }}\"\n"}

A way I got around that was using a sed on shell:

$ cat replace-task.yml
- name: replace variable in template
  hosts: localhost
  environment:
    DOMAIN: ruan.dev
  roles:
    - echo

The role:

$ cat roles/echo/tasks/main.yml
- name: copy script
  copy:
    src: replacer.sh
    dest: /tmp/replacer.sh
    mode: 0644

- name: copy file
  copy:
    src: data.yml
    dest: /tmp/data.yml
    mode: 0644

- name: run script
  shell: "bash /tmp/replacer.sh"

The file with the placeholder:

$ cat roles/echo/files/data.yml
DOMAIN: REPLACE_domain
text: "{{ .CommonAnnotations.description }}"

The script that will replace the values:

$ cat roles/echo/files/replacer.sh
sed -i .bk "s/REPLACE_domain/${DOMAIN}/g" /tmp/data.yml

Run the playbook:

$ ansible-playbook -i inventory.ini -u ruan replace-task.yml

The output:

$ cat /tmp/data.yml
DOMAIN: ruan.dev
text: "{{ .CommonAnnotations.description }}"