Search code examples
listansiblediffpython-unicodeansible-awx

Ansible: convert a list with unicode to a list of strings (and compare them)


I created a list with all the ansible group hosts. But when I print the list it contains unicode characters. u'text' instead of "text" Is there any efficient way to remove/convert this. I looked at other examples online but didn't succeed.

Current (wrong) output with unicode characters:

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' .....

This should have an identical format like the following list. Because I want to compare them with diff. The values in the list itself are different, but should be formatted like:

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", ...

Currently I'm using following code to fetch the list:

- 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 }}"

The second list is fetched with an AWX api. Also note that for some reason there seems to be a " before the [ bracket . Like highlighted below:

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

Which isn't in the first list. Any idea why this is. I assume this will give problems when comparing them later on. The way that I create the lists is identical.


Solution

  • This ended up solving most of my issue.

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

    Which gives following list:

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