ansible - Ansible:检查变量是否包含列表或字典
问题描述
有时,角色需要在调用它们时需要定义不同的强制变量。例如
- hosts: localhost
remote_user: root
roles:
- role: ansible-aks
name: myaks
resource_group: myresourcegroup
在角色内部,可以这样控制:
- name: Assert AKS Variables
assert:
that: "{{ item }} is defined"
msg: "{{ item }} is not defined"
with_items:
- name
- resource_group
我想将列表或字典传递给我的角色,而不是字符串。如何断言变量包含字典或列表?
解决方案
例子:
在字典的情况下,很容易:
---
- 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 )
但是在检查列表时,我们需要确保它不是映射,不是字符串并且是可迭代的:
- name: Assert if list
assert:
that: >
( mylist is defined ) and ( mylist is not mapping )
and ( mylist is iterable ) and ( mylist is not string )
如果您使用字符串、布尔值或数字进行测试,则断言将为假。
另一个不错的选择是:
- 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" )
推荐阅读
- java - 将当前执行函数的参数动态传递给其他函数
- azure - 在门户中运行 Azure 功能时出现内部服务器错误
- ruby - Ruby 微服务 - 如何在生产中重新启动/重生
- c# - 实体框架 mvc 如何使用内部联接?
- c# - 为什么这个表达式接受 & 符号
- microsoft-graph-api - 尝试使用 Graph Explorer 找出每个用户的 Intune managedAppRegistrtaion
- javascript - Google 跟踪代码管理器 - 应为主要表达式
- php - 用于检索购物车总数的 Woocommerce 购物车模型
- javascript - 如何获取图像的宽度和高度?( SVG 的 getBBox() 大小返回 0 )
- java - 解析命令行并将其更改为 Char 或 Boolean