首页 > 解决方案 > Ansible:将带有 unicode 的列表转换为字符串列表(并比较它们)

问题描述

我创建了一个包含所有ansible 组 hosts的列表。但是当我打印列表时,它包含 unicode 字符。u'text'而不是"text" 有没有有效的方法来删除/转换它。我在网上查看了其他示例,但没有成功。

带有 unicode 字符的当前(错误)输出:

ok: [server.name] => {
"msg": " [u'all', u'coaster', u'aes', u'curo, u'dert', u'tomcatdeploy', u'implus-app', u'domain-top', u'tp-general', u'cdaes01', u'dicco-acc' .....

这应该具有与以下列表相同的格式。因为我想将它们与差异进行比较。列表本身中的值是不同的,但应采用如下格式:

ok: [server.name] => {
"msg": [
    "tools", 
    "tools-api", 
    "adr-app", 
    "adr-app-e2j", 
    "aec", 
    "aec-copy", 
    "aes", 
    "aes1", 
    "aes2", 
    "aes3", 
    "ais", 
    "apiman", 
    "apiman-gateway-poc", 
    "apiman-manager", 
    "apiman-manager-poc", 
    "apollo-beheer-aangiftes", ...

目前我正在使用以下代码来获取列表:

- name: register groups
  set_fact:
    inventory_groups: []  # empty list
    inventory_group_keys: "{{ groups.keys() |to_yaml}}" #|list

- name: clean white spaces from list
  set_fact:
    inventory_groups: "{{ inventory_groups}} + ['{{item.strip()}}']"
  with_items: "{{inventory_group_keys[1:-2].split(',')}}"

- name: print inventory_groups from local host for debugging
  debug:
    msg: " {{ inventory_groups }}"

第二个列表是使用 AWX api 获取的。另请注意,由于某种原因, [ 括号之前似乎有一个" 。如下所示:

"msg": " [u'all',....

这不在第一个列表中。知道为什么会这样。我认为这会在以后比较它们时出现问题。我创建列表的方式是相同的。

标签: listansiblediffpython-unicodeansible-awx

解决方案


这最终解决了我的大部分问题。

- name: print list
  debug:
    msg: "{{ groups | list }}"

其中给出了以下列表:

ok: [server.name] => {
    "msg": [
        "all", 
        "coster", 
        "ius1", 
        "curo", 
        "derti", 
        "tomcatdeploy", 
        "implus-app", 
        "domain", 
        "tpgeneral", 
        "cdaes", 
        "diccop-acc", 
        "cdaes", 
         .... 

推荐阅读