How to get the exist cluster by name?

27 Views Asked by At

I am using CDK and would like to use the exist cluster(for ECS)

I try this, however it shows,

error such as Property 'fromClusterName' does not exist on type 'typeof Cluster'. Did you mean 'fromClusterArn'?

const clusterName = "mycluster"
const cluster = ecs.Cluster.fromClusterName(this, "StCluster", {
  clusterName: clusterName
});

Yet, I want to get the cluster by name not arn

I guess I should take arn by name in advance?

I am cheking this document, there is no method to get Cluster by name

https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.Cluster.html

How can I do this?

1

There are 1 best solutions below

2
Wesley Cheek On BEST ANSWER

You can use fromClusterAttributes but you will also need to have the vpc the cluster is in. You can import it if you know the vpc id.

fromClusterAttributes is preferred over fromClusterArn as it also gives access to the vpc and other properties.

const clusterName = "mycluster";
const vpcID = "12345abcde";

const myVpc = ec2.Vpc.fromVpcAttributes(this, "iVPC", {
  vpcId: vpcID,
// For example
  availability_zones: ["us-east-1a"]
});

const cluster = ecs.Cluster.fromClusterAttributes(this, "iCluster", {
  vpc: myVpc,
  clusterName: clusterName
});