Render numbers inside an Ansible yaml template

75 views Asked by At

Very close to Create an int var with Ansible's ternary operator and that answer https://stackoverflow.com/a/69109779/446302

In an Ansible project, I'm trying to have a yaml template file with integer content like so:

---
my_service:
  enable_ipv6: false
  node_listen:
    - port: '{{ http_port | int }}'
      ip: '{{ srv_ip }}'

Unfortunately, it renders to:

---
my_service:
  enable_ipv6: false
  node_listen:
    - port: '8080'
      ip: '192.0.0.2'

The application I'm using is strict about port type, which means it crashes unless I can give it an int port number.

How can I cast it knowing that I need to keep it inside a template file, due to loops for other sub-settings?

2

There are 2 answers

1
U880D On BEST ANSWER

For a Jinja2 Template file service.yml.j2 as input

---
my_service:
  enable_ipv6: false
  node_listen:
    - port: {{ HTTP_PORT }}
      ip: '{{ SRV_IP }}'

processing via a minimal example playbook main.yml

---
- hosts: localhost
  become: false
  gather_facts: false

  vars:

    HTTP_PORT: 8080
    SRV_IP: 127.0.0.1

  tasks:

  - template:
      src: service.yml.j2  #  input file
      dest: service.yml    # output file

will result into an output file service.yml with content of

---
my_service:
  enable_ipv6: false
  node_listen:
    - port: 8080
      ip: '127.0.0.1'
0
Vladimir Botka On

Given the template

shell> cat my_service.yml
---
my_service:
  enable_ipv6: false
  node_listen:
    port: {{ http_port }}
    ip: {{ srv_ip }}

and the variables

  http_port: 8080
  srv_ip: 192.0.0.2

Use the template lookup plugin to read it

  data: "{{ lookup('template', 'my_service.yml')|from_yaml }}"

gives

  data:
    my_service:
      enable_ipv6: false
      node_listen:
        ip: 192.0.0.2
        port: 8080
  data.my_service.node_listen.port|type_debug: int

See Return integer value without quote when using variable


Example of a complete playbook for testing

- hosts: all

  vars:

    http_port: 8080
    srv_ip: 192.0.0.2
    data: "{{ lookup('template', 'my_service.yml')|from_yaml }}"

  tasks:

    - debug:
        var: data

    - debug:
        var: data.my_service.node_listen.port

    - debug:
        var: data.my_service.node_listen.port|type_debug