Terraform de is written in the HarshiCorp Configuration Language (HCL) in files with extestion .tf.HCL is a declarative language. You describe what you want and terraform will figure out how to handle it.
Terrafrom can be used to create infrastructure across a wide variety of platforms eg AWS,Google, DigitalOcean etc. In Terrafrom these are called providers.
In my previous blog i showed you how to create an EC2 instance on AWS. Today we will be looking at running a web server on our instance that can respond to HTTP request.
In this example we will get an EC2 Instance to run a script. Since its a one liner we will use busybox and plain Ubuntu 20.04 AMI. We shall run the "hello world!" script as part of the ec2 Instance's User Data
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "example" {
ami = "ami-0735c191cf914754d"
instance_type = "t3.micro"
vpc_security_group_ids = [aws_security_group.instance.id]
tags = {
Name = "mk-terraform-example"
}
user_data = <<-EOF
#!/bin/bash
echo "Hello, World" > index.html
nohup busybox httpd -f -p 8080 &
EOF
user_data_replace_on_change = true
}
resource "aws_security_group" "instance" {
name = "mk-terraform-security-group"
ingress {
from_port = 8080
to_port = 8080
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
Note:
user_data_replace_on_changeparamater is set to true so that when User Data changes and you apply on terraform it will terminate the original instance and create a new one.
In the code above we have introduced a new resource, security group to allow the EC2 instance to receive traffic on port 8080.
resource "aws_security_group" "instance" {
name = "mk-terraform-security-group"
ingress {
from_port = 8080
to_port = 8080
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
The code above creates a new resource called mk-terraform-security-group. this code specifies that this group allows incoming TCP request on port 8080 from all IP ranges.
After creating the security group, we passed the ID of the security group into the vpc_security_group_ids.
vpc_security_group_ids = [aws_security_group.instance.id]
resource "aws_instance" "example" {
ami = "ami-0735c191cf914754d"
instance_type = "t3.micro"
vpc_security_group_ids = [aws_security_group.instance.id]
tags = {
Name = "mk-terraform-example"
}
user_data = <<-EOF
#!/bin/bash
echo "Hello, World" > index.html
nohup busybox httpd -f -p 8080 &
EOF
user_data_replace_on_change = true
}
Top comments (0)