Referencing Ansible Variables

Hi there,

I am fairly new with ansible and I am having some with variables :-).

Here is my 1st problem, I have a playbook I do have a variable:

`

  • name: Create instance(s)
    hosts: local
    gather_facts: no
    connection: local
    tags: provisioning
    vars:

    groupname: launched
    port: 8080
    `

Later I use it in the add_host line:

`

  • name: Add host to groupname
    add_host: hostname={{ item.public_ip }} ansible_ssh_private_key_file=PATH_TO_KEYFILE groupname={{ groupname }}
    with_items: gce.instance_data

`

and then I use it again at:

Hi Peter,

IMHO it is because your variables are defined for the host “local” within your 1st play, the hosts group “launched” cannot know about variables defined for another group

Hope this help.

Fred

Hi Peter

As Fred says, the variables are not in scope for both plays. You will need to declare your variables such that both plays can see them. You could put them into a separate file and reference it with vars_files in both plays, or you could pass them in as extra vars on the command line. You will not be able to put them into group_vars/ or host_vars/, as they are not able to be resolved at the time the hosts are matched.

Also, you can simplify your role call to

roles:
  - { role: webserver, port: port }

(i.e. without interpolating the port var into a string)

Although the port variable will be in scope within the role just by declaring it in your play, so you can drop it altogether as a role parameter

roles:
  - webserver

Regards
Tom

Thank you guys!!!

Peter