Jinja2: format + join the items of a list

前端 未结 4 2261
無奈伤痛
無奈伤痛 2021-02-12 12:42

play_hosts is a list of all machines for a play. I want to take these and use something like format() to rewrite them like rabbitmq@%s and

相关标签:
4条回答
  • 2021-02-12 13:25

    I believe another way would be using the joiner global function, as you can read in http://jinja.pocoo.org/docs/2.9/templates/#list-of-global-functions:

    A joiner is passed a string and will return that string every time it’s called, except the first time (in which case it returns an empty string). You can use this to join things

    So your code would be something like:

    [
    {% set comma = joiner(",") %}    
    {% for host in play_hosts %}
        {{ comma() }}
        {{ "rabbitmq@%s"|format(host) }}
    {% endfor %}
    ]
    
    0 讨论(0)
  • 2021-02-12 13:35

    You could simply join not only by , but also add the prefix together with it. Now that's not very pythonic or sophisticated but a very simple working solution:

    [rabbitmq@{{ play_hosts | join(', rabbitmq@') }}]
    
    0 讨论(0)
  • 2021-02-12 13:46

    You can create custom filter

    # /usr/share/ansible/plugins/filter/format_list.py (check filter_plugins path in ansible.cfg)
    
    def format_list(list_, pattern):
        return [pattern % s for s in list_]
    
    
    class FilterModule(object):
        def filters(self):
            return {
                'format_list': format_list,
            }
    

    and use it

    {{ play_hosts | format_list('rabbitmq@%s') }}
    
    0 讨论(0)
  • 2021-02-12 13:47

    In ansible you can use regex_replace filter:

    {{ play_hosts | map('regex_replace', '^(.*)$', 'rabbitmq@\\1') | list }}
    
    0 讨论(0)
提交回复
热议问题