问题
I have the following problem:
A host_var defining my nginx sites (excerpt):
nginx_sites:
- server:
name: site1
location1:
config:
name: "/"
[...]
- server:
name: site2
location1:
config:
name: "/"
[...]
location2:
config:
name: "/secretspace"
[...]
htaccess:
username:
password: somepassword
In this example I have 2 sites. The second one has two locations where the second one has a subelement named "htaccess". This is what I want to use in order to create an corresponding htaccess file.
I tried this ansible task:
- name: Creating htaccess files if nessecary
debug: msg="Huhu {{ item.0.name }} {{ item.1 }}"
with_subelements:
- "{{ nginx_sites }}"
- "htaccess"
- flags:
skip_missing: True
This should imho print a debug statement, when there is a subelement named "htaccess" element in nginx_sites
or skip if it is not there.
But nothing happens:
TASK [nginx : Creating htaccess files if nessecary] ****************************
task path: /home/dakky/devzone/ansible-cfg-mgmt/roles/nginx/tasks/main.yml:65
PLAY RECAP *********************************************************************
hostname : ok=1 changed=0 unreachable=0 failed=0
Any idea what I'm doing wrong here?
回答1:
with_subelements
is used to iterate over list subelements.
If you modify your input data to make a list of locations instead of named properties (location1, location2, etc):
nginx_sites:
- server:
name: site1
locations:
- config:
name: "/"
- server:
name: site2
locations:
- config:
name: "/"
- config:
name: "/secretspace"
htaccess:
username:
password: somepassword
Then you can iterate your locations and select those with htaccess defined:
- name: Creating htaccess files if nessecary
debug: msg="Huhu {{ item.0.server.name }} {{ item.1.htaccess }}"
when: item.1.htaccess is defined
with_subelements:
- "{{ nginx_sites }}"
- "server.locations"
Also note that you should specify "full path" for subelements. In your original example htaccess
will never match anything, but server.location2.htaccess
will (although rising error that this item is not a list).
回答2:
This works for me
- name: Creating htaccess files if nessecary
debug: msg="Huhu {{ item.0.name }} {{ item.1 }}"
with_subelements:
- "{{ nginx_sites }}"
- "htaccess"
- skip_missing: True
来源:https://stackoverflow.com/questions/39355598/ansible-with-subelements-and-skip-missing-does-not-work