Reputation: 137
I want to create CloudWatch CPU utilization monitoring of EC2 instances using CDK and I want to create an alarm for each instance which will trigger SNS notification if the threshold is exceeded.
Instead of hard coding those instance ids, I would like to fetch them directly from AWS and save them into an array. The problem is that I didn't find any method which would allow me to list all EC2 instances. Ideally I would like to use method similar to vpc.fromLookup but for EC2, does this even exist?
Upvotes: 1
Views: 4199
Reputation: 3564
You have two options, but it depends on your exact use case.
If you're talking about instances that you're creating in the same stack, the AWS CDK ec2 Instance
type, has a property instanceId
. This instance id will be added in the template as a reference to the correlated Instance
resource and CloudFormation will resolve this when deploying.
If you're talking about creating a different stack and just wanting to fetch the currently running instances, you have to use the AWS SDK. You can use the ec2.describeInstances
method to find all instances and get the instance IDs that way.
Upvotes: 4