简体   繁体   中英

How to override aws_cdk.core.LegacyStackSynthesizer.add_docker_image_asset in AWS CDK for Python

I would like to upload a docker image from local disc to a repository that I created with the AWS CDK.

When i use aws_ecr_assets.DockerImageAsset to add a Docker image to a repository (which works fine except that I am not able to set permissions on its repository via CDK), I get the following deprecation warning:

DockerImageAsset.repositoryName is deprecated. Override "core.Stack.addDockerImageAsset" to control asset locations

When looking into core.Stack.addDockerImageAsset , I get a hint that I should override stack.synthesizer.addDockerImageAsset() .

My simplified stack with a custom synthesizer looks like this:

class CustomSynthesizer(core.LegacyStackSynthesizer):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def add_docker_image_asset(
        self,
        *,
        directory_name,
        source_hash,
        docker_build_args=None,
        docker_build_target=None,
        docker_file=None,
        repository_name=None,
    ):
        # What should I put in this function to upload the docker image into my repository?


class ContainerStack(core.Stack):
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:

        super().__init__(scope, id, synthesizer=CustomSynthesizer(), **kwargs)

        repo = ecr.Repository(self, "TestRepo", repository_name="test_repo")
        repo.grant_pull(iam.AccountPrincipal("123456789123"))

        image_location = self.synthesizer.add_docker_image_asset(
            directory_name="path/to/dir/with/Dockerfile",
            source_hash="latest",
            repository_name=repo.repository_name,
        )

Another thing that I tried is to use the standard stack synthesizer and calling add_docker_image_asset on it. Unfortunately, I get the following error message and the stack fails to deploy:

test-stack: deploying...
[0%] start: Publishing latest:current
[25%] fail: Unable to execute 'docker' in order to build a container asset. Please install 'docker' and try again.
...
 ❌  test-stack failed: Error: Failed to publish one or more assets. See the error messages above for more information.
    at Object.publishAssets (/home/user/.npm-global/lib/node_modules/aws-cdk/lib/util/asset-publishing.ts:25:11)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at Object.deployStack (/home/user/.npm-global/lib/node_modules/aws-cdk/lib/api/deploy-stack.ts:216:3)
    at CdkToolkit.deploy (/home/user/.npm-global/lib/node_modules/aws-cdk/lib/cdk-toolkit.ts:181:24)
    at main (/home/user/.npm-global/lib/node_modules/aws-cdk/bin/cdk.ts:268:16)
    at initCommandLine (/home/user/.npm-global/lib/node_modules/aws-cdk/bin/cdk.ts:188:9)
Failed to publish one or more assets. See the error messages above for more information.

I'm flat on my back as to how to solve this problem and any help is much appreciated!

DockerImageAsset is a managed construct, which handles the repository and versioning by itself. By default it creates a repository for your stack and uploads your docker images to it (tagging them by their hash).

You do not need to create this repository yourself. However, if you are like me and want to have a legible name for the repository, you can name the repo using cdk.json config file and its context section:

// cdk.json
{
  "app": "python3 your_app",
  "context": {
    "@aws-cdk/core:enableStackNameDuplicates": "true",
    "aws-cdk:enableDiffNoFail": "true",
    "assets-ecr-repository-name": "<REPO NAME GOES HERE>"
  }
}

If you want to further alter the repo (I like to leave it fully managed, but hey), you can load the repo into the CDK stack by using one of the static methods on the aws_ecr.Repository construct. https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ecr.Repository.html#static-from-wbr-repository-wbr-namescope-id-repositoryname

Hope this helps a little:-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM