3

Why does this task (from Best way to launch aws ec2 instances with ansible):

  - name: Add the newly created EC2 instance(s) to the local host group (located inside the directory)
    local_action: lineinfile 
                  dest="./hosts" 
                  regexp={{ item.public_ip }} 
                  insertafter="[webserver]" line={{ item.public_ip }}
    with_items: ec2.instances

create this error?

TASK [Add the newly created EC2 instance(s) to the local host group (located inside the directory)] ********************************************************************
fatal: [localhost]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'ansible.vars.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'public_ip'\n\nThe error appears to have been in '/Users/snowcrash/ansible-ec2/ec2_launch.yml': line 55, column 9, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n      - name: Add the newly created EC2 instance(s) to the local host group (located inside the directory)\n        ^ here\n"}
Snowcrash
  • 80,579
  • 89
  • 266
  • 376

2 Answers2

6

the issue is here

with_items: ec2.instances

It should be:

with_items: '{{ ec2.instances }}'

ec2 is variable referencing a dictionary so you will need to reference it with the proper syntax

ADyson
  • 57,178
  • 14
  • 51
  • 63
Akil
  • 75
  • 1
  • 9
1

Put:

  - debug: msg="{{ ec2.instances }}"

before that code and inspect what are the contents of that variable. It should be a list of dictionaries that each have a member public_ip, otherwise you'd get the message that you're getting.

plesiv
  • 6,935
  • 3
  • 26
  • 34