When running code on an EC2 instance, the SDK you use to access AWS resources, automagically talks to a locally linked web server on 169.254.169.254 and gets that instances
The EC2 metadata service will usually be available from within docker (unless you use a more custom networking setup - see this answer on a similar question).
If your docker network setup prevents it from being accessed, you might use the ENV directive in your Dockerfile or pass them directly during run, but keep in mind that credentials from IAM roles are automatically rotated by AWS.