gpt4 book ai didi

Ansible - 检查变量类型

转载 作者:行者123 更新时间:2023-12-04 13:15:09 24 4
gpt4 key购买 nike

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

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

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

有什么办法可以做到吗?

最佳答案

Q: "Execute some ansible logic depending on the variable type."


答: The tests包括 mapping按预期工作。例如
    - set_fact:
myvar:
key1: value1
- debug:
msg: "{{ (myvar is mapping)|
ternary('is a dictionary', 'is something else') }}"
    "msg": "is a dictionary"

Q: "Ansible - check variable type"


答:一个选项是 discover the data type和动态 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 }}
有了这个剧本
- hosts: localhost
vars:
test:
- 123
- '123'
- [a,b,c]
- {key1: value1}
tasks:
- include_tasks: "{{ 'tasks-' ~ item|type_debug }}"
loop: "{{ test }}"
给予(略)
  msg: Processing integer 123

msg: Processing string 123

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

msg: 'Processing dictionary {''key1'': ''value1''}'

关于Ansible - 检查变量类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61255461/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com