You actually don't need the credentials to do so, you will just have to create an IAM role which lets the EC2 instance access the S3 bucket.
Don't add credentials in the instance or your AMI, because if you provide the correct roles, they will take care of it.
Check the IAM Roles for Amazon EC2 documentation to learn more about roles.
Let me provide you the solution in pointers:
- Remove the AWS credentails from the EC2 instance
- Then create the AMI of that instance
- Open your IAM console, create a Role for EC2 which allows access to S3
- Attach this IAM role to the EC2 instance while launching it using the AMI, if did not attach then it will not work
- Now, add your script to the user data part before launching it and it should work
- If it doesn't work, then check your script
Also, I think you can take a look at the AWS Lambda part of this AWS Tutorial and for more insights you can check the AWS training page :)