是否可以在 YAML 中编写 Ansible hosts/inventory 文件?

Is it possible to write Ansible hosts/inventory files in YAML?

在最佳实践页面中,有一个使用 hosts.yml 作为主机文件的示例:

然而,在文档中,我只能找到用于编写主机文件的 INI 语法。

YAML 中清单文件的语法是什么?

是的。

它已 deprecated in version 0.6 in 2012 and reintroduced 在 2016 年首次包含在版本 2.1 中的提交中。

GitHub 上的 example file 包含指南和示例:

  • Comments begin with the '#' character
  • Blank lines are ignored
  • Top level entries are assumed to be groups
  • Hosts must be specified in a group's hosts: and they must be a key (: terminated)
  • groups can have children, hosts and vars keys
  • Anything defined under a hosts is assumed to be a var
  • You can enter hostnames or ip addresses
  • A hostname/ip can be a member of multiple groups

Ex 1: Ungrouped hosts, put in 'ungrouped' group

ungrouped:
  hosts:
      green.example.com:
          ansible_ssh_host: 191.168.100.32
      blue.example.com:
      192.168.100.1:
      192.168.100.10:

Ex 2: A collection of hosts belonging to the 'webservers' group

webservers:
  hosts:
      alpha.example.org:
      beta.example.org:
      192.168.1.100:
      192.168.1.110:

Ex 3: You can create hosts using ranges and add children groups and vars to a group. The child group can define anything you would normally add to a group

testing:
  hosts:
      www[001:006].example.com:
  vars:
      testing1: value1
  children:
      webservers:
          hosts:
              beta.example.org:

以前的答案是正确的,但这里是简单的 hosts.yaml 和 INI,就像在屏幕截图中并排的一样,我也只是在这里复制实际的 hosts.yaml 所以如果你想复制和粘贴自己编辑

--- 
all: 
  hosts:               
    xmp: 
      ansible_connection: ssh
      ansible_host: "192.1.0.1"
      ansible_port: 7822
      ansible_user: nanoseco

更多信息:

https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html

我刚刚在 github 上发现 Ansible INI to YAML inventory converter 对我来说效果很好:

This repository contains a Python script for converting Ansible inventories in INI format to YAML format.

出于某种原因,转换结束时主机范围 ([01:03]) 被 = 分隔,而不是显示和正确的 :