Ansible如何使用变量和字符串的混合作为键从字典中获取值

Ansible how to get value from dictionary using a mix of variable and string as key

我正在努力实现类似的目标,说起来容易做起来难,基本上我想在 import_task 中混合使用变量和字符串作为键从字典中获取值,所以代码应该是这样的像这样:

- import_tasks: "somefile_{{ somedic[ansible_distribution'_'ansible_distribution_major_version ] }}.yml"

dic 应该是这样的:

somedic: { "RedHat_7": "endoffilename" } 

当 运行 在服务器 RedHat 7 上时,它应该结束加载名为

的文件
somefile_endoffilename.yml

你不能用那个字典结构来做,因为它需要嵌套的变量解除引用,而 Jinja2 不支持。所以你的字典需要看起来像这样:

vars:
  somedic:
    "RedHat":
       "7": "endoffilename"

在 JSON 中,看起来像:

vars:
  somedic: { "RedHat": { "7": "endoffilename" } }

那么,你可以得到你需要的东西:

---
- hosts: localhost
  gather_facts: no
  vars:
    somedic: { "RedHat": { "7": "endoffilename" } }

    OS: RedHat
    MajorVersion: "7"

  tasks:
   - debug:
      msg: "somefile_{{ somedic[OS][MajorVersion] }}.yml"

debug 任务的输出是:

TASK [debug] *************************************************************************
Tuesday 26 May 2020  11:14:30 -0400 (0:00:00.027)       0:00:00.146 *********** 
ok: [localhost] => {
    "msg": "somefile_endoffilename.yml"
}