How to use fact information such as IP address in task yml files

Hello there!

I am new to Ansible, I have been searching all through the web for this info, but I couldn’t able to get it correctly.

I am trying to get the IP address of the machine (local) with some variable under tasks/main.yml file using $tag, tag is a variable name, but I am not able to get it.

Have tried in playbook like this,

  • hosts: local

connection: local
become: true
tasks:

  • set_fact:
    tag: “{{ ansible_default_ipv4.address }}”
    roles:
  • conf

Note: this tag variable has got the IP address, even tried to use debug and check the output.

What I am trying to do now is to introduce the IP address to the task file, but I am not able to,

conf/tasks/main.yml

-lineinfile:
path: /root/test.conf
regexps: ‘^IP_ADDR’
line: ‘IP_ADDR:$tag’

Tried like this as well, line: “IP_ADDR:$(tag)” none worked.

Please help me with this case.

- hosts: local

       connection: local
       become: true
       tasks:
           - set_fact:
               tag: "{{ ansible_default_ipv4.address }}"
       roles:
            - conf

<snip />

-lineinfile:
     path: /root/test.conf
     regexps: '^IP_ADDR'
     line: 'IP_ADDR:$tag'

It's only one way to write variables in Ansible, double curly brackets, just as you did in your play above.

   line: 'IP_ADDR:{{ tag }}'

Thanks for the quick response, but that didn’t help. I get the below error,

Error:
TASK [conf : lineinfile] ******************************************************************************
task path: /home/elastic/ansible/roles/conf/tasks/main.yml:61
fatal: [localhost]: FAILED! => {
“failed”: true,
“msg”: “the field ‘args’ has an invalid value, which appears to include a variable that is undefine
d. The error was: ‘tag’ is undefined\n\nThe error appears to have been in ‘/home/elastic/ansible/roles/
conf/tasks/main.yml’: line 61, column 3, but may\nbe elsewhere in the file depending on the exact synta
x problem.\n\nThe offending line appears to be:\n\n\n- lineinfile:\n ^ here\n”
}
to retry, use: --limit @/home/elastic/ansible/sample.retry
PLAY RECAP ********************************************************************************************
localhost : ok=12 changed=0 unreachable=0 failed=1

This is the actual sample.yml(playbook file),

`

Ansible exectue things in the following order.

pre_tasks:
roles:
tasks:
post_tasks:

So you need to move your set_fact to pre_tasks so it will run before roles.

Awesome! It worked, thanks for your help.