How to remove u' from ansible list

351 Views Asked by At

In my playbook, I am trying to get list of sub-directory names using the find module and then extracting the basename from path. I have been able to get the list but the elements are prepended with u'. How can I remove those from the output?

Ansible version 2.9

I tried to look at these SO posts here and here, but couldn't get it to work.
I may not have fully understood how they should be applied

This is part of my playbook:

- name: set item.path | basename
  set_fact: dir_name_list2_basename="{{ item.path | basename}}"
  with_items: "{{ zookeeper_data_dir.files}}"
  register: item_path_basename_list

- debug: 
    msg: "{{item_path_basename_list.results}}"

- name: debug item.path | basename as list 
  debug: 
    var: item.ansible_facts.dir_name_list2_basename
  with_items: "{{item_path_basename_list.results}}"


- debug: msg="item_path_basename_list.results {{ item_path_basename_list.results | map(attribute='ansible_facts.dir_name_list2_basename') | list }}"

- name: set fact to array 
  set_fact: basename_array="{{ item_path_basename_list.results | map(attribute='ansible_facts.dir_name_list2_basename') | list }}"

- debug: 
    msg: "basename_array &&&&&&&& {{basename_array}}"

And this is the output of the last debug:

ok: [zk3-dev] => {
    "msg": "basename_array &&&&&&&& [u'version-2_backup', u'version-2']"
}
ok: [zk2-dev] => {
    "msg": "basename_array &&&&&&&& [u'version-2_backup', u'version-2']"
}
ok: [zk1-dev] => {
    "msg": "basename_array &&&&&&&& [u'version-2_backup', u'version-2']"
}

I would like the basename_array to show up as ["version-2_backup", "version-2"] without the u prefix

How should I change my set fact to array task, so I will get the desired result?

1

There are 1 best solutions below

5
β.εηοιτ.βε On BEST ANSWER

Since ["version-2_backup", "version-2"] is actually a JSON array, you could use the to_json filter.

This said, your long set of tasks looks like an overcomplicated process for a requirement that can be achieved with the right set of map filters, since map can apply the same filter to all the elements of a list, you can easily fit your basename in it.

So, given:

- debug:
    msg: >-
      basename_array &&&&&&&&
      {{
        zookeeper_data_dir.files
          | map(attribute='path')
          | map('basename')
          | to_json
      }}

This yields:

ok: [localhost] => {
    "msg": "basename_array &&&&&&&& [\"version-2_backup\", \"version-2\"]"
}

Note that the double quotes are escaped because you are using the JSON stdout callback. But, if you change the callback to YAML, this would yield exactly what you expected:

ok: [localhost] => 
  msg: basename_array &&&&&&&& ["version-2_backup", "version-2"]