Sunday, August 23, 2020

Terraform aws s3 upload directory example(using bash shell script)

 Terraform aws s3 upload directory example.

 

 Intro: There are a few way to upload directory into s3 aws bucket.
           In this short article, I would like to show how to use bash local shell
           to upload directory. I assume that you already know how to add aws key 
           and use aws cli(basic?). Also, terraform basic.


1. Createing aws-provider.tf

oyj@controller:~/prac/test/awsverless/vue-weather/terra$ cat aws-provider.tf
provider "aws" {
  version = "~> 2.0"
  access_key = ""
  secret_key = ""
  region  = "ap-northeast-2"
}

2.Create variable.tf

oyj@controller:~/prac/test/awsverless/vue-weather/terra$ cat variable.tf
variable "buckname" {
   default = "vweather-2020082402"
   type = "string"
}

3. create s3up_vueweather.tf file.

oyj@controller:~/prac/test/awsverless/vue-weather/terra$ cat s3up_vueweather.tf 


resource "aws_s3_bucket" "vweather" {
  bucket = var.buckname
  acl    = "private"
}

resource "aws_s3_bucket_object" "vweather" {
  key        = "someobject"
  bucket     = aws_s3_bucket.vweather.id
  provisioner "local-exec" {
        command = "bash ./upload_dist.sh"
  }
}

4. create upload.sh file.

oyj@controller:~/prac/test/awsverless/vue-weather/terra$ cat upload_dist.sh
#!/usr/bin/env bash
aws s3 cp ../dist/ s3://vweather-2020082402/ --recursive


5. Terraform apply.(with -auto-approve option)

  oyj@controller:~/prac/test/awsverless/vue-weather/terra$ terraform apply -auto-approve
aws_s3_bucket.vweather: Refreshing state... [id=vweather-2020082402]
aws_s3_bucket_object.vweather: Refreshing state... [id=someobject]
aws_s3_bucket.vweather: Creating...
aws_s3_bucket.vweather: Creation complete after 3s [id=vweather-2020082402]
aws_s3_bucket_object.vweather: Creating...
aws_s3_bucket_object.vweather: Provisioning with 'local-exec'...
aws_s3_bucket_object.vweather (local-exec): Executing: ["/bin/sh" "-c" "bash ./upload_dist.sh"]
aws_s3_bucket_object.vweather (local-exec): Completed 25.2 KiB/928.2 KiB (243.1 KiB/s) with 4 file(s) remaining
aws_s3_bucket_object.vweather (local-exec): Completed 150.5 KiB/928.2 KiB (1.3 MiB/s) with 4 file(s) remaining
aws_s3_bucket_object.vweather (local-exec): upload: ../dist/js/chunk-vendors.43d5126b.js to s3://vweather-2020082402/js/chunk-vendors.43d5126b.js

aws_s3_bucket_object.vweather: Creation complete after 1s [id=someobject]



Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

6. Confirm.

oyj@controller:~/prac/test/awsverless/vue-weather/terra$ aws s3 ls vweather-2020082402
                           PRE css/
                           PRE img/
                           PRE js/
2020-08-24 03:01:39       4286 favicon.ico
2020-08-24 03:01:39        730 index.html


Othere example)

 

Thanks for reading!^^

No comments:

Post a Comment