I'm setting up a complete environment using Ansible. For some reason, Ansible is not picking up variable values.
I'm using Ansible 2.1.1.0.
Here's a strip example of what I'm trying to do:
I have registered my vpc with register: ec2_vpc
.
syntax-1 # This doesn't work
- name: Add to host vars
add_host:
name: "vpc subnets"
groups: vpc_vars
vpc_subnet_id: "{{ ec2_vpc.subnets[0].id }}"
vpcid: "{{ ec2_vpc.vpc_id }}"
- debug: var=vpc_subnet_id
- debug: var=vpcid
syntax-2 # These works
- name: Record vpc id
debug: var=ec2_vpc.vpc_id
- name: Record subnet id
debug: var=ec2_vpc.subnets[0].id
Result of the above strip:
TASK [debug] *******************************************************************
ok: [localhost] => {
"vpc_subnet_id": "VARIABLE IS NOT DEFINED!"
}
TASK [debug] *******************************************************************
ok: [localhost] => {
"vpcid": "VARIABLE IS NOT DEFINED!"
}
TASK [Record vpc id] ***********************************************************
ok: [localhost] => {
"ec2_vpc.vpc_id": "vpc-4sdh3832f"
}
TASK [Record subnet id] ********************************************************
ok: [localhost] => {
"ec2_vpc.subnets[0].id": "subnet-edfjdh3482"
}
Why is my first syntax not picking the value instead it's returning VARIABLE IS NOT DEFINED!
Updated: Here my 2nd syntax describes I am correctly sorting out the value from the JSON result of registered variable. But I want it work for my 1st syntax which means I want to add hosts variables to dynamic inventory. So that I can reuse it in another play
Best Answer
add_host
module creates a host in the dynamic list of hosts. You then run another play (in the same playbook) against this group of hosts and from within that play you will be able to access the variables you set.For example with the following syntax:
The
add_host
in the above example creates an in-memory inventory file with the following content: