Ansible 如何迭代所有指定的主机

Ansible 如何迭代所有指定的主机,ansible,Ansible,我有一个剧本,它应该在我的监控服务器上为所有指定的主机创建一个配置文件 - hosts: all gather_facts: True hosts: monitoring_server tasks: - command: touch {{ hostvars[item]['ansible_fqdn'] }} with_items: "{{ groups['all'] }}" 我使用ansible playbook main.yml-l“新建客户端、新建客户端2、监控服务

我有一个剧本,它应该在我的监控服务器上为所有指定的主机创建一个配置文件

- hosts: all
  gather_facts: True

  hosts: monitoring_server
  tasks:
  - command: touch {{ hostvars[item]['ansible_fqdn'] }}
    with_items: "{{ groups['all'] }}"
我使用ansible playbook main.yml-l“新建客户端、新建客户端2、监控服务器”执行剧本

监视服务器上的结果文件应如下所示:
client1.conf client2.conf


但是我遇到了一个关于缺少引号的错误,我尝试了各种语法更改,但似乎找不到问题。

更新:

- hosts: all
  gather_facts: True

  tasks:
    - file:
        path: "{{ hostvars[item]['ansible_fqdn'] }}"
        state: touch
      delegate_to: host_name # Delegate task to specific host
      with_items: "{{ groups['all'] }}"
您的原始剧本中有拼写错误

  • with:items
    应该是
    with\u items
  • 项目
    应为
    项目
  • 委托给
    的用法:


    只要您以所有主机为目标,就不必进行循环,因为Ansible在所有目标主机上执行任务,除非条件排除

    另一方面,我建议使用
    文件
    模块而不是
    命令
    来触摸文件

    - hosts: all
      tasks:
        - name: Touch a file
          file:
            path: "{{ ansible_fqdn }}"
            state: touch
    
    另外,我假设
    ansible\u fqdn
    是您为每个主机定义的主机变量。

    您需要修复:

  • 带项目:
    而不是
    带项目:

  • 项目
    而不是
    项目

  • 单个
    在播放列表中的每个项目中承载:
    声明

  • 这应该适用于您的情况:

    ---
    - hosts: all
      gather_facts: true
    
    - hosts: monitoring_server
      tasks:
        - command: touch {{ hostvars[item]['ansible_fqdn'] }}
          with_items: "{{ groups['all'] }}"
    

    或者,您可以使用
    delegate\u to:localhost
    完全删除循环以及对
    hostvars
    的引用:

    ---
    - hosts: all
      gather_facts: true
      tasks:
        - command: touch {{ ansible_fqdn }}
          delegate_to: localhost
    

    问题是我想为所有主机创建文件,但只在监控服务器上创建。我只使用触摸调试的原因,原来的任务是复制一个配置文件使用模板。考虑更详细地阐述您的问题。我也会更新我的答案。为此,@David,只需在任务中添加
    delegate\u到:localhost
    。谢谢,我已经在我的剧本中逐一更正了项目。不过,双主机声明是必要的,因为它必须使用gather_facts从其他系统检索变量。YAML不能以这种方式工作。如果你需要收集事实,你需要有两个项目,而不是一个。很抱歉,即使在复制和执行你发给我的示例时,我仍然会遇到一个错误,我就是不知道为什么。我使用
    ansible playbook test.ym-l“new\u client1,monitoring\u server”执行了playbook,错误如下:
    字段“args”有一个无效值。[…]第7行,第7列`@David我包含的示例有6行。你认为我怎样才能知道你的第7行是什么?我包含的错误来自你的第一个例子,在剧本中没有其他内容。但第二个例子也不起作用。