首页 > 解决方案 > 在 Cloudformation 上更新堆栈时轮换 AWS 密钥

问题描述

我有一个 Cloudformation 脚本,它调用多个嵌套堆栈,例如创建数据库的堆栈。我首先在秘密管理器中创建一个秘密,然后在数据库实例中使用它作为用户名和密码。我现在不想启用自动秘密轮换。

我的问题是每次更新堆栈时,它都会生成一个新的秘密,该秘密不会传播到数据库。所以之后,当我更新的ECS服务尝试连接数据库时,它使用了错误的密码,因此无法稳定,然后一切都必须回滚。

为什么即使我没有配置密码,我的密码也会轮换?有没有办法避免这种情况?如果不能,我应该添加 AWS::SecretsManager::SecretTargetAttachment 以至少将更改传播到数据库吗?

DBSecret:
  Type: "AWS::SecretsManager::Secret"
  Properties:
    Name: !Join ['', [!Ref ProductName, '-', !Ref EnvironmentName, '-', !Ref DBName, '-db-secret']]
    Description: Secret to be used for the database 
    KmsKeyId: !Ref KmsKeyId
    GenerateSecretString:
      SecretStringTemplate: !Join ['', ['{"username": "', !Ref DBUser , '"}']]
      GenerateStringKey: "password"
      PasswordLength: 30
      ExcludeCharacters: '"@/\'
    Tags:
      - Key: Name
        Value: !Join ['', [!Ref ProductName, '-', !Ref EnvironmentName, '-', !Ref DBName, '-db-secret']]

PostgresDb:
  Type: AWS::RDS::DBInstance
  Properties:
    AllocatedStorage: !Ref DBAllocatedStorage
    AutoMinorVersionUpgrade: 'true'
    VPCSecurityGroups:
      - Ref: SecurityGroup
    DBName: !Ref DBName
    DBInstanceClass: !Ref DBInstanceClass
    DBSubnetGroupName: !Ref DBSubnetGroup
    Engine: postgres
    EngineVersion: !Ref DBVersion
    MasterUsername: !Join ['', ['{{resolve:secretsmanager:', !Ref DBSecret , ':SecretString:username}}']]
    MasterUserPassword: !Join ['', ['{{resolve:secretsmanager:', !Ref DBSecret , ':SecretString:password}}']]
    MultiAZ: !Ref DBMultiAZ
    StorageType: gp2
    BackupRetentionPeriod: 7
    StorageEncrypted: !Ref DBEncrypted
    # Only add the KMS key if the db is going to be encrypted
    KmsKeyId: !If [IsEncrypted, !Ref KmsKeyId, !Ref "AWS::NoValue"]
    MonitoringInterval: !If [HasEnhancedMonitoring, !Ref DBEnhancedMonitoringInterval, "0"]
    MonitoringRoleArn: !If [HasEnhancedMonitoring, !Ref DBMonitoringRoleARN, !Ref "AWS::NoValue"]
    Port: 5432

    Tags:
      - Key: Name
        Value: !Ref DBIdentifier

标签: amazon-web-servicesamazon-cloudformationamazon-rdsaws-secrets-manager

解决方案


您需要将数据库和数据库配置分开在单独的堆栈中。数据库基础设施和数据库密码不是您会经常更新的东西,而您的代码将处于不断变化的生命周期中。您的 ECS 服务可以使用 Fn::ImportValue 从其他堆栈引用您的密码。在此处查看文档:

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html


推荐阅读