1

I'm trying to do a simple list to show all ports associated with a particular vlan and have this output to a csv.

Code works but can't figure out how can I get around removing the 'u' and the [] associated with the line 'InterfaceID' in the output. I know the array need to be converted to a string just wondering how I can do this without modifying the code too much.

Thank you in advance for any tips.

Code:

   - name: parse output
     set_fact:
      vlan_output: "{{vlan_info.stdout[0] | parse_cli_textfsm(parse_template)}}"

   - name: write lines to file
     copy:
      content: "{{ ['InterfaceID','VlanID','NAME'] | zip([item.INTERFACES,item.VLAN_ID,item.NAME]) | map('join', ', ')  | join('\n') }}"
      dest: "output.csv"
     with_items: "{{vlan_output}}"

   - debug:
      var: vlan_output

Debug of vlan_output:

"vlan_output": [
    {
        "INTERFACES": [
            "Gi1/0/2",
            "Gi1/0/5",
            "Gi1/0/7"
        ],
        "NAME": "test",
        "STATUS": "active",
        "VLAN_ID": "10"
    }
]
Excel Output:
InterfaceID, [u'Gi1/0/2', u'Gi1/0/5', u'Gi1/0/7']
VlanID, 10
NAME, test
loneknight
  • 63
  • 8
  • Does [convert a list with unicode to a list of strings](https://stackoverflow.com/questions/58169705/) answer your question? – U880D Jun 29 '21 at 08:09

2 Answers2

1

While you cannot directly do that, once you upgrade version of python used by ansible to 3.x you get rid of these. Only Python 2.x does print unicode strings with u prefix. On 3 all are unicode anyway and the prefix is not printed anymore.

Keep in mind that the u is part of printing the data, is not part of the data itself.

If you try to parse as string an array that was converted to a string you are already doing something wrong.

sorin
  • 161,544
  • 178
  • 535
  • 806
  • yep i knew the u was not part of the data but thanks for letting me know about the version upgrade. will try this! – loneknight Jun 29 '21 at 09:03
0

Since you have a list of Interfaces, you can use the join filter to "join" the list items into a string. From the question its not clear if you'd like to join them with space or comma, but a small change, such as - item.INTERFACES|join(', ') will give (comma separated) - Gi1/0/2, Gi1/0/5, Gi1/0/7.

Example:

    - name: write lines to file
      copy:
        dest: output.csv
        content: "{{ ['InterfaceID','VlanID','NAME'] | zip([item.INTERFACES|join(', '),item.VLAN_ID,item.NAME]) | map('join', ', ')  | join('\n') }}"
      with_items: "{{ vlan_output }}"

Produces:

InterfaceID, Gi1/0/2, Gi1/0/5, Gi1/0/7
VlanID, 10
NAME, test
seshadri_c
  • 6,906
  • 2
  • 10
  • 24