Everett Toews
Everett Toews

Reputation: 10974

Get all Services from a Fargate Cluster in AWS CDK

I need to be able to get all of the Services given only the Cluster construct in AWS CDK (TypeScript in this example but any language will do).

Something like the following.

import { Cluster, FargateService } from '@aws-cdk/aws-ecs';

private updateClusterServices(cluster: Cluster): void {
  for (const service of cluster.getServices()) {
    // do something with service
  }
}

However there is no such getServices() method on Cluster.

Is there another way to do this or is this fundamentally not possible with CDK for some reason?

Upvotes: 0

Views: 736

Answers (1)

Everett Toews
Everett Toews

Reputation: 10974

Turns out there is a way to do something like this if you at least have the Service name too.

import { Cluster, FargateService } from '@aws-cdk/aws-ecs';

private updateClusterServices(scope: Construct, cluster: Cluster, serviceName: string): void {
  const service = FargateService.fromFargateServiceAttributes(scope, 'FindFargateServices', {
    cluster: cluster,
    serviceName: serviceName,
  });

  console.log(service.serviceArn);

  // do something with service
}

The result appears to be the TaskSet serviceArn.

arn:aws:ecs:ap-southeast-2:1234567890:service/backend

From comparing it with the CLI output.

$ aws ecs describe-services --cluster blue-green-cluster --services backend
{
    "services": [
        {
            "serviceArn": "arn:aws:ecs:ap-southeast-2:1234567890:service/blue-green-cluster/backend",
            "serviceName": "backend",
            "clusterArn": "arn:aws:ecs:ap-southeast-2:1234567890:cluster/blue-green-cluster",
...
            "taskSets": [
                {
                    "taskSetArn": "arn:aws:ecs:ap-southeast-2:1234567890:task-set/blue-green-cluster/backend/ecs-svc/2091139980078414071",
                    "serviceArn": "arn:aws:ecs:ap-southeast-2:1234567890:service/backend",
                    "clusterArn": "arn:aws:ecs:ap-southeast-2:1234567890:cluster/blue-green-cluster",
...
}

Upvotes: 1

Related Questions