### Install pyhelm3 Source: https://github.com/azimuth-cloud/pyhelm3/blob/main/README.md Install the library using pip. ```sh pip install pyhelm3 ``` -------------------------------- ### Manage Helm Releases with pyhelm3 Source: https://github.com/azimuth-cloud/pyhelm3/blob/main/README.md Initialize the Helm client and perform common operations like listing, fetching, installing, and uninstalling releases. ```python from pyhelm3 import Client # This will use the Kubernetes configuration from the environment client = Client() # Specify the kubeconfig file to use client = Client(kubeconfig = "/path/to/kubeconfig") # Specify the kubecontext to use client = Client(kubecontext = "kubecontext") # Specify a custom Helm executable (by default, we expect 'helm' to be on the PATH) client = Client(executable = "/path/to/helm") # List the deployed releases releases = await client.list_releases(all = True, all_namespaces = True) for release in releases: revision = await release.current_revision() print(release.name, release.namespace, revision.revision, str(revision.status)) # Get the current revision for an existing release revision = await client.get_current_revision("cert-manager", namespace = "cert-manager") chart_metadata = await revision.chart_metadata() print( revision.release.name, revision.release.namespace, revision.revision, str(revision.status), chart_metadata.name, chart_metadata.version ) # Fetch a chart chart = await client.get_chart( "cert-manager", repo = "https://charts.jetstack.io", version = "v1.8.x" ) print(chart.metadata.name, chart.metadata.version) print(await chart.readme()) # Install or upgrade a release revision = await client.install_or_upgrade_release( "cert-manager", chart, { "installCRDs": True }, atomic = True, wait = True ) print( revision.release.name, revision.release.namespace, revision.revision, str(revision.status) ) # Uninstall a release # Via the revision revision = await client.get_current_revision("cert-manager", namespace = "cert-manager") await revision.release.uninstall(wait = True) #  Or directly by name await client.uninstall_release("cert-manager", namespace = "cert-manager", wait = True) ``` -------------------------------- ### Install or Upgrade Helm Releases Source: https://context7.com/azimuth-cloud/pyhelm3/llms.txt Performs installation or upgrade operations. Supports deep-merging multiple value dictionaries. ```python import asyncio from pyhelm3 import Client async def install_or_upgrade(): client = Client() # Fetch the chart first chart = await client.get_chart( "cert-manager", repo="https://charts.jetstack.io", version="v1.12.0" ) # Install or upgrade the release revision = await client.install_or_upgrade_release( "cert-manager", chart, {"installCRDs": True, "replicaCount": 2}, # values namespace="cert-manager", atomic=True, # rollback on failure wait=True, # wait for resources to be ready timeout="10m", create_namespace=True, description="Production cert-manager deployment" ) print(f"Release: {revision.release.name}") print(f"Namespace: {revision.release.namespace}") print(f"Revision: {revision.revision}") print(f"Status: {revision.status}") # Multiple value dictionaries are deep-merged revision = await client.install_or_upgrade_release( "my-app", chart, {"global": {"env": "production"}}, {"resources": {"limits": {"memory": "512Mi"}}}, {"replicas": 3}, namespace="production", atomic=True, wait=True ) asyncio.run(install_or_upgrade()) ``` -------------------------------- ### Get Release Information Source: https://context7.com/azimuth-cloud/pyhelm3/llms.txt Retrieve detailed metadata, values, resources, and hooks for a specific release revision. ```python import asyncio from pyhelm3 import Client async def get_release_info(): client = Client() # Get current revision for a release revision = await client.get_current_revision( "cert-manager", namespace="cert-manager" ) # Get chart metadata chart_metadata = await revision.chart_metadata() print(f"Release: {revision.release.name}") print(f"Namespace: {revision.release.namespace}") print(f"Revision: {revision.revision}") print(f"Status: {revision.status}") print(f"Updated: {revision.updated}") print(f"Chart: {chart_metadata.name} v{chart_metadata.version}") print(f"App Version: {chart_metadata.app_version}") print(f"Description: {revision.description}") print(f"Notes: {revision.notes}") # Get values used for this revision values = await revision.values() print(f"Values: {values}") # Get computed values (including defaults) computed_values = await revision.values(computed=True) print(f"Computed Values: {computed_values}") # Get resources created by this revision resources = await revision.resources() for resource in resources: print(f"Resource: {resource['kind']}/{resource['metadata']['name']}") # Get hooks executed for this revision hooks = await revision.hooks() for hook in hooks: print(f"Hook: {hook.name} ({hook.kind}) - {hook.phase}") asyncio.run(get_release_info()) ``` -------------------------------- ### Render Chart Templates Source: https://context7.com/azimuth-cloud/pyhelm3/llms.txt Generates Kubernetes resources from a Helm chart without installing it to the cluster. ```python import asyncio import yaml from pyhelm3 import Client async def template_chart(): client = Client() chart = await client.get_chart( "nginx", repo="https://charts.bitnami.com/bitnami", version="15.x" ) # Render templates with values resources = await client.template_resources( chart, "my-nginx", {"replicaCount": 3, "service": {"type": "LoadBalancer"}}, namespace="web", include_crds=True, is_upgrade=False, no_hooks=False ) for resource in resources: if resource: # Skip empty documents print(f"--- {resource['kind']}: {resource['metadata']['name']}") print(yaml.dump(resource)) asyncio.run(template_chart()) ``` -------------------------------- ### Fetch Chart Metadata with Python Source: https://context7.com/azimuth-cloud/pyhelm3/llms.txt Retrieves chart information, README, default values, CRDs, and dependencies from a repository without installation. ```python import asyncio from pyhelm3 import Client async def fetch_chart(): client = Client() # Get chart from a repository chart = await client.get_chart( "cert-manager", repo="https://charts.jetstack.io", version="v1.8.x" ) print(f"Chart: {chart.metadata.name}") print(f"Version: {chart.metadata.version}") print(f"App Version: {chart.metadata.app_version}") print(f"Description: {chart.metadata.description}") print(f"Type: {chart.metadata.type}") print(f"Home: {chart.metadata.home}") # Get chart README readme = await chart.readme() print(f"README:\n{readme[:500]}...") # Get default values default_values = await chart.values() print(f"Default Values: {default_values}") # Get CRDs crds = await chart.crds() for crd in crds: print(f"CRD: {crd['metadata']['name']}") # Get chart dependencies for dep in chart.metadata.dependencies: print(f"Dependency: {dep.name} {dep.version} ({dep.repository})") asyncio.run(fetch_chart()) ``` -------------------------------- ### Initialize Client Source: https://context7.com/azimuth-cloud/pyhelm3/llms.txt Configure the Helm client with various Kubernetes connection options. ```python from pyhelm3 import Client # Use default Kubernetes configuration from environment client = Client() # Specify kubeconfig file path client = Client(kubeconfig="/path/to/kubeconfig") # Specify kubecontext to use client = Client(kubecontext="my-cluster-context") # Use custom Helm executable with additional options client = Client( executable="/usr/local/bin/helm", default_timeout="10m", history_max_revisions=20, insecure_skip_tls_verify=True, kubeapiserver="https://my-cluster.example.com:6443", kubetoken="my-service-account-token" ) ``` -------------------------------- ### Manage Helm Repositories with pyhelm3 Source: https://context7.com/azimuth-cloud/pyhelm3/llms.txt Demonstrates adding, updating, searching, and removing Helm chart repositories using the `Command` class. Ensure you have an asyncio event loop running. ```python import asyncio from pyhelm3 import Client from pyhelm3.command import Command async def manage_repos(): command = Command() # List current repositories repos = await command.repo_list() for repo in repos: print(f"Repo: {repo['name']} - {repo['url']}") # Add a new repository await command.repo_add( "bitnami", "https://charts.bitnami.com/bitnami" ) print("Added bitnami repository") # Update repository indexes await command.repo_update("bitnami") print("Updated bitnami repository") # Update all repositories await command.repo_update() print("Updated all repositories") # Search for charts results = await command.search( "redis", version_constraints=">=17.0.0" ) for chart in results: print(f"Found: {chart['name']} v{chart['version']}") # Remove repository await command.repo_remove("bitnami") print("Removed bitnami repository") asyncio.run(manage_repos()) ``` -------------------------------- ### Simulate Helm Upgrades Source: https://context7.com/azimuth-cloud/pyhelm3/llms.txt Previews the changes an upgrade would apply to a release without modifying the cluster state. ```python import asyncio from pyhelm3 import Client async def simulate_upgrade(): client = Client() # Get current release revision = await client.get_current_revision( "my-app", namespace="production" ) # Get new chart version new_chart = await client.get_chart( "my-app", repo="https://my-charts.example.com", version="2.0.0" ) new_values = {"replicas": 5, "image": {"tag": "v2.0.0"}} # Simulate upgrade to see diff diff = await revision.release.simulate_upgrade( new_chart, new_values, show_secrets=False, context_lines=3 ) print("Upgrade would produce the following changes:") print(diff) asyncio.run(simulate_upgrade()) ``` -------------------------------- ### List Helm Releases Source: https://context7.com/azimuth-cloud/pyhelm3/llms.txt Retrieve and filter deployed releases across namespaces. ```python import asyncio from pyhelm3 import Client async def list_all_releases(): client = Client() # List all releases across all namespaces releases = await client.list_releases( all=True, all_namespaces=True ) for release in releases: revision = await release.current_revision() print(f"Release: {release.name}") print(f" Namespace: {release.namespace}") print(f" Revision: {revision.revision}") print(f" Status: {revision.status}") print() # Filter releases by status async def list_failed_releases(): client = Client() releases = await client.list_releases( include_deployed=False, include_failed=True, namespace="production", sort_by_date=True, sort_reversed=True, max_releases=50 ) for release in releases: revision = await release.current_revision() print(f"Failed: {release.name} - {revision.description}") asyncio.run(list_all_releases()) ``` -------------------------------- ### Compare Helm Release Revisions with pyhelm3 Source: https://context7.com/azimuth-cloud/pyhelm3/llms.txt Shows how to compare different revisions of a Helm release using the `diff` method on a `Revision` object. This requires an existing release named 'my-app' in the 'production' namespace. ```python import asyncio from pyhelm3 import Client async def compare_revisions(): client = Client() revision = await client.get_current_revision( "my-app", namespace="production" ) # Compare current revision with a previous one diff = await revision.diff( other_revision=1, # Compare with revision 1 context_lines=5, show_secrets=False ) print(f"Diff between revision {revision.revision} and revision 1:") print(diff) asyncio.run(compare_revisions()) ``` -------------------------------- ### Pull and Inspect Charts Locally Source: https://context7.com/azimuth-cloud/pyhelm3/llms.txt Downloads and unpacks a chart to the local filesystem using a context manager for automatic cleanup. ```python import asyncio from pyhelm3 import Client async def pull_and_inspect_chart(): client = Client() # Pull chart as context manager (auto-cleanup) async with client.pull_chart( "nginx-ingress", repo="https://helm.nginx.com/stable", version="0.17.x" ) as chart: print(f"Chart pulled to: {chart.ref}") print(f"Name: {chart.metadata.name}") print(f"Version: {chart.metadata.version}") # Chart directory is available for inspection # The directory is automatically cleaned up on exit asyncio.run(pull_and_inspect_chart()) ``` -------------------------------- ### Check and Perform Helm Upgrades Source: https://context7.com/azimuth-cloud/pyhelm3/llms.txt Determines if a release requires an update by comparing current state with chart metadata and values, then executes the upgrade if necessary. ```python import asyncio from pyhelm3 import Client, ReleaseNotFoundError async def check_upgrade_needed(): client = Client() chart = await client.get_chart( "prometheus", repo="https://prometheus-community.github.io/helm-charts", version="25.x" ) new_values = {"server": {"retention": "30d"}} try: current_revision = await client.get_current_revision( "prometheus", namespace="monitoring" ) except ReleaseNotFoundError: current_revision = None should_upgrade = await client.should_install_or_upgrade_release( current_revision, chart, new_values ) if should_upgrade: print("Upgrade required - chart version or values have changed") revision = await client.install_or_upgrade_release( "prometheus", chart, new_values, namespace="monitoring", wait=True ) print(f"Upgraded to revision {revision.revision}") else: print("No upgrade needed - release is up to date") asyncio.run(check_upgrade_needed()) ``` -------------------------------- ### Ensure Release State Idempotently Source: https://context7.com/azimuth-cloud/pyhelm3/llms.txt Ensures a release matches the desired state by handling pending states and only upgrading if changes are detected. ```python import asyncio from pyhelm3 import Client async def ensure_release(): client = Client() chart = await client.get_chart( "redis", repo="https://charts.bitnami.com/bitnami", version="17.x" ) values = { "architecture": "standalone", "auth": {"enabled": True, "password": "secretpassword"}, "master": {"persistence": {"size": "8Gi"}} } # ensure_release handles: # - Rolling back stuck pending-upgrade/pending-rollback states # - Uninstalling stuck pending-install/uninstalling states # - Only installing/upgrading if chart or values changed revision = await client.ensure_release( "redis-cache", chart, values, namespace="data", atomic=True, wait=True, timeout="5m" ) print(f"Ensured: {revision.release.name} at revision {revision.revision}") print(f"Status: {revision.status}") asyncio.run(ensure_release()) ``` -------------------------------- ### Roll Back Helm Releases Source: https://context7.com/azimuth-cloud/pyhelm3/llms.txt Retrieves release history and performs a rollback to a specific revision. ```python import asyncio from pyhelm3 import Client async def rollback_release(): client = Client() # Get release and its history revision = await client.get_current_revision( "my-app", namespace="production" ) # View revision history history = await revision.release.history() for rev in history: chart_meta = await rev.chart_metadata() print(f"Revision {rev.revision}: {rev.status} - {chart_meta.version} ({rev.updated})") # Simulate rollback to see diff diff = await revision.release.simulate_rollback( revision=2, # Target revision show_secrets=False ) print(f"Rollback diff:\n{diff}") # Perform rollback new_revision = await revision.release.rollback( revision=2, # Rollback to revision 2 wait=True, timeout="5m", cleanup_on_fail=True ) print(f"Rolled back to revision {new_revision.revision}") print(f"Status: {new_revision.status}") asyncio.run(rollback_release()) ``` -------------------------------- ### Handle Helm Errors with pyhelm3 Source: https://context7.com/azimuth-cloud/pyhelm3/llms.txt Illustrates how to catch specific Helm errors like `ReleaseNotFoundError`, `ChartNotFoundError`, and general `Error` exceptions. This code requires a running Kubernetes cluster and Helm Tiller (if applicable, though pyhelm3 targets Helm 3 which doesn't use Tiller). ```python import asyncio from pyhelm3 import Client from pyhelm3.errors import ( Error, ReleaseNotFoundError, ChartNotFoundError, ConnectionError, FailedToRenderChartError, ResourceAlreadyExistsError, InvalidResourceError, CommandCancelledError ) async def handle_errors(): client = Client() try: revision = await client.get_current_revision( "nonexistent-release", namespace="default" ) except ReleaseNotFoundError: print("Release does not exist") try: chart = await client.get_chart( "nonexistent-chart", repo="https://charts.example.com", version="1.0.0" ) except ChartNotFoundError: print("Chart not found in repository") try: chart = await client.get_chart("redis", repo="https://charts.bitnami.com/bitnami") await client.install_or_upgrade_release( "redis", chart, {"invalid": {"config": "value"}}, namespace="default" ) except FailedToRenderChartError as e: print(f"Template rendering failed: {e}") except InvalidResourceError as e: print(f"Invalid resource configuration: {e}") except ResourceAlreadyExistsError as e: print(f"Resource already exists: {e}") except ConnectionError as e: print(f"Cannot connect to Kubernetes: {e}") except CommandCancelledError: print("Command was cancelled") except Error as e: print(f"Helm error (code {e.returncode}): {e}") print(f"Stdout: {e.stdout.decode()}") print(f"Stderr: {e.stderr.decode()}") asyncio.run(handle_errors()) ``` -------------------------------- ### Uninstall Helm Releases Source: https://context7.com/azimuth-cloud/pyhelm3/llms.txt Removes releases from the cluster either directly by name or via a release object. ```python import asyncio from pyhelm3 import Client async def uninstall_release(): client = Client() # Uninstall directly by name await client.uninstall_release( "old-app", namespace="staging", wait=True, timeout="5m" ) print("Release uninstalled directly") # Or uninstall via release object revision = await client.get_current_revision( "another-app", namespace="staging" ) await revision.release.uninstall( wait=True, keep_history=False, # Set True to allow rollback no_hooks=False ) print("Release uninstalled via object") asyncio.run(uninstall_release()) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.