Create AWS EC2 instance using Terraform.

Ranjit mohite
2 min readJan 23, 2021

This is an infrastructure as a code, which is equivalent to the AWS CloudFormation, that allows the user to create, update, and version any of the Amazon Web Services (AWS) infrastructure.

Why Terraform?

Terraform utilizes the cloud provider APIs (Application programming interfaces) to provision infrastructure, hence there’re no authentication techniques after, what the customer is using with the cloud provider already. This could be considered as one of the best option, in terms of maintainability, security and ease-of-use.

Problem:

Engineers would need instances to run some scripts, creating instances and associated policies manually is time consuming.

The motivation behind this post is to, illustrate an example of:

  1. Create a security group with inbound(22, 8080), outbound(3306, 6379) ports open
  2. Create a IAM Role — Access to s3, read and write to a selected bucket
  3. Create EC2 instance attaching the Security group and IAM role create in step 1 and 2

Solution:

  1. Create a security group with inbound(22, 8080), outbound(3306, 6379) ports open

The terraform script:

https://github.com/ranjitm10/terraform_IaC_Assignment/blob/main/aws.tf

2. Create a IAM Role — Access to s3, read and write to a selected bucket

The terraform script:

https://github.com/ranjitm10/terraform_IaC_Assignment/blob/main/iam.tf

3. Create EC2 instance attaching the Security group and IAM role create in step 1 and 2

The following commands should be executed from the terminal in the respective order within the directory where the scripts are being saved.

  1. Initializing a new or an existing Terraform configuration
terraform init

2. Generate and show an execution plan from the resources we’re trying to provision

terraform plan

3. Validating the Terraform files

terraform validate

4. Builds or changes the infrastructure

terraform apply

The complete list of commands are available here.

Complete source-code is available here for grab:

Thankyou !!

--

--