如何避免AWS CloudFormation无配置变更时也重建自定义AMI镜像
问题根因
该现象是AWS::ImageBuilder::Image资源的默认更新逻辑导致:该类型资源默认在每次CloudFormation栈更新时都会触发新的AMI构建,即便关联的镜像配方、基础设施配置没有任何属性变更。
解决方案
可通过以下两种配置实现仅在相关属性变更时才触发AMI重建:
方案1:改用ImagePipeline资源(推荐)
替换直接声明AWS::ImageBuilder::Image的方式,改用AWS::ImageBuilder::ImagePipeline资源,该资源默认仅在关联的镜像配方、组件、基础设施配置发生变更时才触发构建,符合预期。
调整后的模板参考:
Resources: pipelineImageBuilder: Type: AWS::ImageBuilder::ImageRecipe Properties: Components: - ComponentArn: arn:aws:imagebuilder:us-east-1:aws:component/aws-cli-version-2-linux/1.0.2 Name: Nextflow AMI ParentImage: ami-03db9b2aac6af477d Version: 1.0.1 Metadata: aws:cdk:path: pipelineStack/pipelineImageBuilder pipelineImagePipeline: Type: AWS::ImageBuilder::ImagePipeline Properties: Name: Nextflow-AMI-Pipeline ImageRecipeArn: !GetAtt pipelineImageBuilder.Arn InfrastructureConfigurationArn: !GetAtt infrastructureConfig.Arn # 关闭定时构建,仅在配置变更时触发 Schedule: PipelineExecutionStartCondition: EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE Status: ENABLED Metadata: aws:cdk:path: pipelineStack/pipelineImagePipeline
方案2:保留原有结构,通过版本号控制重建
如果不想调整现有资源结构,可以通过绑定镜像配方版本号的方式控制:
- 每次修改镜像配方的配置(如组件、父镜像等)时,同步升级
pipelineImageBuilder的Version属性值 - 给
AWS::ImageBuilder::Image资源设置带版本号的物理名称,CloudFormation会在版本号变更时才触发资源重建
注意事项
如果模板是通过AWS CDK生成的,可直接给ImageRecipe的version参数传入自定义版本值,每次修改镜像配置时手动升级版本号即可,无变更时CDK不会触发镜像重建。
内容的提问来源于stack exchange,提问作者Migwell
相关产品推荐
相关产品推荐

