1

我需要帮助将 Unicode 变量转换为字符串,以便下面的 Ansible 构造起作用。

在这种特殊情况下,我想使用该item.keys()方法来获取当前env名称(即uat),但我得到[u'uat']了。我一直在搜索互联网,但找不到转换[u'uat']为简单uat.

defaults/main.yml

blablabla:
  env:
    - uat:
        accounts:
          - david:
              email: david@example.com
          - anna:
              email: anna@example.com
    - develop:
        accounts:
          - john:
              email: john@example.com

tasks/main.yml

- include_tasks: dosomething.yml
  with_items:
    - "{{ blablabla.env }}"

tasks/dosomething.yml

- name: Get accounts
  set_fact:
    accounts: "{%- set tmp = [] -%}
                 {%- for account in item[item.keys()].accounts -%}  
                      {{ tmp.append(account) }}
                 {%- endfor -%}
               {{ tmp }}"

错误信息:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <failed value="True"/>
  <msg value="The task includes an option with an undefined variable. The error was: dict object has no element [u'uat']

The error appears to have been in 'dosomething.yml': line 9, column 3, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:


- name: Get accounts
  ^ here

exception type: &lt;class 'ansible.errors.AnsibleUndefinedVariable'&gt;
exception: dict object has no element [u'uat']"/>
</root>

或者,我也欢迎其他方法,只要数据结构(即defaults/main.yml文件)保持不变。

4

1 回答 1

2

我明白了[u'uat']

这不是“Unicode 字符串”,这是一个列表——注意[ ]

Asitem.keys()返回一个列表,但您想将其用作 的索引item[],您必须选择该元素。所以要么使用first过滤器或[0]

- name: Get accounts
  set_fact:
    accounts: "{%- set tmp = [] -%}
                 {%- for account in item[item.keys()|first].accounts -%}  
                      {{ tmp.append(account) }}
                 {%- endfor -%}
               {{ tmp }}"
于 2017-11-22T23:02:35.007 回答