Home > Net >  Why does json_query return an empty string in a set_fact?
Why does json_query return an empty string in a set_fact?

Time:07-04

I tried to get metrics2 and metrics3 value like below:

- hosts: localhost

  tasks:
    - set_fact:
       param:
        - - {metrics1: A, metrics2: B, metrics3: C}
          - {metrics1: D, metrics2: E, metrics3: F}
          - {metrics1: G, metrics2: H, metrics3: I}
        - - {metrics1: J, metrics2: K, metrics3: L}
          - {metrics1: M, metrics2: N, metrics3: O}
          - {metrics1: P, metrics2: Q, metrics3: R}
      parseParam: "{{ param | json_query('[][].[metrics2, metrics3]') }}"

    - debug:
        var: parseParam

and the returned value is null:

"parseParam": ""

What should I do?

CodePudding user response:

You won't be able to access param in the set_fact that defines it.

A way around is to declare a variable local to that task, and use it:

- set_fact:
    parseParam: "{{ _param | json_query('[][].[metrics2, metrics3]') }}"
    param: "{{ _param }}"
  vars:
    _param:
      - - {metrics1: A, metrics2: B, metrics3: C}
        - {metrics1: D, metrics2: E, metrics3: F}
        - {metrics1: G, metrics2: H, metrics3: I}
      - - {metrics1: J, metrics2: K, metrics3: L}
        - {metrics1: M, metrics2: N, metrics3: O}
        - {metrics1: P, metrics2: Q, metrics3: R}

If you don't need the param variable outside of the set_fact itself, you can even drop its assignation in a fact, of course.

  • Related