Created
June 23, 2017 23:56
-
-
Save estroz/4f1234d098bfdc18f9e617ef135538cc to your computer and use it in GitHub Desktop.
Tag route53 hosted zones if they don't have a specific tag key
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 | |
## Tags route53 hosted zones not already tagged with the specified key(s) | |
# Example tag file: | |
# [ | |
# { | |
# "Key": "expirationDate", | |
# "Value": "2017-06-22" | |
# } | |
# ] | |
region="${1:-AWS_REGION}" | |
if [ -z "$region" ]; then | |
echo "Must provide an AWS region, set the AWS_REGION, or set a region in your \$HOME/.aws/config}" | |
exit 1 | |
fi | |
region="--region $region" | |
tag_file="${2:-}" | |
if [ -z "$tag_file" ]; then | |
tag_file=$(mktemp) | |
cat <<EOF > "$tag_file" | |
[{"Key": "expirationDate","Value": "$(date +%Y-%m-%d)"}] | |
EOF | |
fi | |
cleanup() { | |
if [ -z "$1" ]; then rm -f "$tag_file"; fi | |
exit | |
} | |
trap "cleanup $2" SIGINT SIGTERM SIGHUP EXIT | |
set -eu | |
private_zones=$(aws $region route53 list-hosted-zones | \ | |
jq ".HostedZones[] | select(.Config.PrivateZone == true) | .Id" | \ | |
sed "s@\"@@g") | |
for key in $(cat "$tag_file" | jq ".[].Key"); do | |
for zone in $private_zones; do | |
is_not_tagged=$(aws $region route53 list-tags-for-resource --resource-type hostedzone --resource-id $(echo ${zone##*/} | \ | |
sed "s@\"@@g") | \ | |
jq ".ResourceTagSet | select(.Tags[]? | .Key == $key) | .ResourceId") | |
if [ -z "$is_not_tagged" ]; then | |
echo "Tagging zone ${zone##*/}" | |
aws $region route53 change-tags-for-resource --resource-type hostedzone --add-tags "$(cat "$tag_file")" --resource-id "${zone##*/}" | |
fi | |
done | |
done | |
set +eu | |
cleanup "$2" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment