使用Ansible和Jinja2将Unicode转换为String

时间:2017-11-22 22:15:25

标签: ansible jinja2 ansible-template

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

1 个答案:

答案 0 :(得分:2)

  

我得到[u'uat']

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

由于item.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 }}"