Skip to content

Commit d498373

Browse files
authored
Merge pull request #48 from buildkite/keithduncan/fix-cross-region-git-credentials
Implement bucket region finding for git-credentials-s3-secrets
2 parents 922b375 + ad1b3c3 commit d498373

File tree

1 file changed

+37
-2
lines changed

1 file changed

+37
-2
lines changed

git-credential-s3-secrets

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,16 +52,51 @@ parse_url() {
5252
done
5353
}
5454

55+
s3_bucket_region() {
56+
local bucket="$1"
57+
58+
local guess_region="${AWS_DEFAULT_REGION:-}"
59+
if [ -z "${guess_region}" ]
60+
then
61+
# This plug-in may not be executing in an AWS VPC or have access to the IDMS
62+
# Fail fast with the --connect-timeout flag
63+
local token=$(curl -X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 60" --fail --silent --show-error --location --connect-timeout 5 http://169.254.169.254/latest/api/token)
64+
if [ -n "${token}" ]
65+
then
66+
guess_region=$(curl -H "X-aws-ec2-metadata-token: $token" --fail --silent --show-error --location http://169.254.169.254/latest/meta-data/placement/region)
67+
fi
68+
fi
69+
if [ -z "${guess_region}" ]
70+
then
71+
guess_region="us-east-1"
72+
fi
73+
74+
# Buckets in us-east-1 have a LocationConstraint of null
75+
# https://docs.aws.amazon.com/cli/latest/reference/s3api/get-bucket-location.html
76+
local bucket_region="$(aws s3api get-bucket-location --bucket "${bucket}" --region "${guess_region}" --output text --query "LocationConstraint || 'us-east-1'")"
77+
78+
echo "${bucket_region}"
79+
}
80+
5581
s3_download() {
5682
local bucket="$1"
5783
local key="$2"
58-
local aws_s3_args=("--quiet" "--region=$AWS_DEFAULT_REGION")
84+
85+
local bucket_region="$(s3_bucket_region "${bucket}")"
86+
if [ -z "${bucket_region}" ]
87+
then
88+
echo "Could not determine the bucket region for ${bucket}" >&2
89+
exit 2
90+
fi
91+
92+
local aws_s3_args=("--quiet" "--region=${bucket_region}")
5993

6094
if [[ "${BUILDKITE_USE_KMS:-true}" =~ ^(true|1)$ ]] ; then
6195
aws_s3_args+=("--sse" "aws:kms")
6296
fi
6397

64-
if ! aws s3 cp "${aws_s3_args[@]}" "s3://$1/$2" - ; then
98+
local s3_uri="s3://${bucket}/${key}"
99+
if ! aws s3 cp "${aws_s3_args[@]}" "${s3_uri}" - ; then
65100
echo "Failed to download s3://$bucket/$key" >&2
66101
exit 1
67102
fi

0 commit comments

Comments
 (0)