Passing variables between nested playbooks

I have a playbook where I am deploying an instance in aws with the ec2 module. To be more flexible, I ask through a prompt for the hostname. I found in the ec2 examples a code snippet that allows you to run a second play with a newly created instance for further customization.

Now I want to set the host name through the hostname module, but I can’t access the variable in the second play.

Here's what my playbook looks like:

 --- - hosts: localhost ... vars_prompt: - name: var_hostname prompt: "Please enter the hostname" private: no tasks: - name: Spin up instance local_action: module: ec2 ... register: ec2 - name: Add new instance to host group add_host: hostname={{ item.public_ip }} groupname=launched with_items: ec2.instances - hosts: launched ... tasks: - name: Set hostname hostname: name="{{ var_hostname }}" 

fatal: [launch] => One or more variables undefined: "var_hostname" - undefined

Is there a way to transfer a variable from one play to another?

Have I found Strong best practice for transferring vars to playbooks embedded in it? but, unfortunately, she did not have a solution that I can use.

+4
source share
2 answers

You can use set_fact and hostvars to achieve what you want.

Make set_fact on one group of hosts (e.g. localhost) and access them in another game using hostvars

{{hostvars ['local'] ["new_fact"]}}

+5
source

You can use local files.

1) Write

 - name: write public ip local_action: template: dest: /tmp/ansible_master_public_ip.txt src: templates/public_ip.j2 

2) Get using http://docs.ansible.com/ansible/playbooks_lookups.html

 hostname: "{{ lookup('file', '/tmp/ansible_master_public_ip.txt') | trim }}" 

PS. Finding an Ini file is also an option if you need more than a few variables.

+2
source

All Articles