[Python] How to pass Git metadata and environment variables securely from Bash to Python when...

Discussão em 'Python' iniciado por Stack, Setembro 8, 2025.

  1. Stack

    Stack Membro Participativo

    I'm setting up a CI/CD pipeline in GitHub Actions where I need to:

    1. Clone the repository from Git.
    2. Run a Python script that:
      • Reads Git metadata (commit SHA, tags, semantic version).
      • Builds a Docker image with this metadata as labels or tags.
    3. Push the image to Docker Hub (or any cloud registry).

    My workflow so far:

    GitHub Actions workflow (simplified):

    name: Build and Push Docker

    on:
    push:
    branches: [ "main" ]

    jobs:
    build:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout code
    uses: actions/checkout@v3

    - name: Run build script
    run: |
    bash scripts/build.sh


    scripts/build.sh

    #!/bin/bash
    set -e

    # Example: Extract Git commit hash and tag
    COMMIT_HASH=$(git rev-parse --short HEAD)
    TAG=$(git describe --tags --always)

    # Pass to Python script
    python3 scripts/docker_builder.py "$COMMIT_HASH" "$TAG"


    scripts/docker_builder.py

    import subprocess, sys

    commit_hash = sys.argv[1]
    tag = sys.argv[2]

    image_name = f"myapp:{tag}-{commit_hash}"

    try:
    subprocess.run(["docker", "build", "-t", image_name, "."], check=True)
    subprocess.run(["docker", "push", image_name], check=True)
    except subprocess.CalledProcessError as e:
    print(f"Error during Docker operation: {e}")
    sys.exit(1)



    My questions

    1. What’s the best practice to securely inject and reuse environment variables across Bash and Python in a CI/CD pipeline (like GitHub Actions)?
    2. Is there a cleaner way in Python to run docker build / docker push and capture errors, instead of chaining subprocess.run?}
    3. Are there recommended libraries or patterns for extracting Git metadata (tags, commits, semver) to improve image tagging logic?

    I’m especially interested in best practices for:

    • Handling secrets (e.g., registry passwords).
    • Avoiding brittle subprocess calls in Python.
    • Making this pipeline portable across different cloud CI/CD platforms (AWS CodeBuild, GCP Cloud Build, Azure Pipelines).

    Thanks in advance!

    Continue reading...

Compartilhe esta Página