hotcheetos
hotcheetos

Reputation: 39

How do I create a list of dynamic Key/Value pairs in valid JSON in Ansible custom facts?

I'm trying to create a valid JSON list of key/values using "set_fact" in my ansible playbook.

Essentially I want my custom fact to look like this:

{
"containerports": [
    "10502" : "two",
    "11502" : "two",
    "10503" : "five", 
    "11503" : "five", 
], 
"numconnections": "2"
}

I can't figure out 1. How to Create dynamic variable names (the port numbers in this example) and 2. How to add this variable to my list "connectorports"

Currently I have this in my fact file:

{
"containerports": [
    "10502 : two", 
    "11502 : two", 
    "10503 : five", 
    "11503 : five", 
], 
}

I can't figure out how to get a JSON key:value mapping so that I can perform a select on my file. Every time I add a new port I want to be able to append to the list. My test.yml file looks like this:

      - name: Adding container ports to facts
    tags:
      - setup
    set_fact:
        containerports: "{{ containerports | default([]) }} + [ '{{ container_port }} {{ ':' }} {{ container_name }}' ]"
        cacheable: true

Upvotes: 3

Views: 2156

Answers (1)

clockworknet
clockworknet

Reputation: 3056

Almost :)

containerports: "{{ containerports | default([]) }} + [ { container_port: container_name } ]"

In the same way that the '[]' are expanded into a list, so also is the '{}' inside expanded into a dictionary.

Upvotes: 1

Related Questions