1

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.

3
  • What do you do for hosts that are not in the other group? Will addresses simply be undefined for them? Commented Jan 31, 2023 at 23:46
  • @Jack Hosts that aren't in the other group simply won't be in the list. For context, this playbook would be run on a group of hosts that aren't other but need the addresses of other. Commented Feb 1, 2023 at 17:01
  • You do not say what you are using it for. Commented Feb 1, 2023 at 17:33

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.