使用cloudformation和Secrets Manager将Jenkins部署到AWS

时间:2019-05-06 23:44:42

标签: jenkins amazon-cloudformation aws-codepipeline aws-secrets-manager

我的目标是将Jenkins构建为docker映像并将其部署到AWS Elastic Beanstalk。

要构建docker映像,我正在使用Configuration as Code插件,并通过Dockerfile中的环境变量注入所有秘密。

我现在想弄清楚的是如何使用CloudFormation或CodePipeline自动执行此部署。

我的问题是:

  • 我可以使用CloudFormation或CodePipeline从AWS Secrets Manager中获取机密,并将其作为环境变量注入到Elastic Beanstalk的部署中吗?

2 个答案:

答案 0 :(得分:1)

不确定一般为什么要用这种方式做事,但是您是否不能仅使用AWS CLI从ELB实例直接从Secrets Manager获取机密?

答案 1 :(得分:0)

Cloudformation模板可以从Secrets Manager中恢复机密。这有点难看,但效果很好。通常,我使用security.yaml嵌套堆栈在SM中为我生成秘密,然后在其他堆栈中恢复它们。

我不能对EB讲太多,但是如果您通过CF进行部署,那应该会有所帮助。

在SM(CF security.yaml)中生成机密:

Parameters:
  DeploymentEnvironment:
    Type: String
    Description: Deployment environment, e.g. prod, stage, qa, dev, or userdev
    Default: "dev"
...
Resources:
...  
  RegistryDbAdminCreds:
    Type: 'AWS::SecretsManager::Secret'
    Properties:
      Name: !Sub "RegistryDbAdminCreds-${DeploymentEnvironment}"
      Description: "RDS master uid/password for artifact registry database."
      GenerateSecretString:
        SecretStringTemplate: '{"username": "artifactadmin"}'
        GenerateStringKey: "password"
        PasswordLength: 30
        ExcludeCharacters: '"@/\+//:*`"'
      Tags:
      -
        Key: AppName
        Value: RegistryDbAdminCreds

在另一个Yaml中使用秘密:

Parameters:
  DeploymentEnvironment:
    Type: String
    Description: Deployment environment, e.g. prod, stage, qa, dev, or userdev
    Default: "dev"
...
Resources:
  DB:
    Type: 'AWS::RDS::DBInstance'
    DependsOn: security
    Properties:
      Engine: postgres
      DBInstanceClass: db.t2.small
      DBName: quilt
      MasterUsername: !Sub '{{resolve:secretsmanager:RegistryDbAdminCreds-${DeploymentEnvironment}:SecretString:username}}'
      MasterUserPassword: !Sub '{{resolve:secretsmanager:RegistryDbAdminCreds-${DeploymentEnvironment}:SecretString:password}}'
      StorageType: gp2
      AllocatedStorage: "100"
      PubliclyAccessible: true
      DBSubnetGroupName: !Ref SubnetGroup
      MultiAZ: true
      VPCSecurityGroups:
      - !GetAtt "network.Outputs.VPCSecurityGroup"
      Tags:
      - Key: Name
        Value: !Join [ '-', [ !Ref StackName, "dbinstance", !Ref DeploymentEnvironment ] ]

诀窍在!Sub '{{resolve:secretsmanager:RegistryDbAdminCreds-${DeploymentEnvironment}:SecretString:username}}'!Sub '{{resolve:secretsmanager:RegistryDbAdminCreds-${DeploymentEnvironment}:SecretString:password}}'