【问题标题】:Ansible Playbook - Import Playbook pass Host Name for each in Group - Rescursive Loop detectedAnsible Playbook - 为组中的每个导入 Playbook 传递主机名 - 检测到递归循环
【发布时间】:2019-11-08 21:22:46
【问题描述】:

请先原谅我的问题。我已经搜索并花时间查看How to iterate over inventory group in ansible?Ansible iterate over hosts in inventory group set by variable 风格问题。

所以会尽量让问题保持简单。

库存看起来像:(这是所有示例,可以更好地解释..)

[GroupA]
host1 country=USA
host2 country=USA
host3 country=UK

所以我想只在没有 hosts 的情况下通过 Group ,以便在每个主机上执行 playbook。然而,作为剧本的一部分,首先我需要在不同的服务器上运行一个脚本(取决于国家)并将主机名传递给该脚本。

在我的测试中,我发现了“inventory_hostname”,这样即使我没有通过主机并且通过了组,我也可以将主机名放入变量中。

当我把它们放在一起并从 import_playbook 开始时(因为这个 playbook 是针对不同的服务器的),我看到了:

Error was a <class 'ansible.errors.AnsibleError'>, original message: An unhandled exception occurred while templating '{{ runninghost }}'. Error was a <class 'ansible.errors.AnsibleError'>, original message: An unhandled exception occurred while templating '{{ v_host_name }}'. Error was a <class 'ansible.errors.AnsibleError'>, original message: recursive loop detected in template string: {{ v_host_name }}

我有一本剧本,其中我有一些基于“国家”的条件

- hosts: "{{ v_world }}"

   vars:
    v_world: "{{ v_world }}"
    hostvalue : "{{ inventory_hostname }}"

 - import_playbook: country-stuff-USA.yml
   vars:
    v_host_name: "{{ hostvalue }}"
   when: hostvars[groups[v_world][0]]['country'] == "USA"

 - import_playbook: country-stuff-UK.yml
   vars:
    v_host_name: "{{ hostvalue }}"
   when: hostvars[groups[v_world][0]]['country']  == "UK"


country-stuff-USA.yml

---
 - hosts: "world-server-usa.world"
   vars:
     runninghost: "{{ v_host_name }}"

   roles:
   - role: world_peace-usa
     poll: 0
     vars:
      hostvalue: "{{ runninghost }}"

country-stuff-UK.yml

---
 - hosts: "world-server-usa.world"
   vars:
     runninghost: "{{ v_host_name }}"

   roles:
   - role: world_peace-uk
     poll: 0
     vars:
      hostvalue: "{{ runninghost }}"      

world_peace-uk ( main.yml )

- name: world_peace-uk
  shell: ksh /mountA/scriptuk.sh -host={{hostvalue}} 

world_peace-uk ( main.yml )

- name: world_peace-usa
  shell: ksh /mountA/scriptusa.sh -host={{hostvalue}} 

有什么想法吗?我确定我在使用这种组合时做错了什么。但我想不出更好的方法来使用 Groups ,而是将主机名传递到另一个盒子上的脚本上。

非常感谢您的阅读!

【问题讨论】:

    标签: ansible conditional-statements roles


    【解决方案1】:

    您的问题过于复杂,当您需要在与剧本中指定的主机不同的主机上执行任务时,您应该使用delegation。例如:

    ---
    
    - hosts: running_hosts
    
      tasks:
      - name: tasks to execute on another host
        module: ...
        delegate_to: other_host
    
      - name: tasks to execute on the running host
        module: ...
    

    关于你得到的错误,这是因为v_world 在语句v_world: "{{ v_world }}" 中引用了自己

    【讨论】:

    • 非常感谢您的回复。我猜我过于复杂了,由于我缺乏经验,我实际上是像“乐高”积木一样接近这个。会试试这个,让你知道。
    猜你喜欢
    • 2016-09-27
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多