问题
I have a host group which have host variables as shown below
[test:children]
test1
test2
test3
[test:vars]
clean_images=true
I have a tasks defined in a role as shown below
- name: clean docker images
template:
dest: "/etc/systemd/system/{{ item.name }}"
with_items:
- { name: "{{ service_name }}.service" }
- name: start service
systemd:
name: "{{ service_name }}.service"
state: started
enabled: yes
when: hostvars['test'].clean_images is defined
This is a simple tasks, where I clean docker images depending on the host. I have a playbook which executes this above role in a different set of host group [test_services]. I want the task - name: start service to run if it come across any of the host groups defined in [test:children]. To check that I have added a variable clean_images=true to the test group to execute a condition check
But the when statement I have included above gives me an error
fatal: [xx.xx.xx.xx]: FAILED! => {"msg": "The conditional check 'hostvars['test'].clean_images is defined' failed. The error was: error while evaluating conditional (hostvars['test'].clean_images is defined): \"hostvars['test']\" is undefined\n\nThe error appears to have been in 'main.yml'
I have a problem in building up this conditional statement using when, any help would be great.
回答1:
when: hostvars['test'].clean_images is defined
should be just:
when: clean_images is defined and clean_images
because there is no host named test
, and thus hostvars of test
will never exist. All hosts that belong to the test
group will have clean_images
defined, however
来源:https://stackoverflow.com/questions/53718577/accessing-host-variables-in-tasks-in-ansible