4
votes

I have a playbook where I'm spinning up an instance in aws with the ec2 module. To be more flexible I ask via prompt for the hostname. I found in the ec2 examples the code snippet, which allows you to run a second playbook with newly spun up instance for further configuration.

Now I want to set the hostname via module hostname but I cannot access the variable in the second playbook.

This is how 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: [launched] => One or more undefined variables: 'var_hostname' is undefined

Is there a way to pass a variable from one playbook to another one?

I found Ansible best practice for passing vars to nested playbooks? but unfortunately it didn't had a solution which I can use.

2

2 Answers

7
votes

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

Do set_fact on one group of hosts( i.e localhost), and access them in a different play using hostvars

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

3
votes

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) Retrieve with http://docs.ansible.com/ansible/playbooks_lookups.html

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

PS. Ini file lookup also an option if you need more than few variables.