Ansible测试变量类型 [英] Ansible testing variable type

查看:119
本文介绍了Ansible测试变量类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用现有角色,并且希望对其进行修改以扩展其功能.当前,其任务之一是创建目录.这些目录作为包含字符串列表的变量传递给角色,然后在with_items语句中进行迭代.但是,我更愿意传递例如格式为的字典列表. {name: foo, mode: 751}.

I'm using an existing role, and I wish to modify it to extend its capabilities. Currently, one of its tasks is to create directories. These directories get passed as a variable containing a list of strings to the role, and then iterated over in a with_items statement. However, I would prefer to pass a list of dictionaries of the form e.g. {name: foo, mode: 751}.

到目前为止,一切都很好.我可以简单地编辑角色以使其接受这种输入.但是,我还想使其与旧格式(即项目为字符串的地方)向后兼容.

So far so good; I can simply edit the role to make it take this sort of input. However, I also want to make it backwards compatible with the old format, i.e. where the items are strings.

是否有一种方法可以测试变量的类型,然后基于此方法返回不同的值(或执行不同的任务)?也许使用Jinja2过滤器?我只是在看手册中列出的条件,但是没有什么吸引我的眼球在这种情况下使用.

Is there a way to test the type of a variable and then return different values (or perform different tasks) based on this? Perhaps using a Jinja2 filter? I was briefly looking at the conditionals listed in the manual, but nothing caught my eye that could be used in this situation.

推荐答案

您可以使用default()来实现向后兼容.

You could use default() for backwards compatibility.

- file:
    path: "{{ item.name | default(item) }}"
    mode: "{{ item.mode | default(omit) }}"
    state: directory
  with_items: your_list

如果item具有name属性,请使用它,否则只需使用项目本身即可.

If the item has a name property, use it, else simply use the item itself.

您在字典中可能拥有的所有其他属性都相同.特殊变量omit将忽略任务中的整个选项,就像没有模式传递给file模块一样.当然,您可以设置任何其他默认值.

Same goes for all other properties you might have in your dict. The special variable omit would omit the whole option from the task, as if no mode was passed to the file module. Of course you could set any other default.

文档参考:

  • default
  • omit

这篇关于Ansible测试变量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