Terraform AWS ECS 模块使用教程
1. 项目的目录结构及介绍
Terraform AWS ECS 模块的目录结构如下:
terraform-aws-ecs/
├── examples/
│ ├── complete/
│ ├── ec2/
│ ├── fargate/
│ └── fargate-public/
├── modules/
│ ├── ecs-cluster/
│ ├── ecs-service/
│ └── ecs-task-definition/
├── README.md
├── main.tf
├── variables.tf
├── outputs.tf
└── versions.tf
目录结构介绍
- examples/: 包含多个示例项目,展示了如何在不同场景下使用 ECS 模块。
- complete/: 完整示例,包含所有组件。
- ec2/: 使用 EC2 实例的示例。
- fargate/: 使用 Fargate 的示例。
- fargate-public/: 使用 Fargate 并公开服务的示例。
- modules/: 包含 ECS 模块的核心组件。
- ecs-cluster/: ECS 集群模块。
- ecs-service/: ECS 服务模块。
- ecs-task-definition/: ECS 任务定义模块。
- README.md: 项目说明文档。
- main.tf: 主配置文件。
- variables.tf: 变量定义文件。
- outputs.tf: 输出定义文件。
- versions.tf: Terraform 和提供者版本定义文件。
2. 项目的启动文件介绍
main.tf
main.tf
是项目的主配置文件,定义了 ECS 集群、服务和任务定义的资源。以下是一个简化的示例:
module "ecs" {
source = "terraform-aws-modules/ecs/aws"
name = "my-ecs-cluster"
container_insights = true
capacity_providers = ["FARGATE", "FARGATE_SPOT"]
default_capacity_provider_strategy = [
{
capacity_provider = "FARGATE_SPOT"
weight = 1
}
]
services = {
my-service = {
name = "my-service"
task_definition = module.ecs_task_definition.task_definition_arn
desired_count = 2
}
}
}
module "ecs_task_definition" {
source = "terraform-aws-modules/ecs/aws//modules/ecs-task-definition"
family = "my-task-definition"
container_definitions = jsonencode([
{
name = "my-container"
image = "nginx:latest"
essential = true
portMappings = [
{
containerPort = 80
hostPort = 80
}
]
}
])
}
variables.tf
variables.tf
定义了项目中使用的变量,例如:
variable "name" {
description = "The name of the ECS cluster"
type = string
default = "my-ecs-cluster"
}
variable "container_insights" {
description = "Enable Container Insights"
type = bool
default = true
}
outputs.tf
outputs.tf
定义了项目的输出,例如:
output "cluster_name" {
description = "The name of the ECS cluster"
value = module.ecs.cluster_name
}
output "service_name" {
description = "The name of the ECS service"
value = module.ecs.services["my-service"].name
}
3. 项目的配置文件介绍
versions.tf
versions.tf
定义了 Terraform 和提供者的版本要求,例如:
terraform {
required_version = ">= 1.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~