I have implemented that a few days ago using CDK, the idea is to create an IAM Role on the target environment and assume this role when running the codebuild(which runs as part of the code pipeline).
In my case, since the codebuild creates CDK stacks I gave an AdministratorAccess policy to this role.
Later, create new codebuild and attach permissions to codebuild project role.
// create the codebuild project used by the codepipeline
const codeBuildProject = new codebuild.PipelineProject(scope, `${props.environment}-${props.pipelineNamePrefix}-codebuild`, {
projectName: `${props.environment}-${props.pipelineNamePrefix}`,
buildSpec: codebuild.BuildSpec.fromSourceFilename('buildspec.yml'),
environment: {
buildImage: codebuild.LinuxBuildImage.AMAZON_LINUX_2,
privileged: true,
environmentVariables: buildEnvVariables,
computeType: props.computeType
},
})
// attach permissions to codebuild project role
codeBuildProject.addToRolePolicy(new PolicyStatement({
effect: Effect.ALLOW,
resources: [props.deploymentRoleArn],
actions: ['sts:AssumeRole']
}));
Be aware that props.deploymentRoleArn
is the ARN of the role you created on the target environment.
Then, create a new pipeline and add codeBuildProject
to codepipelineActions.CodeBuildAction
as project
:
// create codepipeline to deploy cdk changes
const codePipeline = new codepipeline.Pipeline(scope, `${props.environment}-${props.pipelineNamePrefix}-codepipeline`, {
restartExecutionOnUpdate: false,
pipelineName: `${props.environment}-${props.pipelineNamePrefix}`,
stages: [
{
stageName: 'Source',
actions: [
new codepipelineActions.GitHubSourceAction({
branch: props.targetBranch,
oauthToken: gitHubToken,
owner: props.githubRepositoryOwner,
repo: props.githubRepositoryName,
actionName: 'get-sources',
output: pipelineSourceArtifact,
})]
},
{
stageName: 'Deploy',
actions: [
new codepipelineActions.CodeBuildAction({
actionName: 'deploy-cdk',
input: pipelineSourceArtifact,
type: codepipelineActions.CodeBuildActionType.BUILD,
project: codeBuildProject
}),
]
}
]
});
The relevant part from above code snippet is Deploy
stage.The other stage is only required in case you want to get sources from github - More info here.
This is the full solution, in case you want to implement something else, Read more about code pipeline actions here.