【问题标题】:List of other hosts in ansible, without the current hostansible中其他主机列表,不包括当前主机
【发布时间】:2022-11-04 23:01:23
【问题描述】:

我的hosts.yml 文件中有这些主机:

all:
  hosts:
    host1:
      name: name1
      port: port1
    host2:
      name: name2
      port: port2
    host3:
      name: name3
      port: port3

我想要一个包含 hosts.yml 文件中所有主机的字符串,其端口如下:

"http://name2:port2, http://name3:port3"

没有当前主机(在我的示例中,http://name1:port1)。

我希望在运行 ansible-playbook 时为每个主机生成此文件,并且我想在启动过程中将其传递给我的应用程序,例如(对于 host1):

$entrypoint.sh otherUrls="http://name2:port2, http://name3:port3"

我使用这段代码来制作字符串:

  otherUrls: "{%- for host in groups['all'] -%}
    {%- if hostvars[host]['name'] is defined -%}
      {%- if name != hostvars[host]['name'] -%}http://{{ hostvars[host]['name'] }}:{{ hostvars[host]['port'] }}
        {%- if not loop.last -%}\", \"{% endif -%}
      {% endif -%}
    {% endif -%}
  {% endfor -%}"

我用 jinja2 做了这个。但是我在最后一个主机的字符串末尾还有一个额外的','。有什么想法可以解决这个问题吗?

【问题讨论】:

  • 你需要提供一个例子来说明你到目前为止所做的事情。见how much effort is expected from SO users
  • 我编辑了,现在清楚了吗? @Zeitounator
  • 这仍然是一个要求,而不是一个问题。您没有展示您已经尝试过的内容以及您面临的确切编程问题/错误是什么。 SO 是一个询问和回答有关编程问题的问题的地方。而不是一个让开发人员为你编写代码的市场(参见我上面的链接)。如果您希望有更好的机会获得答案,您可能需要付出更多努力来尝试自己实现您的要求。
  • 它好多了,可以回答。但是现在您必须等待问题重新打开才能接受答案。由于我的解决方案是 oneliner,因此我将在此处提供它,并在可能的情况下稍后提供完整的答案。 other_urls: "{{ groups['all'] | reject('==', inventory_hostname) | map('extract', hostvars) | json_query('[][name, port]') | map('join', ':') | map('regex_replace', '^(.*)$', 'https://\\g<1>') | join(', ') }}"
  • 请确保在您的下一个问题中从一开始就提供完整的minimal reproducible example,以避免再次出现相同的情况。

标签: ansible jinja2


【解决方案1】:

我找到了一种没有 json_query 的方法来解决我的问题:

    {%- set groups_without_this = [] -%}
    {% for host in groups['all'] -%}
      {% if node_name != hostvars[host]['name'] -%}
        {% do groups_without_this.append(host) -%}
      {% endif -%}
    {% endfor -%}
    {%- for host in groups_without_this -%}
      {%- if hostvars[host]['nname'] is defined -%}
        {%- if name != hostvars[host]['name'] -%}http://{{ hostvars[host]['name'] }}:{{ hostvars[host]['port'] }}
          {%- if not loop.last -%}", "{% endif -%}
        {% endif -%}
      {% endif -%}
    {% endfor -%}

此代码创建一个没有当前节点的新列表,然后构造“其他 Url”字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    • 2017-01-28
    • 1970-01-01
    • 2018-11-23
    相关资源
    最近更新 更多