如何解决如果存在变量列表中的引用文件,则有条件地包含模板行
我想根据变量列表中定义的目录是否存在有条件地在我的 Nginx 虚拟主机中包含一些配置(实际上它也基于下面的变量列表中是否存在变量,但我正在尝试在这里保持简单)。
变量看起来像这样:
nginx:
sites:
- name: example.com
aliases: www.example.com
tls:
key: /etc/letsencrypt/live/example.com/privkey.pem
certificate: /etc/letsencrypt/live/example.com/fullchain.pem
- name: anotherexample.com
aliases: www.anotherexample.com
tls:
key: /etc/letsencrypt/live/anotherexample.com/privkey.pem
certificate: /etc/letsencrypt/live/anotherexample.com/fullchain.pem
假设目录 /etc/letsencrypt/live/example.com/
存在,而目录 /etc/letsencrypt/live/anotherexample.com
不存在。
以上内容用于以下模板(with_items: nginx.sites
):
- name: Nginx Site Templates
template:
src: nginx/nginx_site.conf.j2
dest: /etc/nginx/sites-available/{{ item.name }}.conf
with_items: "{{ nginx.sites }}"
notify: reload nginx
tags:
- conf
“nginx/nginx_site.conf.j2”是部分:
server {
...
{% if [MY CONDITION THAT I NEED HELP WITH] %}
listen 443 ssl;
ssl_certificate_key {{ item.tls.key }};
ssl_certificate {{ item.tls.certificate }};
{% endif %}
...
}
我收集了有关 nginx.sites[].tls
中引用的目录是否存在以下注册事实的事实:
- name: Register Fact About Available TLS Certificates
stat:
path: "/etc/letsencrypt/live/{{ item.name }}"
register: tls_site_certificates
changed_when: false
with_items: "{{ nginx.sites }}"
- conf
- facts
对于每个站点,仅当引用的目录存在时,我才希望将这些行包含在模板的 if
条件中。我想我几乎就在那里,但我很难弄清楚。到目前为止,我有:
{% if tls_site_certificates.results | select('item.name','equalto',item.name) | select('stat.exists') == true %}
解决方法
select
是过滤列表。
第一次使用 select('item.name','equalto',item.name)
几乎是正确的:使用 selectattr
您只保留与当前项目同名的元素。
但是你想访问第一个元素的字段,而不是再次过滤(并且不需要将 bool 与 true
进行比较):
{% if (tls_site_certificates.results | selectattr('item.name',item.name) | first).stat.exists %}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。