How to authenticate REST API calls from AWS EC2 instance – Role creation
October 15, 2020
There are some applications running on your EC2 instance and you need these applications to access some AWS resources. As you know, all requests (REST API calls in this case) should be authenticated. One option is to create a login / password and hardcode these values into your app. Such approach is discouraged and EC2 IAM role is recommended to be used. How this could be done, I will guide you through in this post.
Once you are logged in into AWS Management Console, go to EC2 Dashboard and select an EC2 instance, from which you will need your apps to make authenticated calls. In the Actions menu select “Instance settings” -> “Modify IAM role”.
The next screen will offer you to either select an existing IAM role or create a new one. For the purpose of this manual, we are going to create a new one, by clicking on the corresponding button as per screen above. On the top of the next screen, let’s click “Create role”.
Now you need to select for which entity (AWS service) you would like to create a role. In our case it is EC2, which is already available in the “Common use cases” section. Select it and click on the button “Next: Permissions”.
Now we need to select policies, which determine what AWS resources / actions on AWS resources our applications will be able to perform once authenticated through EC2 role. Please remember – always assign only policies really needed for applications to work! Don’t assign any policies beyond!
Let’s suppose I will have an application running on my EC2 instance, which will need to read objects from S3 buckets. The application will not use any other AWS resources or do actions on these resources. So I need to find and attach a policy which allows readOnly access to S3 objects. As alternative, if such a policy does not exist, I can create my own policy.
In “Filter policies” search bar let’s enter “S3” and see which options AWS IAM can offer to us.
As we can see, there is a policy called “AmazonS3ReadOnlyAccess”, which is the policy we are looking for. Select it and click on “Next: Tags”. Here you can add some tags to the role if you like. If not, just press “Next: Review”. On the next screen you should give a name to this role and once done click on “Create role”.
Now let’s go back to EC2 Dashboard, select an instance we would like to assign a role. Then select “Actions” -> “Instance settings” -> “Modify IAM role”. Now in the drop-down list we should see our newly created role “TestRole”. Select it and click save. To confirm that EC2 indeed has a “TestRole” assigned to it, select an instance and you should instance details in the bottom part of the page. You should see something similar to screenshot below.
Well done! Now we have everything in place to authenticate our app requests towards S3 buckets. How we can this actually do, let’s discuss in a next post. Stay turned!