Last active
December 13, 2020 21:03
-
-
Save ismailbaskin/d7222dc7a74807431399ecff9e259792 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
## This script create necessary firewall rule based on validating and mutating webhooks for private GKE clusters. | |
## Usage : ./add_gcp_fw.sh [YOUR_GKE_CLUSTER_NAME] | |
set -e | |
CLUSTER=$1 | |
validationg_svcs=$(kubectl get validatingwebhookconfigurations -ojson | \ | |
jq -c '.items[].webhooks[].clientConfig.service | del(.path) | select(. != null)') | |
mutating_svcs=$(kubectl get mutatingwebhookconfigurations -ojson | \ | |
jq -c '.items[].webhooks[].clientConfig.service | del(.path) | select(. != null)') | |
webhook_svcs="${validationg_svcs} | |
${mutating_svcs}" | |
rule_arr=() | |
while IFS= read -r line | |
do | |
svc_ns=$(echo ${line} | jq -r '.namespace') | |
svc_name=$(echo ${line} | jq -r '.name') | |
target=$(kubectl get svc -n ${svc_ns} ${svc_name} -ojson | \ | |
jq ".spec.ports[] | select( .port == 443) | .targetPort") | |
if [[ $target -eq 10250 ]] || [[ $target -eq 443 ]] || [ -z "$target" ]; then | |
continue | |
fi | |
rule_arr+=("tcp:${target}") | |
done < <(printf '%s\n' "$webhook_svcs") | |
rules=$(printf ",%s" "${rule_arr[@]}") | |
rules=${rules:1} | |
gcloud compute firewall-rules delete ${CLUSTER}-webhooks || echo "" | |
if [[ ${#rule_arr[@]} -eq 0 ]]; then | |
echo "No need to create a firewall rule." | |
exit | |
fi | |
source_ranges=$(gcloud container clusters describe $CLUSTER --format="value(privateClusterConfig.masterIpv4CidrBlock)") | |
source_tags=$(gcloud compute instances list --filter="tags.items~^gke-$CLUSTER" --limit=1 --format="value(tags.items[0])") | |
gke_network=$(gcloud container clusters describe $CLUSTER --format="value(network)") | |
gcloud compute firewall-rules create ${CLUSTER}-webhooks \ | |
--action ALLOW --direction INGRESS \ | |
--source-ranges $source_ranges \ | |
--target-tags $source_tags \ | |
--network $gke_network \ | |
--rules $rules |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment