jinja2のforループ[閉じる]

jinja2のforループ[閉じる]

この問題を解決する方法を説明してもよろしいですか?このファイルがあります。defaults/main.yml

---
node1:
 ip: 1.1.1.1

node2:
 ip: 2.2.2.2

node3:
 ip: 3.3.3.3 

それでは、テンプレートファイル内の各サーバーのIPにip.j2アクセスして保存しましょう。for loopaddress variable

このように:

address= 1.1.1.1,2.2.2.2,3.3.3.3

私はこのコードを試しました:

address={% for x in {{nubmer_nodes}} %}
{{node[x].ip}}
{% if loop.last %},{% endif %}
{% endfor %}

しかし、問題が発生しました。どうすればいいですか?

間違い:

TASK [Gathering Facts] *********************************************************************

ok: [db2]
ok: [db3]
ok: [db1]

TASK [ssh : -- my loop --] *************************************************************************

fatal: [db1]: FAILED! => {"changed": false, "msg": "AnsibleError: template error while templating string: expected token ':', got '}'. String: \r\naddress={% for x in {{number_nodes}} %}\r\n{{node[x].ip}}\r\n{% if loop.last %},{% endif %}\r\n{% endfor %}"}
fatal: [db2]: FAILED! => {"changed": false, "msg": "AnsibleError: template error while templating string: expected token ':', got '}'. String: \r\naddress={% for x in {{number_nodes}} %}\r\n{{node[x].ip}}\r\n{% if loop.last %},{% endif %}\r\n{% endfor %}"}
fatal: [db3]: FAILED! => {"changed": false, "msg": "AnsibleError: template error while templating string: expected token ':', got '}'. String: \r\naddress={% for x in {{number_nodes}} %}\r\n{{node[x].ip}}\r\n{% if loop.last %},{% endif %}\r\n{% endfor %}"}
        to retry, use: --limit @/etc/ansible/playbooks/get_ip_ssh.retry

PLAY RECAP ********************************************************

db1                        : ok=1    changed=0    unreachable=0    failed=1
db2                        : ok=1    changed=0    unreachable=0    failed=1
db3                        : ok=1    changed=0    unreachable=0    failed=1

編集-1

templateとコードを変更しましたdefault/main.yml。名前(ノード)はありますが、まだIPにアクセスできません default/main.yml。 :

nodes:
 node1:
     ip: 1.1.1.1

 node2:
     ip: 2.2.2.2

 node3:
     ip: 3.3.3.3

get-ip.j2

address={% for host in nodes %}{{host}}{% if not loop.last %},{% endif %}{% endfor %}

出力は次のとおりです

address=node1,node3,node2

私も次のコードを使用しました。

address={% for host in nodes %}{{host.ip}}{% if not loop.last %},{% endif %}{% endfor %}

または

address={% for host in nodes %}{{host.[ip]}}{% if not loop.last %},{% endif %}{% endfor %}

しかし、まだ動作していません! !

修正する

私の問題は解決しました。次のコードを使用します。

address={% for host in nodes %}{{ nodes[host].ip }}{% if not loop.last %},{% endif %}{% endfor %}

ベストアンサー1

何。

まずnumber_nodes値が 1,2,3 と仮定してその要素にアクセスしようとしますがnode、提供された yaml にはそのような変数がありません。

第二に、このようにして3つの異なる変数を繰り返すことはできません。

ただし、yamlファイルが次の場合:

---
nodes:
  - ip: 1.1.1.1
  - ip: 2.2.2.2
  - ip: 3.3.3.3 

コードは次のとおりです。

address={% for x in {{ nodes }} %}
{{ x.ip }}
{% if not loop.last %},{% endif %}
{% endfor %}

コードとの違いは次のとおりです。

  • 最初の行では要素を繰り返しますnodes
  • 2番目は、ループ内のすべての要素であるip要素を選択します。x
  • 3行目では、最後の要素を除くすべての要素の間にコンマが必要であると仮定しますnot

おすすめ記事