Search code examples
amazon-web-servicesaws-cloudformationaws-secrets-manager

How to add a key into an existing AWS::SecretsManager::Secret


I have a CloudFormation template where I create and RDS instance. First I create a AWS::SecretsManager::Secret and save there values that I will use as MasterUserPassword MasterUsername and DBName in AWS::RDS::DBInstance under some secret name. But I also would like to put into this secret the RDS instance hostname which I'll get after the DBInstance will be created.

Is it possible to update an existing secret in CloudFormation?

Example of a template I have:

Resources:
  RDSInstanceSecret:
    Type: AWS::SecretsManager::Secret
    Properties:
      Name: "mysecret"
      GenerateSecretString:
        SecretStringTemplate: !Sub '{"username":"root", "dbname":"db"}'
        GenerateStringKey: 'password'
        PasswordLength: 16
        ExcludeCharacters: '"@/\'
  RDSInstance:
    DependsOn: RDSInstanceSecret
    Properties:
      DBName: !Join ['', ['{{resolve:secretsmanager:', !Ref RDSInstanceSecret, ':SecretString:dbname}}' ]]
      Engine: "postgres"
      EngineVersion: "9.6"
      MasterUserPassword: !Join ['', ['{{resolve:secretsmanager:', !Ref RDSInstanceSecret, ':SecretString:password}}' ]]
      MasterUsername: !Join ['', ['{{resolve:secretsmanager:', !Ref RDSInstanceSecret, ':SecretString:username}}' ]]

Outputs:
  EndpointRDS:
    Value: !Sub '${RDSInstance.Endpoint.Address}:${RDSInstance.Endpoint.Port}'  # I would like to save it to RDSInstanceSecret

My current thoughts are to create another Secret after I created an instance and put there all the secrets from the first Secret + RDS endpoint. But this will leave one useless Secret resource.


Solution

  • I think you are looking for the CFN AWS::SecretsManager::SecretTargetAttachment resource which adds the DB type and connection details to the secret.