Willian Cardoso
Willian Cardoso

Reputation: 57

Ansible: How print number instead string in JSON - module uri


Hi, I need to print a variable as a number instead a string. Example:

- name: Create input
  uri:
    url: "https://{{ url_graylog }}/api/system/inputs"
    ...
    body_format: json
    body:
      title: "{{ name }}"
      configuration:
      bind_address: "0.0.0.0"
      port: "{{ port }}"  <-- its print as string, I need number
    global: true

I tried

port: {{ port }}          <-- not work
port: "{{ port | int }}"  <-- not work

Any idea? Thanks!

Upvotes: 4

Views: 2791

Answers (3)

DS Steven Matison
DS Steven Matison

Reputation: 441

Create your variable as such:

    variableName:
      name: "demo"
      capacityUnits: 1

Then body like this:

body: "{{ variableName | to_json }}"

Then the int will persist:

"body": "{\"name\": \"demo\", \"capacityUnits\": 1}"

Upvotes: 1

Lo&#239;c-R
Lo&#239;c-R

Reputation: 31

Actually it seems not possible to convert jinja template into integer since it always return string to Ansible. Detailed explanation here : https://github.com/ansible/ansible/issues/9362#issuecomment-302432118

However, I found a workaround consisting of using folded string bloc in yaml. In your case the Ansible task should look like this :

- name: Create inputenter code here
  uri:
    url: "https://{{ url_graylog }}/api/system/inputs"
    ...
    body_format: json
    body: >
      {
        "title": "{{ name }}",
        "configuration": {
          "bind_address": "0.0.0.0",
          "port": {{ port | int }}
        }
      }
    global: true

It is a little bit less readable but will produce a non-quoted value for port. The body sent looks like this :

...
"body": {
    "configuration": {
        "bind_address": "0.0.0.0",
        "port": 25565
    },
    "title": "My title"
},
...

Hope it helped !

Upvotes: 3

akamac
akamac

Reputation: 31

You can set in ansible.cfg: jinja2_native = True

Upvotes: 1

Related Questions