Ansible: How to access hostvars in task?
I'm trying to use hostvars in my task. But it seems that ansible is interpolating the variable and then trying to look it up in the main variable dict object. Here's my code:
- name: Configure the instance
hosts: rundeck-masters
sudo: True
gather_facts: True
tasks:
- name: Gather EC2 facts
ec2_facts:
# show all known facts for this host
- debug: msg={{ hostvars[groups['rundeck-masters'][0]][ansible_ec2_instance_id] }}
- name: Snapshot the instance
local_action:
module: ec2_ami
description: "Rundeck master - {{ ansible_date_time.date }}"
instance_id: "{{ hostvars[groups['rundeck-masters'][0]][ansible_ec2_instance_id] }}"
wait: no
And the error I get is:
TASK: [debug msg={{ hostvars[groups['rundeck-masters'][0]][ansible_ec2_instance_id] }}] ***
fatal: [ec2-xx-xx-xx-xx.eu-west-1.compute.amazonaws.com] => One or more undefined variables: 'dict object' has no attribute u'i-12341234'
So the instance ID is obviously in the hostvars dict, but I don't seem to have any way of actually using it as the instance_id parameter for the ec2_ami module.
What am I doing wrong? Quoting the debug msg makes no difference, and removing the braces just prints the literal hostvars string.
It seems the answer is to quote the variable name: 'ansible_ec2_instance_id', i.e.:
- debug: msg="{{ hostvars[groups['rundeck-masters'][0]]['ansible_ec2_instance_id'] }}"
Now it works correctly.