touch upload-s3-usingec2role.py
echo "import boto3" > upload-s3-usingec2role.py
echo "s3 = boto3.client( 's3' )" >> upload-s3-usingec2role.py
echo "s3.upload_file('test.txt', '<S3BUCKETNAME>', 'test.txt')" >> upload-s3-usingec2role.py
python upload-s3-usingec2role.py
When using an IAM role assigned to an EC2 instance (also known as an EC2 instance profile). The application on the EC2 server retrieves the security credentials provided by the IAM Role from the EC2 metadata iam/ security-credentials/role -name. The application is authorized for the actions and resources that we have defined for the IAM role through the security credentials associated with the IAM role.
We can check the security credentials generated for the IAM role ec2roles3upload with the following command. We can see that the credentials have an expiration time ( Expiration ) and will be automatically refreshed after this expiration period.
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/ec2roles3upload
When we assign an EC2 role to an EC2 instance, the generation of temporary credentials is automatically done for us through a service called Security Token Service ( STS ). We can also use the AWS CLI in an EC2 instance that has been assigned the IAM role without any configuration. ( aws configure )
Run the following command to list the S3 bucket in the account:
aws s3 ls