How to create an EC2 instance with user_data
- Define your Terraform configuration: Create a
.tf
file, for example,ec2_instance.tf
, and define your EC2 instance configuration along with user data:
provider "aws" {
region = "your_aws_region"
}
resource "aws_instance" "example" {
ami = "your_ami_id"
instance_type = "t2.micro"
key_name = "your_key_pair_name"
security_groups = ["your_security_group_name"]
subnet_id = "your_subnet_id"
user_data = <<-EOF
#!/bin/bash
# Update package repositories
apt-get update -y
# Install nginx
apt-get install nginx -y
# Start nginx service
systemctl start nginx
# Enable nginx to start on boot
systemctl enable nginx
EOF
}
Here is the Terraform code to create the ec2 instance on the aws.
Here is the aws Instance created on the aws console.
Here is the system log the userdata commands executed while creating the container.
The service status of the nginx was successfully running on the instance.
Accessed the nginx using the IP of the address.
How to Create AWS EC2 using Terraform?
AWS EC2 (Elastic Compute Cloud) is a web service provided by Amazon Web Services (AWS) that allows users to launch and oversee virtual servers, known as examples, in the cloud. It gives an adaptable and versatile foundation for running different sorts of applications and jobs. With Terraform EC2, clients have unlimited authority over their virtual servers, including the capacity to pick the sort, operating system, and storage options of each instance.
Terraform is an open-source framework and code instrument created by HashiCorp. It empowers clients to characterize and arrange framework assets using a definitive language. Terraform upholds numerous cloud suppliers, including AWS, Azure, and Google Cloud Platform, allowing users to deal with their infrastructure reliably across various stages.