pycomposefile
pycomposefile provides structured deserialization of Docker Compose files into Python objects, making it easier to programmatically inspect and manipulate Compose configurations. It is currently at version 0.0.34 and sees regular, minor releases.
Warnings
- gotcha Environment variable replacement logic, particularly with default values (e.g., `${VAR:-default}`), was subject to fixes in versions prior to 0.0.33. Older versions might exhibit incorrect parsing for complex variable patterns. Always test environment variable resolution if upgrading from older versions.
- gotcha The library deserializes Docker Compose files, which themselves have version specifications (e.g., `version: '3.8'`). While `pycomposefile` aims for broad compatibility, using it with a Docker Compose file version that introduces new, unsupported features or significantly different structures may lead to parsing errors or incomplete object models. Consult Docker Compose documentation on versioning.
- gotcha As a file parsing library, common file I/O errors like `FileNotFoundError` (if the compose file path is incorrect) or `PermissionError` (if the script lacks read access) are frequent. Ensure correct file paths and appropriate permissions.
- gotcha Attempting to access non-existent keys (e.g., `compose_file.services['non_existent_service']`) or attributes on deserialized objects (e.g., `service.non_existent_attribute`) will result in `KeyError` or `AttributeError`. The structure of the Python objects mirrors the Compose file's YAML structure.
Install
-
pip install pycomposefile
Imports
- ComposeFile
from pycomposefile.compose_file import ComposeFile
- load_composefile
from pycomposefile.compose_file import load_composefile
Quickstart
import os
from pycomposefile.compose_file import load_composefile
# Create a dummy docker-compose.yaml file for demonstration
compose_content = """
version: '3.8'
services:
web:
image: nginx:latest
ports:
- "${APP_PORT:-8080}:80"
environment:
- DB_HOST=${DB_HOST:-localhost}
db:
image: postgres:13
volumes:
- db_data:/var/lib/postgresql/data
volumes:
db_data:
"""
with open("docker-compose.yaml", "w") as f:
f.write(compose_content)
# Set environment variables for testing
os.environ['APP_PORT'] = os.environ.get('APP_PORT', '9000')
# DB_HOST is intentionally left unset to test default value
# Load the compose file
compose_file = load_composefile("docker-compose.yaml")
# Access services and their properties
web_service = compose_file.services['web']
print(f"Web service image: {web_service.image}")
print(f"Web service ports: {web_service.ports}")
print(f"Web service DB_HOST environment variable: {web_service.environment.get('DB_HOST')}")
# Clean up the dummy file
os.remove("docker-compose.yaml")