<p>I have a list of ports </p>

<pre class="lang-yaml prettyprint-override"><code>ports:
  - 123
  - 456
  - 789
</code></pre>

<p>that I like to turn into <code>containerPort</code> for usage in a Kubernetes deployment:</p>

<pre><code>"container_ports": [
            {
                "containerPort": 123
            },
            {
                "containerPort": 456
            },
            {
                "containerPort": 789
            }
        ]
</code></pre>

<p>The example above is created when I define <code>ports</code> as </p>

<pre class="lang-yaml prettyprint-override"><code>ports:
  - containerPort: 123
  - containerPort: 456
  - containerPort: 789
</code></pre>

<p>However, I'd like to save the user some typing and add <code>containerPort</code> automatically. I am able to prepend it using </p>

<pre class="lang-yaml prettyprint-override"><code>- name: Creating custom ports
  set_fact:
    container_ports: "{{ ports | map('regex_replace', '(^)', '- containerPort: \\1') | list }}"
  when: ports is defined

</code></pre>

<p>This does only create </p>

<pre><code>    ok: [localhost] =&gt; {
        "container_ports": [
            "- containerPort: 123",
            "- containerPort: 456",
            "- containerPort: 789"
        ]
    }
</code></pre>

<p>though, which is close, but not quite right.</p>

<p>You can do this like so:</p>

<pre><code>---
- 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
...
</code></pre>

<p>The trick is to convert each item into a YAML hash and then convert that to a Python dict using <code>from_yaml</code>.</p>

<p>Debug output:</p>

<pre><code>ok: [localhost] =&gt; {
    "container_ports": [
        {
            "containerPort": 123
        }, 
        {
            "containerPort": 456
        }
    ]
}
</code></pre>
