Create AWS S3 and EC2 with Terraform
Before creating this we need some pre-requisite:
AWS IAM USER
AWS CLI
Provider : AWS provider install in terraform
tf file
Step1: Create an IAM USER
- Create user with terra-admin name
Attach policy directly: Admin Access
We are giving admin access for this but not recommended for productionCreate User - “Terra-admin”
Step2: Bind AWS EC2 (CLI) with Terra-Admin “IAM”
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
Connect EC2 CLI with “terra-admin” IAM
Create access key: You need to create an access key with help of “terra-admin”
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
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
- Paste the code in file
$vim terraform.tf
- now do
$terraform init
We got AWS and local in Hashicorp folder in .terraform
- Create a s3.tf file
- Now do
$terraform plan
Now write command
$terraform apply
Go to your “AWS Account” in “S3 Bucket”
You will successfully get “tws-junoon-batch-amit” in your aws s3 bucket
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
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
To delete this specific terraform file
terraform state list terrform destroy --target=<name>
After destroy our instance got automatically terminated