TagParameterContainerImage Class
A special type of ContainerImage that uses an ECR repository for the image, but a CloudFormation Parameter for the tag or digest of the image in that repository.
This allows providing this tag or digest 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.
| Source | aws-ecs/lib/images/tag-parameter-container-image.ts |
|---|---|
| Type last changed |
Example
ts
/**
* These are the construction properties for `EcsAppStack`.
* They extend the standard Stack properties,
* but also require providing the ContainerImage that the service will use.
* That Image will be provided from the Stack containing the CodePipeline.
*/
export interface EcsAppStackProps extends cdk.StackProps {
readonly image: ecs.ContainerImage;
}
/**
* This is the Stack containing a simple ECS Service that uses the provided ContainerImage.
*/
export class EcsAppStack extends cdk.Stack {
constructor(scope: Construct, id: string, props: EcsAppStackProps) {
super(scope, id, props);
const taskDefinition = new ecs.TaskDefinition(this, 'TaskDefinition', {
compatibility: ecs.Compatibility.FARGATE,
cpu: '1024',
memoryMiB: '2048',
});
taskDefinition.addContainer('AppContainer', {
image: props.image,
});
new ecs.FargateService(this, 'EcsService', {
taskDefinition,
cluster: new ecs.Cluster(this, 'Cluster', {
vpc: new ec2.Vpc(this, 'Vpc', {
maxAzs: 1,
}),
}),
});
}
}
/**
* This is the Stack containing the CodePipeline definition that deploys an ECS Service.
*/
export class PipelineStack extends cdk.Stack {
public readonly tagParameterContainerImage: ecs.TagParameterContainerImage;
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
/* ********** ECS part **************** */
// this is the ECR repository where the built Docker image will be pushed
const appEcrRepo = new ecr.Repository(this, 'EcsDeployRepository');
// the build that creates the Docker image, and pushes it to the ECR repo
const appCodeDockerBuild = new codebuild.PipelineProject(this, 'AppCodeDockerImageBuildAndPushProject', {
environment: {
// we need to run Docker
privileged: true,
},
buildSpec: codebuild.BuildSpec.fromObject({
version: '0.2',
phases: {
build: {
commands: [
// login to ECR first
'$(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)',
// if your application needs any build steps, they would be invoked here
// build the image, and tag it with the commit hash
// (CODEBUILD_RESOLVED_SOURCE_VERSION is a special environment variable available in CodeBuild)
'docker build -t $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION .',
],
},
post_build: {
commands: [
// push the built image into the ECR repository
'docker push $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION',
// save the declared tag as an environment variable,
// that is then exported below in the 'exported-variables' section as a CodePipeline Variable
'export imageTag=$CODEBUILD_RESOLVED_SOURCE_VERSION',
],
},
},
env: {
// save the imageTag environment variable as a CodePipeline Variable
'exported-variables': [
'imageTag',
],
},
}),
environmentVariables: {
REPOSITORY_URI: {
value: appEcrRepo.repositoryUri,
},
},
});
// needed for `docker push`
appEcrRepo.grantPullPush(appCodeDockerBuild);
// create the ContainerImage used for the ECS application Stack
this.tagParameterContainerImage = new ecs.TagParameterContainerImage(appEcrRepo);
const cdkCodeBuild = new codebuild.PipelineProject(this, 'CdkCodeBuildProject', {
buildSpec: codebuild.BuildSpec.fromObject({
version: '0.2',
phases: {
install: {
commands: [
'npm install',
],
},
build: {
commands: [
// synthesize the CDK code for the ECS application Stack
'npx cdk synth --verbose',
],
},
},
artifacts: {
// store the entire Cloud Assembly as the output artifact
'base-directory': 'cdk.out',
'files': '**/*',
},
}),
});
/* ********** Pipeline part **************** */
const appCodeSourceOutput = new codepipeline.Artifact();
const cdkCodeSourceOutput = new codepipeline.Artifact();
const cdkCodeBuildOutput = new codepipeline.Artifact();
const appCodeBuildAction = new codepipeline_actions.CodeBuildAction({
actionName: 'AppCodeDockerImageBuildAndPush',
project: appCodeDockerBuild,
input: appCodeSourceOutput,
});
new codepipeline.Pipeline(this, 'CodePipelineDeployingEcsApplication', {
artifactBucket: new s3.Bucket(this, 'ArtifactBucket', {
removalPolicy: cdk.RemovalPolicy.DESTROY,
}),
stages: [
{
stageName: 'Source',
actions: [
// this is the Action that takes the source of your application code
new codepipeline_actions.CodeCommitSourceAction({
actionName: 'AppCodeSource',
repository: new codecommit.Repository(this, 'AppCodeSourceRepository', { repositoryName: 'AppCodeSourceRepository' }),
output: appCodeSourceOutput,
}),
// this is the Action that takes the source of your CDK code
// (which would probably include this Pipeline code as well)
new codepipeline_actions.CodeCommitSourceAction({
actionName: 'CdkCodeSource',
repository: new codecommit.Repository(this, 'CdkCodeSourceRepository', { repositoryName: 'CdkCodeSourceRepository' }),
output: cdkCodeSourceOutput,
}),
],
},
{
stageName: 'Build',
actions: [
appCodeBuildAction,
new codepipeline_actions.CodeBuildAction({
actionName: 'CdkCodeBuildAndSynth',
project: cdkCodeBuild,
input: cdkCodeSourceOutput,
outputs: [cdkCodeBuildOutput],
}),
],
},
{
stageName: 'Deploy',
actions: [
new codepipeline_actions.CloudFormationCreateUpdateStackAction({
actionName: 'CFN_Deploy',
stackName: 'SampleEcsStackDeployedFromCodePipeline',
// this name has to be the same name as used below in the CDK code for the application Stack
templatePath: cdkCodeBuildOutput.atPath('EcsStackDeployedInPipeline.template.json'),
adminPermissions: true,
parameterOverrides: {
// 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
[this.tagParameterContainerImage.tagParameterName]: appCodeBuildAction.variable('imageTag'),
},
}),
],
},
],
});
}
}
const app = new cdk.App();
// the CodePipeline Stack needs to be created first
const pipelineStack = new PipelineStack(app, 'aws-cdk-pipeline-ecs-separate-sources');
// we supply the image to the ECS application Stack from the CodePipeline Stack
new EcsAppStack(app, 'EcsStackDeployedInPipeline', {
image: pipelineStack.tagParameterContainerImage,
});
python
#
# 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, notificationArns=None, synthesizer=None, terminationProtection=None, analyticsReporting=None, crossRegionReferences=None, permissionsBoundary=None, suppressTemplateIndentation=None, propertyInjectors=None):
super().__init__(scope, id, image=image, description=description, env=env, stackName=stackName, tags=tags, notificationArns=notificationArns, synthesizer=synthesizer, terminationProtection=terminationProtection, analyticsReporting=analyticsReporting, crossRegionReferences=crossRegionReferences, permissionsBoundary=permissionsBoundary, suppressTemplateIndentation=suppressTemplateIndentation, propertyInjectors=propertyInjectors)
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, notificationArns=None, synthesizer=None, terminationProtection=None, analyticsReporting=None, crossRegionReferences=None, permissionsBoundary=None, suppressTemplateIndentation=None, propertyInjectors=None):
super().__init__(scope, id, description=description, env=env, stackName=stackName, tags=tags, notificationArns=notificationArns, synthesizer=synthesizer, terminationProtection=terminationProtection, analyticsReporting=analyticsReporting, crossRegionReferences=crossRegionReferences, permissionsBoundary=permissionsBoundary, suppressTemplateIndentation=suppressTemplateIndentation, propertyInjectors=propertyInjectors)
# ********* 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
)
java
/**
* These are the construction properties for `EcsAppStack`.
* They extend the standard Stack properties,
* but also require providing the ContainerImage that the service will use.
* That Image will be provided from the Stack containing the CodePipeline.
*/
public class EcsAppStackProps extends StackProps {
private ContainerImage image;
public ContainerImage getImage() {
return this.image;
}
public EcsAppStackProps image(ContainerImage image) {
this.image = image;
return this;
}
}
/**
* This is the Stack containing a simple ECS Service that uses the provided ContainerImage.
*/
public class EcsAppStack extends Stack {
public EcsAppStack(Construct scope, String id, EcsAppStackProps props) {
super(scope, id, props);
TaskDefinition taskDefinition = TaskDefinition.Builder.create(this, "TaskDefinition")
.compatibility(Compatibility.FARGATE)
.cpu("1024")
.memoryMiB("2048")
.build();
taskDefinition.addContainer("AppContainer", ContainerDefinitionOptions.builder()
.image(props.getImage())
.build());
FargateService.Builder.create(this, "EcsService")
.taskDefinition(taskDefinition)
.cluster(Cluster.Builder.create(this, "Cluster")
.vpc(Vpc.Builder.create(this, "Vpc")
.maxAzs(1)
.build())
.build())
.build();
}
}
/**
* This is the Stack containing the CodePipeline definition that deploys an ECS Service.
*/
public class PipelineStack extends Stack {
public final TagParameterContainerImage tagParameterContainerImage;
public PipelineStack(Construct scope, String id) {
this(scope, id, null);
}
public PipelineStack(Construct scope, String id, StackProps props) {
super(scope, id, props);
/* ********** ECS part **************** */
// this is the ECR repository where the built Docker image will be pushed
Repository appEcrRepo = new Repository(this, "EcsDeployRepository");
// the build that creates the Docker image, and pushes it to the ECR repo
PipelineProject appCodeDockerBuild = PipelineProject.Builder.create(this, "AppCodeDockerImageBuildAndPushProject")
.environment(BuildEnvironment.builder()
// we need to run Docker
.privileged(true)
.build())
.buildSpec(BuildSpec.fromObject(Map.of(
"version", "0.2",
"phases", Map.of(
"build", Map.of(
"commands", List.of("$(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)", "docker build -t $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION .")),
"post_build", Map.of(
"commands", List.of("docker push $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION", "export imageTag=$CODEBUILD_RESOLVED_SOURCE_VERSION"))),
"env", Map.of(
// save the imageTag environment variable as a CodePipeline Variable
"exported-variables", List.of("imageTag")))))
.environmentVariables(Map.of(
"REPOSITORY_URI", BuildEnvironmentVariable.builder()
.value(appEcrRepo.getRepositoryUri())
.build()))
.build();
// needed for `docker push`
appEcrRepo.grantPullPush(appCodeDockerBuild);
// create the ContainerImage used for the ECS application Stack
this.tagParameterContainerImage = new TagParameterContainerImage(appEcrRepo);
PipelineProject cdkCodeBuild = PipelineProject.Builder.create(this, "CdkCodeBuildProject")
.buildSpec(BuildSpec.fromObject(Map.of(
"version", "0.2",
"phases", Map.of(
"install", Map.of(
"commands", List.of("npm install")),
"build", Map.of(
"commands", List.of("npx cdk synth --verbose"))),
"artifacts", Map.of(
// store the entire Cloud Assembly as the output artifact
"base-directory", "cdk.out",
"files", "**/*"))))
.build();
/* ********** Pipeline part **************** */
Artifact appCodeSourceOutput = new Artifact();
Artifact cdkCodeSourceOutput = new Artifact();
Artifact cdkCodeBuildOutput = new Artifact();
CodeBuildAction appCodeBuildAction = CodeBuildAction.Builder.create()
.actionName("AppCodeDockerImageBuildAndPush")
.project(appCodeDockerBuild)
.input(appCodeSourceOutput)
.build();
Pipeline.Builder.create(this, "CodePipelineDeployingEcsApplication")
.artifactBucket(Bucket.Builder.create(this, "ArtifactBucket")
.removalPolicy(RemovalPolicy.DESTROY)
.build())
.stages(List.of(StageProps.builder()
.stageName("Source")
.actions(List.of(
// this is the Action that takes the source of your application code
CodeCommitSourceAction.Builder.create()
.actionName("AppCodeSource")
.repository(Repository.Builder.create(this, "AppCodeSourceRepository").repositoryName("AppCodeSourceRepository").build())
.output(appCodeSourceOutput)
.build(),
// this is the Action that takes the source of your CDK code
// (which would probably include this Pipeline code as well)
CodeCommitSourceAction.Builder.create()
.actionName("CdkCodeSource")
.repository(Repository.Builder.create(this, "CdkCodeSourceRepository").repositoryName("CdkCodeSourceRepository").build())
.output(cdkCodeSourceOutput)
.build()))
.build(), StageProps.builder()
.stageName("Build")
.actions(List.of(appCodeBuildAction,
CodeBuildAction.Builder.create()
.actionName("CdkCodeBuildAndSynth")
.project(cdkCodeBuild)
.input(cdkCodeSourceOutput)
.outputs(List.of(cdkCodeBuildOutput))
.build()))
.build(), StageProps.builder()
.stageName("Deploy")
.actions(List.of(
CloudFormationCreateUpdateStackAction.Builder.create()
.actionName("CFN_Deploy")
.stackName("SampleEcsStackDeployedFromCodePipeline")
// this name has to be the same name as used below in the CDK code for the application Stack
.templatePath(cdkCodeBuildOutput.atPath("EcsStackDeployedInPipeline.template.json"))
.adminPermissions(true)
.parameterOverrides(Map.of(
// 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
this.tagParameterContainerImage.getTagParameterName(), appCodeBuildAction.variable("imageTag")))
.build()))
.build()))
.build();
}
}
App app = new App();
// the CodePipeline Stack needs to be created first
PipelineStack pipelineStack = new PipelineStack(app, "aws-cdk-pipeline-ecs-separate-sources");
// we supply the image to the ECS application Stack from the CodePipeline Stack
// we supply the image to the ECS application Stack from the CodePipeline Stack
new EcsAppStack(app, "EcsStackDeployedInPipeline", new EcsAppStackProps()
.image(pipelineStack.getTagParameterContainerImage())
);
csharp
// Install: dotnet add package Amazon.CDK.Lib
/**
* These are the construction properties for `EcsAppStack`.
* They extend the standard Stack properties,
* but also require providing the ContainerImage that the service will use.
* That Image will be provided from the Stack containing the CodePipeline.
*/
class EcsAppStackProps : StackProps
{
public ContainerImage Image { get; set; }
}
/**
* This is the Stack containing a simple ECS Service that uses the provided ContainerImage.
*/
class EcsAppStack : Stack
{
public EcsAppStack(Construct scope, string id, EcsAppStackProps props) : base(scope, id, props)
{
var taskDefinition = new TaskDefinition(this, "TaskDefinition", new TaskDefinitionProps {
Compatibility = Compatibility.FARGATE,
Cpu = "1024",
MemoryMiB = "2048"
});
taskDefinition.AddContainer("AppContainer", new ContainerDefinitionOptions {
Image = props.Image
});
new FargateService(this, "EcsService", new FargateServiceProps {
TaskDefinition = taskDefinition,
Cluster = new Cluster(this, "Cluster", new ClusterProps {
Vpc = new Vpc(this, "Vpc", new VpcProps {
MaxAzs = 1
})
})
});
}
}
/**
* This is the Stack containing the CodePipeline definition that deploys an ECS Service.
*/
class PipelineStack : Stack
{
public TagParameterContainerImage TagParameterContainerImage { get; }
public PipelineStack(Construct scope, string id, StackProps? props=null) : base(scope, id, props)
{
/* ********** ECS part **************** */
// this is the ECR repository where the built Docker image will be pushed
var appEcrRepo = new Repository(this, "EcsDeployRepository");
// the build that creates the Docker image, and pushes it to the ECR repo
var appCodeDockerBuild = new PipelineProject(this, "AppCodeDockerImageBuildAndPushProject", new PipelineProjectProps {
Environment = new BuildEnvironment {
// we need to run Docker
Privileged = true
},
BuildSpec = BuildSpec.FromObject(new Dictionary<string, object> {
{ "version", "0.2" },
{ "phases", new Dictionary<string, IDictionary<string, string[]>> {
{ "build", new Struct {
Commands = new [] { "$(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)", "docker build -t $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION ." }
} },
{ "post_build", new Struct {
Commands = new [] { "docker push $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION", "export imageTag=$CODEBUILD_RESOLVED_SOURCE_VERSION" }
} }
} },
{ "env", new Dictionary<string, string[]> {
// save the imageTag environment variable as a CodePipeline Variable
{ "exported-variables", new [] { "imageTag" } }
} }
}),
EnvironmentVariables = new Dictionary<string, BuildEnvironmentVariable> {
{ "REPOSITORY_URI", new BuildEnvironmentVariable {
Value = appEcrRepo.RepositoryUri
} }
}
});
// needed for `docker push`
appEcrRepo.GrantPullPush(appCodeDockerBuild);
// create the ContainerImage used for the ECS application Stack
TagParameterContainerImage = new TagParameterContainerImage(appEcrRepo);
var cdkCodeBuild = new PipelineProject(this, "CdkCodeBuildProject", new PipelineProjectProps {
BuildSpec = BuildSpec.FromObject(new Dictionary<string, object> {
{ "version", "0.2" },
{ "phases", new Dictionary<string, IDictionary<string, string[]>> {
{ "install", new Struct {
Commands = new [] { "npm install" }
} },
{ "build", new Struct {
Commands = new [] { "npx cdk synth --verbose" }
} }
} },
{ "artifacts", new Dictionary<string, string> {
// store the entire Cloud Assembly as the output artifact
{ "base-directory", "cdk.out" },
{ "files", "**/*" }
} }
})
});
/* ********** Pipeline part **************** */
var appCodeSourceOutput = new Artifact();
var cdkCodeSourceOutput = new Artifact();
var cdkCodeBuildOutput = new Artifact();
var appCodeBuildAction = new CodeBuildAction(new CodeBuildActionProps {
ActionName = "AppCodeDockerImageBuildAndPush",
Project = appCodeDockerBuild,
Input = appCodeSourceOutput
});
new Pipeline(this, "CodePipelineDeployingEcsApplication", new PipelineProps {
ArtifactBucket = new Bucket(this, "ArtifactBucket", new BucketProps {
RemovalPolicy = RemovalPolicy.DESTROY
}),
Stages = new [] { new StageProps {
StageName = "Source",
Actions = new [] {
// this is the Action that takes the source of your application code
new CodeCommitSourceAction(new CodeCommitSourceActionProps {
ActionName = "AppCodeSource",
Repository = new Repository(this, "AppCodeSourceRepository", new RepositoryProps { RepositoryName = "AppCodeSourceRepository" }),
Output = appCodeSourceOutput
}),
// this is the Action that takes the source of your CDK code
// (which would probably include this Pipeline code as well)
new CodeCommitSourceAction(new CodeCommitSourceActionProps {
ActionName = "CdkCodeSource",
Repository = new Repository(this, "CdkCodeSourceRepository", new RepositoryProps { RepositoryName = "CdkCodeSourceRepository" }),
Output = cdkCodeSourceOutput
}) }
}, new StageProps {
StageName = "Build",
Actions = new [] { appCodeBuildAction,
new CodeBuildAction(new CodeBuildActionProps {
ActionName = "CdkCodeBuildAndSynth",
Project = cdkCodeBuild,
Input = cdkCodeSourceOutput,
Outputs = new [] { cdkCodeBuildOutput }
}) }
}, new StageProps {
StageName = "Deploy",
Actions = new [] {
new CloudFormationCreateUpdateStackAction(new CloudFormationCreateUpdateStackActionProps {
ActionName = "CFN_Deploy",
StackName = "SampleEcsStackDeployedFromCodePipeline",
// this name has to be the same name as used below in the CDK code for the application Stack
TemplatePath = cdkCodeBuildOutput.AtPath("EcsStackDeployedInPipeline.template.json"),
AdminPermissions = true,
ParameterOverrides = new Dictionary<string, object> {
// 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
{ TagParameterContainerImage.TagParameterName, appCodeBuildAction.Variable("imageTag") }
}
}) }
} }
});
}
}
var app = new App();
// the CodePipeline Stack needs to be created first
var pipelineStack = new PipelineStack(app, "aws-cdk-pipeline-ecs-separate-sources");
// we supply the image to the ECS application Stack from the CodePipeline Stack
// we supply the image to the ECS application Stack from the CodePipeline Stack
new EcsAppStack(app, "EcsStackDeployedInPipeline", new EcsAppStackProps {
Image = pipelineStack.TagParameterContainerImage
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
/**
* These are the construction properties for `EcsAppStack`.
* They extend the standard Stack properties,
* but also require providing the ContainerImage that the service will use.
* That Image will be provided from the Stack containing the CodePipeline.
*/
type EcsAppStackProps struct {
StackProps
image ContainerImage
}
/**
* This is the Stack containing a simple ECS Service that uses the provided ContainerImage.
*/
type EcsAppStack struct {
Stack
}
func NewEcsAppStack(scope Construct, id *string, props EcsAppStackProps) *EcsAppStack {
this := &EcsAppStack{}
cdk.NewStack_Override(this, scope, id, props)
taskDefinition := ecs.NewTaskDefinition(this, jsii.String("TaskDefinition"), &TaskDefinitionProps{
Compatibility: ecs.Compatibility_FARGATE,
Cpu: jsii.String("1024"),
MemoryMiB: jsii.String("2048"),
})
taskDefinition.AddContainer(jsii.String("AppContainer"), &ContainerDefinitionOptions{
Image: props.image,
})
ecs.NewFargateService(this, jsii.String("EcsService"), &FargateServiceProps{
TaskDefinition: TaskDefinition,
Cluster: ecs.NewCluster(this, jsii.String("Cluster"), &ClusterProps{
Vpc: ec2.NewVpc(this, jsii.String("Vpc"), &VpcProps{
MaxAzs: jsii.Number(1),
}),
}),
})
return this
}
/**
* This is the Stack containing the CodePipeline definition that deploys an ECS Service.
*/
type PipelineStack struct {
Stack
tagParameterContainerImage TagParameterContainerImage
}tagParameterContainerImage TagParameterContainerImage
func NewPipelineStack(scope Construct, id *string, props StackProps) *PipelineStack {
this := &PipelineStack{}
cdk.NewStack_Override(this, scope, id, props)
/* ********** ECS part **************** */
// this is the ECR repository where the built Docker image will be pushed
appEcrRepo := ecr.NewRepository(this, jsii.String("EcsDeployRepository"))
// the build that creates the Docker image, and pushes it to the ECR repo
appCodeDockerBuild := codebuild.NewPipelineProject(this, jsii.String("AppCodeDockerImageBuildAndPushProject"), &PipelineProjectProps{
Environment: &BuildEnvironment{
// we need to run Docker
Privileged: jsii.Boolean(true),
},
BuildSpec: codebuild.BuildSpec_FromObject(map[string]interface{}{
"version": jsii.String("0.2"),
"phases": map[string]map[string][]*string{
"build": map[string][]*string{
"commands": []*string{
jsii.String("$(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)"),
jsii.String("docker build -t $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION ."),
},
},
"post_build": map[string][]*string{
"commands": []*string{
jsii.String("docker push $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION"),
jsii.String("export imageTag=$CODEBUILD_RESOLVED_SOURCE_VERSION"),
},
},
},
"env": map[string][]*string{
// save the imageTag environment variable as a CodePipeline Variable
"exported-variables": []*string{
jsii.String("imageTag"),
},
},
}),
EnvironmentVariables: map[string]BuildEnvironmentVariable{
"REPOSITORY_URI": &BuildEnvironmentVariable{
"value": appEcrRepo.repositoryUri,
},
},
})
// needed for `docker push`
appEcrRepo.GrantPullPush(appCodeDockerBuild)
// create the ContainerImage used for the ECS application Stack
this.tagParameterContainerImage = ecs.NewTagParameterContainerImage(appEcrRepo)
cdkCodeBuild := codebuild.NewPipelineProject(this, jsii.String("CdkCodeBuildProject"), &PipelineProjectProps{
BuildSpec: codebuild.BuildSpec_*FromObject(map[string]interface{}{
"version": jsii.String("0.2"),
"phases": map[string]map[string][]*string{
"install": map[string][]*string{
"commands": []*string{
jsii.String("npm install"),
},
},
"build": map[string][]*string{
"commands": []*string{
jsii.String("npx cdk synth --verbose"),
},
},
},
"artifacts": map[string]*string{
// store the entire Cloud Assembly as the output artifact
"base-directory": jsii.String("cdk.out"),
"files": jsii.String("**/*"),
},
}),
})
/* ********** Pipeline part **************** */
appCodeSourceOutput := codepipeline.NewArtifact()
cdkCodeSourceOutput := codepipeline.NewArtifact()
cdkCodeBuildOutput := codepipeline.NewArtifact()
appCodeBuildAction := codepipeline_actions.NewCodeBuildAction(&CodeBuildActionProps{
ActionName: jsii.String("AppCodeDockerImageBuildAndPush"),
Project: appCodeDockerBuild,
Input: appCodeSourceOutput,
})
codepipeline.NewPipeline(this, jsii.String("CodePipelineDeployingEcsApplication"), &PipelineProps{
ArtifactBucket: s3.NewBucket(this, jsii.String("ArtifactBucket"), &BucketProps{
RemovalPolicy: cdk.RemovalPolicy_DESTROY,
}),
Stages: []StageProps{
&StageProps{
StageName: jsii.String("Source"),
Actions: []IAction{
// this is the Action that takes the source of your application code
codepipeline_actions.NewCodeCommitSourceAction(&CodeCommitSourceActionProps{
ActionName: jsii.String("AppCodeSource"),
Repository: codecommit.NewRepository(this, jsii.String("AppCodeSourceRepository"), &RepositoryProps{
RepositoryName: jsii.String("AppCodeSourceRepository"),
}),
Output: appCodeSourceOutput,
}),
// this is the Action that takes the source of your CDK code
// (which would probably include this Pipeline code as well)
codepipeline_actions.NewCodeCommitSourceAction(&CodeCommitSourceActionProps{
ActionName: jsii.String("CdkCodeSource"),
Repository: codecommit.NewRepository(this, jsii.String("CdkCodeSourceRepository"), &RepositoryProps{
RepositoryName: jsii.String("CdkCodeSourceRepository"),
}),
Output: cdkCodeSourceOutput,
}),
},
},
&StageProps{
StageName: jsii.String("Build"),
Actions: []IAction{
appCodeBuildAction,
codepipeline_actions.NewCodeBuildAction(&CodeBuildActionProps{
ActionName: jsii.String("CdkCodeBuildAndSynth"),
Project: cdkCodeBuild,
Input: cdkCodeSourceOutput,
Outputs: []Artifact{
cdkCodeBuildOutput,
},
}),
},
},
&StageProps{
StageName: jsii.String("Deploy"),
Actions: []IAction{
codepipeline_actions.NewCloudFormationCreateUpdateStackAction(&CloudFormationCreateUpdateStackActionProps{
ActionName: jsii.String("CFN_Deploy"),
StackName: jsii.String("SampleEcsStackDeployedFromCodePipeline"),
// this name has to be the same name as used below in the CDK code for the application Stack
TemplatePath: cdkCodeBuildOutput.AtPath(jsii.String("EcsStackDeployedInPipeline.template.json")),
AdminPermissions: jsii.Boolean(true),
ParameterOverrides: map[string]interface{}{
// 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
this.tagParameterContainerImage.tagParameterName: appCodeBuildAction.variable(jsii.String("imageTag")),
},
}),
},
},
},
})
return this
}
app := cdk.NewApp()
// the CodePipeline Stack needs to be created first
pipelineStack := NewPipelineStack(app, jsii.String("aws-cdk-pipeline-ecs-separate-sources"))
// we supply the image to the ECS application Stack from the CodePipeline Stack
// we supply the image to the ECS application Stack from the CodePipeline Stack
NewEcsAppStack(app, jsii.String("EcsStackDeployedInPipeline"), &EcsAppStackProps{
image: pipelineStack.tagParameterContainerImage,
})
Initializer
ts
new TagParameterContainerImage(repository: IRepository, props?: TagParameterContainerImageProps)
python
TagParameterContainerImage(repository: IRepository, props: typing.Optional[TagParameterContainerImageProps] = None)
java
new TagParameterContainerImage(IRepository repository, TagParameterContainerImageProps props)
csharp
new TagParameterContainerImage(IRepository repository, TagParameterContainerImageProps? props = null)
go
NewTagParameterContainerImage(Repository IRepository, Props TagParameterContainerImageProps)
Properties
tagParameterNamestringtag_parameter_namestrtagParameterNameStringTagParameterNamestringTagParameterName*string #Returns the name of the CloudFormation Parameter that represents the tag or digest of the image in the ECR repository.
tagParameterValuestringtag_parameter_valuestrtagParameterValueStringTagParameterValuestringTagParameterValue*string #Returns the value of the CloudFormation Parameter that represents the tag or digest of the image in the ECR repository.
Methods
bind(scope: Construct, containerDefinition: ContainerDefinition): ContainerImageConfigdef bind(self, scope: Construct, container_definition: ContainerDefinition) -> ContainerImageConfigpublic ContainerImageConfig bind(Construct scope, ContainerDefinition containerDefinition)public ContainerImageConfig Bind(Construct scope, ContainerDefinition containerDefinition)func Bind(Scope Construct, ContainerDefinition ContainerDefinition) ContainerImageConfig #Called when the image is used by a ContainerDefinition.
fromAsset(directory: string, props?: AssetImageProps): AssetImage@staticmethod def from_asset(directory: str, props: typing.Optional[AssetImageProps] = None) -> AssetImagepublic static AssetImage fromAsset(String directory, AssetImageProps props)public static AssetImage FromAsset(string directory, AssetImageProps? props = null)func FromAsset(Directory *string, Props AssetImageProps) AssetImage static #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.
1 parameter
Parameters
directorydirectorydirectorydirectoryDirectory— The directory containing the Dockerfile.
fromDockerImageAsset(asset: DockerImageAsset): ContainerImage@staticmethod def from_docker_image_asset(asset: DockerImageAsset) -> ContainerImagepublic static ContainerImage fromDockerImageAsset(DockerImageAsset asset)public static ContainerImage FromDockerImageAsset(DockerImageAsset asset)func FromDockerImageAsset(Asset DockerImageAsset) ContainerImage static #Use an existing `DockerImageAsset` for this container image.
1 parameter
Parameters
assetassetassetassetAsset— TheDockerImageAssetto use for this container definition.
fromEcrRepository(repository: IRepository, tag?: string): EcrImage@staticmethod def from_ecr_repository(repository: IRepository, tag: typing.Optional[str] = None) -> EcrImagepublic static EcrImage fromEcrRepository(IRepository repository, String tag)public static EcrImage FromEcrRepository(IRepository repository, string? tag = null)func FromEcrRepository(Repository IRepository, Tag *string) EcrImage static #Reference an image in an ECR repository.
1 parameter
Parameters
tagtagtagtagTag— If you don't specify this parameter,latestis used as default.
fromRegistry(name: string, props?: RepositoryImageProps): RepositoryImage@staticmethod def from_registry(name: str, props: typing.Optional[RepositoryImageProps] = None) -> RepositoryImagepublic static RepositoryImage fromRegistry(String name, RepositoryImageProps props)public static RepositoryImage FromRegistry(string name, RepositoryImageProps? props = null)func FromRegistry(Name *string, Props RepositoryImageProps) RepositoryImage static #Reference an image on DockerHub or another online registry.
fromTarball(tarballFile: string): ContainerImage@staticmethod def from_tarball(tarball_file: str) -> ContainerImagepublic static ContainerImage fromTarball(String tarballFile)public static ContainerImage FromTarball(string tarballFile)func FromTarball(TarballFile *string) ContainerImage static #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.
1 parameter
Parameters
tarballFiletarball_filetarballFiletarballFileTarballFile— Absolute path to the tarball.