Ansible template add value to list -

based on the following values โ€‹โ€‹of the downloadable book.

target: "actual.domain.com" aliases: - "alias1.domain.com" - "alias2.domain.com" 

I am trying to configure an indispensable template for creating nginx server_name which in this case should be:

 server_name: "actual.domain.com alias1.domain.com alias2.domain.com" 

So, I tried the following jinja2 script ...

 {% if item.aliases is defined %} {% set servername = [ item.target ] %} {% for alias in item.aliases.iteritems() %} {% if alias|length > 0 %} {% servername|join(' '), alias %} # <= line 30 {% endif %} {% endfor %} server_name {{ servername }}; {% else %} server_name {{ item.target }}; {% endif %} .... 

but it does not work, line number: 30, error: Unknown tag 'servername'

Where can I be wrong?

Thanks for the help and HNY!

+6
source share
2 answers

It seems that you have made it significantly more complicated than necessary. Why not?

 $ ansible-playbook -i hosts play.yml PLAY [localhost] ************************************************************** TASK: [template src='servername.j2' dest=tmp/servername-{{item.target}}] ****** changed: [localhost] => (item={'target': 'actual.domain.com', 'aliases': ['alias1.domain.com', 'alias2.domain.com']}) PLAY RECAP ******************************************************************** localhost : ok=1 changed=1 unreachable=0 failed=0 

File contents

 $ tail -n 1000 `find ./ -type f` ==> .//hosts <== [localhost] localhost ansible_connection=local ==> .//play.yml <== - hosts: localhost gather_facts: false vars: servers: - target: "actual.domain.com" aliases: - "alias1.domain.com" - "alias2.domain.com" tasks: - template: src='servername.j2' dest=tmp/servername-{{item.target}} with_items: servers ==> .//servername.j2 <== server_name {{ item.target }} {{ item.aliases|join(" ") }} ==> .//tmp/servername-actual.domain.com <== server_name actual.domain.com alias1.domain.com alias2.domain.com 
+7
source

Why not just combine target and aliases and then run join(' ') as a result?

 {% set servername = [ item.target ] %} {% set aliases = item.aliases if item.aliases is defined else [] %} {% set ignored = servername.extend(aliases) %} servername: {{ servername | join(' ') }} 
+4
source

Source: https://habr.com/ru/post/980404/


All Articles