使用 Ansible 和 Jinja2 将 Unicode 转换为字符串

Convert Unicode to String with Ansible and Jinja2

我需要帮助将 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 文件)保持不变即可。

I get [u'uat']

这不是 "Unicode string",这是一个列表 ― 注意 [ ]

作为item.keys()returns一个列表,但是你想用它作为item[]的索引,你必须select这个元素。所以要么使用 first 过滤器,要么使用 [0]:

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