cheezsteak
cheezsteak

Reputation: 2917

How do I format each string in a list of strings in ansible

I'm trying to write a json file with a list of ip addresses formatted as "http://{ip_address}:{port}" as a part of an ansible playbook. I'm able to get `"{ip_address}:port" with the following code:

vars:
  config:
    addresses: "{{ groups['other']
      | map('extract', hostvars)
      | map(attribute='ansible_host')
      | product([':' ~ other_port]) | map('join')
      }}" 

I tried using the format filter but it expects the input to be the format pattern not a variable to insert into a format.

If I was allowed to execute arbitrary python would express what I want as:

vars:
  config:
    addresses: "{{ [ f'http://{host.hostvars.ansible_host}:{port}' for host in groups['other'] }}"

but it's all got to be in jinja2 filters. I feel like being able to even tack on the port number was a fluke. Is there a way to express this in jinja? Right now I'm looking at hard-coding the format into the hosts file.

Upvotes: 1

Views: 391

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68034

For example, given the inventory

shell> cat hosts
[other]
test_11 ansible_host=10.1.0.61
test_12 ansible_host=10.1.0.62
test_13 ansible_host=10.1.0.63

The playbook below

- hosts: localhost

  vars:

    other_port: 80
    addresses: "{{ groups.other|
                   map('extract', hostvars, 'ansible_host')|
                   map('regex_replace', '^(.*)$', addresses_replace)|
                   list }}"
    addresses_replace: 'http://\1:{{ other_port }}'

  tasks:

    - debug:
        var: addresses

gives (abridged)

  addresses:
  - http://10.1.0.61:80
  - http://10.1.0.62:80
  - http://10.1.0.63:80

Upvotes: 2

Related Questions