Skip to content

Instantly share code, notes, and snippets.

@arunvelsriram
Created August 21, 2017 21:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save arunvelsriram/03ea1c49a78cce32470b980e82b1ce2f to your computer and use it in GitHub Desktop.
Save arunvelsriram/03ea1c49a78cce32470b980e82b1ce2f to your computer and use it in GitHub Desktop.
Terraform dependency injection style de-coupling resources
# di_terraform.tf
# Example Terraform configuration that shows de-coupling resources (Amazon S3 bucket and bucket policy)
# with the help of modules analogous to dependency injection technique
# modules/s3_bucket/main.tf
# Base S3 bucket that can be attached a policy
variable "bucket_name" {}
variable "region" {
default = "us-east-1"
}
variable "policy" {
default = ""
}
resource "aws_s3_bucket" "bucket" {
bucket = "${var.bucket_name}"
region = "${var.region}"
policy = "${var.policy}"
}
# modules/policies/make_objects_public/main.tf
# A policy made available as a module
# Make each available policies a module and output the resulting JSON
variable "bucket_name" {}
data "aws_iam_policy_document" "make_objects_public" {
statement {
sid = "MakeItPublic"
actions = [
"s3:GetObject"
]
resources = [
"arn:aws:s3:::${var.bucket_name}/*",
]
principals {
type = "AWS"
identifiers = ["*"]
}
}
}
output "policy_json" {
value = "${data.aws_iam_policy_document.make_objects_public.json}"
}
# staging/s3_bucket/bucket_using_policy_module.tf
# Attaching existing make_objects_public policy to a bucket
module "policy" {
source = "modules/policies/make_objects_public"
bucket_name = "bucket-with-policy"
}
module "s3_bucket_with_policy" {
source = "modules/s3_bucket"
bucket_name = "bucket-with-policy"
policy = "${module.policy.policy_json}"
}
# staging/s3_bucket/bucket_using_custom_policy.tf
# Attaching custom policy to a bucket
data "aws_iam_policy_document" "custom_policy" {
statement {
sid = "MakeItPublic"
actions = [
"s3:GetObject"
]
resources = [
"arn:aws:s3:::bucket-with-custom-policy/*",
]
principals {
type = "AWS"
identifiers = ["*"]
}
}
}
module "s3_bucket_with_custom_policy" {
source = "modules/s3_bucket"
bucket_name = "bucket-with-custom-policy"
policy = "${data.aws_iam_policy_document.custom_policy.json}"
}
# staging/s3_bucket/bucket_without_policy.tf
# Bucket with no policy
# This is possible as variable policy's default value is set to an empty string
module "s3_bucket_with_no_policy" {
source = "modules/s3_bucket"
bucket_name = "bucket-with-no-policy"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment