Create AWS S3 and EC2 with Terraform

Before creating this we need some pre-requisite:

  1. AWS IAM USER

  2. AWS CLI

  3. Provider : AWS provider install in terraform

  4. tf file

Step1: Create an IAM USER

  1. Create user with terra-admin name

  1. Attach policy directly: Admin Access
    We are giving admin access for this but not recommended for production

  2. Create User - “Terra-admin”

    Step2: Bind AWS EC2 (CLI) with Terra-Admin “IAM”

  3. Install AWS CLI in EC2 where Terraform is installed:

     curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
     unzip awscliv2.zip
     sudo ./aws/install
    

  4. Connect EC2 CLI with “terra-admin” IAM

    1. Create access key: You need to create an access key with help of “terra-admin”

      1. Now go to AWS CLI and put access key & Secret access key

         aws configure
        

        Successfully configured AWS cli in ec2 Linux

        To check write:

         aws ec2 ls
        

  5. AWS Terraform Provider

Now tell terraform to connect with AWS, with help of installing AWS terraform provider(plugin)

Example: We are using S3 as provider
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket

  1. Paste the code in file $vim terraform.tf

  1. now do $terraform init

We got AWS and local in Hashicorp folder in .terraform

  1. Create a s3.tf file

  1. Now do $terraform plan

  1. Now write command $terraform apply

  2. Go to your “AWS Account” in “S3 Bucket”

    You will successfully get “tws-junoon-batch-amit” in your aws s3 bucket

  3. Now create ec2 with terraform

    resource aws_instance my_instance {
    
            instance_type = "t2.micro"
            ami = "ami-02141377eee7defb9"
                    tags = {
                    Name = "junoon-batch-amit"
                    }
    

    Now do $terraform apply

  4. Now you can find your ec2 instance in Ireland, we have used us-west-1

    This was the basic ec2 with the minimal config in ec2 file

  5. To delete this specific terraform file

    terraform state list
    terrform destroy --target=<name>
    

    After destroy our instance got automatically terminated