Prepend string to list item and turn it into JSON in Ansible
You can do this like so:
---- hosts: localhost connection: local gather_facts: no vars: ports: - 123 - 456 tasks: - name: Creating custom ports set_fact: container_ports: '{{ ports | map("regex_replace", "^(.*)$", "containerPort: \1") | map("from_yaml") | list }}' - debug: var: container_ports...
The trick is to convert each item into a YAML hash and then convert that to a Python dict using from_yaml
.
Debug output:
ok: [localhost] => { "container_ports": [ { "containerPort": 123 }, { "containerPort": 456 } ]}
An other solution using json_query
---- hosts: localhost gather_facts: false vars: ports: - 123 - 456 tasks: - name: Tranform raw list to Kubernetes compatible format debug: msg: "{{ ports | json_query('[].{\"containerPort\": @}') }}"
Which gives:
PLAY [localhost] ***********************************************************************************************************************************************************************************************************************TASK [Tranform raw list to Kubernetes compatible format] *******************************************************************************************************************************************************************************ok: [localhost] => { "msg": [ { "containerPort": 123 }, { "containerPort": 456 } ]}PLAY RECAP *****************************************************************************************************************************************************************************************************************************localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0