如何在CircleCI中关闭PR时触发构建及删除K8s预览环境?
Hey there! Let's break down your two CircleCI questions with practical, actionable steps:
CircleCI lets you target specific GitHub events (like PR closures) using workflow conditionals. Here's how to set it up in your .circleci/config.yml:
- Define a workflow that only runs when a PR is closed:
workflows: pr-closed-trigger: jobs: - your-cleanup-job-name # Replace this with the job you want to run when: and: - equal: [ github.event_name, pull_request ] - equal: [ github.event.action, closed ] - If you need to filter further (e.g., only trigger for PRs targeting your
mainbranch), add an extra condition:when: and: - equal: [ github.event_name, pull_request ] - equal: [ github.event.action, closed ] - equal: [ github.event.pull_request.base.ref, main ]
Absolutely! You can tie this cleanup directly to the PR closure trigger we just set up. Here's how to make it work:
Step 1: Grant CircleCI Access to Your Kubernetes Cluster
First, ensure CircleCI can authenticate with your K8s cluster:
- Create a Context in the CircleCI dashboard, and add your Kubernetes credentials (e.g., a
KUBECONFIGfile content, or cluster API keys/certificates). - Reference this context in your cleanup job to grant it cluster access.
Step 2: Write the Cleanup Job
Define a job that runs kubectl commands to delete your preview environment. Most teams tag preview resources with the PR number (e.g., pr-id: ${CIRCLE_PR_NUMBER}) for easy targeting:
jobs: cleanup-preview-environment: docker: - image: cimg/base:stable context: - your-k8s-context-name # Replace with your CircleCI context name steps: - run: name: Install kubectl command: | curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl" chmod +x kubectl sudo mv kubectl /usr/local/bin/ - run: name: Authenticate to Kubernetes command: | # Load your kubeconfig (adjust this to match your auth method) echo "$KUBECONFIG_CONTENT" > ~/.kube/config - run: name: Delete Preview Environment Resources command: | # Delete all resources tagged with the PR number kubectl delete all -l pr-id=${CIRCLE_PR_NUMBER} # Or delete the entire namespace if you created one for the PR # kubectl delete namespace preview-pr-${CIRCLE_PR_NUMBER}
Step 3: Link the Job to the PR Closure Workflow
Update your workflow to use this cleanup job, just like in the first example:
workflows: pr-closed-trigger: jobs: - cleanup-preview-environment when: and: - equal: [ github.event_name, pull_request ] - equal: [ github.event.action, closed ]
内容的提问来源于stack exchange,提问作者joseph

