Ansible - 检查变量类型

Meg*_*esh 14 jinja2 ansible

显然,根据几个小时的搜索,没有人遇到过这个用例:

它很简单 - 我想根据变量类型执行一些可靠的逻辑。基本上相当于eg,instanceof(dict, var_name)但在Ansible中:

- name: test
  debug:
    msg: "{{ instanceof(var_name, dict) | ternary('is a dictionary', 'is something else') }}"
Run Code Online (Sandbox Code Playgroud)

有什么办法可以做到这一点吗?

Vla*_*tka 12

问:“根据变量类型执行一些 ansible 逻辑。”

答:包括映射在内的测试 按预期工作。例如,下面的任务

    - set_fact:
        myvar:
          key1: value1
    - debug:
        msg: "{{ (myvar is mapping)|
                 ternary('is a dictionary', 'is something else') }}"
Run Code Online (Sandbox Code Playgroud)

    msg: is a dictionary
Run Code Online (Sandbox Code Playgroud)

问:“Ansible - 检查变量类型”

答:一种选择是动态发现数据类型include_tasks。例如,下面的任务

shell> cat tasks-int
- debug:
    msg: Processing integer {{ item }}

shell> cat tasks-str
- debug:
    msg: Processing string {{ item }}

shell> cat tasks-list
- debug:
    msg: Processing list {{ item }}

shell> cat tasks-dict
- debug:
    msg: Processing dictionary {{ item }}
Run Code Online (Sandbox Code Playgroud)

有了这本剧本

- hosts: localhost
  vars:
    test:
    - 123
    - '123'
    - [a,b,c]
    - {key1: value1}
  tasks:
    - include_tasks: "tasks-{{ item|type_debug }}"
      loop: "{{ test }}"
Run Code Online (Sandbox Code Playgroud)

给(删节)

  msg: Processing integer 123

  msg: Processing string 123

  msg: Processing list ['a', 'b', 'c']

  msg: 'Processing dictionary {''key1'': ''value1''}'
Run Code Online (Sandbox Code Playgroud)

如果你想模拟switch语句创建一个字典

  case:
    int: tasks-int
    str: tasks-str
    list: tasks-list
    dict: tasks-dict
    default: tasks-default
Run Code Online (Sandbox Code Playgroud)

并在包含中使用它

    - include_tasks: "{{ case[item|type_debug]|d(case.default) }}"
      loop: "{{ test }}"
Run Code Online (Sandbox Code Playgroud)


mus*_*ons 7

从 Ansible 版本 2.3 开始,有type_debug

- name: test
  debug:
        msg: "{{ (( var_name | type_debug) == 'dict') | ternary('is a dictionary', 'is something else') }}"
Run Code Online (Sandbox Code Playgroud)

请注意,文档声明了对“类型测试”的偏好。