Terraform 项目:简单 EC2 + 安全组
Source: Dev.to
项目结构
terraform-project/
│── main.tf
│── variables.tf
│── outputs.tf
│── providers.tf
│── terraform.tfvars
│── modules/
│ └── ec2/
│ ├── main.tf
│ ├── variables.tf
│ └── outputs.tf
└── README.md
providers.tf
Defines AWS provider + region.
定义 AWS 提供商 + 区域。
terraform {
required_version = ">= 1.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = var.aws_region
}
variables.tf
All input variables.
所有输入变量。
variable "aws_region" {
description = "AWS region"
type = string
default = "us-east-2"
}
variable "instance_type" {
description = "EC2 instance size"
type = string
default = "t2.micro"
}
variable "project_name" {
description = "Tag for resources"
type = string
default = "tf-demo"
}
main.tf
Calls module and passes variables.
调用模块并传递变量。
module "ec2_demo" {
source = "./modules/ec2"
instance_type = var.instance_type
project_name = var.project_name
}
outputs.tf
output "ec2_public_ip" {
description = "Public IP of EC2"
value = module.ec2_demo.public_ip
}
output "ec2_id" {
description = "EC2 Instance ID"
value = module.ec2_demo.instance_id
}
terraform.tfvars (optional inputs)
aws_region = "us-east-2"
instance_type = "t2.micro"
project_name = "students-demo"
Module: modules/ec2/main.tf
Creates a security group and an EC2 instance with tags.
创建安全组和带标签的 EC2 实例。
resource "aws_security_group" "demo_sg" {
name = "${var.project_name}-sg"
description = "Allow SSH"
ingress {
description = "SSH"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_instance" "demo" {
ami = "ami-0c02fb55956c7d316" # Amazon Linux 2 us-east-2
instance_type = var.instance_type
security_groups = [aws_security_group.demo_sg.name]
tags = {
Name = "${var.project_name}-ec2"
}
}
Module: modules/ec2/variables.tf
variable "instance_type" {
type = string
}
variable "project_name" {
type = string
}
Module: modules/ec2/outputs.tf
output "public_ip" {
value = aws_instance.demo.public_ip
}
output "instance_id" {
value = aws_instance.demo.id
}
如何运行(教学步骤)
-
Initialize Terraform
初始化 Terraformterraform init -
Validate configuration
验证配置terraform validate -
Review the execution plan
查看执行计划terraform plan -
Apply the configuration
应用配置terraform apply -auto-approve -
View output values
查看输出值terraform output -
Destroy the infrastructure when finished
完成后销毁基础设施terraform destroy -auto-approve
学生通过此项目可以学习的内容
| Component | What it Teaches |
|---|---|
providers.tf | 提供商设置、版本约束 |
variables.tf | 变量、类型、默认值 |
terraform.tfvars | 覆盖默认值 |
main.tf | 调用模块 |
modules/ | 真实生产设计 |
| EC2 + SG | 简单的基础设施供应 |
outputs.tf | 导出值 |
Terraform workflow (init, plan, apply, destroy) | 完整的生命周期管理 |