Skip to content

Instantly share code, notes, and snippets.

@ntippie
Last active January 10, 2024 18:56
Show Gist options
  • Save ntippie/4560548dde3b4bc8e8d6963dd8128231 to your computer and use it in GitHub Desktop.
Save ntippie/4560548dde3b4bc8e8d6963dd8128231 to your computer and use it in GitHub Desktop.
AWS CDK v2 AwsCustomResource to look up an AMI
import {
type IMachineImage,
OperatingSystemType,
UserData,
} from 'aws-cdk-lib/aws-ec2';
import {
AwsCustomResource,
AwsCustomResourcePolicy,
PhysicalResourceId,
} from 'aws-cdk-lib/custom-resources';
import { Construct } from 'constructs';
type AmiLookupProps = {
name: string;
owners: string[];
};
export default class AmiLookup extends AwsCustomResource {
amiName: string;
machineImage: IMachineImage;
constructor(scope: Construct, id: string, props: AmiLookupProps) {
const { name, owners } = props;
super(scope, id, {
installLatestAwsSdk: false,
onUpdate: {
service: 'EC2',
action: 'describeImages',
parameters: {
Filters: [
{ Name: 'name', Values: [name] },
{ Name: 'state', Values: ['available'] },
{ Name: 'image-type', Values: ['machine'] },
],
Owners: owners,
},
physicalResourceId: PhysicalResourceId.of(
`${id}AmiLookupCustomResource`,
),
},
policy: AwsCustomResourcePolicy.fromSdkCalls({
resources: AwsCustomResourcePolicy.ANY_RESOURCE,
}),
});
this.amiName = this.getResponseField('Images.0.ImageId');
this.machineImage = {
getImage: () => {
const osType = OperatingSystemType.LINUX;
return {
imageId: this.amiName,
osType,
userData: UserData.forOperatingSystem(osType),
};
},
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment