Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible-playbook - how to add upper case in a string

Tags:

ansible

I am new to ansible. I want to simplify my networking tasks with ansible. One thing I want to do is to log in to all the network (Cisco) switches and display the interfaces with descriptions containing a certain string. I plan to use the cisco.ios.ios_command module to send a command to the switch. The switch should return the lines with the search_str included

show interface description | include {{search_str}}

The descriptions may contain upper or lower case letters. For example, it can be "abc123" or "Abc123" or "ABC123" configured on the switch. Cisco does allow you to use regex to find all cases. The command becomes like this and it will match all cases.

show interface description | include [aA][bB][cC]123

So now my challenge is how to convert "abc123" to "[aA][bB][cC]123". "abc123" is a variable I will set when I run the playbook with -e "search_str=abc123" option.

My attempt was first to make the string a list with each character as an item: {{ my_var | lower | list }}. It also make my search string to all lower case letters. "Abc123" becomes "['a','b','c',1,2,3]"

Then I tried to use loop to go through each character and add an upper case of the character. I can't really write it right.. My best attempt is like this:

- name: add upper case characters
  loop: "{{search_str}}"
  ansible.builtin.set_fact:
    search_str_converted: "{{ item + (item|upper) }}"

In the above code, I would also add "[]" as a string in the variable. If this step works, then I planned to do a join to turn it back to a string again.

Let me know whether the logic is right and please help me with adding the upper case characters

Thanks! Difan

like image 777
Difan Zhao Avatar asked Oct 21 '25 02:10

Difan Zhao


1 Answers

The tasks below do the job

    - set_fact:
        search_list: "{{ search_list|default([]) + [element] }}"
      loop: "{{ search_str|list }}"
      vars:
        is_number: "{{ item is match('\\d') }}"
        double: "[{{ item|lower }}{{ item|upper }}]"
        element: "{{ is_number|ternary(item, double) }}"
    - set_fact:
        search_regex: "{{ search_list|join }}"
like image 169
Vladimir Botka Avatar answered Oct 23 '25 19:10

Vladimir Botka