1. 程式人生 > 其它 >Ansible template中j2檔案呼叫var中定義變數報錯解決辦法

Ansible template中j2檔案呼叫var中定義變數報錯解決辦法

報錯內容如下:

fatal: [10.86.132.130]: FAILED! => {"changed": false, "msg": "AnsibleError: template error while templating string: expected token ':', got '}'. String: # Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# The number of milliseconds of each tick\ntickTime=2000\n# The number of ticks that the initial \n# synchronization phase can take\ninitLimit=10\n# The number of ticks that can pass between \n# sending a request and getting an acknowledgement\nsyncLimit=5\n# the directory where the snapshot is stored.\ndataDir={{ zookeeper_data_dir }}\n# the port at which the clients will connect\nclientPort=2181\n# disable the per-ip limit on the number of connections since this is a non-production config\nmaxClientCnxns=0\n# Disable the adminserver by default to avoid port conflicts.\n# Set the port to something non-conflicting if choosing to enable this\nadmin.enableServer=false\n# admin.serverPort=8080\n#{% for zookeeper_cluster in zookeeper_cluster_server %}\n#server.{{ zookeeper_cluster.id }}={{ zookeeper_cluster.host }}:2888:3888\n#{% endfor %}\n\n{% for server in groups[{{ group_name }}] %}\nserver.{{ hostvars[server]['zookeeper_myid'] }}={{ hostvars[server]['inventory_hostname'] }}:2888:3888\n{% endfor %}\n"}

j2檔案中配置如下:

原因:
j2檔案中使用變數的時候,不需要 {{}},遇到if,for等條件判斷語句,變數的話,只需要變數名即可,字串需要 加上引號。

解決辦法:
{% for server in groups[{{group_name}}] %}改為{% for server in groups[group_name] %}即可