AWS JS SDK中waitUntilInstanceRunning方法执行挂起问题求助
解决AWS SDK v3中waitUntilInstanceRunning挂起的问题
你的代码里waitUntilInstanceRunning的调用方式有误,这是导致方法挂起的核心原因:
第一个参数必须传入已初始化的EC2Client实例
waitUntilInstanceRunning的第一个参数需要AWS客户端实例或包含客户端的配置对象,你传了空对象{},导致它无法发起有效的EC2状态查询请求——哪怕控制台已经显示实例处于运行状态,方法也拿不到状态更新,自然会一直挂起。查询参数建议直接用InstanceIds而非Filters
虽然用Filters能匹配实例ID,但直接传入InstanceIds参数更简洁,也能避免Filter格式可能带来的隐性问题。
修正后的代码片段:
// 确保你已经初始化了ec2Client实例,比如: // const ec2Client = new EC2Client({ region: '你的区域' }); const startEC2Command = new StartInstancesCommand({ InstanceIds }); const startEC2Response = await ec2Client.send(startEC2Command); // 正确调用waitUntilInstanceRunning:第一个参数传ec2Client,第二个参数传InstanceIds await waitUntilInstanceRunning(ec2Client, { InstanceIds: [STAGING_API_SERVER_EC2_ID] }); // 后续注册目标组的代码保持不变 const registerTargetsCommand = new RegisterTargetsCommand({ TargetGroupArn: STAGING_TG_ARN, Targets: [ { Id: STAGING_API_SERVER_EC2_ID, Port: 4000, } ] }); const registerTargetResponse = await elbv2Client.send(registerTargetsCommand);
额外说明:
- 如果你需要自定义等待超时或轮询间隔,可以在第一个参数位置传入带配置的对象,比如:
await waitUntilInstanceRunning( { client: ec2Client, maxWaitTime: 300 }, // 最大等待300秒 { InstanceIds: [STAGING_API_SERVER_EC2_ID] } ); - 确认EC2实例的IAM权限允许SDK调用
DescribeInstances接口,否则也会导致等待失败。
内容的提问来源于stack exchange,提问作者MorayM
相关产品推荐
相关产品推荐

