You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在Ansible Playbook中嵌入Inventory?单文件示例实现咨询

在单个Ansible Playbook文件中嵌入Inventory

你想要构建单文件的最小Ansible Playbook,无需拆分多文件目录,之前已经知道可以直接指定localhost为目标主机、不用单独Inventory的写法:

- name: Example playbook
  hosts: localhost
  connection: local  # 注意:原示例中的connections是拼写错误,应为connection
  tasks:
    - ansible.builtin.debug:
        msg: "hello!"

现在需要把如下的Inventory内容嵌入到Playbook中:

all:
  hosts:
    localhost:
      ansible_connection: local
    host1:
      http_port: 80
      maxRequestsPerChild: 808
      ansible_host: 127.0.0.2

Ansible支持在Playbook的Play级别直接通过inventory关键字嵌入静态Inventory,不需要单独的Inventory文件。完整的单文件Playbook示例如下:

- name: 单文件嵌入Inventory示例
  hosts: all  # 指定要执行的主机组/主机,这里all对应嵌入Inventory中的all组
  inventory:
    all:
      hosts:
        localhost:
          ansible_connection: local
        host1:
          http_port: 80
          maxRequestsPerChild: 808
          ansible_host: 127.0.0.2
  tasks:
    - name: 输出localhost的信息
      ansible.builtin.debug:
        msg: "localhost的连接方式: {{ ansible_connection }}"
      when: inventory_hostname == 'localhost'

    - name: 输出host1的端口配置
      ansible.builtin.debug:
        msg: "host1的HTTP端口: {{ http_port }}"
      when: inventory_hostname == 'host1'

关键说明:

  • inventory字段直接在Play中定义静态Inventory,格式和单独的Inventory YAML文件完全一致
  • hosts字段可以指定嵌入Inventory中的任意组或主机,比如hosts: localhost,host1可以只针对这两台主机执行
  • 嵌入的Inventory中定义的变量(比如host1的http_port)可以直接在任务中引用
  • 原示例中的connections是拼写错误,正确的参数名是connection

内容的提问来源于stack exchange,提问作者Wang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 14:22:36