Passing a variable into 'hosts' in the same playbooks

Hi

Sorry I’m coding and learning at the same time

I’m writing a playbook to generate an AMI in ansible

basic steps of the playbook

  1. launch an EC2 instance in AWS
    1.a wait for ssh port to come up
  2. refresh cached output from ec2.py
  3. build the instance with a role
  4. generate the AMI
    4.a terminate running instance

I’ve got this working with 3 playbooks

  1. Launch instance
  2. Build instance
  3. create AMI (includes termination)

I would like to combine all the above in 1 playbook

the issue I have is passing in the hosts as a variable after I refreshed the ec2.py cache

the area on the code I’m focusing on is

  • set_fact:
    target_host: “tag_Name_RHEL-base-{{ instance_date }}-01”

  • debug: var=target_host

  • name: Build RHEL Base AMI image
    hosts: “{{ target_host }}”
    #hosts: tag_Name_RHEL-base*
    connection: local
    gather_facts: False
    tasks:

  • debug: msg=“Hostname is {{ target_host }}”

The error is
TASK [set_fact] ****************************************************************
ok: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
“target_host”: “tag_Name_RHEL-base-20170421-01”
}
ERROR! the field ‘hosts’ has an invalid value, which appears to include a variable that is undefined. The error was: ‘target_host’ is undefined

The error appears to have been in ‘/home/opentext/playbooks/launch_base_RHELAWSinstance.yml’: line 71, column 3, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

  • name: Build RHEL Base AMI image
    ^ here

Any suggestions to solving the issue?

Kind Regards
Tony

You need to specify from which you are fetching the variable from.

{{ hostvars.localhost.target_host }}