Skip to content

Instantly share code, notes, and snippets.

@leonardonsantos
Created December 3, 2018 22:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonardonsantos/885a7e116d9f36ed9a98efb107794015 to your computer and use it in GitHub Desktop.
Save leonardonsantos/885a7e116d9f36ed9a98efb107794015 to your computer and use it in GitHub Desktop.
---
- hosts: localhost
connection: local
gather_facts: no
vars:
var_name: "william"
var_port: "80"
tasks:
- set_fact:
json_str: |
{
"title": "_NAME_",
"port": _PORT_
}
- debug: var=json_str
- set_fact:
json_str_with_variables: "{{ json_str | regex_replace('_NAME_', var_name) | regex_replace('_PORT_', var_port) }}"
- debug: var=json_str_with_variables
- set_fact:
my_dict:
some: thing
data: "{{ json_str_with_variables }}"
- debug: var=my_dict
@leonardonsantos
Copy link
Author

Output:

$ ansible-playbook test.yml 

PLAY [localhost] ***********************************************************************************************************

TASK [set_fact] ************************************************************************************************************
ok: [localhost]

TASK [debug] ***************************************************************************************************************
ok: [localhost] => {
    "json_str": "{\n  \"title\": \"_NAME_\",\n  \"port\": _PORT_\n}\n"
}

TASK [set_fact] ************************************************************************************************************
ok: [localhost]

TASK [debug] ***************************************************************************************************************
ok: [localhost] => {
    "json_str_with_variables": {
        "port": 80, 
        "title": "william"
    }
}

TASK [set_fact] ************************************************************************************************************
ok: [localhost]

TASK [debug] ***************************************************************************************************************
ok: [localhost] => {
    "my_dict": {
        "data": {
            "port": 80, 
            "title": "william"
        }, 
        "some": "thing"
    }
}

PLAY RECAP *****************************************************************************************************************
localhost                  : ok=6    changed=0    unreachable=0    failed=0   

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment