如何使用表达式设置结构化变量

时间:2015-01-26 13:26:18

标签: ansible

Ansible中有没有办法将变量设置为从表达式构造的某个结构化值(例如列表或字典)?

例如,我有这些变量:

all_flavours: ["vanilla", "chocolate", "strawberry", "banana"]
flavours_to_keep: ["chocolate", "banana"]

我想评估表达式all_flavours | difference(flavours_to_keep)并将结果集合(列表或确实设置)存储在变量flavours_to_drop中,这样对于这些值,就好像我已定义:

flavours_to_drop: ["vanilla", "strawberry"]

但是,我找不到这样做的语法。以下是我的尝试:

尝试1

flavours_to_drop: all_flavours | difference(flavours_to_keep)

这只是解释为一个字符串:

flavours_to_drop: "all_flavours | difference(flavours_to_keep)"

尝试2

flavours_to_drop: {{ all_flavours | difference(flavours_to_keep) }}

这是一个错误,因为YAML将“{”解释为字典。

尝试3

flavours_to_drop: "{{ all_flavours | difference(flavours_to_keep) }}"

这正确地设置了差异,但随后将其转换为字符串,所以我最终得到:

flavours_to_drop: "set([\"vanilla\", \"strawberry\"])"

如何评估表达式,但是将结构化对象直接存储回变量而不是将其转换为字符串?

我应该补充说我正在使用Ansible版本1.6.2。这种行为是否在Ansible版本之间发生了变化?

1 个答案:

答案 0 :(得分:1)

格式化等可能有点棘手。您需要引用过滤器以便正确解析它。您可以将其作为var或set_fact来执行。你想要这样的东西:

vars:
  all_flavours: ["vanilla", "chocolate", "strawberry", "banana"]
  flavours_to_keep: ["chocolate", "banana"]
  flavours_to_drop_1: "{{ all_flavours | difference(flavours_to_keep) }}"

tasks:
  - debug: var=all_flavours

  - debug: var=flavours_to_keep

  - set_fact:
      flavours_to_drop_2: "{{ all_flavours | difference(flavours_to_keep) }}"

  - debug: var=flavours_to_drop_1

  - debug: var=flavours_to_drop_2

以上结果是:

TASK: [debug var=all_flavours]     ************************************************
ok: [localhost] => {
    "all_flavours": [
        "vanilla",
        "chocolate",
        "strawberry",
        "banana"
    ]
}

TASK: [debug var=flavours_to_keep] ********************************************
ok: [localhost] => {
    "flavours_to_keep": [
        "chocolate",
        "banana"
    ]
}

TASK: [set_fact ] *************************************************************
ok: [localhost]

TASK: [debug var=flavours_to_drop_1] ********************************************
ok: [localhost] => {
    "flavours_to_drop_1": [
        "vanilla",
        "strawberry"
    ]
}

TASK: [debug var=flavours_to_drop_2] ********************************************
ok: [localhost] => {
    "flavours_to_drop_2": [
        "vanilla",
        "strawberry"
    ]
}