Search code examples
ansibleansible-inventory

Ansible: use host address of hosts.ini in playbook


I have to do a POST request with ansible.

My hosts.ini file is:

[workers]
worker1 ansible_host=111.111.111.111 
worker2 ansible_host=222.222.222.222 

The url I have to connect to needs the ip address of worker1, so I wrote my playbook as:

- hosts: worker1

  tasks:
  - name: inizialize worker                                          
    uri:
      url: "http://{{ worker1 }}:8080/xxx/yyy"
      method: POST
      user: admin
      password: password
      force_basic_auth: yes
      return_content: yes
      body: "field=myfield"

But running it, I get:

the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'worker1' is undefined

Where is the problem?


Solution

  • You don't have a variable named worker1 defined.

    If you wanted to replace the value with 111.111.111.111, you should use magic variables:

    url: "http://{{ hostvars['worker1']['ansible_host'] }}:8080/xxx/yyy"
    

    but considering your whole play, you might as well wanted:

    url: "http://{{ ansible_host }}:8080/xxx/yyy"
    

    Mind that your inventory file defines a host group named workers and your play refers to a host group named worker1 -- this makes no sense altogether.