在Cloudformation中使用AWS Secrets Manager的秘密

时间:2019-01-17 08:01:38

标签: amazon-cloudformation aws-secrets-manager

我想将read_only_user的密码导出到EC2实例。如何访问UserData中创建的密码?

Resources:
  ReadOnlyUserCredentials:
      Type: AWS::SecretsManager::Secret
      Properties:
        Name: !Sub "${AWS::StackName}/readonly-user-credentials"
        GenerateSecretString:
          SecretStringTemplate: '{"username": "read_only_user"}'
          GenerateStringKey: 'password'
          PasswordLength: 16
          ExcludeCharacters: '"@/\'
  WebServer:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: ami-a4c7edb2
      InstanceType: t2.micro
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash
          echo "${!Join ['', ['{{resolve:secretsmanager:', !Ref ReadOnlyUserCredentials, ':SecretString:password}}' ]]}" > password

我尝试使用!Join,但是当然不起作用。非常感谢您的帮助。

更新:

      UserData:
        Fn::Base64:
         Fn::Sub:
          - |
            echo ${PasswordStr} > password
          - PasswordStr: !Join ['', ['{{resolve:secretsmanager:', !Ref ReadOnlyUserCredentials, ':SecretString:password}}' ]]

通过更改上面显示的代码,我确实获得了解析字符串,但是它没有提供实际的密码。如何解析arn以获取普通密码?

1 个答案:

答案 0 :(得分:0)

您可能不希望CFN在用户数据中扩展秘密,因为密码将嵌入在EC2控制台中可见的base64编码的用户数据脚本中。

相反,您应该利用以下事实:您有一个脚本在主机上执行,并在脚本执行时调用秘密管理器(警告,未经测试):

Resources:
  ReadOnlyUserCredentials:
      Type: AWS::SecretsManager::Secret
      Properties:
        Name: !Sub "${AWS::StackName}/readonly-user-credentials"
        GenerateSecretString:
          SecretStringTemplate: '{"username": "read_only_user"}'
          GenerateStringKey: 'password'
          PasswordLength: 16
          ExcludeCharacters: '"@/\'
  WebServer:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: ami-a4c7edb2
      InstanceType: t2.micro
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash
          yum update -y
          yum install -y jq
          aws --region ${AWS::Region} secretsmanager get-secret-value --secret-id !Ref ReadOnlyUserCredentials --query SecretString --output text | jq -r .password > password