How to authenticate REST API calls from AWS EC2 instance – AWS CLI example

In the previous post we talked about creating a new IAM role and assigning it to our running EC2 instance. This will allow to authenticate any calls made towards AWS resources from any application running on this EC2. If we use AWS CLI or creating a program using AWS SDK, no further actions are needed from our side. In today’s post, I will demonstrate this on AWS CLI example.

Let’s first assign a new IAM role we created last time to our EC2 instance. As a recap, we created an IAM role, which grants ReadOnly permissions to S3. To valide that, select our desired instance and check field “IAM Role”. You should see something similar to screen below

IAM role of the instance

If you don’t see a role assigned to an instance, go through the steps related to that from the previous manual

Working with AWS CLI

Now let’s connect to this instance and setup AWS CLI. Please note, that in this example we will setup it for Linux (Debian 10).

From the directory you are comfortable to save data in, execute the following command to download the latest version of CLI

 curl "" -o ""

Once it is done, unzip it and start the installation process. Please note, that you will require to launch installation process using sudo permissions.

sudo ./aws/install

To verify that installation completed successfully, check the version of AWS CLI currently installed:

admin@ip-172-31-xx-xx:~$ aws --version
aws-cli/2.0.57 Python/3.7.3 Linux/4.19.0-11-cloud-amd64 exe/x86_64.debian.10

Now let’s list the S3 buckets available within our account. By doing so, we will check that indeed we can execute authenticated requests towards S3 (strictly ReadOnly as defined by the role, of course).

admin@ip-172-31-xx-xx:~$ aws s3 ls
2020-09-07 07:56:44 app.xxxxxx
2020-07-06 07:25:41 com.xxxxxx
2020-09-09 06:26:37 guide.dataguru
2020-06-22 20:25:34
2020-06-22 22:57:58

Now, let’s modify our running EC2 instance by detaching IAM role and executing the same command once again. Select your instance, Actions -> Instance settings -> Modify AIM role and on the next screen select “No IAM Role”. Confirm your choice by clicking Save. You will be asked to confirm once again, by entering word “Detach” and clicking Detach. Please do so.

Now let’s execute the same LS command, with IAM role being detached.

admin@ip-172-31-xx-xxx:~$ aws s3 ls
Unable to locate credentials. You can configure credentials by running "aws configure".

That is! We have just confirmed that using IAM role, which is attached to EC2 instance, we can easily authenticate requests without any further actions or setup if we use CLI or AWS SDK.

In the next post, we will go through the steps how else we can pass the authentication and execute AWS CLI commands – we will talk about generating access keys for a particular IAM user. Stay turned!

Leave a Reply