首页 文章

ansible模板循环jinja2“我需要一行分隔,但最后一个条目没有,

提问于
浏览
1

我想为我的基础设施创建一个动态的剧本 .

我在配置中需要这一行:

wsrep_cluster_address ='gcomm://192.168.126.38,192.168.126.39,192.168.126.40'

我的模板看起来像这样:

wsrep_cluster_address ='gcomm:// {%for groups in groups ['db-server']%} {{hostvars [host] ['ansible_host']}},{%endfor%}'

它在主机上有效并且看起来像这样:

wsrep_cluster_address ='gcomm://172.16.120.45,172.16.120.40,172.16.120.42,'

最后一个逗号让我神经紧张 .

有没有办法告诉ansible不要逗号循环的最后一个条目?

坦克提供任何帮助,祝你有个美好的一天

2 回答

  • 0

    找到解决方案,感谢我的开发人员 .

    wsrep_cluster_address ='gcomm:// {%for groups in groups ['db-server']%} {{hostvars [host] ['ansible_host']}} {%if if loop.last%},{%endif% } {%endfor%}'

  • 1

    你救了我的一天!另外,如果您需要像JSON这样的配置文件中的行:

    nodelist = ["192.168.126.38","192.168.126.39","192.168.126.40"]

    这是你的Ansible:

    nodelist={%for host in groups['mygroup']%}"{{hostvars[host].ansible_eth0.ipv4.address}}"{% if not loop.last %},{% endif %}{% endfor %}

    这是完整的例子:

    - name: Create List of nodes to be added into Cluster
       set_fact: nodelist={%for host in groups['mygroup']%}"{{hostvars[host].ansible_eth0.ipv4.address}}"{% if not loop.last %},{% endif %}{% endfor %}
    
     - debug: msg=[{{nodelist}}]
    
     - name: Set Cluster node list in config file
       lineinfile:
             path: "/etc/myfonfig.cfg"
             line: "hosts: [{{ nodelist }}]"
    

    作为结果,您将在配置文件中包含以下行:

    hosts: ["192.168.126.38","192.168.126.39","192.168.126.40"]

相关问题