I hope that, you are well aware that AWS Instance Profiles should be used to access AWS services by running EC2 instances as a best practice and, let’s see how we can use the Instance Profile Credentials in awscli. This might be quite useful when you are developing some applications which are going to use EC2 credentials without specifying a user account, also to test few configuration in your infrastructure.
To demonstrate that, I have logged in to the EC2 instance with a user named “tc-user” who doesn’t have the permissions to list the S3 buckets.

Now I have created a Role with the Policy attached witch required to access my S3 bucket called “tc-s3-ec2-access”.

The created role attached to the instance, but here I have attached only the policy which allows to access the S3 bucket and, let’s create a Profile to use the instance credentials.
Read More:
- Building A Kubernetes Cluster on AWS With Terraform, Ansible And GitLab CI/CD
- How To Configure Terraform AWS Backend With S3 And DynamoDB Table
- How To Create A Multi-Node ECS Cluster And A Task Definition In AWS
- VMware Cloud On AWS Outposts Announced!
In order to create a profile for this, “config” file should be created in “~/.aws/config” location with the role Arn and, specifying the “credential_source” as “Ec2InstanceMetadata“

To list the S3 buckets with the Instance Profile credentials below command should be used specifying the access profile, which is “insprofile” in this example.
aws s3 ls [bucket_name] –profile [profile_name]
Unfortunately, only attaching a policy with S3 access will not be doing the job, and role should have the permissions to assume the specified role. I have created a policy with the STS, assume role permissions for all resources, but for the sake of the security, I advice you to specify only the required resources instead of “All resources”.

Two policies attached to the role as below

Now accessing with the “insprifile” will list the S3 bucket, I have also created a folder inside the bucket for more clarity in the example as below.

I suppose this article will help anyone to understand and use the Instance Profile credentials in awscli. To read more about instance profiles follow the AWS Documentation.