DEV Community

Hemant Patil
Hemant Patil

Posted on

Automation of creating an EC2 instances with the help of “data” key word in terraform.

We all know with the help of terraform we can create infra or resources from different cloud providers ( AWS , Azure , GCP ) , for that we need to authenticate terraform and your cloud provider , for example in terms authenticating both terraform and AWS in order to create resource with the help of code ( hcl language ) we need to use " aws configure " command , after that it will ask set of values that include AceesKey id , Security AccessKey id , region and output type ( mainly json ) and after that you need to confirm it by writing the command " aws sts get-caller-identity " it will show values of your account.

Suppose if we want to create a EC2 instances with ubuntu OS , then we need to focus on 3 main things , those are instance type ( size ) , AMI ( amazon machine image ) , etc.

Today I will explain how we can create EC2 instace with hardcoded values and without hard coded.

When we are ceating with hard code values , then we need to write every value of an EC2 insstances. for example

resource "aws_insace" "web_server" {
ami = here we mention ami id.
instace_type = here we mention type of instance you need

}

So the problem with this method is that we need to write values manually for example here we need to write ami id , instace type manually so its not automation.

There is another method with the help of that we can easily craete an EC2 instance without or less hardcore values , here we use "data" keyword , the use of this keyword is that it will fetches info from AWS so there is no need of hardcode values.

for example

data "aws_ami" "latest_al2023" {
most_recent = true
owners = ["amazon"]

filter {
name = "name"
values = ["al2023-ami-2023.*-x86_64"]
}
}

here we are fetching most recent instance info from AWS to create EC2 instance , we need to use filter to describe which type of instance we need, In this I'm asking AWS create latest 2023 EC2 instances with x86_64 computing architecture, and later we can use this info resource filed to create EC2 instances.

for example

resource "aws_instance" "web_server" {
ami = This value is fetched from keyword "data"
instance_type = "t3.micro"
tags = {
Name = "SRE-Automated-Web"
ManagedBy = "Terraform"
}
}
Why I like this: By using the data keyword, Terraform "queries" AWS for the most recent image. It makes our infrastructure more reliable and saves us from searching for IDs in the console.

Top comments (0)