TagParameterContainerImage

class aws_cdk.aws_ecs.TagParameterContainerImage(repository)

Bases: ContainerImage

A special type of {@link ContainerImage} that uses an ECR repository for the image, but a CloudFormation Parameter for the tag of the image in that repository.

This allows providing this tag through the Parameter at deploy time, for example in a CodePipeline that pushes a new tag of the image to the repository during a build step, and then provides that new tag through the CloudFormation Parameter in the deploy step.

See:

#tagParameterName

ExampleMetadata:

lit=test/integ.pipeline-ecs-separate-source.lit.ts infused

Example:

#
# This is the Stack containing a simple ECS Service that uses the provided ContainerImage.
#
class EcsAppStack(cdk.Stack):
    def __init__(self, scope, id, *, image, description=None, env=None, stackName=None, tags=None, synthesizer=None, terminationProtection=None, analyticsReporting=None):
        super().__init__(scope, id, image=image, description=description, env=env, stackName=stackName, tags=tags, synthesizer=synthesizer, terminationProtection=terminationProtection, analyticsReporting=analyticsReporting)

        task_definition = ecs.TaskDefinition(self, "TaskDefinition",
            compatibility=ecs.Compatibility.FARGATE,
            cpu="1024",
            memory_mi_b="2048"
        )
        task_definition.add_container("AppContainer",
            image=image
        )
        ecs.FargateService(self, "EcsService",
            task_definition=task_definition,
            cluster=ecs.Cluster(self, "Cluster",
                vpc=ec2.Vpc(self, "Vpc",
                    max_azs=1
                )
            )
        )

#
# This is the Stack containing the CodePipeline definition that deploys an ECS Service.
#
class PipelineStack(cdk.Stack):

    def __init__(self, scope, id, *, description=None, env=None, stackName=None, tags=None, synthesizer=None, terminationProtection=None, analyticsReporting=None):
        super().__init__(scope, id, description=description, env=env, stackName=stackName, tags=tags, synthesizer=synthesizer, terminationProtection=terminationProtection, analyticsReporting=analyticsReporting)

        # ********* ECS part ****************

        # this is the ECR repository where the built Docker image will be pushed
        app_ecr_repo = ecr.Repository(self, "EcsDeployRepository")
        # the build that creates the Docker image, and pushes it to the ECR repo
        app_code_docker_build = codebuild.PipelineProject(self, "AppCodeDockerImageBuildAndPushProject",
            environment=codebuild.BuildEnvironment(
                # we need to run Docker
                privileged=True
            ),
            build_spec=codebuild.BuildSpec.from_object({
                "version": "0.2",
                "phases": {
                    "build": {
                        "commands": ["$(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)", "docker build -t $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION ."
                        ]
                    },
                    "post_build": {
                        "commands": ["docker push $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION", "export imageTag=$CODEBUILD_RESOLVED_SOURCE_VERSION"
                        ]
                    }
                },
                "env": {
                    # save the imageTag environment variable as a CodePipeline Variable
                    "exported-variables": ["imageTag"
                    ]
                }
            }),
            environment_variables={
                "REPOSITORY_URI": codebuild.BuildEnvironmentVariable(
                    value=app_ecr_repo.repository_uri
                )
            }
        )
        # needed for `docker push`
        app_ecr_repo.grant_pull_push(app_code_docker_build)
        # create the ContainerImage used for the ECS application Stack
        self.tag_parameter_container_image = ecs.TagParameterContainerImage(app_ecr_repo)

        cdk_code_build = codebuild.PipelineProject(self, "CdkCodeBuildProject",
            build_spec=codebuild.BuildSpec.from_object({
                "version": "0.2",
                "phases": {
                    "install": {
                        "commands": ["npm install"
                        ]
                    },
                    "build": {
                        "commands": ["npx cdk synth --verbose"
                        ]
                    }
                },
                "artifacts": {
                    # store the entire Cloud Assembly as the output artifact
                    "base-directory": "cdk.out",
                    "files": "**/*"
                }
            })
        )

        # ********* Pipeline part ****************

        app_code_source_output = codepipeline.Artifact()
        cdk_code_source_output = codepipeline.Artifact()
        cdk_code_build_output = codepipeline.Artifact()
        app_code_build_action = codepipeline_actions.CodeBuildAction(
            action_name="AppCodeDockerImageBuildAndPush",
            project=app_code_docker_build,
            input=app_code_source_output
        )
        codepipeline.Pipeline(self, "CodePipelineDeployingEcsApplication",
            artifact_bucket=s3.Bucket(self, "ArtifactBucket",
                removal_policy=cdk.RemovalPolicy.DESTROY
            ),
            stages=[codepipeline.StageProps(
                stage_name="Source",
                actions=[
                    # this is the Action that takes the source of your application code
                    codepipeline_actions.CodeCommitSourceAction(
                        action_name="AppCodeSource",
                        repository=codecommit.Repository(self, "AppCodeSourceRepository", repository_name="AppCodeSourceRepository"),
                        output=app_code_source_output
                    ),
                    # this is the Action that takes the source of your CDK code
                    # (which would probably include this Pipeline code as well)
                    codepipeline_actions.CodeCommitSourceAction(
                        action_name="CdkCodeSource",
                        repository=codecommit.Repository(self, "CdkCodeSourceRepository", repository_name="CdkCodeSourceRepository"),
                        output=cdk_code_source_output
                    )
                ]
            ), codepipeline.StageProps(
                stage_name="Build",
                actions=[app_code_build_action,
                    codepipeline_actions.CodeBuildAction(
                        action_name="CdkCodeBuildAndSynth",
                        project=cdk_code_build,
                        input=cdk_code_source_output,
                        outputs=[cdk_code_build_output]
                    )
                ]
            ), codepipeline.StageProps(
                stage_name="Deploy",
                actions=[
                    codepipeline_actions.CloudFormationCreateUpdateStackAction(
                        action_name="CFN_Deploy",
                        stack_name="SampleEcsStackDeployedFromCodePipeline",
                        # this name has to be the same name as used below in the CDK code for the application Stack
                        template_path=cdk_code_build_output.at_path("EcsStackDeployedInPipeline.template.json"),
                        admin_permissions=True,
                        parameter_overrides={
                            # read the tag pushed to the ECR repository from the CodePipeline Variable saved by the application build step,
                            # and pass it as the CloudFormation Parameter for the tag
                            "self.tag_parameter_container_image.tag_parameter_name": app_code_build_action.variable("imageTag")
                        }
                    )
                ]
            )
            ]
        )

