footonwonton
footonwonton

Reputation: 794

Remove special characters using regex on list item with Ansible

I cannot figure this out.

How would I remove any special characters & spaces leaving only text within the item.0 variable below?

For example the show commands would convert like so.

show running-config >> show_running_config

show ip interface brief | include up >> show_ip_interface_brief_include_up

The output is saved to a file which has the same name as the command. So special characters like |/\ etc cause problems.

I have tried using this but I just get errors.

dest: "/media/share/ansible_out/{{ inventory_hostname }}/{{ item.0 | regex_replace('@?\+(.*)', '_') }}.bck"

Here is the ansible code which thows an error while trying to write a file with | in the file name.

---
- name: Create show command list
  set_fact:
    command_list:
      - show running-config
      - show ip interface brief | include up

- name: Execute commands on device
  ios_command:
    commands: "{{ command_list }}"
  register: output
  when: ansible_network_os == 'ios'

- name: Copy show command output to file
  copy:
    content: '{{ item.1 }}'
    force: yes
    dest: "/media/share/ansible_out/{{ inventory_hostname }}/{{ item.0 }}.bck"
  loop: "{{ command_list|zip(output.stdout)|list }}"
  when: ansible_network_os == 'ios'

Upvotes: 1

Views: 4079

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68254

Q: "How would I remove any special characters & spaces leaving only text within a variable?"

A: It's possible to use the combination of map and regex_replace because a string in YAML is an array of characters. For example the play

- hosts: localhost
  vars:
    regex: '[^A-Za-z0-9._-]'
    replace: '_'
    command_list:
      - show running-config
      - show ip interface brief | include up
  tasks:
    - debug:
        msg: "{{ item|map('regex_replace', regex, replace)|list|join() }}"
      loop: "{{ command_list }}"

gives

"msg": "show_running-config"
"msg": "show_ip_interface_brief___include_up"

Upvotes: 1

Related Questions