Search code examples
regexansiblelowercase

Ansible: Convert all strings that match a regexp in a file to lowercase


How do you convert all strings in a file to lowercase using ansible? Either the entire string or just a portion?

If I have an .ini file where the options are camelcase, and I want to switch them to lowercase without changing their values, how I can I do that in ansible?


Solution

  • Say you have an INI file structured as such:

    [Customers]
    
    customerName = James Robinson
    customerAge = 17
    customerID = 1234
    IsAdmin = True
    

    and you want to convert the file to the following:

    
    [Customers]
    
    customername = James Robinson
    customerage = 17
    customerid = 1234
    isadmin = True
    
    

    The replace module won't natively let you do this. For example, you can't do the following task:

    
    - name: Convert all options to lowercase
      replace:
        regexp: "(.* =)(.*)"
        replace: '{{ \1 | lower }}\2'
    
    

    or any variation thereof.

    What you can do, is read the content of the file into a variable, lowercase all strings that match a regexp, and then use the replace module.

    For example:

    
     - set_fact:
       file_content: "{{ lookup('file', '/path/to/file') | regex_findall('.* =') }}"
    
    

    This will read all the strings in the file that match your regexp into a list

    Then you can use the replace module:

    
     - name: Convert all options to lowercase
       replace:
         regexp: "{{ item }}(.*)"
         replace: '{{ item | lower }}\1'
       with_items: "{{ file_content }}"
    
    

    And this will result in the strings that match your regexp being converted to lowercase, but the rest of the line remaining the same.

    This solution assumes the strings are all in the same format, and that the string begins with the portion you want to convert to lowercase.

    If the string does not begin with the portion you want to convert to lowercase, you can just change the regexp & replace params in the replace module to match.