We can query for a host in a play like
- name: Test1
hosts: "{{ target1 }}"
gather_facts: false
vars_prompt:
- name: target1
prompt: "Specify deployment target1"
private: false
default: 'localhost'
tasks:
- name: Output 1
ansible.builtin.debug:
msg:
- "{{ target1 }}"
The problem however is if I try to access target1
from another play, if we e.g. add
- name: Test2
hosts: "{{ target1 }}"
tasks:
- name: Output 2
ansible.builtin.debug:
msg:
- "{{ target1 }}"
It fails with an undefined variable error. In addition when I set target1
as a fact via
- name: Store Variable for cross play visibility
ansible.builtin.set_fact:
target1: "{{ target1 }}"
in the play Test1, the play Test2 still fails with
ERROR! The field 'hosts' has an invalid value, which includes an undefined variable. The error was: 'target1' is undefined. 'target1' is undefined
once I remove the variable in hosts
of play Test2 it works. So it seems that I need to add
I also tried to use add_host
using something like
- name: Define hosts dynamically
ansible.builtin.add_host:
hostname: "{{ target1 }}"
groups: dynamically_created_hosts
but this also fails.
So how do I use the host variable defined via vars_prompt
in one play in another one?