Terraform 基础
Definition
Use Infrastructure as COde to provision and manage any cloud, infrastructure, or service.
Requirements
- An AWS account
Setup
Terraform CLI
VS code Editor
Providers
Commands
Init project
terraform init # Init all dependencies
Deploy
terraform plan # Try running "terraform plan" to see any changes that are required for your infrastructure.
terraform apply # Apply to run codes
terraform apply --auto-approve
terraform apply --target [resource_id]
terraform apply -var-file="example.tfvars" # Specify variable from .tfvars file
terraform destroy
terraform destroy --target [resource_id]
terraform destroy -var "subnet_prefix=10.0.100.0/24" # Specify varaible from command line
Monitor
terraform state list
terraform state show [resource_id]
terraform refresh
main.tf
output "server_public_ip" {
value = aws_eip.one.public_ip
}
output "server_private_ip" {
value = aws_instance.web-server-instance.id
}
output "server_id" {
value = aws_instance.web-server-instance.private_ip
}
Create Env file first then run terraform apply
command
terraform.tfvars
subnet_prefix="10.0.200.0/24"
subnet_prefix_list=["10.0.2.0/24", "10.0.3.0/24"]
tags = {
Name = "lab-terraform-from-env-file"
}
AWS Provider
Configure AWS provider
AWS provider
provider "aws" {
region = "us-east-1"
access_key = "access_key"
secret_key = "secret_key"
}
Ubuntu 24.04
: ami-04b70fa74e45c3917
EC2 resource configure
resource "aws_instance" "my-first-server" {
ami = "ami-04b70fa74e45c3917"
instance_type = "t2.nano"
tags = {
Name = "to-delete"
}
}
Questions
How to apply env file ?
.env.dev.tfvars
AWS_REGION = "us-east-1";
AWS_ACCESS_KEY = "access-key";
AWS_SECRET_KEY = "secret-key";
terraform [command] -var-file=".env.dev.tfvars" # Apply .env.dev.tfvars file
Resource
- Terraform Course - Automate your AWS cloud infrastructure: https://youtu.be/SLB_c_ayRMo?si=HbIJXWHc-9SZtYED