Search code examples
ansiblecastingjinja2ansible-template

Render numbers inside an Ansible yaml template


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?


Solution

  • 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'