问题
I'm aware of how to read set_fact across different plays. I have also read about issues regarding set_fact in another play.
However, I did not come across any example where the set_fact used under a Play having dynamically constructed host using add_host and it now needs to be read by another play having hosts: localhost
I was expecting host_vars to help me but the below playbook test shows that host_vars also does not help and I get a variable undefined error. You can run the playbook and test yourself.
Here is my requirement:
I have a playbook where I add the dynamic host to group "desthosts" in [Play 1]
In [Play 2] I append a string variable "storerecords" with values specific to each host in desthosts group.
In [Play 3] I try to remove duplicate entries in "storerecords" variable where the challenge is. I get the undefined 'storerecords' variable error.
Below is my playbook.
---
- name: Play 1
hosts: localhost
tasks:
- add_host:
name: "{{ item }}"
group: desthosts
with_items:
- "{{ SourceHost.split(',') }}"
- name: Play 2
hosts: desthosts
tasks:
- set_fact:
storerec: "{{storerec | default('') + 'Hello ' + inventory_hostname + '\n'}}"
with_fileglob:
- "{{ playbook_dir }}/tmpfiles/*"
- name: Play 3
hosts: localhost
tasks:
- local_action: lineinfile line="{{ hostvars['dest_nodes']['storerec'] }}" path="{{ playbook_dir }}/files/tricky.txt" create=yes
Playbook run command:
ansible-playbook test.yml -e SourceHost="10.9.9.56,10.9.9.63,10.9.9.33"
Error running the playbook is:
TASK [lineinfile] *******************************************************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: \"hostvars['desthosts']\" is undefined\n\nThe error appears to be in '/app/test.yml': line 28, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n tasks:\n - local_action: lineinfile line=\"{{ hostvars['desthosts']['storerec'] }}\" path=\"{{ playbook_dir }}/files/tricky.txt\" create=yes\n ^ here\nWe could be wrong, but this one looks like it might be an issue with\nmissing quotes. Always quote template expression brackets when they\nstart a value. For instance:\n\n with_items:\n - {{ foo }}\n\nShould be written as:\n\n with_items:\n - \"{{ foo }}\"\n"}
At the end of Play 2 my string variable storerecords when dumped to a file using inline module has has below entries:
/app/logs/scripts
/app/logs/mrt
/app/logs/com
/app/logs/exe
/app/logs/scripts
/app/logs/mrt
/app/logs/com
/app/logs/exe
/app/logs/scripts
/app/logs/mrt
/app/logs/com
/app/logs/exe
Can you please suggest how I can get the value of storerecords from desthost to Play 3?
来源:https://stackoverflow.com/questions/58979061/is-it-possible-to-read-set-fact-of-a-dynamically-constructed-host-in-different-a