Terraform部署AWS防火墙项目:EC2实例无法连接问题求助
AWS Network Firewall项目中EC2 SSH/SSM连接超时的Terraform代码排查与修复
核心代码问题分析
1. 受保护子网缺少路由表关联
你的ProtectedWebServerSubnet未关联任何自定义路由表,默认使用VPC主路由表,而主路由表未配置互联网转发规则。即使你在控制台配置了Network Firewall路由,也需要确保受保护子网的路由表指向防火墙端点,同时防火墙所在子网具备到IGW的路由。
修复示例(根据防火墙配置调整路由目标):
# 受保护子网路由表(指向Network Firewall ENI,替换为实际防火墙ENI ID) resource "aws_route_table" "ProtectedSubnetRouteTable" { vpc_id = aws_vpc.InspectionVPC.id route { cidr_block = "0.0.0.0/0" network_interface_id = "your-firewall-eni-id" } tags = { Name = "Protected Subnet Route Table" } } # 关联受保护子网到路由表 resource "aws_route_table_association" "ProtectedSubnetRouteTableAssociation" { subnet_id = aws_subnet.ProtectedWebServerSubnet.id route_table_id = aws_route_table.ProtectedSubnetRouteTable.id }
2. EC2未绑定SSM实例配置文件
你已创建具备SSM权限的实例配置文件,但Terraform代码中的aws_instance.WebServer未关联该配置文件,导致SSM Agent无法获取权限,EC2 Instance Connect无法正常工作。
修复:在EC2资源中添加实例配置文件绑定(替换为你的实例配置文件名称):
resource "aws_instance" "WebServer" { ami = "ami-0f844a9675b22ea32" instance_type = "t2.micro" availability_zone = "us-east-1a" key_name = "Project-Key-Pair" # 绑定SSM实例配置文件 iam_instance_profile = "your-ssm-instance-profile-name" network_interface { device_index = 0 network_interface_id = aws_network_interface.web-server-nic.id } user_data = <<-EOF #!/bin/bash sudo amazon-linux-extras install nginx1 -y sudo systemctl enable nginx sudo systemctl start nginx # 确保SSM Agent运行 sudo systemctl status amazon-ssm-agent || sudo systemctl start amazon-ssm-agent EOF tags = { Name = "Test Workload" } }
3. EIP关联参数冲突
你的aws_eip.ec2_eip同时指定了instance和network_interface字段,会导致Terraform关联异常,需移除其中一个字段。
修复:仅保留网络接口关联:
resource "aws_eip" "ec2_eip" { vpc = true network_interface = aws_network_interface.web-server-nic.id associate_with_private_ip = "10.1.3.4" depends_on = [aws_internet_gateway.InspectionVPCInternetGateway] }
额外排查要点
- 安全组验证:确认
allow_httpssh安全组的入站规则中,你的公网IP(180.191.165.6/32)是否准确,可临时替换为当前公网IP测试。 - 防火墙规则检查:确保Network Firewall允许SSH(22端口)和SSM相关HTTPS(443端口)流量双向通行,尤其是EC2的出站流量需能访问SSM服务。
- VPC端点配置:若无需互联网访问SSM,可配置SSM、EC2 Messages的VPC接口端点,确保受保护子网能访问这些端点。
内容的提问来源于stack exchange,提问作者Eson
相关产品推荐
相关产品推荐

