Skip to main content

redcube.de

Convert Dict Keys to Snake Case in Ansible

I’m currently writing an Ansible role, where I needed to convert a dictionary with camelCase keys to snake_case keys. I can’t change the source dict directly, as it is some form of external config for which the camelCase actually makes sense. As ansible works with snake_case variables normally, I needed to convert the input to a sane format for later consumption.

After a lot of trail-and-error and searching, I found the following two Stack Overflow questions, which massively inspired my final solution:

Combining these two methods, I came up with the following solution, which I’d like to share:

converted_dict: |-
  {{
    source_dict.keys()
    | map('regex_replace', '((?!^)|\b[a-zA-Z][a-z]*)([A-Z][a-z]*|\d+)', '\1_\2')
    | map('lower')
    | zip(source_dict.values())
    | items2dict(key_name=0, value_name=1)
  }}  

Full example playbook

- hosts: localhost
  gather_facts: false
  connection: local
  vars:
    source_dict:
      myCamelCaseVar: my value
      test: 123
  tasks:
    - name: Convert source_dict keys from camelCase to snake_case
      set_fact:
        converted_dict: |-
          {{
            source_dict.keys()
            | map('regex_replace', '((?!^)|\b[a-zA-Z][a-z]*)([A-Z][a-z]*|\d+)', '\1_\2')
            | map('lower')
            | zip(source_dict.values())
            | items2dict(key_name=0, value_name=1)
          }}          

    - name: Print result
      debug:
        msg: "{{ converted_dict }}"