Monday, 8 July 2024

Getting Started With Terraform

 Let’s create a simple Terraform configuration to launch an EC2 instance on AWS on a Linux VM.

 

1. Set Up AWS Provider: 

 On shell - 

 

mkdir my-terraform-project
cd my-terraform-project

 

 Create a file named main.tf and add the following content: 

 

provider "aws" {
region = "us-west-2"
}

 

2. Define an EC2 Instance Resource:

In the same main.tf file, add the following resource definition:


resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0" # Example AMI ID
instance_type = "t2.micro"

tags = {
Name = "example-instance"
}
}

 

3. Initialize Terraform:

Initialize your Terraform project, which will download the necessary provider plugins:

 
terraform init


4. Format and Validate Configuration:

Format your configuration files for readability:


terraform fmt


Validate the configuration for syntax errors:

terraform validate


5. Preview and Apply Changes:

Preview the changes Terraform will make to your infrastructure:


terraform plan


Apply the changes to create the EC2 instance:


terraform apply


When prompted, type yes to confirm.


 

6. Verify the Instance:

 

Go to the AWS Management Console and navigate to the EC2 dashboard to see your new instance running.


7. Managing State


Terraform’s state file, terraform.tfstate, keeps track of the resources it manages. This file is crucial for planning and applying changes accurately.
It’s recommended to store your state file in a remote backend (e.g., AWS S3) for collaboration and reliability.

8. Cleaning Up


To destroy the resources created by your configuration, use the destroy command:


terraform destroy


Type yes when prompted to confirm the destruction of resources.
 

 

 

 

 

 

No comments:

Post a Comment