question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Proposed way to use iam access and secretKey in cdk

See original GitHub issue

❓ General Issue

There are a lot of application out there that still require an access/secretKey pair and do not work with roles. What’s the ideal/secure way to use those in cdk without creating resources manually beforehand.

The Question

There is the parameter store (SSM) and the secrets manager (SM) available. In SSM I can only create “normal” strings from cdk/cloudformation - not secure strings. In SM I can only get a new secret but not store my own one.

So the only option currently seems to be this:

const user = new iam.User(this, 'User', {
    userName: this.getConfig('bucketName'),
})

const accessKey = new iam.CfnAccessKey(this, 'AccessKey', {
    userName: user.userName,
})

const ssmSecretKey = new ssm.StringParameter(this, 'SsmSecretKey', {
    parameterName: '/' + [this.account, this.stackName, 'secretKey'].join('/'),
    stringValue: accessKey.attrSecretAccessKey,
})

const bucket = new s3.Bucket(this, 'Bucket', {
    bucketName: this.getConfig('bucketName'),
    versioned: false,
    removalPolicy: RemovalPolicy.RETAIN,
    publicReadAccess: false,
    blockPublicAccess: BlockPublicAccess.BLOCK_ALL,
})

bucket.grantReadWrite(user)

and then of course using it later in my case in ecs:

const loadBalancedEcsService = new ecsPatterns.ApplicationLoadBalancedEc2Service(this, 'Service', {
    cluster: cluster,
    memoryLimitMiB: 1024,
    taskImageOptions: {
        image: ecs.ContainerImage.fromEcrRepository(asset.repository),
        environment: {
            AWS_ACCESS_KEY_ID: accessKey.ref,
            AWS_DEFAULT_REGION: this.region,
        },
        secrets: {
            AWS_SECRET_ACCESS_KEY: ecs.Secret.fromSsmParameter(ssmSecretKey),
        },
        containerPort: 4873,
    },
    desiredCount: 1,
    domainName: this.getConfig('domainName'),
    protocol: ApplicationProtocol.HTTPS,
    domainZone: domainZone,
    healthCheckGracePeriod: cdk.Duration.seconds(60),
})

Other information

#1857 #3520

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:6
  • Comments:17 (11 by maintainers)

github_iconTop GitHub Comments

4reactions
flochazcommented, Sep 16, 2020

Unfortunately we are a little bound by what CloudFormation supports in this area. I think a Custom Resource that creates the keypair and stores it in SecretsManager is going to be your best bet.

Here is an example using awsCustomResource to store accessKeyId and secretAccessKey in

const adminPassword = new secretsmanager.Secret(this, "AdminUserPassword");

    const mainAdminUser = new iam.User(this, "admin", {
      userName: "admin",
      password: adminPassword.secretValue,
    });

    const accessKey = new iam.CfnAccessKey(this, "AdminUserAccessKey", {
      userName: mainAdminUser.userName,
    });

    new cr.AwsCustomResource(this, 
      "AdminAccessKeyIdSecret", 
      {
        onCreate: {
          service: 'SecretsManager',
          action: 'createSecret',
          physicalResourceId: cr.PhysicalResourceId.fromResponse('Name'),
          parameters:
            {
              Name: "AdminAccessKeyId", 
              SecretString: accessKey.ref
            }
        },
        installLatestAwsSdk: false, 
        policy: cr.AwsCustomResourcePolicy.fromSdkCalls(
          {
            resources: cr.AwsCustomResourcePolicy.ANY_RESOURCE
          }
        ),
        logRetention: RetentionDays.ONE_DAY
      }
    );

    new cr.AwsCustomResource(this, 
      "AdminSecretAccessKeySecret", 
      {
        onCreate: {
          service: 'SecretsManager',
          action: 'createSecret',
          physicalResourceId: cr.PhysicalResourceId.fromResponse('Name'),
          parameters:
            {
              Name: "AdminSecretAccessKey", 
              SecretString: accessKey.attrSecretAccessKey
            }
        },
        installLatestAwsSdk: false, 
        policy: cr.AwsCustomResourcePolicy.fromSdkCalls(
          {
            resources: cr.AwsCustomResourcePolicy.ANY_RESOURCE
          }
        ),
        logRetention: RetentionDays.ONE_DAY
      }
    );

But custom resource lambda logs will contains your secret for 24h (might have a way to force delete the logStream though)

2reactions
sblackstonecommented, Aug 7, 2020

Ideally when creating a user, you would be able to just specify a key and it would populate that key in your secrets manager on your behalf… Then you’d never need to actually see the key in the first place and it would programatically be available to your app.

Read more comments on GitHub >

github_iconTop Results From Across the Web

class AccessKey (construct) · AWS CDK
Creates a new IAM user, access and secret keys, and stores the secret access key in a Secret. const user = new iam.User(this,...
Read more >
Create AWS access key and secret access key for an IAM user
Create long-term AWS IAM credentials for your CI/CD system or a legacy microservice, or anything that doesn't support IAM Roles and STS credentials....
Read more >
AWS CDK - How to pass Access Key Secret and Secret Key Id ...
My issue is I cannot get aws secret key and id and then, pass as Env variable to my container. See below: First,...
Read more >
Managing AWS S3 Bucket And Write IAM User Access Key ...
A simple way of accessing a user's access key Id and the secret is to created AWS CloudFormation outputs for it. ... To...
Read more >
AWS Account and User | AWS CDK Workshop
Open a terminal window and use aws configure to set up your environment. Type the access key ID and secret key and choose...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found