Skip to content

Instantly share code, notes, and snippets.

@lex64
Created April 11, 2024 09:02
Show Gist options
  • Save lex64/1551cc976f2b57265f3f0f114290716c to your computer and use it in GitHub Desktop.
Save lex64/1551cc976f2b57265f3f0f114290716c to your computer and use it in GitHub Desktop.
#!/bin/bash
set -e
# Usage check
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <bucket-name>"
exit 1
fi
BUCKET_NAME=$1
IAM_USER_NAME="${BUCKET_NAME}-user"
POLICY_NAME="${BUCKET_NAME}-policy"
AWS_PAGER="" aws s3api create-bucket --bucket $BUCKET_NAME --region eu-central-1 --create-bucket-configuration LocationConstraint=eu-central-1 --output json
# Create IAM user, specifying JSON output
echo "Creating IAM user..."
AWS_PAGER="" aws iam create-user --user-name $IAM_USER_NAME --output json
# Create policy JSON file
POLICY_JSON=$(cat <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:ListBucket"
],
"Resource": ["arn:aws:s3:::$BUCKET_NAME"]
},
{
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:GetObject",
"s3:DeleteObject"
],
"Resource": ["arn:aws:s3:::$BUCKET_NAME/*"]
}
]
}
EOF
)
# Create a named IAM policy, specifying JSON output
CREATE_POLICY_OUTPUT=$(AWS_PAGER="" aws iam create-policy --policy-name $POLICY_NAME --policy-document "$POLICY_JSON" --output json)
POLICY_ARN=$(echo $CREATE_POLICY_OUTPUT | jq -r '.Policy.Arn')
echo "IAM policy $POLICY_NAME created with ARN $POLICY_ARN."
# Attach the policy to the IAM user, specifying JSON output
AWS_PAGER="" aws iam attach-user-policy --user-name $IAM_USER_NAME --policy-arn $POLICY_ARN --output json
echo -e "Policy attached to IAM user $IAM_USER_NAME.\n"
# Create access keys for the IAM user, specifying JSON output
ACCESS_KEYS=$(AWS_PAGER="" aws iam create-access-key --user-name $IAM_USER_NAME --output json)
echo -e "======================================================\n"
echo -e "Bucket \033[0;32m$BUCKET_NAME\033[0m created."
echo -e "User \033[0;32m$IAM_USER_NAME\033[0m created."
echo -e "Access Key ID: \033[0;32m$(echo $ACCESS_KEYS | jq -r '.AccessKey.AccessKeyId')\033[0m"
echo -e "Secret Access Key: \033[0;32m$(echo $ACCESS_KEYS | jq -r '.AccessKey.SecretAccessKey')\033[0m"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment