sokolata
sokolata

Reputation: 549

Use variable in Ansible template

I need to create a file via jinja template but facing some issues.

My Variable

my:
  acl:
        - name: test
          allow:
            - 0.0.0.0
          deny:
            - 1.1.1.1
        - name: china
          allow:
            - 1.2.3.4
          deny:
            - 10.10.10.10

My Task:

- name: Create acl file
  template:
    force: yes
    src: acl.conf.j2
    dest: "/etc/nginx/conf.d/{{ item.name }}.conf"
  become: yes
  with_items:
    - "{{ my.acl }}"

My Template

{% for allow in my.acl %}
allow {{allow.allow}};
{% endfor %}
{% for deny in my.acl %}
deny {{deny.deny}};
{% endfor %}

Result china.conf

allow ['0.0.0.0'];
allow ['1.2.3.4'];
deny ['1.1.1.1'];
deny ['10.10.10.10'];

Result test.conf

allow ['0.0.0.0'];
allow ['1.2.3.4'];
deny ['1.1.1.1'];
deny ['10.10.10.10'];

I need in the china file only the ip addresses that are defined in the object china without the [' ']

How can I do this?

Upvotes: 3

Views: 1672

Answers (2)

Vladimir Botka
Vladimir Botka

Reputation: 68229

Fix the template

{% for allow in item.allow %}
allow {{ allow }};
{% endfor %}
{% for deny in item.deny %}
deny {{ deny }};
{% endfor %}

Upvotes: 3

gary lopez
gary lopez

Reputation: 1954

Add an if and print the first object in the allow and deny list:

{% for allow in my.acl %}
  {% if allow.name == 'china' %}
    allow {{ allow.allow[0] }};
  {% endif %}
{% endfor %}
{% for deny in my.acl %}
  {% if allow.name == 'china' %}
    deny {{ deny.deny[0] }};
  {% endif %}
{% endfor %}

If the allow and deny lists will have more than one element use this:

{% for allow in my.acl %}
  {% if allow.name == 'china' %}
    {% for ip in allow.allow %}
      allow {{ ip }};
    {% endfor %}
  {% endif %}
{% endfor %}
{% for deny in my.acl %}
  {% if deny.name == 'china' %}
    {% for ip in deny.deny %}
      deny {{ ip }};
    {% endfor %}
  {% endif %}
{% endfor %}

Upvotes: -1

Related Questions