Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

uri

ansible


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!

like image 259
Willian Cardoso Avatar asked Oct 30 '25 01:10

Willian Cardoso


2 Answers

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 !

like image 182
Loïc-R Avatar answered Nov 01 '25 15:11

Loïc-R


You can set in ansible.cfg: jinja2_native = True

like image 26
akamac Avatar answered Nov 01 '25 16:11

akamac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!