3

I am trying to get some files from S3 on startup in an EC2 instance by using a User Data script and the command

/usr/bin/aws s3 cp ...

The log tells me that permission was denied and I believe it is due to aws cli not finding any credentials when executing the user data script.

Running the command with sudo after the instance has started works fine.

I have run aws configure both with sudo and without.

I do not want to use cronjob to run something on startup since I am working with an AMI and often need to change the script, therefore it is more convenient for me to change the user data instead of creating a new AMI everytime the script changes.

If possible, I would also like to avoid writing the credentials into the script.

How can I configure awscli in such a way that the credentials are used when running a user data script?

2 Answers 2

3

I suggest you remove the AWS credentials from the instance/AMI. Your userdata script will be supplied with temporary credentials when needed by the AWS metadata server.

See: IAM Roles for Amazon EC2

  • Clear/delete AWS credentials configurations from your instance and create an AMI
  • Create a policy that has the minimum privileges to run your script
  • Create a IAM role and attach the policy you just created
  • Attach the IAM role when you launch the instance (very important)
  • Have your userdata script call /usr/bin/aws s3 cp ... without supplying credentials explicitly or using credentials file
Sign up to request clarification or add additional context in comments.

Comments

1

You can configure your EC2 instance to receive a pre-defined IAM Role that has its credentials "baked-in" to the instance that it fetches upon instantiation, which it turn will allow it to call aws-cli commands in your User Data script without the need to configure credentials at all.

Here's more info on IAM Roles for EC2: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html

It's worth noting here that you'll need to attach the appropriate policies to the IAM Role that you assign to your instance in order for the aws-cli commands to succeed. More information on that can be found here: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#working-with-iam-roles

2 Comments

IAM credentials are never baked-in to the instance. They are fetched on demand from the metadata server.
@helloV Good point. Edited above. Anyone that wanders in here should see helloV's answer for a more succinct, detailed explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.