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

How to rename/update stage label of secret in AWS secret manager - java


I am storing my keys in aws key manager. It has 2 stage labels AWSCURRENT and AWSPREVIOUS after rotation

Can we update/rename AWSPREVIOUS to TESTJK I tried below code, I didnt throw any error how ever it doesnt do what i was expecting

What I am expecting

Rename AWSPREVIOUS as TESTJK and keep secret value as it is

        GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest().withSecretId(secretKey)
            .withVersionStage("AWSPREVIOUS");
        GetSecretValueResult getSecretValueResult = client.getSecretValue(getSecretValueRequest);

        log.info("jkdata ww {}", getSecretValueResult.getSecretString());
        log.info("verison id{}", getSecretValueResult.getVersionId());

        UpdateSecretVersionStageRequest updateSecretVersionStageRequest = new UpdateSecretVersionStageRequest()
            .withSecretId(secretKey)
            .withMoveToVersionId(getSecretValueResult.getVersionId())
            .withRemoveFromVersionId(getSecretValueResult.getVersionId());
        client.updateSecretVersionStage(updateSecretVersionStageRequest).setName("TESTJK");

What is expected :

It will rename AWSPREVIOUS to TESTJK so next time if i query with AWSPREVIOUS i will get error and if i query with TESTJK i should get secret value.

Current : I am getting value for AWSPREVIOUS but error for TESTJK

com.amazonaws.services.secretsmanager.model.ResourceNotFoundException: Secrets Manager can’t find the specified secret value for staging label: TESTJK (Service: AWSSecretsManager; Status Code: 400; Error Code: ResourceNotFoundException; Request ID: 4c15706e-e1bd-424a-ba03-4914e6523a34)

Solution

  • This would require two api requests. The first one take version id of AWSPREVIOUS and assign it to 'TESTJK':

    GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest()
    .withSecretId(secretKey)
    .withVersionStage("AWSPREVIOUS");
    
    GetSecretValueResult getSecretValueResult = client.getSecretValue(getSecretValueRequest);
    
    UpdateSecretVersionStageRequest updateSecretVersionStageRequest = new UpdateSecretVersionStageRequest()
                .withSecretId(secretKey)
                .withVersionStage("TESTJK")
                .withMoveToVersionId(getSecretValueResult.getVersionId())
            client.updateSecretVersionStage(updateSecretVersionStageRequest);
    

    At this point, you could leave both stages associated with the same versionId or you could remove the AWSPREVIOUS version stage:

    UpdateSecretVersionStageRequest updateSecretVersionStageRequest = new UpdateSecretVersionStageRequest()
                .withSecretId(secretKey)
                .withVersionStage("AWSPREVIOUS")
                .withRemoveFromVersionId(getSecretValueResult.getVersionId())
            client.updateSecretVersionStage(updateSecretVersionStageRequest);