Created
September 27, 2023 13:06
-
-
Save VerosK/30e1b64cf6a288bb0445559a4b0ba08a to your computer and use it in GitHub Desktop.
Remote state in Teraform shortcut
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
resource "random_integer" "suffix" { | |
min = 1000000 | |
max = 9999999 | |
} | |
resource "aws_s3_bucket" "remote_state" { | |
bucket = "tf-remote-state-${random_integer.suffix.result}" | |
} | |
resource "aws_dynamodb_table" "remote_state_lock" { | |
name = "tf-remote-state-${random_integer.suffix.result}" | |
hash_key = "LockID" | |
billing_mode = "PAY_PER_REQUEST" | |
attribute { | |
name = "LockID" | |
type = "S" | |
} | |
} | |
data "aws_iam_policy_document" "remote_state" { | |
statement { | |
sid = "EnableAccess" | |
effect = "Allow" | |
actions = [ | |
"dynamodb:GetItem", | |
"dynamodb:PutItem", | |
"dynamodb:DeleteItem" | |
] | |
resources = [ | |
"arn:aws:dynamodb:*:*:table/${aws_dynamodb_table.remote_state_lock.name}" | |
] | |
} | |
statement { | |
sid = "ListState" | |
effect = "Allow" | |
resources = [aws_s3_bucket.remote_state.arn] | |
actions = ["s3:ListBucket"] | |
} | |
statement { | |
sid = "PutState" | |
effect = "Allow" | |
resources = ["${aws_s3_bucket.remote_state.arn}/*"] | |
actions = ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"] | |
} | |
} | |
resource "aws_iam_policy" "terraform_remote_state" { | |
name = "ManageState" | |
policy = data.aws_iam_policy_document.remote_state.json | |
path = "/terraform/" | |
description = "Terraform policy" | |
} | |
/* attach the policy to users | |
resource "aws_iam_user_policy_attachment" "terraform_remote_state" { | |
policy_arn = aws_iam_policy.terraform_remote_state.arn | |
user = module.iam_users.usernames[count.index] | |
count = module.iam_users.user_count | |
} | |
*/ | |
/* create ansible group_vars | |
resource "local_file" "remote_bucket_name" { | |
filename = "playbooks/group_vars/all/remote_state.yml" | |
content = <<EOF | |
terraform_remote_state_bucket_name: ${aws_s3_bucket.remote_state.bucket} | |
terraform_remote_state_lock_name: ${aws_dynamodb_table.remote_state_lock.name} | |
EOF | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment