Home > other >  Setting fact from json with hyphens
Setting fact from json with hyphens

Time:10-13

I have a json coming from an API like this -

{
    "Clusters": {
        "cluster_name": "cluster1",
        "desired_configs": {
            "ams-env": {
                "tag": "15646576543547354",
                "version": 2
            },
            "ams-grafana-env": {
                "tag": "156765743275788",
                "version": 2
            },
            "ams-grafana-ini": {
                "tag": "987657435754385457",
                "version": 2
            }
        }
    }
}

And I need to parse it with ansible. The trouble is, the variable that will be passed is the part with the hyphens.

I'm able to print the tag name with debug: var but I cant turn it into a fact and I also cant make it print when I use debug: msg

This is the play - I would like to take the "tag" for whichever config_name is passed at runtime and create a new var to be passed into later tasks

- name: Parsing Json
  hosts: localhost
  connection: local
  tags: setup_infra

  vars:
    - config_name: ams-env

  tasks:

  - name: access fact
    set_fact:
      access_auths: "{{ lookup('file', 'ambari.json') | from_json }}"

  - name: This works
    debug:
      var: access_auths.Clusters.desired_configs['{{ config_name }}'].tag

  - name: This does not work
    set_fact:
      new_config: "{{ access_auths.Clusters.desired_configs['{{ config_name }}'].tag }}"

  - name: Debug 0.3
    debug:
      var: new_config

Thanks in advance for any help

CodePudding user response:

This issue is happening because of the nesting of {{ jinja delimiters. The config_name var you set is already a text "ams-env", so we don't need to quote it again as well.

The following tasks should work:

    - debug:
        msg: "tag is {{ access_auths['Clusters']['desired_configs'][config_name]['tag'] }}"

    - set_fact:
        new_config: "{{ access_auths['Clusters']['desired_configs'][config_name]['tag'] }}"
  • Related