在我的主机变量结构中,我的网络服务器有一个这样的数据结构:
“wordpress”:{ “配置”:{ “端口”:80, “SSL”:{ “端口”:443 }, }
我希望能够对其进行动态访问,无论我是否使用 ssl。 直接访问很简单 - 其中 host 是 inventory_hostname;例如在 {% for 循环中:
问题是:我可以有一个变量名称的动态后缀吗,例如:
谢谢
对我来说,数据结构和方法看起来不必要的复杂和笨拙。由于您似乎正在寻找布尔状态,因此是否配置了 TLS、是或否、真或假,一个简单的最小示例剧本可能如下所示
---
- hosts: localhost
become: false
gather_facts: false
vars:
wordpress:
config:
ssl: true
tasks:
- name: Construct URL
debug:
msg: "http{% if wordpress.config.ssl %}s{% endif %}://wordpress.example.com"
- name: With port if necessary
debug:
msg: "https://wordpress.example.com:443"
when: wordpress.config.ssl
产生
的输出TASK [Construct URL] *******************
ok: [localhost] =>
msg: https://wordpress.example.com
TASK [With port if necessary] **********
ok: [localhost] =>
msg: https://wordpress.example.com:443
ternary
过滤器,根据条件选择一个值或另一个值:
- debug:
msg: "{{ ssl_enabled | ternary(hostvars[host].wordpress.config.ssl.port, hostvars[host].wordpress.config.port) }}"