|
| 1 | +#!/bin/bash |
| 2 | + |
| 3 | +RETRIES=3 |
| 4 | +DELAY=30 |
| 5 | + |
| 6 | +# Function to retry a command with exponential backoff |
| 7 | +retry_command() { |
| 8 | + local retries=$1 |
| 9 | + local wait_time=60 |
| 10 | + shift |
| 11 | + until "$@"; do |
| 12 | + if ((retries == 0)); then |
| 13 | + echo "Command failed after multiple retries. Exiting." |
| 14 | + exit 1 |
| 15 | + fi |
| 16 | + echo "Command failed. Retrying in $wait_time seconds..." |
| 17 | + sleep $wait_time |
| 18 | + ((retries--)) |
| 19 | + wait_time=$((wait_time * 2)) |
| 20 | + done |
| 21 | +} |
| 22 | + |
| 23 | +# Fetch the list of LKE cluster IDs |
| 24 | +CLUSTER_IDS=$(curl -s -H "Authorization: Bearer $LINODE_TOKEN" \ |
| 25 | + -H "Content-Type: application/json" \ |
| 26 | + "https://api.linode.com/v4/lke/clusters" | jq -r '.data[].id') |
| 27 | + |
| 28 | +# Check if CLUSTER_IDS is empty |
| 29 | +if [ -z "$CLUSTER_IDS" ]; then |
| 30 | + echo "All clusters have been cleaned and properly destroyed. No need to apply inbound or outbound rules" |
| 31 | + exit 0 |
| 32 | +fi |
| 33 | + |
| 34 | +for ID in $CLUSTER_IDS; do |
| 35 | + echo "Applying Calico rules to nodes in Cluster ID: $ID" |
| 36 | + |
| 37 | + # Download cluster configuration file with retry |
| 38 | + for ((i=1; i<=RETRIES; i++)); do |
| 39 | + config_response=$(curl -sH "Authorization: Bearer $LINODE_TOKEN" "https://api.linode.com/v4/lke/clusters/$ID/kubeconfig") |
| 40 | + if [[ $config_response != *"kubeconfig is not yet available"* ]]; then |
| 41 | + echo $config_response | jq -r '.[] | @base64d' > "/tmp/${ID}_config.yaml" |
| 42 | + break |
| 43 | + fi |
| 44 | + echo "Attempt $i to download kubeconfig for cluster $ID failed. Retrying in $DELAY seconds..." |
| 45 | + sleep $DELAY |
| 46 | + done |
| 47 | + |
| 48 | + if [[ $config_response == *"kubeconfig is not yet available"* ]]; then |
| 49 | + echo "kubeconfig for cluster id:$ID not available after $RETRIES attempts, mostly likely it is an empty cluster. Skipping..." |
| 50 | + else |
| 51 | + # Export downloaded config file |
| 52 | + export KUBECONFIG="/tmp/${ID}_config.yaml" |
| 53 | + |
| 54 | + retry_command $RETRIES kubectl get nodes |
| 55 | + |
| 56 | + retry_command $RETRIES calicoctl patch kubecontrollersconfiguration default --allow-version-mismatch --patch='{"spec": {"controllers": {"node": {"hostEndpoint": {"autoCreate": "Enabled"}}}}}' |
| 57 | + |
| 58 | + retry_command $RETRIES calicoctl apply --allow-version-mismatch -f "$(pwd)/lke-policy.yaml" |
| 59 | + fi |
| 60 | +done |
0 commit comments