【问题标题】:Ansible var jinja2 templateAnsible var jinja2 模板
【发布时间】:2016-04-10 01:35:07
【问题描述】:

我一直试图在 Ansible 中引用一个变量,但每次都收到错误消息。

yaml var 文件有:

nodes:
  barni:
    - { name: 'LoginGraceTime', value: '2m'}
    - { name: 'MaxSessions', value: '6'}
    - { name: 'ChallengeResponseAuthentication', value: 'yes'}

其中 barni 是“主机名 -s”。我需要 sshd_config.j2 模板中的动态内容来匹配变量中的主机名。如果我指定 node.barni.sshdextra,模板可以正常工作,但我需要将“barni”动态替换为服务器名称的短名称。

{% for item in node.barni.sshdextra %}
{{ item.name }} {{ item.value }}
{% endfor %}

在任务中,我可以使用 hostname_mounts: "{{hostname_shortname.replace('-','')} hostname_shortname: "{{inventory_hostname.split('.')[0]}}在变量def文件中

- name: nfs - edit - remove nfs lines from /etc/fstab
  command: sed -i '/nfs/d' /etc/fstab
  ignore_errors: yes
  when: "'{{inventory_hostname}}'.startswith('{{hostname_mounts}}')"
  tags: [ nfs ]

【问题讨论】:

    标签: jinja2 ansible


    【解决方案1】:

    首先让我们确保您了解 Ansibles host_vars 的概念。

    如果您有一个文件host_vars/barni.yml(尽管使用全名而不是短名),其中包含以下内容:

    nodes:
      - { name: 'LoginGraceTime', value: '2m'}
      - { name: 'MaxSessions', value: '6'}
      - { name: 'ChallengeResponseAuthentication', value: 'yes'}
    

    ...然后您可以简单地遍历nodeshost_varsgroup_vars 通常用于解决这种不同主机或主机组配置不同的情况。

    但我同意在某些情况下这会让人不舒服 - 最后回答您的问题:您可以使用变量 inventory_hostname_short 来获取主机的简称:

    {% for item in node[inventory_hostname_short].sshdextra %}
    {{ item.name }} {{ item.value }}
    {% endfor %}
    

    【讨论】:

    • 我把你关于循环的想法提升到了一个新的水平,我能够通过在模板文件中使用来解决这个问题:` # node specific settings {% if nodes is defined and nodes != [] %} {% for nodename, val in nodes.iteritems() %} {% if nodename == hostname_shortname %} # node.{{ nodename }}.sshdextra options: {% for option, defs in val.iteritems() % } {% if option == 'sshdextra' %} {% for item in defs %} {{ item.name }} {{ item.value }} {% endfor %} {% endif %} {% endfor %} { % endif %} {% endfor %} {% endif %} `谢谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多