AWS Builder Center
The Secret Wasn't in Git. It Was in CloudWatch Logs.

The Secret Wasn't in Git. It Was in CloudWatch Logs.

You removed API keys from your source code, configured AWS Lambda environment variables, and thought your application was secure. But what happens when a debug statement, exception, or event payload sends sensitive information straight into CloudWatch Logs? Explore a realistic serverless security mistake and learn how to protect secrets properly.

I'm a btech final year student, i'm passionate about cyber security especially in cloud security

The Secret Wasn't in Git. It Was in CloudWatch Logs.

You checked your GitHub repository.
No API keys.
No database passwords.
No hardcoded credentials.
You even moved your application's configuration into AWS Lambda environment variables.
Everything looks secure.
Then someone opens CloudWatch Logs and finds an API key sitting inside a debug message.
No sophisticated exploit. No complicated attack chain.
Just one careless logging statement.
This is a security mistake that is easy to overlook when building serverless applications: protecting secrets at storage time is not enough if your application exposes them during execution.
Let's look at how this happens and how to prevent it.

1. How does a secret end up in CloudWatch Logs?

Imagine a Lambda function that receives an API request and connects to an external service.
The application needs an API key to authenticate.
A developer stores the key as an environment variable:
import os

API_KEY = os.environ.get("API_KEY")
This is better than hardcoding the key directly into the source code.
But during debugging, someone adds:
print("Using API key:", API_KEY)
The function executes.
The output gets sent to CloudWatch Logs.
Now the API key may be visible to anyone who has sufficient access to that log data.
The original intention was debugging. The result was an unnecessary exposure of sensitive information.
Other common mistakes include:
  • Logging complete HTTP request headers.
  • Printing authorization tokens.
  • Logging database connection strings.
  • Recording entire event payloads without checking their contents.
  • Including secrets in exception messages.
  • Returning sensitive configuration in API responses.
The important lesson: a secret can be stored securely and still be exposed by application behavior.

2. Environment variables are not a complete secrets-management strategy

AWS Lambda supports environment variables and encrypts their values at rest.
They are useful for passing configuration into a function.
However, AWS recommends using AWS Secrets Manager instead of environment variables for sensitive values such as database credentials, API keys, and authorization tokens.
Why?
Because managing a secret involves more than storing a value.
You also need to consider:
  • Who can retrieve it?
  • How is access controlled?
  • Can it be rotated?
  • Can access be audited?
  • Where could the application accidentally expose it?
AWS Secrets Manager provides dedicated secret-management capabilities, including access control, encryption, and rotation support.
Moving a secret into Secrets Manager does not automatically make the application secure, though. Your code must still avoid printing or exposing the retrieved value.

3. A better approach: retrieve secrets when the application needs them

Instead of hardcoding a secret or casually placing sensitive values in application configuration, use AWS Secrets Manager.
A simplified architecture looks like this:
Application Request
|
v
AWS Lambda Function
|
v
Lambda Execution Role
|
v
AWS Secrets Manager
|
v
Retrieve Required Secret
|
v
Connect to External Service
The Lambda execution role should have permission to retrieve only the specific secret required by that function.
For example, a narrowly scoped IAM policy could look like this:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"secretsmanager:GetSecretValue"
],
"Resource": "arn:aws:secretsmanager:REGION:ACCOUNT_ID:secret:my-app-api-key-*"
}
]
}
Replace the placeholders with your actual AWS Region, account ID, and secret ARN.
This is an illustrative policy. Validate the resource ARN and any additional permissions required by your configuration, including KMS permissions if you use a customer-managed key.
The idea is to avoid giving every Lambda function access to every secret in your account.

4. Example: retrieving a secret using Python

Here is a simplified Python example using  boto3 :
import json
import boto3

secrets_client = boto3.client("secretsmanager")

def get_api_key():
response = secrets_client.get_secret_value(
SecretId="my-app-api-key"
)

secret = json.loads(response["SecretString"])

return secret["api_key"]

def lambda_handler(event, context):
api_key = get_api_key()

# Use the key to authenticate with the service.
# Never print or log the secret.

return {
"statusCode": 200,
"body": "Request processed"
}
For this example, assume the secret contains JSON with an  api_key  field.
Notice something important: the function retrieves the secret and uses it, but does not print the value.
For production workloads, consider caching secrets appropriately to reduce repeated retrieval calls and latency. If you cache a secret, account for rotation and expiration so that the application does not continue using an outdated value indefinitely.

5. Fix the logging problem before it becomes an incident

Moving secrets into Secrets Manager is only one part of the solution.
Your logging practices also need attention.
Consider these two examples.
Unsafe logging:
logger.info(
"Request headers: %s",
request.headers
)
The request headers could contain authorization credentials.
Safer logging:
logger.info(
"Request received",
extra={
"request_id": request_id,
"service": "payment-api",
"status": "processing"
}
)
The second example records useful operational context without exposing the complete request headers.
A few practices worth following:
  • Never log API keys, passwords, tokens, or private keys.
  • Avoid logging complete request and response bodies by default.
  • Redact sensitive fields before logging.
  • Keep production logging levels appropriate.
  • Restrict access to CloudWatch log groups.
  • Define log retention instead of keeping everything indefinitely.
  • Review third-party libraries that may log request details automatically.
Remember: structured JSON logging improves observability, but it does not automatically remove sensitive information. You still need to control what your application sends to the logger.

6. What if a secret has already been exposed?

Suppose you discover an API key in CloudWatch Logs.
Deleting the log entry, if possible, should not be your first and only response.
Treat the secret as potentially compromised.
A sensible response process is:
Step 1 — Identify the exposure
Find the affected log group, log stream, time range, and application.
Step 2 — Identify the secret
Determine which API key, token, or credential was exposed.
Step 3 — Rotate or revoke it
Follow the relevant provider's procedure to invalidate the exposed credential and issue a replacement.
Step 4 — Investigate access
Review available application logs, CloudTrail activity, and the external service's audit records to identify potentially unauthorized use.
Step 5 — Fix the source
Remove unsafe logging statements and add appropriate redaction.
Step 6 — Review access
Check who can read the affected CloudWatch log groups and restrict unnecessary access.
Do not assume that a secret was misused simply because it appeared in a log. Investigate the evidence, but treat the exposure seriously.

7. My serverless security checklist

Before deploying a Lambda function, I would review these points:
Security check
What to verify
Source code
No hardcoded credentials
Secrets Manager
Sensitive values stored appropriately
IAM execution role
Only required permissions granted
Logging
No passwords, tokens, or API keys
Event payloads
Sensitive fields are filtered or redacted
CloudWatch access
Log permissions are restricted
Rotation
Secret rotation is planned where appropriate
Dependencies
Libraries do not unnecessarily expose credentials
Incident response
A process exists for exposed credentials
These checks are small, but they can prevent a surprisingly common category of application security mistakes.

Final thoughts

When we discuss cloud security, we often focus on IAM permissions, network exposure, encryption, and access control.
Those are important.
But sometimes the problem is much simpler.
A developer wants to understand why a Lambda function is failing, adds one debugging statement, and unintentionally exposes a credential.
The secret was not committed to Git.
It was not stored in a public S3 bucket.
It was not stolen through an advanced attack.
It was simply logged.
Security doesn't end when you store a secret safely. It also depends on how your application handles that secret throughout its entire lifecycle.
One question for AWS developers:
Have you ever found sensitive information in application logs that was never supposed to be there? What logging practice do you use to prevent it?
I'd love to hear your experiences and approaches.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article