Ansible loop over range of letters in template

2019-08-19 00:13发布

I'm trying to generate an Ansible template that increments on letters alphabetically rather than numbers. Is there a function similar to range(x) that could help me?

pseudo code example

{% for letter in range(a, d) %}
{{ letter }}
{% endfor %}

expected output

a
b
c
d

Alternatively is there a way to convert a number into it's alphabetical equivalent in Ansible?

{% for i in range(6) %}
{{ convert(i) }}
{% endfor %}

UPDATE

For those who are curious, here's how I ended up applying @zigam's solution. The goal was to create xml tags with every host from a hostgroup.

In my role defaults:

ids: "ABCDEFGHIGJKLMNPQRSTUVWXYZ"

In my template:

{% for host in groups['some_group'] %}
<host-id="{{ ids[loop.index] }}" hostName="{{ host }}" port="8888" />
{% endfor %}

2条回答
再贱就再见
2楼-- · 2019-08-19 01:00

you can use a custom filter plugin to do what you want

in filter_plugins/scratch_filter.py:

def scratch_filter(n):
    return chr(n)

class FilterModule(object):
    ''' Number to Character filter '''
    def filters(self):
        return {
            'scratch_filter': scratch_filter
        }

in scratch-template.j2:

{% for x in range(101, 113) %}
    {{ x|scratch_filter }}
{% endfor %}

in scratch_playbook.yml

---
- hosts: localhost
  tasks:

  - name: test loop
    template: 
      src: "{{ playbook_dir }}/scratch-template.j2"
      dest: "{{ playbook_dir }}/scratch-template-output.txt"
查看更多
家丑人穷心不美
3楼-- · 2019-08-19 01:01

You can iterate over a string:

 {% for letter in 'abcd' %}
 {{ letter }}
 {% endfor %}

If you want to iterate over a range of the alphabet:

 {% set letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' %}
 {% for letter in letters[:6] %} {# first 6 chars #}
 {{ letter }}
 {% endfor %}
查看更多
登录 后发表回答