Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
802 views
in Technique[技术] by (71.8m points)

ansible - How can I take a list of server names and append a resource URI and port to each?

I merged two lists from an Ansible inventory:

set_fact:
  fact1: "{{ groups['group1'] + groups[group2']|list }}

The output is:

fact1:
  - server01
  - server02
  - server03

With the above results, I need to append https:// to the front, and a port number to the back of each element. Then I need to convert it to a comma delimited list for a server config.

In this example I want: https://server01:8000,https://server02:8000,https://server03:8000.

I tried using a join:

set_fact:
  fact2: "{{ fact1|join(':8000,') }}"

which partly worked but it left the last server without a port.

How can I achieve my goal?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Solution

set_fact:
  fact2: "{{ fact1 | map('regex_replace', '(.*)', 'https://\1:8000') | join(',') }}"

Explanation

  1. map filter applies a filter (regex_replace) to individual elements of the list;

  2. regex_replace filter (with the following regular expression) adds a prefix and suffix to a string;

    current_list | map('regex_replace', '(.*)', 'prefix\1suffix')
    
  3. join filter converts the list to comma-delimited string in the output.


Alternative

Another possible solution (builds on what you already know) would be to use Jinja2 to directly for the target string:

set_fact:
  fact2: "{{ 'https://' + fact1|join(':8000,https://') + ':8000' }}"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...