fredag den 1. november 2019

Upload folder to AWS S3 using Terraform

With the introduction of terraform 0.12, the configuration can now be alot more dynamic.
The following example is written using terraform version 0.12.8 and AWS provider version 0.26.0.

The configuration creates a S3 bucket and makes it easier to upload the content of a folder and subfolders to the bucket, then sets the content type for each file, in this example indented for a static website.
Configuring the bucket as a website have not been included in this example.

resource "aws_s3_bucket" "website" {
  bucket = var.fqdn
  acl = "private" 

resource "aws_s3_bucket_object" "website_files" {
  for_each = fileset(path.module, "${var.file_path}**")
  content_type = lookup(var.content_typeelement(split(".", each.value), length(split(".", each.value))-1), "text/html")
  bucket =
  key = replace(each.value, var.file_path"")
  source = each.value
  etag = filemd5(each.value)

variable "content_type" {
  type = map(string)
description = "The file MIME types"
  default = {
    "html" = "text/html"
    "htm" = "text/html"
    "svg" = "image/svg+xml"
    "jpg" = "image/jpeg"
    "jpeg" = "image/jpeg"
    "gif" = "image/gif"
    "png" = "application/pdf"
    "css" = "text/css"
    "js" = "application/javascript"
    "txt" = "text/plain"

variable "file_path" {
  type = string
  description = "The path to the folder of the files you want to upload to S3"
  default = "../website/"

variable "fqdn" {
  type = string
  description = "The fully qualified domain name for the website"
  default = ""

Ingen kommentarer:

Send en kommentar