Skip to content

Instantly share code, notes, and snippets.

@edtshuma
Forked from si3mshady/workspaces_ec2_s3_deploy.tf
Created September 10, 2022 11:04
Show Gist options
  • Save edtshuma/9a8948949d1e86586a1713eec1ae5f67 to your computer and use it in GitHub Desktop.
Save edtshuma/9a8948949d1e86586a1713eec1ae5f67 to your computer and use it in GitHub Desktop.
Terraform workspaces and variables practice - deploy ec2 and s3
terraform {
backend "s3" {
bucket = "elliott-arnold-dev-bucket"
region = "us-east-1"
key= "tfstate"
}
}
provider "aws" {}
data "aws_iam_user" "iam_user" {
user_name = "gh_actions"
}
variable "tags" {
type = map(string)
default = {
"dev" = "Elliott_EC2_DEV",
"uat" = "Elliott_EC2_QA",
"prod" = "Elliott_EC2_PROD"
}
}
variable "env_config" {
type = map(object({bucket_name=string,force_destroy=bool,acl=string,instance_type=string,ami=string}))
default = {
"dev" = {
acl = "private"
bucket_name = "elliott-arnold-dev-bucket"
force_destroy = true
ami = "ami-049af3f632cf18964"
instance_type = "t2.micro"
},
"uat" = {
acl = "private"
bucket_name = "elliott-arnold-uat-bucket"
force_destroy = true
ami = "ami-049af3f632cf18964"
instance_type = "t2.small"
},
"prod" = {
acl = "private"
bucket_name = "elliott-arnold-public-bucket"
force_destroy = false
ami = "ami-049af3f632cf18964"
instance_type = "t2.medium"
}
}
}
resource "aws_s3_bucket" "s3_cicd" {
bucket = var.env_config[terraform.workspace].bucket_name
acl = var.env_config[terraform.workspace].acl
force_destroy = var.env_config[terraform.workspace].force_destroy
policy = <<EOF
{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Action": "s3:*",
"Principal": {
"AWS": "${data.aws_iam_user.iam_user.arn}"
},
"Resource":"arn:aws:s3:::${var.env_config[terraform.workspace].bucket_name}/*"
}
]
}
EOF
}
output "s3_bucket" {
value = aws_s3_bucket.s3_cicd.bucket
}
resource "aws_instance" "blog_site" {
ami = var.env_config[terraform.workspace].ami
instance_type = var.env_config[terraform.workspace].instance_type
tags = {
Name = var.tags[terraform.workspace]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment