Search code examples
pythonamazon-web-servicesaws-cdkaws-fargateamazon-ecr

AWS CDK reference existing image on ECR


New to AWS CDK and I'm trying to create a load balanced fargate service with the construct ApplicationLoadBalancedFargateService.

I have an existing image on ECR that I would like to reference and use. I've found the ecs.ContainerImage.from_ecr_repository function, which I believe is what I should use in this case. However, this function takes an IRepository as a parameter and I cannot find anything under aws_ecr.IRepository or aws_ecr.Repository to reference a pre-existing image. These constructs all seem to be for making a new repository.

Anyone know what I should be using to get the IRepository object for an existing repo? Is this just not typically done this way?

Code is below. Thanks in Advance.

from aws_cdk import (
    # Duration,
    Stack,
    # aws_sqs as sqs,
)
from constructs import Construct
from aws_cdk import (aws_ec2 as ec2, aws_ecs as ecs,
                     aws_ecs_patterns as ecs_patterns,
                     aws_route53,aws_certificatemanager,
                     aws_ecr)

class NewStack(Stack):

    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)
        _repo = aws_ecr.Repository(self, 'id1', repository_uri = repo_uri)
        vpc = ec2.Vpc(self, "applications", max_azs=3)     # default is all AZs in region

        cluster = ecs.Cluster(self, "id2", vpc=vpc)

        hosted_zone = aws_route53.HostedZone.from_lookup(self,
                                                         'id3',
                                                         domain_name = 'domain' 
        )
        certificate = aws_certificatemanager.Certificate.from_certificate_arn(self, 
                                                                             id4,
                                                                             'cert_arn'
        )
        image = ecs.ContainerImage.from_ecr_repository(self, _repo)
        
        ecs_patterns.ApplicationLoadBalancedFargateService(self, "id5",
            cluster=cluster,            # Required
            cpu=512,                    # Default is 256
            desired_count=2,            # Default is 1
            task_image_options=ecs_patterns.ApplicationLoadBalancedTaskImageOptions(
                image = image,
                container_port=8000),
            memory_limit_mib=2048,      # Default is 512
            public_load_balancer=True,
            domain_name = 'domain_name',
            domain_zone = hosted_zone,           
            certificate = certificate,            
            redirect_http = True)

Solution

  • You are looking for from_repository_attributes() to create an instance of IRepository from an existing ECR repository.