How do I correctly use waitUntilInstanceRunning in the JS SDK?

0

I'm writing a small function to start and stop our staging environment outside of office hours, based on this article.

Currently my code looks like this - edited for brevity.

import { EC2Client, StartInstancesCommand, waitUntilInstanceRunning } from '@aws-sdk/client-ec2';
import { ElasticLoadBalancingV2Client, RegisterTargetsCommand } from "@aws-sdk/client-elastic-load-balancing-v2";

// ...get the InstanceIds of EC2 instances to start...

const startEC2Command = new StartInstancesCommand({ InstanceIds });
const startEC2Response = await ec2Client.send(startEC2Command);

await waitUntilInstanceRunning({}, {
  Filters: [
    {
      Name: 'instance-id',
      Values: [
        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);
// ... starts more resources, RDS etc.

Previously, my code was failing because register targets only works if the instance is in the running state, so I added waitUntilInstanceRunning to ensure that the instance is running before it tries to register with the target group. For some reason, the script hangs at the line await waitUntilInstanceRunning, even when the console shows that the instance is in fact running.

The documentation for this command is sparse to say the least, so does anyone know how to use it correctly?

Thanks!

MorayM
asked 8 months ago298 views
1 Answer
0

Hi, I personally wait until both system and instance status checks are fine before doing anything with an EC2 instance that I start.

See https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-system-instance-status-check.html#types-of-instance-status-checks

In Java, I use DescribeInstanceStatusRequest to obtain a list of those status checks and I wait until they are ok. In particular, I wait for PASSED on status REACHABILITY.

Best,

Didier

profile pictureAWS
EXPERT
answered 8 months ago
  • Yes I understand that but the target group has health checks on so even if the instance has started the target group will be able to wait until it's healthy without the need for writing more checks in the code. Specifically though I was hoping to be able to use a built-in feature of the EC2 SDK to wait until the instance is running rather than having to poll it's state constantly.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions