-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaws_terraform_create_dynamodb_table.sh
83 lines (65 loc) · 2.48 KB
/
aws_terraform_create_dynamodb_table.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env bash
set -euo pipefail
[ -n "${DEBUG:-}" ] && set -x
srcdir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck disable=SC1090,SC1091
. "$srcdir/lib/aws.sh"
# shellcheck disable=SC2034,SC2154
usage_description="
Creates a DynamoDB table for Terraform state locking
Also creates a policy for a permission limited Terraform account to use to lock/unlock the table.
This is useful when creating a Read Only account for GitHub Actions environment secret for Pull Requests to not need workflow approval
Idempotent - skips creation of table and policy if they already exist
$usage_aws_cli_required
"
# used by usage() in lib/utils.sh
# shellcheck disable=SC2034
usage_args="<table_name> [<aws_cli_options>]"
help_usage "$@"
min_args 1 "$@"
table="$1"
shift || :
export AWS_DEFAULT_OUTPUT=json
aws_account_id="$(aws_account_id)"
aws_region="$(aws_region)"
timestamp "Checking for existing DynamoDB table '$table'"
if aws dynamodb list-tables "$@" | jq -r '.TableNames[]' | grep -Fxq "$table"; then
timestamp "WARNING: table '$table' already exists in region '$aws_region', not creating..."
else
timestamp "Creating Terraform DynamoDB table '$table' in region '$aws_region'"
aws dynamodb create-table --table-name "$table" \
--key-schema AttributeName=LockID,KeyType=HASH \
--attribute-definitions AttributeName=LockID,AttributeType=S \
--billing-mode PAY_PER_REQUEST \
"$@"
timestamp "DynamoDB table created"
fi
echo
policy="Terraform-DynamoDB-Lock-Table-$table"
timestamp "Generating policy document '$policy'"
policy_document="$(cat <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "TerraformLock",
"Effect": "Allow",
"Action": [
"dynamodb:PutItem",
"dynamodb:DeleteItem"
],
"Resource": "arn:aws:dynamodb:$aws_region:$aws_account_id:table/$table"
}
]
}
EOF
)"
timestamp "Checking for existing policy"
set +o pipefail # early termination from the pipeline will fail the check otherwise
if aws iam list-policies | jq -r '.Policies[].PolicyName' | grep -Fxq "$policy"; then
timestamp "WARNING: policy '$policy' already exists, not creating..."
else
timestamp "Creating Terraform DynamoDB Policy '$policy'"
aws iam create-policy --policy-name "$policy" --policy-document "$policy_document"
timestamp "DynamoDB policy created"
fi