Skip to content

Instantly share code, notes, and snippets.

@eladtamary
Last active November 2, 2021 11:47
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eladtamary/49de1406e2605d2d659cbcd0b420eba1 to your computer and use it in GitHub Desktop.
Save eladtamary/49de1406e2605d2d659cbcd0b420eba1 to your computer and use it in GitHub Desktop.
This script is used tag AWS volumes that were created by Kubernetes CSI external provisioner. In each execution, the script will tag all AWS volumes that are un-tagged using the tags of the attached instance. This is a workaround until it will be implemented by the external-provisioner natively. See related issue: https://github.com/kubernetes-c…
#!/usr/bin/env bash
echo "$(date) - started to tag untagged CSI volumes"
untagged_csi_volumes=$(aws --profile my-aws-profile --output json ec2 describe-volumes \
--query 'Volumes[?!not_null(Tags[?Key == `Environment`].Value)] | []')
for volume in $(echo "${untagged_csi_volumes}" | jq -r '.[] | @base64'); do
volume_id=$(echo "$volume" | base64 --decode | jq -r '.VolumeId')
instance_id=$(echo "$volume" | base64 --decode | jq -r '.Attachments[].InstanceId')
instance_environment_tag=$(aws --profile my-aws-profile --output json ec2 describe-instances --instance-ids "$instance_id" \
| jq -r '.Reservations[].Instances[].Tags[] | select(.Key=="Environment") | .Value')
if [ -z "$instance_environment_tag" ]
then
echo "cannot tag volume $volume_id since $instance_id is not tagged with \"Environment\" tag"
else
echo "tagging $volume_id with Environment = $instance_environment_tag"
aws --profile harmandev --output json ec2 create-tags --resources "$volume_id" \
--tags Key=Environment,Value="$instance_environment_tag"
fi
done
echo "$(date) - finished to tag untagged CSI volumes"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment