Creating AWS S3 bucket with Terraform

I recommend to read the first example1,because this is a extenstion to that. However, instead of AWS EC2, here the target resource is AWS S3 for the simplicity. Here the providers.tf file.

provider "aws" {
  region = "${var.s3_region}"
}

terraform {
    required_version =  ">= 0.11.13"
    backend "s3" {
        bucket = "ojitha"
        key = "test/backbone"
        region = "ap-southeast-2"
        encrypt = "true"
    }
}

As shown in the above, the stage is maintain in the S3 bucket instead of locally as specified in the line# 7.

resource "aws_s3_bucket" "main" {
  bucket = "${var.s3_bucket_prefix}-${var.environment}-${var.s3_region}"
  acl = "private"
  tags = "${local.s3_tags}"
  region = "${var.s3_region}"

  lifecycle {
      prevent_destroy = "false"
  }

  server_side_encryption_configuration {
      rule {
          apply_server_side_encryption_by_default {
              sse_algorithm = "AES256"
          }
      }
  }

  versioning {
      enabled = "true"
  }
  lifecycle_rule {
      id = "state"
      prefix = "state/"
      enabled = "true"

      noncurrent_version_expiration {
          days =  1
      }
  }
}

The contents of the S3 bucket is encrypted as shown in the line# 11. The lifecycle rules in the line# 22 define that state should be save for one day. Above file is the s3.tf that is the resource file.

variable "environment" {
  type = "string"
  default = "test"
}

variable "s3_bucket_prefix" {
    default = "ojithatest1"
    description ="Prefix of the s3 bucket to delete"
    type = "string"
}


variable "s3_region" {
  type = "string"
}

locals {
   s3_tags = {
      created_by="Terraform"
      environment = "${var.environment}"
  }
}



Above file is variables.tf in my local directory. The most important part to hilight in the above code is line#17 local variable.

s3_bucket_name = "ojtest1"
s3_region = "ap-southeast-2"

Simply, the above file is terraform.tfvars which define all the variables.

Comments

Popular posts from this blog

Parse the namespace based XML using Python

Blog Writing Workflows

Markdown blog writer for blogger