app = cdk.App()

# the CodePipeline Stack needs to be created first
pipeline_stack = PipelineStack(app, "aws-cdk-pipeline-ecs-separate-sources")
# we supply the image to the ECS application Stack from the CodePipeline Stack
EcsAppStack(app, "EcsStackDeployedInPipeline",
    image=pipeline_stack.tag_parameter_container_image
)
Parameters:

repository (IRepository) –

Methods

bind(scope, container_definition)

Called when the image is used by a ContainerDefinition.

Parameters:
Return type:

ContainerImageConfig

Attributes

tag_parameter_name

Returns the name of the CloudFormation Parameter that represents the tag of the image in the ECR repository.

tag_parameter_value

Returns the value of the CloudFormation Parameter that represents the tag of the image in the ECR repository.

Static Methods

classmethod from_asset(directory, *, build_args=None, file=None, invalidation=None, network_mode=None, platform=None, repository_name=None, target=None, extra_hash=None, exclude=None, follow=None, ignore_mode=None, follow_symlinks=None)

Reference an image that’s constructed directly from sources on disk.

If you already have a DockerImageAsset instance, you can use the ContainerImage.fromDockerImageAsset method instead.

Parameters:
  • directory (str) – The directory containing the Dockerfile.

  • build_args (Optional[Mapping[str, str]]) – Build args to pass to the docker build command. Since Docker build arguments are resolved before deployment, keys and values cannot refer to unresolved tokens (such as lambda.functionArn or queue.queueUrl). Default: - no build args are passed

  • file (Optional[str]) – Path to the Dockerfile (relative to the directory). Default: ‘Dockerfile’

  • invalidation (Union[DockerImageAssetInvalidationOptions, Dict[str, Any], None]) – Options to control which parameters are used to invalidate the asset hash. Default: - hash all parameters

  • network_mode (Optional[NetworkMode]) – Networking mode for the RUN commands during build. Support docker API 1.25+. Default: - no networking mode specified (the default networking mode NetworkMode.DEFAULT will be used)

  • platform (Optional[Platform]) – Platform to build for. Requires Docker Buildx. Default: - no platform specified (the current machine architecture will be used)

  • repository_name (Optional[str]) – (deprecated) ECR repository name. Specify this property if you need to statically address the image, e.g. from a Kubernetes Pod. Note, this is only the repository name, without the registry and the tag parts. Default: - the default ECR repository for CDK assets

  • target (Optional[str]) – Docker target to build to. Default: - no target

  • extra_hash (Optional[str]) – (deprecated) Extra information to encode into the fingerprint (e.g. build instructions and other inputs). Default: - hash is only based on source content

  • exclude (Optional[Sequence[str]]) – (deprecated) Glob patterns to exclude from the copy. Default: nothing is excluded

  • follow (Optional[FollowMode]) – (deprecated) A strategy for how to handle symlinks. Default: Never

  • ignore_mode (Optional[IgnoreMode]) – (deprecated) The ignore behavior to use for exclude patterns. Default: - GLOB for file assets, DOCKER or GLOB for docker assets depending on whether the ‘

  • follow_symlinks (Optional[SymlinkFollowMode]) – A strategy for how to handle symlinks. Default: SymlinkFollowMode.NEVER

Return type:

AssetImage

classmethod from_docker_image_asset(asset)

Use an existing DockerImageAsset for this container image.

Parameters:

asset (DockerImageAsset) – The DockerImageAsset to use for this container definition.

Return type:

ContainerImage

classmethod from_ecr_repository(repository, tag=None)

Reference an image in an ECR repository.

Parameters:
Return type:

EcrImage

classmethod from_registry(name, *, credentials=None)

Reference an image on DockerHub or another online registry.

Parameters:
  • name (str) –

  • credentials (Optional[ISecret]) – The secret to expose to the container that contains the credentials for the image repository. The supported value is the full ARN of an AWS Secrets Manager secret.

Return type:

RepositoryImage

classmethod from_tarball(tarball_file)

Use an existing tarball for this container image.

Use this method if the container image has already been created by another process (e.g. jib) and you want to add it as a container image asset.

Parameters:

tarball_file (str) – Absolute path to the tarball. You can use language-specific idioms (such as __dirname in Node.js) to create an absolute path based on the current script running directory.

Return type:

ContainerImage