Blog 10: Using Terrform to run AWS EC2 Instance
Terraform
Terraform is an open-source infrastructure as code software tool created by HashiCorp. The configurations and settings applied on Terraform code allows us to run a single application or entire datacenter.
Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently. Terraform can manage existing and popular service providers as well as custom in-house solutions.
Using Terrafrom to create AWS EC2 Instance
By using different terraform tags we can create and launch new EC2 instance.
Here, we are defining the provider’s name and region where the Instance will be created.
provider "aws"{
region = "us-west-2"
}
Creating AWS AMI
We will use ubuntu as Linux OS distribution for the AWS AMI. We will define the aws ami(amazon machine image) with latest version. The reference strings is denoted as “ubuntu”.
data "aws_ami" "ubuntu"{
most_recent= true
filter {
name= "name"
values= ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
}
filter{
name= "virtualization-type'
values= ["hvm"]
}
owners = ["<id>"]
}
Creating AWS Instance with AMI
Here, we have defined a AWS EC2 Instance with resource tag aws_instance along with ec2_web as reference that can be called in other resource tags.
In the ami section we have used the reference from the above data for AWS AMI which will create new AWS Instance*.
resource "aws_instance" "ec_2web"{
ami= data.aws_ami.ubuntu.id
instance_type = "t3.micro"
tags= {
Name= "Hello Earth"
}
}
Defining AWS Policy for S3 Bucket
AWS policies are written in JSON format. Thus, we need to write a code that will denote the policies in JSON format. Here, we will write a small code in JSON format that will provide the policy for AWS S3 bucket usage.
First, we create a S3 Bucket with a globally-unique name.
resource "aws_s3_bucket" "buck" {
bucket= "limbu_blog_bucket"
}
Providing Full AWS S3 Access
Now, we will define the policy attached to S3 bucket b providing the S3 bucket name on the bucket section. We can see the action section allows to use every resources with *** option attached to **S3 bucket.
resource "aws_s3_bucket_policy" "buck" {
bucket= aws_s3_bucket.buck.id
policy = <<EOF
{
"Version": "2020-10-17",
"Statement": [
{
"Action": [
"s3:*"
],
"Effect": "Allow"
"Resource": "*"
}
]
}
EOF
}
}