假设我想从 ansible 运行以下任务:
- name: dns-cloudflare | Request certificate
ansible.builtin.shell:
cmd: certbot certonly \
--dns-cloudflare \
--dns-cloudflare-credentials {{ certbot_cloudflare_credentials_file }} \
--non-interactive \
--agree-tos \
--expand \
--email {{ certbot_email }} \
--domain {{ __domains }}
args:
executable: /bin/bash
creates: "{{ certbot_directory }}/{{ item.name }}/{{ item.name }}/cert.pem"
我用这样的块构建它:
certbot_cert:
- name: test1.example.com
cn:
- test2-cn.example.com
post-hook: systemctl restart apache2
- name: test3.example.com
我想将 --post-hook 参数添加到我的 certbot 命令中,具体取决于
item.post-hook
。而且这个钩子的内容不是静态的,我在那里输入的任何内容都应该落在我的 certbot 命令中,例如 --post-hook 'systemctl restart apache2'
但是当我不定义这个变量时,不应该有一个空的后钩子,它根本不应该出现在 certbot 命令中。
我怎样才能实现这个目标?
我尝试了变量和过滤器,并通读了文档,但没有找到正确的方法来处理 is。对于每个可能的可选参数重复此任务多次不应该是这样。
您编写
cmd
值的方式不会保留换行符 - 这就是您想要的,因为这意味着(a)您不需要像您一样转义(\
)行尾'已经在您的示例中完成了,并且(b)您可以方便地使用 jinja 条件来抑制某些行。
像这样:
- hosts: localhost
gather_facts: false
vars:
certbot_cloudflare_credentials_file: creds.conf
certbot_email: [email protected]
__domains: example.com
certbot_directory: certs
certbot_cert:
- name: test1.example.com
cn:
- test2-cn.example.com
post-hook: systemctl restart apache2
- name: test3.example.com
tasks:
- name: dns-cloudflare | Request certificate
loop: "{{ certbot_cert }}"
ansible.builtin.shell:
cmd: certbot certonly
--dns-cloudflare
--dns-cloudflare-credentials "{{ certbot_cloudflare_credentials_file }}"
--non-interactive
--agree-tos
--expand
--email "{{ certbot_email }}"
--domain "{{ __domains }}"
{% if 'post-hook' in item %}
--post-hook "{{ item["post-hook"] }}"
{% endif %}
args:
executable: /bin/bash
creates: "{{ certbot_directory }}/{{ item.name }}/{{ item.name }}/cert.pem"
对于
certbot_cert
中的第一项,将运行:
certbot certonly --dns-cloudflare --dns-cloudflare-credentials creds.conf --non-interactive --agree-tos --expand --email [email protected] --domain example.com --post-hook systemctl restart apache2
对于第二行,它将运行:
certbot certonly --dns-cloudflare --dns-cloudflare-credentials creds.conf --non-interactive --agree-tos --expand --email [email protected] --domain example.com