- Newest
- Most votes
- Most comments
There isn't a standardized or officially recommended way to programmatically detect LocalStack as opposed to real AWS. However, there are a few approaches you can consider:
-
Environment Variable: You can set an environment variable in your local development environment to indicate that you're using LocalStack. Your application can then check for this variable to determine its environment.
-
Endpoint URL: LocalStack typically uses a different endpoint URL than real AWS services. You could check the endpoint URL your application is configured to use. If it's pointing to localhost or a LocalStack-specific URL, you're likely using LocalStack.
-
AWS SDK Configuration: When initializing your AWS SDK client, you're likely setting a custom endpoint for LocalStack. You could add a flag or property to your configuration object to indicate you're using LocalStack.
-
Service-Specific Behavior: As you've noticed with KMS, there are behavioral differences between LocalStack and real AWS. You could potentially use these differences to detect which environment you're in. For example, you could attempt to use a KMS feature that's not implemented in LocalStack and catch the resulting error.
-
Custom Endpoint: While there isn't a built-in endpoint specifically for detecting LocalStack, you could potentially create a custom endpoint in your LocalStack setup that returns information about the environment.
Given your specific use case with KMS, you might want to combine these approaches. For example, you could set an environment variable when running tests with LocalStack, and have your application check this variable before attempting to use KMS features that aren't implemented in LocalStack.
Remember that relying on environment detection can make your code environment-specific, which might not be ideal for production use. Consider structuring your code so that environment-specific logic is isolated and easy to manage.
Sources
download events from EventBridge into a Docker image for automated testing? | AWS re:Post
best practice on marketplace apis when running locally | AWS re:Post
One way I've used to detect whether code is running in AWS is to see whether the Instance Metadata Service is available. If a connection attempt to IMDS is rejected then you're most probably running outside AWS. This is only helpful if you're running tests (or other components) on EC2...
Thanks for the reply. I think in my case performing a probe using ListKeyRotations probably makes most sense. If I get a 501 back, I know I'm on LocalStack (or LocalStack has been enhanced to track key rotations), otherwise I assume I'm on real AWS (cloud or on-prem).
answered 2 years ago
Relevant content
- AWS OFFICIALUpdated 7 months ago
