4-结构化配置示例

前面的单文件配置虽然也能创建资源,但是不便于维护,在实际的环境中,通常把配置结构化。例如:

  • main.tf → 主配置文件(资源定义)

  • variables.tf → 变量定义

  • outputs.tf → 输出定义

这样结构清晰,适合团队使用。下面是一个完整的项目结构(基于 ECS + EIP 的需求,使用 count 模式批量创建)。

项目目录结构:

terraform-alicloud-ecs/
├── main.tf
├── variables.tf
├── outputs.tf

main.tf

terraform {
  required_providers {
    alicloud = {
      source  = "aliyun/alicloud"
      version = ">= 1.200.0"
    }
  }
  required_version = ">= 1.1.0"
}

provider "alicloud" {
  region     = var.region
  access_key = var.access_key
  secret_key = var.secret_key
}

# 创建 ECS 实例
resource "alicloud_instance" "ecs" {
  count           = var.ecs_count
  instance_name   = "${var.ecs_name_prefix}-${count.index + 1}"
  image_id        = var.image_id
  instance_type   = var.instance_type
  security_groups = [var.security_group_id]
  vswitch_id      = var.vswitch_id
  internet_max_bandwidth_out = 0
}

# 创建 EIP
resource "alicloud_eip" "eip" {
  count                = var.ecs_count
  bandwidth            = var.eip_bandwidth
  internet_charge_type = "PayByTraffic"
}

# 绑定 ECS 和 EIP
resource "alicloud_eip_association" "assoc" {
  count        = var.ecs_count
  instance_id  = alicloud_instance.ecs[count.index].id
  allocation_id = alicloud_eip.eip[count.index].id
}

variables.tf

# 基础配置
variable "region" {
  description = "阿里云区域"
  type        = string
  default     = "cn-beijing"
}

variable "access_key" {
  description = "阿里云 Access Key"
  type        = string
}

variable "secret_key" {
  description = "阿里云 Secret Key"
  type        = string
}

# ECS 配置
variable "ecs_count" {
  description = "要创建的 ECS 数量"
  type        = number
  default     = 2
}

variable "ecs_name_prefix" {
  description = "ECS 实例名前缀"
  type        = string
  default     = "my-ecs"
}

variable "image_id" {
  description = "ECS 镜像 ID"
  type        = string
  default     = "ubuntu_24_04_x64_20G_alibase_20250722.vhd"
}

variable "instance_type" {
  description = "ECS 实例规格"
  type        = string
  default     = "ecs.t5-lc1m1.small"
}

variable "security_group_id" {
  description = "安全组 ID"
  type        = string
}

variable "vswitch_id" {
  description = "交换机 ID"
  type        = string
}

# EIP 配置
variable "eip_bandwidth" {
  description = "EIP 带宽"
  type        = number
  default     = 5
}

outputs.tf

output "ecs_private_ips" {
  description = "ECS 私网 IP 列表"
  value       = [for i in alicloud_instance.ecs : i.private_ip]
}

output "ecs_public_ips" {
  description = "ECS 公网 IP 列表(EIP)"
  value       = [for i in alicloud_eip.eip : i.ip_address]
}

执行步骤:

1. 进入项目目录

cd terraform-alicloud-ecs

2. 初始化

terraform init

3. 规划执行计划

terraform plan -var="access_key=你的AK" -var="secret_key=你的SK" -var="security_group_id=sg-xxx" -var="vswitch_id=vsw-xxx"

4. 应用

terraform apply -var="access_key=你的AK" -var="secret_key=你的SK" -var="security_group_id=sg-xxx" -var="vswitch_id=vsw-xxx" -auto-approve

执行完成后,会输出私网 IP 和公网 IP 列表。

posted @ 2025-09-10 14:39  羊脂玉净瓶  阅读(4)  评论(0)    收藏  举报