|
| 1 | +import { ISchedule, IScheduleTarget } from '@aws-cdk/aws-scheduler-alpha'; |
| 2 | +import { Names } from 'aws-cdk-lib'; |
| 3 | +import { IProject } from 'aws-cdk-lib/aws-codebuild'; |
| 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 CodeBuild as a target for AWS EventBridge Scheduler. |
| 10 | + */ |
| 11 | +export class CodeBuildStartBuild extends ScheduleTargetBase implements IScheduleTarget { |
| 12 | + constructor( |
| 13 | + private readonly project: IProject, |
| 14 | + private readonly props: ScheduleTargetBaseProps = {}, |
| 15 | + ) { |
| 16 | + super(props, project.projectArn); |
| 17 | + } |
| 18 | + |
| 19 | + protected addTargetActionToRole(schedule: ISchedule, role: IRole): void { |
| 20 | + if (!sameEnvDimension(this.project.env.region, schedule.env.region)) { |
| 21 | + throw new Error(`Cannot assign project in region ${this.project.env.region} to the schedule ${Names.nodeUniqueId(schedule.node)} in region ${schedule.env.region}. Both the schedule and the project must be in the same region.`); |
| 22 | + } |
| 23 | + |
| 24 | + if (!sameEnvDimension(this.project.env.account, schedule.env.account)) { |
| 25 | + throw new Error(`Cannot assign project in account ${this.project.env.account} to the schedule ${Names.nodeUniqueId(schedule.node)} in account ${schedule.env.region}. Both the schedule and the project must be in the same account.`); |
| 26 | + } |
| 27 | + |
| 28 | + if (this.props.role && !sameEnvDimension(this.props.role.env.account, schedule.env.account)) { |
| 29 | + throw new Error(`Cannot grant permission to execution role in account ${this.props.role.env.account} to invoke target ${Names.nodeUniqueId(schedule.node)} in account ${schedule.env.account}. Both the target and the execution role must be in the same account.`); |
| 30 | + } |
| 31 | + |
| 32 | + role.addToPrincipalPolicy(new PolicyStatement({ |
| 33 | + actions: ['codebuild:StartBuild'], |
| 34 | + resources: [this.project.projectArn], |
| 35 | + })); |
| 36 | + } |
| 37 | +} |
0 commit comments