I want to activate ECR enhanced scanning (continuous scanning) for an ECR registry via AWS CDK. I checked the API reference but the AWS ECR ImageScanningConfigurationProperty does not provide an enhanced scanning option. I checked aws-inspector v1 and v2 as well but was not able to find something. Any suggestions how to realize this in AWS CDK?
Yes you definitely can do that with AWS CDK. Check out my sample below. Hope it helps!
import {
Stack,
StackProps,
aws_iam as iam,
custom_resources as cr,
ArnFormat
} from 'aws-cdk-lib';
import {
Construct
} from 'constructs';
import * as AWS from 'aws-sdk';
export class MyStack extends Stack {
constructor(scope: Construct, id: string, props ? : StackProps) {
super(scope, id, props);
const onCreateParam: AWS.ECR.PutRegistryScanningConfigurationRequest = {
scanType: 'ENHANCED',
rules: [{
repositoryFilters: [{
filter: '*',
filterType: 'WILDCARD',
}, ],
scanFrequency: 'SCAN_ON_PUSH',
}]
};
const onDeleteParam: AWS.ECR.PutRegistryScanningConfigurationRequest = {
scanType: 'BASIC',
rules: [{
repositoryFilters: [{
filter: '*',
filterType: 'WILDCARD',
}, ],
scanFrequency: 'SCAN_ON_PUSH',
}]
};
const enabler = new cr.AwsCustomResource(this, 'EnhancedScanningEnabler', {
policy: cr.AwsCustomResourcePolicy.fromSdkCalls({
resources: cr.AwsCustomResourcePolicy.ANY_RESOURCE,
}),
onCreate: {
service: 'ECR',
physicalResourceId: cr.PhysicalResourceId.of('id'),
action: 'putRegistryScanningConfiguration',
parameters: onCreateParam,
},
onDelete: {
service: 'ECR',
action: 'putRegistryScanningConfiguration',
parameters: onDeleteParam,
},
})
enabler.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({
actions: ['inspector2:ListAccountPermissions'],
resources: [
Stack.of(this).formatArn({
service: 'inspector2',
resource: '/accountpermissions',
arnFormat: ArnFormat.SLASH_RESOURCE_NAME,
resourceName: 'list',
}),
],
}));
}
}
Make sure to activate AWS inspector from the console to create the service-linked role.