6

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.

7

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.

1
  • Im trying to pull in the ec2 facts, I get One or more undefined variables: 'ec2_facts' is undefined from - debug: msg="{{ ec2_facts }}" wish i knew why :( – CMag Dec 15 '15 at 1:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.