Transform dictionary keys to uppercase

Viewed 312

I have some ansible automation which deploys aws lambda functions. At some point I use below syntax:

env: "{{ l_common_env_vars | combine(l_per_env_vars) }}"

to create a dict with environment variables for a given function. The problem is that content of l_common_env_vars and l_per_env_vars source dictionaries has lowercase keys, example:

redis_url: some_url

and as a result destination env dictionary has keys also in lowercase. I would like to have all mentioned keys in uppercase:

REDIS_URL: some_url

I tried to use {{ env | upper }} but it changes case for both keys and their values which is not what I need:

REDIS_URL: SOME_URL

Is there any way to convert to uppercase only keys of env dictionary?

Thanks in advance for all help!

Best regards, Rafal.

1 Answers

The idea demonstrated below is to create tupples using zip of up-cased dict keys (using map) and values to reconstruct a dict using items2dict

The following playbook:

---
- name: Upcase dict keys
  hosts: localhost
  gather_facts: false

  vars:
    some_dict:
      redis_url: https://www.test.tld/
      some_other_key: other value

     some_dict_upper: >-
      {{
        some_dict.keys() | map('upper') 
        | zip(some_dict.values())
        | items2dict(key_name=0, value_name=1)
      }}

  tasks:
    - name: Show results
      debug:
        msg: "{{ some_dict_upper }}"

gives:

PLAY [Upcase dict keys] ****************************************************************************************************************************************************************************************************************

TASK [Show results] ********************************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": {
        "REDIS_URL": "https://www.test.tld/",
        "SOME_OTHER_KEY": "other value"
    }
}

PLAY RECAP *****************************************************************************************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  
Related