Reputation: 11
Please help set variable for another host:
For example:
---
- name: host1 - varaible from vars_prompt
hosts: '{{ host }}'
become: yes
vars_prompt:
- name: "host"
prompt: "Enter host:"
default: 'Aubuntu'
tasks:
- name:
set_fact:
monitip: "{{ansible_host}}"
- name: host2 - static host
hosts: 'host2'
tasks:
- name: Добавляем в мониторинг
shell: echo {{monitip}}
How to send {{monitip}}
to host2 ?
I need get ip from host1 based on vars_prompt {{ host }}
and use it in host2
fatal: [host2]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'monitip' is undefined
UPD:
thanks for the replies, but I’m doing it all by myself by saving the variable to a file
---
- name: host1 - varaible from vars_prompt
hosts: '{{ host }}'
become: yes
vars_prompt:
- name: "host"
prompt: "Enter host:"
default: 'Aubuntu'
tasks:
- lineinfile : >
dest=/tmp/s_ip.txt
create=yes
line='{{ansible_host}}'
delegate_to: localhost
- name: host2 - static host
hosts: 'host2'
tasks:
- command: cat /tmp/s_ip.txt
register: monitip
delegate_to: localhost
- name: Добавляем в мониторинг
shell: echo {{monitip.stdout}}
Upvotes: 0
Views: 6366
Reputation: 41
interesting request, I think I managed to get it working with slightly other approach. Inventory file like for example:
$ cat inv
[myhosts]
host1.example.com
host2.example.com
and then a playbook like:
---
- hosts: myhosts
become: yes
vars_prompt:
- name: "myhost"
prompt: "Enter host:"
default: localhost
tasks:
- name: Use it
debug:
msg: "IP used on {{ ansible_fqdn }} is {{ hostvars[myhost]['ansible_default_ipv4']['address'] }}"
when: ansible_fqdn == myhost
Upvotes: 0
Reputation: 33231
You can reference the hostvars
of the other host by name:
- hosts: host2
tasks:
- name: copy over monitip from the other host
set_fact:
monitip: '{{ hostvars[the_first_host].monitip }}'
vars:
the_first_host: '{{ groups.all | difference([inventory_hostname]) | first }}'
Of course, that won't work if host2
represents a group of them, but that's the general idea, anyway
While that's the answer to your question, you are also likely jumping through a lot of hoops needlessly, since you can always access that hostvar directly, in the same playbook:
- hosts: host2
vars_prompt:
- # as before
tasks:
- set_fact:
monitip: '{{ hostvars[host].ansible_host }}'
# tada, drama free
Upvotes: 1