Skip to content

Instantly share code, notes, and snippets.

@Dark-Kernel
Created July 15, 2024 15:01
Show Gist options
  • Save Dark-Kernel/7a1289d56f1e1a38e9551911d5b5fa68 to your computer and use it in GitHub Desktop.
Save Dark-Kernel/7a1289d56f1e1a38e9551911d5b5fa68 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Perform a blue-green deployment in Kubernetes. Still not perfect, modify accordingly.
# check the pod readiness
check_readiness() {
local deployment=$1
local timeout=300
local interval=5
local elapsed=0
while [ "$elapsed" -lt "$timeout" ]; do
if kubectl get deployment "$deployment" -o jsonpath='{.status.readyReplicas}' | grep -q '3'; then
echo "Deployment $deployment is ready"
return 0
fi
sleep $interval
elapsed=$((elapsed + interval))
done
echo "Timeout waiting for deployment $deployment to be ready"
return 1
}
# Determine current active color for vice-versa
ACTIVE_COLOR=$(kubectl get service myapp-service -o jsonpath='{.spec.selector.version}')
if [ "$ACTIVE_COLOR" == "blue" ]; then
NEW_COLOR="green"
OLD_COLOR="blue"
else
NEW_COLOR="blue"
OLD_COLOR="green"
fi
echo "Current active color: $ACTIVE_COLOR"
echo "Deploying to $NEW_COLOR"
# Deploy the new version
kubectl apply -f "$NEW_COLOR-deployment.yaml"
# Wait for new deployment to be ready
if ! check_readiness "myapp-$NEW_COLOR"; then
echo "New deployment failed to become ready. Aborting."
exit 1
fi
# Run tests, replace with the actual one.
if ! ./run_smoke_tests.sh "$NEW_COLOR"; then
echo "Smoke tests failed. Aborting deployment."
kubectl delete -f "$NEW_COLOR-deployment.yaml"
exit 1
fi
# Switch traffic to the new version
kubectl patch service myapp-service -p "{\"spec\":{\"selector\":{\"version\":\"$NEW_COLOR\"}}}"
echo "Traffic switched to $NEW_COLOR"
# Wait and monitor for any issues
echo "Monitoring for 60 seconds..."
sleep 60
# If everything is fine, delete the old deployment (At your own risk)
kubectl delete -f "$OLD_COLOR-deployment.yaml"
echo "Blue-green deployment completed successfully"
#!/bin/bash
# This script updates Kubernetes manifest files with a new image tag. Simple*
# Check if a commit SHA is provided
if [ $# -eq 0 ]; then
echo "No commit SHA provided. Usage: $0 <commit-sha>"
exit 1
fi
COMMIT_SHA=$1
IMAGE_NAME="your-registry.com/your-image"
NEW_IMAGE="$IMAGE_NAME:$COMMIT_SHA"
# Update blue deployment
sed -i "s|image: $IMAGE_NAME:.*|image: $NEW_IMAGE|g" blue-deployment.yaml
# Update green deployment
sed -i "s|image: $IMAGE_NAME:.*|image: $NEW_IMAGE|g" green-deployment.yaml
echo "Kubernetes manifests updated with image: $NEW_IMAGE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment