Last active
April 8, 2024 23:25
-
-
Save orihomie/1ec54a4ee4c1cf6e0c955422010f96ca to your computer and use it in GitHub Desktop.
Create s3 backend along with user and Dynamo DB
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
BUCKET_NAME=terraform-your_company-remote-store # this should be unique, and by that I mean really UNIQUE | |
BUCKET_REGION=eu-central-1 | |
USER_NAME=terraform-deployer | |
POLICY_FILE_NAME=$PWD/policy.json | |
AWS_PROFILE=your_company | |
aws s3api create-bucket \ | |
--profile $AWS_PROFILE \ | |
--bucket $BUCKET_NAME \ | |
--region $BUCKET_REGION \ | |
--create-bucket-configuration \ | |
LocationConstraint=$BUCKET_REGION 1> /dev/null | |
echo "Bucket has been created" | |
aws s3api put-bucket-encryption \ | |
--profile $AWS_PROFILE \ | |
--bucket $BUCKET_NAME \ | |
--server-side-encryption-configuration={\"Rules\":[{\"ApplyServerSideEncryptionByDefault\":{\"SSEAlgorithm\":\"AES256\"}}]} 1> /dev/null | |
echo "Bucket encryption has been set" | |
USER_ARN=$(aws iam create-user --profile $AWS_PROFILE --user-name $USER_NAME --output text --query 'User.Arn') | |
echo "User has been created (or already exists)" | |
sleep 5 | |
aws iam attach-user-policy \ | |
--profile $AWS_PROFILE \ | |
--policy-arn arn:aws:iam::aws:policy/AmazonS3FullAccess \ | |
--user-name $USER_NAME 1> /dev/null | |
aws iam attach-user-policy \ | |
--profile $AWS_PROFILE \ | |
--policy-arn arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess \ | |
--user-name $USER_NAME 1> /dev/null | |
echo "User policies has been attached" | |
cat <<-EOF >> $POLICY_FILE_NAME | |
{ | |
"Version": "2012-10-17", | |
"Statement": [ | |
{ | |
"Effect": "Allow", | |
"Principal": { | |
"AWS": "${USER_ARN}" | |
}, | |
"Action": "s3:*", | |
"Resource": "arn:aws:s3:::${BUCKET_NAME}" | |
} | |
] | |
} | |
EOF | |
aws s3api put-bucket-policy \ | |
--profile $AWS_PROFILE \ | |
--bucket $BUCKET_NAME \ | |
--policy file://$POLICY_FILE_NAME 1> /dev/null | |
echo "Bucket policy has been set" | |
rm $POLICY_FILE_NAME | |
aws s3api put-bucket-versioning \ | |
--profile $AWS_PROFILE \ | |
--bucket $BUCKET_NAME \ | |
--versioning-configuration Status=Enabled 1> /dev/null | |
echo "Bucket versioning has been set" | |
aws dynamodb create-table \ | |
--profile $AWS_PROFILE \ | |
--table-name terraform-state-lock \ | |
--attribute-definitions \ | |
AttributeName=LockID,AttributeType=S \ | |
--key-schema \ | |
AttributeName=LockID,KeyType=HASH \ | |
--provisioned-throughput \ | |
ReadCapacityUnits=20,WriteCapacityUnits=20 \ | |
--table-class STANDARD 1> /dev/null | |
echo "Dynamo DB has been created" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment