首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Ansible:检查变量是否包含列表或字典

Ansible:检查变量是否包含列表或字典
EN

Stack Overflow用户
提问于 2020-03-18 03:26:58
回答 1查看 5.4K关注 0票数 7

有时,角色需要不同的强制变量,在调用它们时需要定义这些变量。例如

代码语言:javascript
运行
复制
- hosts: localhost
  remote_user: root

  roles:
    - role: ansible-aks
      name: myaks
      resource_group: myresourcegroup

在角色内部,可以像这样控制它:

代码语言:javascript
运行
复制
- name: Assert AKS Variables
  assert:
    that: "{{ item }} is defined"
    msg: "{{ item  }} is not defined"
  with_items:
    - name
    - resource_group

我希望将列表或字典传递给我的角色,而不是字符串。我如何断言一个变量包含字典或列表?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-18 03:26:58

示例:

在使用字典的情况下,这很简单:

代码语言:javascript
运行
复制
---
- name: Assert if variable is list or dict
  hosts: localhost
  connection: local
  gather_facts: false

  vars:
    mydict: {}
    mylist: []

  tasks:

  - name: Assert if dictionary
    assert:
      that: ( mydict is defined ) and ( mydict is mapping )

但在检查列表时,我们需要确保不是映射,而不是字符串和可迭代:

代码语言:javascript
运行
复制
  - name: Assert if list
    assert:
      that: >
           ( mylist is defined ) and ( mylist is not mapping )
           and ( mylist is iterable ) and ( mylist is not string )

如果使用string、boolean或numeric进行测试,则断言将为false。

另一个好的选择是:

代码语言:javascript
运行
复制
  - name: Assert if dictionary
    assert:
      that: ( mydict is defined ) and ( mydict | type_debug == "dict" )

  - name: Assert if list
    assert:
      that: ( mylist is defined ) and ( mylist | type_debug == "list" )
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60729009

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档