Ansible/Jinja2 在字典层次结构中使用不同名称后缀进行动态变量替换

问题描述 投票:0回答:2

在我的主机变量结构中,我的网络服务器有一个这样的数据结构:

“wordpress”:{ “配置”:{ “端口”:80, “SSL”:{ “端口”:443 }, }

我希望能够对其进行动态访问,无论我是否使用 ssl。 直接访问很简单 - 其中 host 是 inventory_hostname;例如在 {% for 循环中:

  • 调试: 消息:“{{ hostvars[host].wordpress.config.port }}”

问题是:我可以有一个变量名称的动态后缀吗,例如:

  • 主机:lb1 变量: 主机:web1 后缀:'.wordpress.config.port' 任务:
    • 调试: 消息:“{{主机变量[主机]+后缀}}”
    • 调试: 消息:“{{查找('vars',hostvars[主机]+后缀)}}”

谢谢

ansible jinja2
2个回答
0
投票

对我来说,数据结构和方法看起来不必要的复杂和笨拙。由于您似乎正在寻找布尔状态,因此是否配置了 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

0
投票

不是那样的。您想要的是

ternary
过滤器,根据条件选择一个值或另一个值:

- debug:
    msg: "{{ ssl_enabled | ternary(hostvars[host].wordpress.config.ssl.port, hostvars[host].wordpress.config.port) }}"
© www.soinside.com 2019 - 2024. All rights reserved.