Cloudformation best practices

From findscripter/everything-skills · View interactive version

Cloudformation best practices is an AI agent skill from the GitHub repository findscripter/everything-skills. 当编写/审查 AWS CloudFormation 模板、设计嵌套或跨栈架构、排查栈创建更新失败与漂移时使用;产出可维护、可多环境复用的生产级模板与部署/校验命令;不适用于用户选用 CDK/Terraform 或纯应用代码的场景。触发词:CloudFormation、嵌套栈、漂移检测

How to use this skill

Skill file

何时使用

不该用:

步骤

  1. 优先用 YAML 而非 JSON,可读性更好。
  2. 把环境相关值参数化(Parameters);静态查表用 Mappings。
  3. 有状态资源(RDS、S3、DynamoDB)加 DeletionPolicy: Retain,并配套 UpdateReplacePolicy。
  4. 用 Conditions 支撑多环境模板(dev/staging/prod)。
  5. 部署前用 aws cloudformation validate-template 校验。
  6. 字符串拼接优先 !Sub 而非 !Join。
  7. 跨栈引用用 Outputs + Export,被引用方再用 Fn::ImportValue。
  8. 模板拆分:避免单一巨型模板,按职责拆成嵌套栈或独立栈。

指令

# 部署前校验模板语法
aws cloudformation validate-template --template-body file://template.yaml

# CI 中静态检查与安全扫描
cfn-lint template.yaml
cfn-nag_scan --input-path template.yaml

# 检测已部署栈的配置漂移
aws cloudformation detect-stack-drift --stack-name my-stack

示例

参数化 VPC 模板(多环境 + 跨栈导出):

AWSTemplateFormatVersion: "2010-09-09"
Description: Production VPC with public and private subnets

Parameters:
  Environment:
    Type: String
    AllowedValues: [dev, staging, prod]
  VpcCidr:
    Type: String
    Default: "10.0.0.0/16"

Conditions:
  IsProd: !Equals [!Ref Environment, prod]

Resources:
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: !Ref VpcCidr
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: !Sub "${Environment}-vpc"

Outputs:
  VpcId:
    Value: !Ref VPC
    Export:
      Name: !Sub "${Environment}-VpcId"

注意事项

互见


采编自 sickn33/antigravity-awesome-skills(MIT)。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.