Retrieve Your IAM Security Credentials from an EC2 Instance from the Command Line

If you are planning to use other AWS resources from your EC2 Instances, then you will generally have to provide a credential set to authenticate. One good method of granting authentication to your EC2 instance is through the IAM role system. This allows applications or scripts to access EC2 resources without the need to hardcode* an IAM access key within the code or configuration.

*Hardcode might be a slightly misleading description because in many cases you can change these credentials with your puppet | ansible | chef configuration management system

For example if you need my EC2 Instances to write their backup or other data to an s3 bucket, you can write a shell script that utilises the AWS CLI to write the data to an S3 bucket. Before using the IAM Role concept you might have created an IAM user and added these IAM security credentials to my script or users environment.

With the IAM role the idea is similar except you build your script to collect the dynamically created IAM security credentials for you. This means there is no credentials stored on the EC2 Instance’s file system.

Here is a quick walk through on how to use IAM roles with your EC2 Instances. We are going to have you EC2 Instance connect to S3 Bucket.

1. Setup an IAM role.

Choose Internet and Access Management (IAM)

Choose Role -> Create New Role

Enter a name for the new role e.g toolservers

Choose the type of role. We want an Amazon EC2


Attach a policy – since we want to access s3 we can use one of the pre made policies so select Amazons3FullAccess (naturally you might want to create your own more granular policy)


2. Launch an EC2 instance with the role we create in the previous steps.

Choose EC2

Launch Instance – here you choose the instance type you wish to use but here I am using Amazon Linux to demonstrate a IAM role use in Bash and AWS CLI.

Under step 3 Choose the role “toolservers” that you created earlier.


Launch the E2 Instance and connect to it with SSH.

3. Create a shell script on your new instance to list your EC2 Bucket.

If you are using the AWS CLI tools to access s3 then you don’t need to set the credentials; the AWS CLI tool just “knows” about the IAM ROLE and can see the buckets as the role permissions allow.

Like so

aws s3 ls s3://wildchiefs-test-bucket

However, if you need to use something that isn’t IAM aware then you can grab it from the meta-data using command like so (below fetches the AWS Access key):

IAM_CREDENTIALS_KEY=$( curl | awk 'FNR == 5 {print $3}' | sed 's/[,"]//g' )

Comments are closed.