Append keys to existing Secret in AWS Secrets Manager

The AWS update-secret operation for Secrets Manager replaces all keys of a secret with the new value provided in the --secret-string.

But sometimes we want to add a few extra keys, without replacing values already present in a secret.

In this post we show how to use bash to add keys to a secret without replacing existing values.

What you need

  • jq installed

1. Prepare the list of secrets you want to add the new keys

This command generates a file named all-secrets. Run the command and update the file to reflect the list of secrets you want to add the new keys.

# Create `all-secrets` fileaws secretsmanager list-secrets | jq .SecretList | jq '.[]' | jq -r .ARN > all-secrets
Keep only the the secrets you want to add the new keys in the generated all-secrets file

2. Store the new keys in a json file named new-keys.json

echo '{  "AWS_ACCESS_KEY_ID": "AKIAIOSFODNN7EXAMPLE"  "AWS_SECRET_ACCESS_KEY": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"}' > new-keys.json

3. Run the script

The script uses the all-secrets and new-keys.json files created in steps 1 and 2.

while read line; do  aws secretsmanager get-secret-value \  --secret-id $line | \  jq -c '.SecretString | fromjson' > current-keys.json    jq -s '.[0] * .[1]' current-keys.json new-keys.json > merge.json    aws secretsmanager update-secret --secret-id $line --secret-string file://merge.json > updateddone <all-secrets

For each line in the all-secrets file, the script:

  • Gets current secret value and save to current-keys.json file
  • Merges current-keys.soj and new-keys.json into merge.json
  • Updates the secret value with the merge.json file contents as the secret-string