podman-py

repository·main·Indexed 18 days ago

https://github.com/containers/podman-py

A Python library providing bindings to the Podman RESTful API. It allows developers to programmatically manage containers, images, and other Podman resources using the PodmanClient and APIClient classes. The library supports multiple connection schemes, including Unix Domain Sockets (UDS), SSH, and TCP, and can be initialized directly or via environment variables using the from_env() helper.

Tokens
4.5K
Snippets
17
Records
21
Agent score
63%

What's inside podman-py

  1. Connect to Podman services using URI schemes

    main

    PodmanPy interacts with Podman services via a RESTful API. You specify the connection method using a URI scheme. The following schemes are supported:

    • SSH: http+ssh://[<login>@]<hostname>[:<port>]/<full filesystem path> (The ssh scheme is also accepted as an alias).
    • Unix Domain Socket (UDS): http+unix://<full filesystem path> (The unix scheme is also accepted as an alias).
    • TCP: tcp://<hostname>:<port> (Note: TCP support may be limited depending on the package version; check current implementation status).
    http+ssh://alice@api.example:22/run/user/1000/podman/podman.sock
    http+unix:///run/podman/podman.sock
    tcp://api.example:8888
  2. Access Podman resource managers

    main

    The PodmanClient provides access to specialized managers for different Podman resources via cached properties. Each manager handles a specific domain of the Podman API.

    from podman import PodmanClient
    
    with PodmanClient() as client:
        client.containers.list()  # Use ContainersManager
        client.images.list()     # Use ImagesManager
        client.volumes.list()    # Use VolumesManager
        client.networks.list()   # Use NetworksManager
        client.pods.list()       # Use PodsManager
        client.secrets.list()   # Use SecretsManager
        client.manifests.list() # Use ManifestsManager
        client.quadlets.list()   # Use QuadletsManager
  3. List images and containers with PodmanClient

    main

    Use client.images.list() to retrieve all available images and client.containers.list() to retrieve all containers.

    Note on Containers: When iterating through containers returned by list(), it is recommended to call container.reload() on each instance. This refreshes the object's attributes (such as status) from the server to ensure you are working with the most current state. Note that list() ignores the sparse option and assumes True by default.

    import json
    from podman import PodmanClient
    
    uri = "unix:///run/user/1000/podman/podman.sock"
    
    with PodmanClient(base_url=uri) as client:
        # Get all images
        for image in client.images.list():
            print(image, image.id)
    
        # Find all containers
        for container in client.containers.list():
            # Reload to get current status and attributes
            container.reload()
            print(container, container.id)
            print(container, container.status)
            print(container.attrs.keys())
    
        # Get disk usage information
        print(json.dumps(client.df(), indent=4))
  4. Basic usage of PodmanClient

    main

    To use PodmanPy, instantiate a podman.PodmanClient(). It is recommended to use the client as a context manager to ensure proper resource handling. You can use client.ping() to verify the connection and then access various resources like client.images or client.containers.

    import podman
    
    with podman.PodmanClient() as client:
        if client.ping():
            images = client.images.list()
            for image in images:
                print(image.id)
  5. Check Podman version and API compatibility

    main

    Call client.version() to retrieve a dictionary containing version information, including the release version, compatible API version, and specific Podman component details.

    from podman import PodmanClient
    
    uri = "unix:///run/user/1000/podman/podman.sock"
    
    with PodmanClient(base_url=uri) as client:
        version = client.version()
        print("Release: ", version["Version"])
        print("Compatible API: ", version["ApiVersion"])
        print("Podman API: ", version["Components"][0]["Details"]["APIVersion"]) 
  6. Initialize a PodmanClient

    main

    To interact with Podman, instantiate a PodmanClient by providing a base_url. Currently, only Unix Domain Sockets (UDS) are supported; TCP connections are not yet implemented. Use the client as a context manager to ensure proper resource handling.

    from podman import PodmanClient
    
    # Use a Unix Domain Socket (UDS) path
    uri = "unix:///run/user/1000/podman/podman.sock"
    
    with PodmanClient(base_url=uri) as client:
        # client is ready for use
        pass
  7. Configure APIClient connection settings

    main

    When instantiating APIClient, you can tune connection pooling and security:

    • version: Override the default Podman API version prefix.
    • compatible_version: Override the version prefix used when compatible=True is passed to requests.
    • timeout: Default timeout for all requests made by this client.
    • tls: Configuration for TLS connections (accepts TLSConfig or bool).
    • user_agent: Custom User-Agent string.
    • num_pools: Number of connection pools to cache.
    • max_pool_size: Maximum number of connections to maintain in a pool.
    • credstore_env: A mapping of environment variables for storing credentials.
    • use_ssh_client: If True (default), uses the system SSH agent instead of the Python ssh module.
  8. Use TLSConfig for secure connections

    main

    The TLSConfig class is used to hold TLS configuration settings. Note that as of the current version, this class is provided for compatibility and its configuration is currently ignored by the library.

    When initializing TLSConfig, you can provide several keyword arguments that may be delegated to the underlying SSH client configuration:

    • client_cert (tuple of str): A tuple containing the path to the client certificate and the path to the client key.
    • ca_cert (str): The path to the CA certificate file.
    • verify (bool or str): Set to False to disable verification, or provide a string representing the path to a CA certificate file.
    • assert_hostname (bool): Whether to verify the hostname of the server.
    • ssl_version (int): Currently ignored.

    You can use the configure_client static method to attempt to add TLS configuration to a client instance.

    from podman.tlsconfig import TLSConfig
    
    # Initialize configuration
    tls_config = TLSConfig(
        client_cert=('/path/to/cert.pem', '/path/to/key.pem'),
        ca_cert='/path/to/ca.pem',
        verify='/path/to/ca.pem',
        assert_hostname=True
    )
    
    # Apply to a client
    TLSConfig.configure_client(client)
  9. Use System and Information methods

    main

    The PodmanClient exposes several high-level methods for system-wide operations, often delegating to a SystemManager:

    • client.info(*args, **kwargs): Returns system information.
    • client.version(*args, **kwargs): Returns the API version information.
    • client.ping(): Returns True if the client can communicate with the Podman service.
    • client.df(): Returns disk usage information.
    • client.login(*args, **kwargs): Performs a login operation.
    • client.events(*args, **kwargs): Lists events from the Podman service.
  10. Create a PodmanClient from environment variables

    main

    Use PodmanClient.from_env() to create a client using standard environment variables. This is useful for compatibility with tools expecting Docker-style environment configurations.

    Supported environment variables:

    • CONTAINER_HOST or DOCKER_HOST: URL to the Podman service.
    • CONTAINER_TLS_VERIFY or DOCKER_TLS_VERIFY: Verify host against CA certificate.
    • CONTAINER_CERT_PATH or DOCKER_CERT_PATH: Path to TLS certificates.

    Arguments:

    • version: API version to use (default auto).
    • timeout: Timeout for API calls in seconds.
    • max_pool_size: Number of connections to save in pool.
    • environment: Dict containing input environment (defaults to os.environ).
    • credstore_env: Dict containing environment for credential store.
    • use_ssh_client: Use system ssh client rather than ssh module (defaults to True).
    from podman import PodmanClient
    
    # Creates a client using CONTAINER_HOST or DOCKER_HOST env vars
    client = PodmanClient.from_env()
  11. Initialize PodmanClient

    main

    The PodmanClient is the primary entry point for interacting with a Podman service. It can be initialized directly with connection parameters or via environment variables. It supports various connection protocols including Unix domain sockets, SSH, and TCP (though TCP implementation status should be verified).

    from podman import PodmanClient
    
    # Example: Connecting via SSH
    with PodmanClient(base_url="ssh://root@api.example:22/run/podman/podman.sock?secure=True",
                      identity="~alice/.ssh/api_ed25519") as client:
        print(client.info())