João Amaro
João Amaro

Reputation: 496

How to convert to valid JSON when running an Ansible command?

So, I have this list:

ip_range:
- "1.x.x.x/24"
- "2.x.x.x/24"

And I'm trying to pass it on to an AWS cli command as a valid JSON:

- name: list of IPs
  set_fact:
    allowed_cidrs: "{{ ip_range | ipaddr('network/prefix') }}"

- debug:
     msg: "{{ allowed_qualys_cidrs | to_json }}"

- name: send command
  command: >
    aws wafv2 update-ip-set
      --addresses "{{ allowed_cidrs | to_json }}"

That debug prints:

["1.x.x.x/24", "2.x.x.x/24"]

But what the command tries to send is:

"cmd": [
    "aws",
    "wafv2",
    "update-ip-set",
    "--addresses",
    "[1.x.x.x/24, 2.x.x.x/24]",
]

Which, because the double quotes are gone, is not a valid JSON. I already tried every possible approach with Ansible and Jinja2, but I can't figure out a way to send that command with a valid JSON.

Upvotes: 1

Views: 403

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39119

Use single quotes in your command rather than double quotes:

- name: list of IPs
  set_fact:
    allowed_cidrs: "{{ ip_range | ipaddr('network/prefix') }}"
  vars:
    ip_range:
      - "1.1.1.1/24"
      - "2.2.2.2/24"

- name: send command
  command: >-
    aws wafv2 update-ip-set
      --addresses '{{ allowed_cidrs | to_json }}'
  register: _cmd

- debug:
    var: _cmd.cmd

Yields:

TASK [list of IPs] **********************************************************
ok: [localhost]

TASK [send command] *********************************************************
changed: [localhost]

TASK [debug] ****************************************************************
ok: [localhost] => {
    "_cmd.cmd": [
        "aws",
        "wafv2",
        "update-ip-set",
        "--addresses",
        "[\"1.1.1.0/24\", \"2.2.2.0/24\"]"
    ]
}

Upvotes: 2

Related Questions