# Use PostgreSQL as Ansible Inventory CMDB

> Use the Pigsty v2.7 inventory scripts to switch between the static YAML inventory and the PostgreSQL CMDB.
---

Pigsty v2.7 normally reads its Ansible inventory from `pigsty.yml`. The release
also ships three scripts that can load that inventory into the `pigsty` schema
of the `meta` database and switch Ansible to a generated dynamic inventory.

The implementation in this page is tied to the v2.7.0 objects
[`bin/inventory_load`](https://github.com/Vonng/pigsty/blob/v2.7.0/bin/inventory_load),
[`bin/inventory_cmdb`](https://github.com/Vonng/pigsty/blob/v2.7.0/bin/inventory_cmdb),
and [`bin/inventory_conf`](https://github.com/Vonng/pigsty/blob/v2.7.0/bin/inventory_conf).

## Prerequisites

The CMDB schema is created from
[`files/cmdb.sql`](https://github.com/Vonng/pigsty/blob/v2.7.0/files/cmdb.sql)
when the default `pg-meta` cluster is provisioned. Complete `infra.yml` and the
`pg-meta` database initialization first, then verify that the `meta` service is
reachable.

By default, [`ansible.cfg`](https://github.com/Vonng/pigsty/blob/v2.7.0/ansible.cfg)
contains:

```ini
[defaults]
inventory = pigsty.yml
```

## Load the YAML inventory

`bin/inventory_load` reads a YAML inventory and replaces the rows in
`pigsty.group`, `pigsty.host`, `pigsty.group_var`, `pigsty.host_var`, and
`pigsty.global_var`. Back up or review the target CMDB before loading a new
inventory.

```bash
bin/inventory_load                                      # use $PIGSTY_HOME/pigsty.yml and $METADB_URL
bin/inventory_load -p files/pigsty/demo.yml             # load another v2.7 inventory
bin/inventory_load -p pigsty.yml \
  -d postgresql://dbuser_meta:DBUser.Meta@10.10.10.10:5432/meta
```

The script accepts `-p|--path` for the YAML file and `-d|--data` for the
PostgreSQL connection string. Its defaults come from `PIGSTY_HOME` and
`METADB_URL`.

## Switch inventory source

Switch Ansible to the CMDB-backed `inventory.sh`:

```bash
bin/inventory_cmdb
ansible-inventory --list
```

`bin/inventory_cmdb` writes `inventory.sh`, makes it executable, and changes
the `inventory` entry in `ansible.cfg`. The generated script queries
`pigsty.inventory` through the `meta` PostgreSQL service.

Switch back to the static `pigsty.yml` inventory with:

```bash
bin/inventory_conf
ansible-inventory --list
```

These scripts only change the inventory source. Continue to edit and validate
the source configuration deliberately; loading a new YAML file is not an
automatic two-way synchronization mechanism.
