如果变量列表中的引用文件存在,则有条件地包含模板行

Conditionally Include Template Lines if Referenced Files from Variable List Exist

我想根据变量列表中定义的目录是否存在,有条件地在我的 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', 'equalto', item.name) | first).stat.exists %}