set_fact variable not working in template

1,280 views
Skip to first unread message

kiran sangeetam

unread,
May 3, 2017, 5:05:56 PM5/3/17
to Ansible Project
Hi Everyone,

I want to use variable that I defined in set_fact task in template. But it's not working. Can anyone please suggest if I'm doing anything wrong.

Below is the syntax I am using in tasks file.

- name: Setting fact for logfile
  set_fact: log_file_path="/home/log.txt" include_path="true"
  when: "'job' in inventory_hostname"

and below is the syntax I'm using in template.

{%if include_path == "true" %}
some steps
{% else %}
some steps
{%endif%}

Even include_path="true" while executing the playbook, template is always adding the steps in else statement.

Kai Stian Olstad

unread,
May 4, 2017, 3:04:55 AM5/4/17
to ansible...@googlegroups.com
On 03.05.2017 13:56, kiran sangeetam wrote:
> I want to use variable that I defined in set_fact task in template. But
> it's not working. Can anyone please suggest if I'm doing anything
> wrong.
>
> Below is the syntax I am using in tasks file.
>
> - name: Setting fact for logfile
> set_fact: log_file_path="/home/log.txt" include_path="true"
> when: "'job' in inventory_hostname"

Since you haven't explained what you are trying to do some guessing is
required.

Your when will only trigger if the inventory_hostname is "job".
So for all the other hosts this fact is not set.

The in clause is normally used to find an element in a dictonary,
inventory_hostname is a string.

I guess you are looking for .find as shown in this example
https://docs.ansible.com/ansible/playbooks_conditionals.html#register-variables

--
Kai Stian Olstad

kiran sangeetam

unread,
May 5, 2017, 1:46:26 PM5/5/17
to Ansible Project, ansible-pr...@olstad.com
Thanks for the reply.
My bad, I did not explain it clearly.

Actually what I'm trying to achieve is:

I want to give conditions on template that I am copying to server. When the client hostname has 'job' word in it then template should have some text else template should have some other text.

For example: if host name is 'dev-jobs.company.com', the template I am copying should have log_file_path="/home/log.txt" otherwise it should have log_file_path="/tmp/log.txt"

What is the best way to achieve this ??

Larry Smith

unread,
May 5, 2017, 5:51:45 PM5/5/17
to Ansible Project, ansible-pr...@olstad.com
Have you tried with your conditional in your template as:

{% if include_path %}

some steps
{% else %}
some steps
{% endif %}

Or add a debug prior to template for:
- debug: var=include_path

My guess would be you will see include_path as True rather than true.
Reply all
Reply to author
Forward
0 new messages