c2.21 Keep secrets out of code
Hardcoding secrets in code risks exposing a credential to anyone who can read the repository. Fetch secrets at runtime from AWS Secrets Manager, and scan code so a committed secret is caught before it ships.
Implementation guidance
Do not hardcode secrets
A secret in code can be read by anyone with access to the repository, is easily leaked to public repositories, and is hard to rotate. If the hardcoded secret is an access key, prefer temporary credentials via roles instead.
Fetch long-lived secrets at runtime
When your code needs a genuine long-lived secret (a database password, a third-party API key), store it in AWS Secrets Manager and retrieve it at runtime. Grant the workload permission to read the secret through its IAM role (instance profile, Lambda/ECS execution role), so no credential is embedded in the code. Secrets Manager can rotate supported secrets automatically — see the best practices.
Catch secrets before they ship
Scan code for committed secrets with tools such as git-secrets, and integrate secret scanning into your pipeline so a detected secret blocks promotion. Amazon Q Developer also flags secrets as code is written.
Fetch at runtime, scan before commit
Retrieve the secret at runtime instead of hardcoding it:
aws secretsmanager get-secret-value \
--secret-id prod/db/password \
--query SecretString --output text
Add a repository scan so a committed secret blocks the pipeline:
git secrets --install
git secrets --register-aws
git secrets --scanHow to validate
- Do you use AWS Secrets Manager (or similar) to store and rotate secrets such as database passwords?
- Are you preventing secrets from being committed to code (scanning, pre-commit checks)?
- Are developers trained not to store secrets in code?
- Does the pipeline stop when a secret is detected?
Threats addressed
- Secrets in code can be taken by anyone with read access (testers, reviewers) and used outside the code or sold to adversaries.
- Developers may push code to public repositories such as GitHub, exposing the credentials; adversaries actively scrape repositories for them.
- Hardcoded secrets are hard to rotate quickly, which matters most during a known compromise. The same risks apply to secrets in config files committed alongside the code.
AWS services
Pricing
AWS Secrets Manager costs USD 0.40 per secret per month plus USD 0.05 per 10,000 API calls, with a 30-day free trial. See Secrets Manager pricing.
Cloud Security Maturity Model