能否在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
相关产品推荐
相关产品推荐

