Storing secrets in code is a mistake that may cause a credential to be unintentionally exposed.
Access Keys are long-term credentials that should NOT be stored in code, and we should strive not to use them at all.
Instance Profiles will allow the OS to have credentials to AWS resources that the application (or script) can leverage without having embeded credentials:
If you need to access from your code to some service that uses long-term credentials, leverage AWS Secrets Manager to provide the credential when needed and handle rotation:
It works in a similar way, using Instance Profiles to get the permissions to check out a secret from AWS Secrets Manager, and then the application can retrieves the password and uses it to connect to the resource:
You can try AWS Secrets Manager at no additional cost with a 30-day free trial. The free trial allows you to rotate, manage, and retrieve sensitive data for a period of 30 days.