Using variables in the Jinja2 template in ansible Playbook
Solution 1
Yes, this is possible. The main.yml will be sourced automatically when the ansible role is invoked. You just have to write a jinja2 template file for the same.
For example the below file:
A better representation of the main.yml file would be
---
asm_disk_detail:
- name: OCR
path: "/dev/sde1"
- name: DATA
path: "/dev/sdf1"
- name: ARCH
path: "/dev/sdg1"
jinja2 template: supports for loop so you can apply with_items on the above variable asm_disk_detail and create a config file as needed.
Note:- Please try the jinja2 file creation from your side in case any issues please shout :)
===============Play and jinja2 template
playbook-->
---
- name: test
hosts: localhost
tasks:
- name: test
include_vars: vars.yml
- name: jinja2
template:
src: template/template.yml
dest: target/target.yml
jinja2-->
{%- for item in asm_disk_detail -%}
{%- if not loop.last -%}
{{ item.path }}/{{ item.name }},
{%- else -%}
{{ item.path }}/{{ item.name }}
{%- endif -%}
{%- endfor -%}
output-->
oracle.install.asm.diskGroup.disks=/dev/sde1/OCR,/dev/sdf1/DATA,/dev/sdg1/ARCH
Solution 2
Use Ansible template module with a For loop in your template.
{% for disk in asm_disk_detail %}
disk name: {{ disk.name}}
disk path: {{ disk.path }}
{% endfor %}
Related videos on Youtube
IOT
Updated on June 04, 2022Comments
-
IOT almost 2 years
Any idea of how we can use dynamic variables inside the Jinja2 Template. Below is the data from my Jinja2 template.
oracle.install.asm.diskGroup.disks=/dev/oracleasm/disks/DATA,/dev/oracleasm/disks/ARCH,/dev/oracleasm/disks/OCR
The variable values in the
defaults/main.yml
is:asm_disk_detail: - { name: 'OCR', path: '/dev/sde1' } - { name: 'DATA', path: '/dev/sdf1' } - { name: 'ARCH', path: '/dev/sdg1' }
I am trying to use these variable values to pass dynamically at the time of running the playbook. These values should automatically get populated in the template.
-
IOT about 5 yearsThanks for the reply..! My Template has the following line..! oracle.install.asm.diskGroup.disks=/dev/oracleasm/disks/{{ item }},/dev/oracleasm/disks/{{ item }},/dev/oracleasm/disks/{{ item }}. My vars file containes the below lines. asm_disk_detail: - { name: 'OCR', path: '/dev/sde1' } - { name: 'DATA', path: '/dev/sdf1' } - { name: 'ARCH', path: '/dev/sdg1' } The line in the template has to fetch the value from vars file, which is not working for me. I tried using For loop as well. @error404
-
IOT about 5 yearsHere it,s taking the same name for the 3 variables. @sebthebert
-
error404 about 5 years@IOT Added the play, jinja2 template and the output format I am generating. Let me know in case you are looking for another output format