Reputation: 922
I am trying to create an S3 bucket policy via Terraform 0.12 that will change based on environment (dev/prod). Here is a portion of the policy:
{
"Sid": "AllowAdminAccessToBuckets",
"Effect": "Allow",
"Principal": "*",
"Action": [
"s3:GetBucket*"
],
"Resource": [
"arn:aws:s3:::${var.env-bucket}",
"arn:aws:s3:::${var.env-bucket}/*"
],
"Condition": {
"StringEquals": {
"aws:sourceVpce": "${var.env-vpce}"
}
}
}
If I do it with a JSON formatted document (not a template) the following works:
resource "aws_s3_bucket" "b" {
bucket = "my-tf-test-bucket"
policy = "${file("templates/policy.json")}"
}
How do I specify the variables in the policy?
Upvotes: 1
Views: 3126
Reputation: 56839
You don't need a template file just to be able to pass variables in, you can do that directly inline by using a heredoc:
variable "env-bucket" {
default = "example"
}
variable "env-vpce" {
default = "vpce-1234567890abcdef"
}
resource "aws_s3_bucket" "b" {
bucket = var.env-bucket
policy = <<POLICY
{
"Sid": "AllowAdminAccessToBuckets",
"Effect": "Allow",
"Principal": "*",
"Action": [
"s3:GetBucket*"
],
"Resource": [
"arn:aws:s3:::${var.env-bucket}",
"arn:aws:s3:::${var.env-bucket}/*"
],
"Condition": {
"StringEquals": {
"aws:sourceVpce": var.env-vpce
}
}
}
POLICY
}
It's also worth noting that that is allowing all access to the GetBucket*
API calls to anything where the traffic flows through that VPC endpoint rather than just admins (basically anything that is in that VPC) and also won't allow any object based actions so the "arn:aws:s3:::${var.env-bucket}/*"
resource is unnecessary or you need to change GetBucket*
to Get*
to allow traffic from that VPC to get objects.
Upvotes: 0
Reputation: 5743
You can use data resource to create a JSON template for policy by passing the variables based on your environment and use that template_file as policy in aws_s3_bucket
resource.
variable "env-bucket" {
default = "sample"
}
variable "env-vpce" {
default = "sample-vpc"
}
data "template_file" "policy" {
template = "${file("policy.json")}"
vars = {
env-bucket = "${var.env-bucket}"
env-vpce = "${var.env-vpce}"
}
}
resource "aws_s3_bucket" "b" {
bucket = "my-tf-test-bucket"
policy = "${data.template_file.policy.rendered}"
}
Upvotes: 1