You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Terraform AWS ECS模块创建FARGATE_SPOT服务异常问题咨询

问题:Terraform AWS ECS模块创建Fargate Spot服务失败,实际使用普通Fargate

我正在学习Terraform,尝试使用AWS ECS模块创建ECS Fargate Spot服务。执行terraform apply后,集群、服务等资源均在AWS账户中正常创建,但查看服务配置时发现其为普通FARGATE实例,而非预期的FARGATE_SPOT。手动通过AWS UI创建服务时可正常创建Fargate Spot服务。

我的HCL脚本如下:

module "ecs" {
  source  = "terraform-aws-modules/ecs/aws"
  version = "5.7.2"

  cluster_name = "ecs-test"

  fargate_capacity_providers = {
    FARGATE = {
      default_capacity_provider_strategy = {
        weight = 50
      }
    }
    FARGATE_SPOT = {
      default_capacity_provider_strategy = {
        weight = 50
      }
    }
  }

  services = {
    my_app = {
      name          = "my_app_service"
      cpu           = 256
      memory        = 512
      desired_count = 1

      capacity_provider_strategies = [
        {
          capacity_provider = "FARGATE_SPOT"
          base              = 0
          weight            = 1
        }
      ]

      # Task definition
      container_definitions = {
        postgres = {
          cpu       = 256
          memory    = 512
          essential = true
          image     = "my_app_image"

          port_mappings = [
            {
              name          = "my-app-port"
              containerPort = 123
              protocol      = "tcp"
            }
          ]
        }
      }

      # Network
      subnet_ids = [
        "subnet-123",
      ]

      security_group_rules = {
        egress_all = {
          type        = "egress"
          from_port   = 0
          to_port     = 0
          protocol    = "-1"
          cidr_blocks = ["0.0.0.0/0"]
        }
      }

      assign_public_ip = true
    }
  }
}

错误原因

在你使用的Terraform AWS ECS模块(5.7.2版本)中,服务的launch_type参数默认值为FARGATE。当AWS ECS服务同时指定launch_type和capacity_provider_strategies时,launch_type的优先级更高,会直接忽略容量提供商策略配置,导致服务使用普通Fargate实例而非Spot实例。

修正方案

在服务配置中显式设置launch_type = null,让AWS使用你定义的capacity_provider_strategies:

services = {
  my_app = {
    name          = "my_app_service"
    cpu           = 256
    memory        = 512
    desired_count = 1
    # 新增:显式设置launch_type为null,启用容量提供商策略
    launch_type   = null

    capacity_provider_strategies = [
      {
        capacity_provider = "FARGATE_SPOT"
        base              = 0
        weight            = 1
      }
    ]

    # 其余配置保持不变...
  }
}

执行terraform apply后,服务将正确使用FARGATE_SPOT容量提供商。

内容的提问来源于stack exchange,提问作者vegidio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 11:05:56