Welcome to the Terraform Basics repository! This guide provides an overview of Terraform's core concepts, commands, examples, and best practices to help you get started with Infrastructure as Code (IaC).
Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp. It allows you to define, deploy, and manage cloud infrastructure in a declarative manner.
- Definition: Plugins to interact with cloud platforms and services.
- Example:
provider "aws" { region = "us-east-1" }
- Definition: Represents infrastructure components like servers, databases, and networks.
- Example:
resource "aws_instance" "example" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" }
- Definition: Makes configurations dynamic and reusable.
- Example:
variable "region" { default = "us-east-1" }
- Tracks the real-world state of your infrastructure (
terraform.tfstate
).
- Groups of reusable Terraform code.
- Displays useful information after infrastructure deployment.
- Example:
output "instance_id" { value = aws_instance.example.id }
Command | Description |
---|---|
terraform init |
Initializes the working directory and downloads provider plugins. |
terraform validate |
Validates the syntax of configuration files. |
terraform plan |
Previews the changes Terraform will make. |
terraform apply |
Builds or modifies infrastructure as per the configuration. |
terraform destroy |
Deletes all resources defined in the configuration. |
Typical Terraform project file structure:
project-folder/
│
├── main.tf # Main configuration file
├── variables.tf # Variable definitions
├── outputs.tf # Output definitions
└── terraform.tfstate # State file (auto-generated)
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "ExampleInstance"
}
}
output "instance_id" {
value = aws_instance.example.id
}
- Initialize Terraform:
terraform init
- Plan Infrastructure:
terraform plan
- Apply Changes:
terraform apply
- Use Variables: Keep configurations dynamic and reusable.
- Organize Code: Separate variables, resources, and outputs into separate files.
- Use Version Control: Track changes in code using Git.
- Remote State Management: Store state files remotely (e.g., AWS S3) for better collaboration.
- Avoid Hardcoding: Use
terraform.tfvars
or environment variables for sensitive data. - Modules: Break down infrastructure into reusable modules.
- Back Up State Files: Always secure your
terraform.tfstate
file.
Feel free to fork this repository, contribute by adding new templates, or create issues for improvements!