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

如何通过Terraform获取AWS API Gateway IP地址以配置安全组规则

解决方案

AWS 公有API Gateway没有固定的公网IP地址,其IP属于对应区域AWS服务的动态IP池,无法直接通过aws_api_gateway_deployment资源的属性获取单个固定IP。以下是两种可实现EC2仅与指定API Gateway通信的实现方案:

方案1:使用VPC端点实现内网通信(推荐)

该方案流量全部走AWS内网,安全性更高,规则配置更稳定可控。

  • 首先为API Gateway创建接口类型的VPC端点,指定EC2所在的VPC、子网和安全组
  • 配置API Gateway的资源策略,仅允许通过该VPC端点调用接口
  • EC2的安全组入站/出站规则直接放行该VPC端点的安全组ID即可
    对应Terraform示例代码:
# 获取当前区域信息
data "aws_region" "current" {}

# 创建API Gateway VPC端点
resource "aws_vpc_endpoint" "apigw" {
  vpc_id              = "替换为你的VPC ID"
  service_name        = "com.amazonaws.${data.aws_region.current.name}.execute-api"
  vpc_endpoint_type   = "Interface"
  security_group_ids  = ["替换为VPC端点关联的安全组ID"]
  subnet_ids          = ["替换为EC2所在子网ID列表"]
  private_dns_enabled = true
}

# 配置API Gateway访问策略,仅允许指定VPC端点调用
resource "aws_api_gateway_rest_api_policy" "api_policy" {
  rest_api_id = aws_api_gateway_rest_api.api.id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect    = "Allow"
        Principal = "*"
        Action    = "execute-api:Invoke"
        Resource  = "${aws_api_gateway_rest_api.api.arn}/*/*/*"
        Condition = {
          StringEquals = {
            "aws:SourceVpce" = aws_vpc_endpoint.apigw.id
          }
        }
      }
    ]
  })
}

# 配置EC2安全组入站规则,放行API Gateway流量
resource "aws_security_group_rule" "apigw_inbound" {
  type                     = "ingress"
  from_port                = 替换为EC2提供服务的端口
  to_port                  = 替换为EC2提供服务的端口
  protocol                 = "tcp"
  source_security_group_id = aws_vpc_endpoint.apigw.security_group_ids[0]
  security_group_id        = "替换为EC2关联的安全组ID"
}

方案2:公网场景下配置动态IP段规则

如果业务必须走公网通信,可以调用AWS官方公开的IP范围数据源,筛选对应区域的API Gateway服务IP段配置到安全组。
对应Terraform示例代码:

# 获取当前区域API Gateway的公网IP段
data "aws_ip_ranges" "apigw" {
  regions  = [data.aws_region.current.name]
  services = ["API_GATEWAY"]
}

# 配置EC2安全组入站规则,放行对应区域所有API Gateway IP段
resource "aws_security_group_rule" "apigw_inbound_public" {
  type              = "ingress"
  from_port         = 替换为EC2提供服务的端口
  to_port           = 替换为EC2提供服务的端口
  protocol          = "tcp"
  cidr_blocks       = data.aws_ip_ranges.apigw.cidr_blocks
  security_group_id = "替换为EC2关联的安全组ID"
}

注意事项

  • 方案2的IP段会由AWS不定期更新,建议配置自动化流程定期同步更新安全组规则,避免IP段变更导致业务中断
  • 如果你的API Gateway配置了自定义域名、WAF或者CloudFront,需要对应调整IP段筛选的服务类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 23:15:00