【问题标题】:Get nth host from inventory_hostname in Ansible从 Ansible 中的 inventory_hostname 获取第 n 个主机
【发布时间】:2021-02-04 15:50:50
【问题描述】:

下面是我的库存主机文件的样子。

[all_hosts]
server1 USER=user1
server3 USER=user2
server5 USER=user1
…..

在我的 ansible playbook 中,我希望始终引用第一个主机,即 server1USER=user1 来执行 copy 任务,因为要复制的文件始终位于 inventory_hostname 中的第一个主机上。考虑-e domain_home=all_hosts

---

- name: "Play 1"

  hosts: "{{ domain_home }}"
  gather_facts: false
  vars:
    ansible_ssh_extra_args: -o StrictHostKeyChecking=no
  tasks:

    - debug:
        msg: "Although the inventory hostname is {{ inventory_hostname }} the first host will always be  <need help get first host> and the user will always be <need help get user for first host>

   

你能推荐一下吗?

【问题讨论】:

    标签: ansible ansible-inventory inventory


    【解决方案1】:

    groups["all_hosts"] 事实是按它们在 .ini 文件中的位置排序的,所以你可以只要求[0]th 项(或使用| first 过滤器),然后主机变量dict 类似按他们的名字索引

    - debug:
        msg: >-
         Although the inventory hostname is {{ inventory_hostname }}
         the first host will always be {{ host0 }}
         and the user will always be {{ hostvars[host0].USER }}
      vars:
        host0: '{{ groups[domain_home][0] }}'
    

    在未来,为了帮助自学钓鱼,- debug: var=vars- debug: var=hostvars 是说明性的,可以在剧本中的任何时候查看哪些信息可供您使用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-30
      相关资源
      最近更新 更多