Metadata-Version: 2.1
Name: cloud-metadata
Version: 1.0.0
Summary: One metadata command and Python API for every public cloud
License: GPL-3.0-or-later
Author: Sean Marlow
Author-email: sean.marlow@suse.com
Maintainer: Sean Marlow
Maintainer-email: sean.marlow@suse.com
Requires-Python: >=3.11
Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Dist: jmespath (>=1.0.1)
Description-Content-Type: text/markdown

# cloud-metadata

One command and one Python API that return the same standard instance
metadata (instance ID, region, IP address, and so on) on every supported
public cloud. The cloud is detected automatically.

```
$ cloud-metadata provider
amazon
$ cloud-metadata get private-ipv4
10.0.1.25
$ cloud-metadata get region
eu-central-1
```

Supported clouds:

| Provider name | Cloud |
|---|---|
| `amazon` | AWS EC2 |
| `microsoft` | Azure |
| `google` | Google Compute Engine |
| `oracle` | Oracle Cloud Infrastructure |
| `alibaba` | Alibaba Cloud ECS |

## Install

Python 3.11 or later is required. `jmespath` is the only dependency.

```
pip install cloud-metadata
```

On SUSE distributions, install the `python3*-cloud-metadata` package for your
Python flavour. See [Packaging](#packaging).

## Command line

```
cloud-metadata get <key> [--provider P] [--timeout N]
cloud-metadata provider [--timeout N]
cloud-metadata keys [--provider P] [--timeout N]
cloud-metadata query '<jmespath>' [--document NAME] [--provider P] [--timeout N]
cloud-metadata raw [--document NAME] [--provider P] [--timeout N]
```

- `get` prints one standard key.
- `provider` prints the detected provider name.
- `keys` prints the standard keys the provider supports.
- `query` evaluates a [JMESPath](https://jmespath.org/) expression against a
  metadata document. `raw` prints the document unchanged.
- `--provider` skips detection. `--timeout` is in seconds (default 2).

The value is printed on its own on stdout, so it works in shell substitution:

```
region=$(cloud-metadata get region) || exit 1
```

Strings are printed as they are. Other values from `query` and `raw` are
printed as JSON. Messages go to stderr.

| Exit code | Meaning |
|---|---|
| 0 | Success |
| 2 | Provider not detected or unknown name, or a usage error |
| 3 | Key not available |
| 4 | The metadata service failed, timed out or cannot be reached |

## Container image

`go/` has a Go version of the command line tool that reads the same provider
tables, and `go/Containerfile` packages it on SUSE's `bci-micro` image:

```
podman build -t cloud-metadata -f go/Containerfile go
podman run --rm --network host cloud-metadata get region
```

It has `get`, `provider`, `keys`, `query` and `raw` with the same exit codes,
but no Python API. A few results differ from the Python tool, mostly the order
of keys in objects that an expression builds. On AWS, a container needs an
IMDS hop limit of 2 or host networking. `DESIGN.md` section 16 lists the
differences and what a container needs.

**The image has not been built or run yet**, because the machine it was
written on has no container runtime.

## Python API

```python
import cloud_metadata as cm

cm.detect_provider()                  # "amazon", "microsoft", ...
cm.get("private-ipv4")                  # str
cm.get("region", provider="google", timeout=5)
cm.query("compute.tags")              # JMESPath against the primary document
cm.raw()                              # the primary document, unevaluated
cm.keys()                             # standard keys the provider supports
cm.providers()                        # registered provider names
cm.clear_cache()                      # forget cached documents and the detected provider
```

Errors derive from `cloud_metadata.CloudMetadataError`:

- `ProviderNotDetected`
- `KeyNotAvailable`
- `MetadataUnavailable`
- `DocumentNotFound`, also a `KeyError`: `query` or `raw` got an unknown document
- `InvalidExpression`, also a `ValueError`: `query` got an invalid expression

## Standard keys

`instance-id`, `instance-type`, `region`, `zone`, `private-ipv4`,
`private-ipv6`, `public-ipv4`, `public-ipv6`, `ipv6`, `hostname`, `image-id`

IPv4 and IPv6 addresses are separate keys, so you always know which address
family you get. On an IPv6-only instance the IPv4 keys are unavailable, and
the other way round.

`ipv6` returns the first IPv6 address without saying whether it is public or
private. It works on every cloud. Use `private-ipv6` or `public-ipv6` when the
scope matters.

A provider may not support every key. A key whose value is empty on the
instance is also unavailable. Both cases raise `KeyNotAvailable` and exit
with code 3.

Known gaps:

- **Oracle:** IMDS does not expose public IP addresses, so `public-ipv4` and
  `public-ipv6` are unavailable. No external service is called to work around
  this.
- **AWS:** EC2 has no private IPv6 address, so `private-ipv6` is unavailable.
- **Alibaba:** the metadata does not say whether an IPv6 address is public or
  private, so `private-ipv6` and `public-ipv6` are unavailable. Use `ipv6`.
- **Google:** internal and external IPv6 addresses share one field, so they
  are told apart by range (`fd..` is private, `2...` is public).
- **AWS:** `architecture` (`x86_64`, `arm64` and so on, as EC2 spells it) is
  mapped on AWS only, so it is not a standard key. The other clouds have no
  such field in their metadata. `cloud-metadata keys` lists it after the
  standard keys on AWS.
- **Azure:** `image-id` is the resource ID for images that are addressed by
  one (custom and gallery images). For Marketplace images it is the URN
  `publisher:offer:sku:version`, with the real version from `exactVersion`
  (or `version`, which may be `latest`, if that is empty). It is unavailable
  if the image has neither. `latest` can name different images over time.
- **Azure and Google:** `zone` is empty on instances that are not in a zone.
- **Alibaba:** `public-ipv4` is the public address of the primary network
  interface. An attached Elastic IP (`eipv4`) is not mapped.
- **AWS in containers:** with IMDSv2 and a hop limit of 1, the token request
  from inside a container times out. The error message then names the hop
  limit. Raise `HttpPutResponseHopLimit` to 2 or allow IMDSv1.

The test fixtures are derived from each cloud's documentation. They have not
yet been replaced by captures from real instances.

## Detection

1. If `CLOUD_METADATA_PROVIDER` is set, that provider is used.
2. The DMI files (`sys_vendor`, `product_name`, `chassis_asset_tag`) are
   compared with each provider. A match is confirmed with the provider's
   metadata service. If that fails, DMI is trusted and a warning is logged.
3. If DMI is inconclusive, every provider's metadata service is probed in
   registry order.
4. As a last step, `dmidecode -s system-manufacturer` is tried.
5. If nothing matches, `ProviderNotDetected` is raised.

`DMI_DIR_PATH` overrides the DMI directory (default `/sys/class/dmi/id`), for
testing. The result is cached for the life of the process. Each failed
metadata probe can wait for the timeout, so use `--provider` or
`CLOUD_METADATA_PROVIDER` where the cloud is known.

The detection code is ported from
[cloud-registration-engine](https://github.com/SUSE-Enceladus/cloud-registration-engine).

## Adding a provider

In the code base, a cloud is one JSON file in
`src/cloud_metadata/providers/data/` and one line in `index.json` there. The
file layout is described in `providers/_loader.py`. At runtime,
register a `ProviderSpec` from Python:

```python
import cloud_metadata as cm

cm.register(
    cm.ProviderSpec(
        name="examplecloud",
        dmi_match=("examplecloud",),
        probes=(cm.Probe("/v1/"),),
        base_urls=("http://169.254.169.254",),
        documents={"instance": cm.Document("/v1/instance", "json")},
        keys={"instance-id": ("instance", "id")},
    )
)
cm.get("instance-id", provider="examplecloud")
```

`register()` validates the spec and raises `ValueError` for a duplicate name
unless `replace=True` is given. The command line only knows the built-in
providers. `DESIGN.md` describes the spec in detail.

## Requirements and limits

The package needs a Python interpreter. For minimal or container images this
is a real cost, so the command line tool is also available as a static Go
binary in a minimal container image. See [Container image](#container-image).

Metadata requests never use a proxy from the environment, because metadata
services are link-local.

## Packaging

`python-cloud-metadata.spec` is a SUSE multibuild Python spec. It builds the
package for each Python flavour that is 3.11 or later and installs
`/usr/bin/cloud-metadata` through `update-alternatives`.
`python-cloud-metadata.changes` is the changelog for OBS. The details are in
`DESIGN.md` section 12.

The Go version has its own spec, `cloud-metadata.spec`. Make its sources with
`go/scripts/make-rpm-sources.sh`. The two packages install the same
`/usr/bin/cloud-metadata`, so they conflict, and a system has one or the
other. `DESIGN.md` section 12 has the details.

**Neither spec has been built or linted yet.** Build them with `osc build` and
run `rpmlint` on the results before relying on them.

## Development

```
poetry install
make check      # ruff, ruff format --check, pytest with coverage, poetry build
make fmt        # fix lint findings and format
make go-check   # gofmt, go vet and go test for the Go version in go/
make check-all  # both
```

To release, run `poetry run bump-my-version bump patch` (or `minor` or `major`).
It updates the version in `pyproject.toml`, `src/cloud_metadata/__init__.py`
and both spec files. It does not commit or tag, and it does not write the
`.changes` entries, so add those by hand.

The test suite uses no network access. See `DESIGN.md` for the design and
`PLAN.md` for the implementation plan.

## License

GPL-3.0-or-later. See `LICENSE`.

