Gulshan
Gulshan

Reputation: 83

Rotating a Secret Using a Custom Lambda Function

How to write a lambda for a rotating secret (CDK in Typescript)where password changes every hour .

const templatedSecret = new secretsmanager.Secret(this, 'TemplatedSecret', {
      generateSecretString: {
        secretStringTemplate: JSON.stringify({ username: 'user' }),
        generateStringKey: 'password',
      },
    });

    new iam.User(this, 'OtherUser', {
      userName: templatedSecret.secretValueFromJson('username').toString(),
      password: templatedSecret.secretValueFromJson('password'),
    });

till now i only have this code and for reference i have https://docs.aws.amazon.com/cdk/api/latest/docs/aws-secretsmanager-readme.html#rotating-a-secret But i am confused how to proceed and complete my desired task

Upvotes: 2

Views: 3214

Answers (1)

kgiannakakis
kgiannakakis

Reputation: 104168

As your link states you need to add a schedule to your secret:

const fn = new lambda.Function(...);
const secret = new secretsmanager.Secret(this, 'Secret');

secret.addRotationSchedule('RotationSchedule', {
  rotationLambda: fn,
  automaticallyAfter: Duration.days(15)
});

Modify duration as needed. You also need to create a lambda function (fn) that will handle rotation. It is probably a generic secret that you need, so you should base your sample on this template.

You need to fill in the set_secret and test_secret methods. The set_secret sets the secret in your service. If it is a DB, it calls an API that updates the password of the user. If you don't need it, leave an empty application. The test_secret tests that the new secret is operational. An empty implementation will also work.

You also need to add lambda invoke permission for secrets manager. Something like this:

fn.addPermission('allowInvocation',{
  principal: new ServicePrincipal('secretsmanager.amazonaws.com')
})

In AWS Console, go to Lambda Configuration, scroll down to Resource-based policy and add the following Permission:

enter image description here

Upvotes: 3

Related Questions