使用Terraform连接AWS EC2并执行命令时遇超时问题求助
Terraform EC2 Provisioner 超时问题排查与解决
Terraform通过Provisioner执行操作时超时,本质是无法建立SSH连接到EC2实例,按以下步骤排查修复:
1. 补全安全组配置(最常见原因)
你的配置里未指定安全组,默认安全组会拒绝所有外部SSH请求。必须创建允许22端口入站的安全组:
resource "aws_security_group" "web_sg" { name = "web-server-sg" description = "Allow SSH inbound" ingress { from_port = 22 to_port = 22 protocol = "tcp" # 限制为你的公网IP更安全;测试阶段可临时用0.0.0.0/0(不推荐生产环境) cidr_blocks = ["你的公网IP/32"] } egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] } tags = { Name = "Web Server SG" } }
然后在aws_instance资源中关联该安全组:
resource "aws_instance" "web" { # 保留原有配置... vpc_security_group_ids = [aws_security_group.web_sg.id] }
2. 确保实例分配公有IP
如果实例部署在自定义子网中,默认不会自动分配公有IP,需显式开启:
resource "aws_instance" "web" { # 保留原有配置... associate_public_ip_address = true }
3. 修复本地私钥权限
SSH要求私钥文件权限必须为600(仅当前用户可读),否则会拒绝连接,执行以下命令修改权限:
chmod 600 ./example
4. 增加连接超时时间
若本地与AWS区域网络延迟较高,可延长SSH连接超时时间:
connection { type = "ssh" host = self.public_ip user = "ubuntu" private_key = file("./example") timeout = "5m" # 延长至5分钟 }
手动验证连接
Terraform报错后,先手动用SSH连接实例,确认网络和密钥是否正常:
ssh -i ./example ubuntu@<实例公网IP>
修改后的完整配置
provider "aws" { region = "us-west-2" } resource "aws_key_pair" "example" { key_name = "keypair" public_key = file("./example.pub") tags = { Name = "Example Key Pair" } } resource "aws_security_group" "web_sg" { name = "web-server-sg" description = "Allow SSH inbound" ingress { from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = ["你的公网IP/32"] } egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] } tags = { Name = "Web Server SG" } } resource "aws_instance" "web" { ami = "ami-003634241a8fcdec0" instance_type = "t2.micro" key_name = aws_key_pair.example.key_name vpc_security_group_ids = [aws_security_group.web_sg.id] associate_public_ip_address = true tags = { Name = "Example EC2" } connection { type = "ssh" host = self.public_ip user = "ubuntu" private_key = file("./example") timeout = "5m" } provisioner "file" { content = "Hello World!" destination = "/home/ubuntu/example.txt" } }
内容的提问来源于stack exchange,提问作者Darth Vader
相关产品推荐
相关产品推荐

