我正在尝试编写一个自动化脚本(在 trypscript 中)升级 AMI 映像,为此我会将实例数量加倍(即在自动缩放组中进行缩放),这样我就可以得到与新 AMI 映像完全相同数量的新实例,然后我将在新实例上部署我的应用程序,但我不知道新实例何时准备就绪,aws ec2 sdk 或 aws 自动缩放组内是否有回调通知程序
此刻我正在努力
const timer = setTimeout(() => { if (newInstanceIds.length >= currentDesiredNumberOfInstances) clearTimeout(timer) const asgAfterUpdate = await getAutoScalingGroup(asgName,credentials,region); const allInstances = {}.AutoScalingGroups![0].Instances; if (allInstances.length >= myNewScalingSize) clearTimeout(timer) }, 10000);
这些是我正在尝试使用的sdk (@aws-sdk/client-auto-scaling": "^3.635.0", "@aws-sdk/client-ec2": "^3.620.0"
您可以使用 waitUntilInstanceStatusOk
轮询 EC2 实例的状态类似这样的事情:
import { EC2Client, DescribeInstanceStatusCommand, waitUntilInstanceStatusOk } from "@aws-sdk/client-ec2";
import { AutoScalingClient, DescribeAutoScalingGroupsCommand } from "@aws-sdk/client-auto-scaling";
const ec2Client = new EC2Client({ region });
const asgClient = new AutoScalingClient({ region });
async function waitForInstances(asgName: string, desiredCount: number) {
let ready = false;
while (!ready) {
const asgResponse = await asgClient.send(new DescribeAutoScalingGroupsCommand({ AutoScalingGroupNames: [asgName] }));
const instances = asgResponse.AutoScalingGroups?.[0].Instances || [];
// Filter out instances that are still pending
const instanceIds = instances.filter(instance => instance.LifecycleState === 'InService').map(instance => instance.InstanceId);
if (instanceIds.length >= desiredCount) {
ready = true;
// Wait for all instances to pass status checks
for (const instanceId of instanceIds) {
await waitUntilInstanceStatusOk({ client: ec2Client, maxWaitTime: 300, minDelay: 10 }, { InstanceIds: [instanceId] });
}
} else {
await new Promise(res => setTimeout(res, 10000)); // Wait 10 seconds before polling again
}
}
}