|
| 1 | +import { ISchedule, IScheduleTarget } from '@aws-cdk/aws-scheduler-alpha'; |
| 2 | +import { Names } from 'aws-cdk-lib'; |
| 3 | +import { IPipeline } from 'aws-cdk-lib/aws-codepipeline'; |
| 4 | +import { IRole, PolicyStatement } from 'aws-cdk-lib/aws-iam'; |
| 5 | +import { ScheduleTargetBase, ScheduleTargetBaseProps } from './target'; |
| 6 | +import { sameEnvDimension } from './util'; |
| 7 | + |
| 8 | +/** |
| 9 | + * Use an AWS CodePipeline pipeline as a target for AWS EventBridge Scheduler. |
| 10 | + */ |
| 11 | +export class CodePipelineStartPipelineExecution extends ScheduleTargetBase implements IScheduleTarget { |
| 12 | + constructor( |
| 13 | + private readonly pipeline: IPipeline, |
| 14 | + private readonly props: ScheduleTargetBaseProps = {}, |
| 15 | + ) { |
| 16 | + super(props, pipeline.pipelineArn); |
| 17 | + } |
| 18 | + |
| 19 | + protected addTargetActionToRole(schedule: ISchedule, role: IRole): void { |
| 20 | + const region = this.pipeline.env.region ?? ''; |
| 21 | + const account = this.pipeline.env.account ?? ''; |
| 22 | + |
| 23 | + if (!sameEnvDimension(region, schedule.env.region)) { |
| 24 | + throw new Error(`Cannot assign pipeline in region ${region} to the schedule ${Names.nodeUniqueId(schedule.node)} in region ${schedule.env.region}. Both the schedule and the pipeline must be in the same region.`); |
| 25 | + } |
| 26 | + |
| 27 | + if (!sameEnvDimension(account, schedule.env.account)) { |
| 28 | + throw new Error(`Cannot assign pipeline in account ${account} to the schedule ${Names.nodeUniqueId(schedule.node)} in account ${schedule.env.region}. Both the schedule and the pipeline must be in the same account.`); |
| 29 | + } |
| 30 | + |
| 31 | + if (this.props.role && !sameEnvDimension(this.props.role.env.account, account)) { |
| 32 | + throw new Error(`Cannot grant permission to execution role in account ${this.props.role.env.account} to invoke target ${Names.nodeUniqueId(this.pipeline.node)} in account ${account}. Both the target and the execution role must be in the same account.`); |
| 33 | + } |
| 34 | + |
| 35 | + role.addToPrincipalPolicy(new PolicyStatement({ |
| 36 | + actions: ['codepipeline:StartPipelineExecution'], |
| 37 | + resources: [this.pipeline.pipelineArn], |
| 38 | + })); |
| 39 | + } |
| 40 | +} |
0 commit comments