When launching a new Windows EC2 instance from a custom AMI, everything may seem to work fine—network access is available, the IAM role is attached, and you can browse websites—but AWS CLI or SDKs might still throw the error: "Unable to locate credentials. You can configure credentials by running 'aws configure'". I encountered this while running aws sts get-caller-identity on a Windows EC2 instance placed in a private subnet. Despite having internet access through a NAT gateway and correct IAM role permissions, the CLI couldn’t retrieve credentials. After some investigation, I discovered the root cause was with the default gateway. Since the EC2 instance was created from an existing server AMI, it inherited the old network configuration, including a gateway pointing to the original subnet, not the current one. This broke communication with the Instance Metadata Service (IMDS), which is essential for retrieving temporary credentials and is only accessible at the link-local address 169.254.169.254.
To troubleshoot, I did the following:
Opened PowerShell as Administrator
Ran route print to inspect the routing table
Ran ipconfig /all to confirm the incorrect default gateway (e.g., 10.21.11.1)
To fix it, I used the built-in EC2Launch module provided by AWS:
powershell -
$ Import-Module "C:\ProgramData\Amazon\EC2-Windows\Launch\Module\Ec2Launch.psd1"
$ Add-Routes
This command automatically added the correct default route for the new subnet. A follow-up route print confirmed the correct gateway was now in place. After this fix, running:
$ aws sts get-caller-identity
successfully returned the expected identity response, confirming that the EC2 could now access IMDS and retrieve credentials via its instance profile.
Key Takeaways:
EC2s launched from custom AMIs may retain old network routes, including outdated default gateways.
Even if the IAM role is correctly attached and permissions are in place, an incorrect route can break access to IMDS.
Always check:
route print for routing
ipconfig /all for current gateway info
Use Add-Routes from the EC2Launch module to fix the routing automatically.
Pro Tip:
Add the following command to your User Data script when launching Windows instances from AMIs:
powershell:-
Import-Module "C:\ProgramData\Amazon\EC2-Windows\Launch\Module\Ec2Launch.psd1"
Add-Routes
This ensures your EC2 instance has a proper gateway set at boot time, avoiding credential and metadata access issues.
This experience taught me that credential errors aren't always permission-related—they can stem from low-level networking misconfigurations inherited during AMI-based provisioning. Double-checking routes can save hours of unnecessary debugging.