terraformterraform-provider-awsterraform-template-file

terraform copy/upload files to aws ec2 instance


We have cronjob and shell script which we want to copy or upload to aws ec2 instance while creating instance using terraform.

we tried

  1. file provisioner : but its not wokring , and read this option does not work with all terraform version
      provisioner "file" {
        source      = "abc.sh"
        destination = "/home/ec2-user/basic2.sh"
      }
  1. tried data template file option
    data "template_file" "userdata_line" {
      template = <<EOF
    #!/bin/bash
    mkdir /home/ec2-user/files2
    cd /home/ec2-user/files2
    sudo touch basic2.sh
    sudo chmod 777 basic2.sh
    base64 basic.sh |base64 -d >basic2.sh
    EOF
    }

tried all option but none of them working.
could u please help or advise .
I am new to terraform so struggling on this from long time.


Solution

  • somehow in corporate domain none of the options worked. but finally we were able to copy /download files using s3 bucket.

    create s3.tf to upload this files basic2.sh

    resource "aws_s3_bucket" "demo-s3" {
    
      bucket = "acom-demo-s3i-<bucketID>-us-east-1"
      acl    = "private"
    
    
      tags {
        Name = "acom-demo-s3i-<bucketID>-us-east-1"
        StackId = "demo-s3"
      }
    }
    
    resource "aws_s3_bucket_policy" "s3_policy" {
    
      bucket = "${aws_s3_bucket.demo-s3.id}"
    
      policy = <<EOF
    {
        "Version": "2009-10-17",
        "Statement": [
                {
                "Sid": "Only allow specific role",
                "Effect": "allow",
                "Principal":{ "AWS": ["arn:aws:iam::<bucketID>:role/demo-s3i"]},
                "Action":  "s3:*",
                "Resource": [
              "arn:aws:s3:::acom-demo-s3i-<bucketID>-us-east-1",
              "arn:aws:s3:::acom-demo-s3i-<bucketID>-us-east-1/*"
                ]
    
            }
        ]
    }
    EOF
    }
    
    
    resource "aws_s3_bucket_object" "object" {
      bucket = "acom-demo-s3i-<bucketID>-us-east-1"
      key    = "scripts/basic2.sh"
      source = "scripts/basic2.sh"
      etag = "${filemd5("scripts/basic2.sh")}"
    }
    

    and then declared file download portion in other tpl file.

     aws s3 cp s3://acom-demo-s3i-<bucketID>-us-east-1/scripts/basic2.sh /home/ec2-user/basic2.sh