Skip to content
This repository has been archived by the owner on Jun 24, 2024. It is now read-only.

add from_json filter, useful to move any object through env vars #70

Open
ollofx opened this issue Jun 12, 2021 · 0 comments
Open

add from_json filter, useful to move any object through env vars #70

ollofx opened this issue Jun 12, 2021 · 0 comments

Comments

@ollofx
Copy link

ollofx commented Jun 12, 2021

container_env:
  mongo_servers: '{{ mongo_servers | to_json }}'

consider creation of ENV variable on into Docker Container, couldn't pass object but a serialized json string.

        "mongo_servers": [
            {
                "addr": "tkd-anex_store01.tkd-dev.teramag.com:27017",
                "fqdn": "tkd-anex_store01.tkd-dev.teramag.com",
                "hostname": "tkd-anex_store01",
                "port": 27017,
                "vm_lb_id": "01"
            },
            {
                "addr": "tkd-anex_store02.tkd-dev.teramag.com:27017",
                "fqdn": "tkd-anex_store02.tkd-dev.teramag.com",
                "hostname": "tkd-anex_store02",
                "port": 27017,
                "vm_lb_id": "02"
            },
            {
                "addr": "tkd-anex_store03.tkd-dev.teramag.com:27017",
                "fqdn": "tkd-anex_store03.tkd-dev.teramag.com",
                "hostname": "tkd-anex_store03",
                "port": 27017,
                "vm_lb_id": "03"
            }
        ]

ENV

$ env | grep mongo_servers
mongo_servers=[{"vm_lb_id": "01", "hostname": "tkd-anex_store01", "fqdn": "tkd-anex_store01.tkd-dev.teramag.com", "addr": "tkd-anex_store01.tkd-dev.teramag.com:27017", "port": 27017}, {"vm_lb_id": "02", "hostname": "tkd-anex_store02", "fqdn": "tkd-anex_store02.tkd-dev.teramag.com", "addr": "tkd-anex_store02.tkd-dev.teramag.com:27017", "port": 27017}, {"vm_lb_id": "03", "hostname": "tkd-anex_store03", "fqdn": "tkd-anex_store03.tkd-dev.teramag.com", "addr": "tkd-anex_store03.tkd-dev.teramag.com:27017", "port": 27017}]
$  env | grep mongo_servers | j2 --format=env servers.conf.jinja2 -o servers.conf
jinja2.exceptions.TemplateAssertionError: No filter named 'from_json'.

now this object could be recovered back into j2cli from this ENV var with this simple filter (already available as an extra filter into ansible)

{% for server in mongo_servers | from_json %}
    '{{ server.addr }}',
{% endfor %}

this filter could be added by appending these to changes to j2cli package
j2cli/extras/filters.py add

import json

def from_json(data):
    return json.loads(data)

to j2cli/extras/cli.py add at line 176

    # Filters, Tests
    renderer.register_filters({
        'docker_link': filters.docker_link,
        'env': filters.env,
        'from_json': filters.from_json,
    })
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant