Skip to content

AWS CLI: Assuming a Role Via The CLI


AWS CLI
For more information on the AWS CLI, visit aws.amazon.com


Description


There are many ways to authenticate to AWS in order to launch new services, or query an existing one. Beyond using the AWS console, and available SDK's there is also a command line tool that allows a user an easy way to fire off an API request, and receive the response using just a simple command line argument in the AWS CLI tool from your local shell environment. Normally, you would simply issue an aws configure command to set an Access Key and Secret Key both of which are stored in the .aws directory found within your home directory path. However when your organization uses ADFS to bind Active Directory users to groups, which are mapped to Roles, then you must first authenticate with ADFS and assume a corresponding role via the issuance of an authentication token, temporary access key, and its associated temporary secret key all of which are issued by the AWS Security Token Service or STS. This walk through will cover authenticating to AWS via assuming a role by using the STS service via the AWS CLI.


Pre-Requisites


Follow the steps as outlined in this pre-requisite article. This walk through will build on the steps performed in Using The AWS CLI


CLI User Permissions


In our previous tutorial, we set up our IAM user to allow ReadOnly access to S3, allowing the user to view buckets, and their corresponding objects, but thats it. Later We also decide to allow our user to write objects to S3 via the command line, but only for a limited amount of time. The easy way to do this is to allow our current user the ability to assume a role that grants the user S3 Write Access. First we will validate that our user doesn't currently have this level of access, then we will add a policy to our user to grant them permissions to assume a role, and we will assume a pre-existing role named S3_Full_Access.

For this example a bucket named a.demo.bucket has been created in S3 and an attempt to PUT a file named testfile.txt into that bucket is used in the CLI tool:


Request:

aws s3 cp testfile.txt s3://a.demo.bucket

Response:

upload failed: ./testfile.txt to s3://a.demo.bucket/testfile.txt An error occurred (AccessDenied) when calling the PutObject operation: Access Denied


We can also test to see if we have the ability to assume a role. We use the following Syntax from the CLI to assume a role:


Request:

aws sts assume-role --role-arn "arn:aws:iam::123456789012:role/S3_Full_Access" --role-session-name "Test_CLI_Session"


Example:

iMac27$ aws sts assume-role --role-arn "arn:aws:iam::123456789012:role/S3_Full_Access" --role-session-name "Test_CLI_Session"

An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:iam::123456789012:user/aws_cli_test is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::123456789012:role/S3_Full_Access


Modify a Roles Trust Policy

In order to allow a user to assume a role we need to add the following policy statement into the role's trust relationships.


1.    Locate and navigate to the IAM Service:
From the top left side of the navigational menu bar, click on the Services menu, and then choose IAM by either navigating to the Security, Identity, and Compliance section of the listed services, or by typing the first few letters of the service name in the search box, and then choosing it from the filtered list.


IAM


2.    Modifying a Role:
From the IAM console dashboard, click on Roles in the right side navigational menu to see a list of all available roles. From the Roles view, click on the role that you want to allow a user to assume and click the role name to go to the role summary.


IAM Dashboard

IAM Select Role


3.    Edit Role Trust:
In order to allow a user to assume a role, we need to add a policy statement to the role that will allow the defined user to assume the role. We do this in the Trust Relationship of the role. In order to modify the roles trust relationship, from the role summary screen, Click the Trust relationships tab, and then click the Edit trust relationship button.


IAM Role Trusts


4.    Add Policy to Trust:
Next, we need to add the following policy statement to the Role's trust policy statement. Once we have modified the Trust policy, then click the Update Trust Policy button.


{
    "Sid": "",
    "Effect": "Allow",
    "Principal": {
        "AWS": "arn:aws:iam::123456789012:user/aws_cli_test"
    },
    "Action": "sts:AssumeRole"
}


IAM Role Add Trust Policy


Verify the Role Trust

Now that the trust policy has been modified to allow the user that you want to assume the role the ability to do so, check the role summary page to ensure the user is now listed under the Trust relationships tab, under the Trusted entities section.


IAM Role Verify Trust Policy


Retesting CLI Access


Now that the user has been added to the trust relationships section of the role, we should now be able to assume the role with our user, and use the return to authenticate to AWS using that role, and allowing us to write to S3.


1.    Assume Role:
In order to assume the role that will allow us to write objects to S3, first we must use the aws sts assume-role command to retrieve the temporary AccessKeyId, SecretAccessKey, and SessionToken that we will use when calling the S3 PUT command.


iMac27$ aws sts assume-role --role-arn "arn:aws:iam::123456789012:role/S3_Full_Access" --role-session-name "Test_CLI_Session"


Response:

{
    "Credentials": {
        "AccessKeyId": "ASIAIYGXOTLDUXMP3QOA",
        "SecretAccessKey": "5P0202EwqmMlEkQvxXuFm0IGxqzk2xNJU5L7OgaJ",
        "SessionToken": "FQoDYXdzEB4aDHjunccp5d6ZTo+RUCL0Af4uIxKdX219+uFs+SX8fiMCxatqI+7FVVfAdaUjQtWP6Ht2DmXFwMi4PZzslPHPOZvCB2bYFsWqbkTDOcgmQwjLxneLsSjE/0bpcZTcry5tlcch8woCrk0oGBmDmc0a6NYyMouhxC9g3iGGi7l/f1cQ9VcipBHI5ushQnW20/umgdM27zGgg9Q9Otk9qmJnzdTljkQZzMvX2zLVPeh8qVWgOvczbreXMpsm1SrLswAgdRao802lTVAsrm6kBTG611jVGPpDvtEVZdLaeSz/Rg7xA8b2e99Mq6I7aatGoKNs06WqOxs0jmgKxM6ZeIoTKUunQxIomIOr2QU=",
        "Expiration": "2018-06-20T22:05:28Z"
    },
    "AssumedRoleUser": {
        "AssumedRoleId": "AROAJF6Q7S3ZI242PMDZU:Test_CLI_Session",
        "Arn": "arn:aws:sts::123456789012:assumed-role/S3_Full_Access/Test_CLI_Session"
    }
}


2.    Set AWS CLI Credentials:
Now that we have the values required to authenticate to AWS correctly, we need to reconfigure our CLI to use the new credentials that were issued by STS. In order to do so, we can use the aws configure command, however using it, would replace the existing [default] profile credentials that are already configured, which we don't want to do. Another way we can override those existing credentials without permanently changing anything would be to set environment variables that the AWSCLI will look for when it looks for authentication credentials. Perform the following command set to export the new values that the AWSCLI will use.


export AWS_ACCESS_KEY_ID=<AccessKeyId>
export AWS_SECRET_ACCESS_KEY=<SecretAccessKey>
export AWS_SESSION_TOKEN=<SessionToken>


Example:

export AWS_ACCESS_KEY_ID="ASIAIYGXOTLDUXMP3QOA"
export AWS_SECRET_ACCESS_KEY="5P0202EwqmMlEkQvxXuFm0IGxqzk2xNJU5L7OgaJ"
export AWS_SESSION_TOKEN="FQoDYXdzEB4aDHjunccp5d6ZTo+RUCL0Af4uIxKdX219+uFs+SX8fiMCxatqI+7FVVfAdaUjQtWP6Ht2DmXFwMi4PZzslPHPOZvCB2bYFsWqbkTDOcgmQwjLxneLsSjE/0bpcZTcry5tlcch8woCrk0oGBmDmc0a6NYyMouhxC9g3iGGi7l/f1cQ9VcipBHI5ushQnW20/umgdM27zGgg9Q9Otk9qmJnzdTljkQZzMvX2zLVPeh8qVWgOvczbreXMpsm1SrLswAgdRao802lTVAsrm6kBTG611jVGPpDvtEVZdLaeSz/Rg7xA8b2e99Mq6I7aatGoKNs06WqOxs0jmgKxM6ZeIoTKUunQxIomIOr2QU="


3.    Verify Role Assumption:
Now that we have set our environment variables, lets test a call to STS to verify that we have the assumed role that we should. Use the following command to test your current credentials:


aws sts get-caller-identity


Response:

{
    "UserId": "AROAJF6Q7S3ZI242PMDZU:Test_CLI_Session",
    "Account": "123456789012",
    "Arn": "arn:aws:sts::123456789012:assumed-role/S3_Full_Access/Test_CLI_Session"
}


4.    Retest PUT:
Now that we have the variable values set lets retry our PUT operation to see if our new assumed role gives our user the required access to do so.


aws s3 cp testfile.txt s3://a.demo.bucket

Response:

upload: ./testfile.txt to s3://a.demo.bucket/testfile.txt


Assume Role Time Limits:

By default, the temporary security credentials created by assume-role last for one hour. However, you can use the optional DurationSeconds parameter to specify the duration of your session. You can provide a value from 900 seconds (15 minutes) up to the maximum session duration setting for the role. This setting can have a value from 1 hour to 12 hours.


Cleanup


No steps are necessary in order to clean up or roll back the steps provided in this tutorial.


Conclusion


Once the uploading of the file test succeeds, then the assume role test has been verified, and you are now able to perform all of the actions with your new assumed role permissions for the session duration of the assume role action (default 1 hour). After the session expiration time, you can gain access back by re-issuing the command to again assume the role and updating your exported environment variables containing the connection credentials.


Additional Resources


No Additional Resources.


Site/Information References


AWS STS Assume Role Command Reference
AWS How do I assume an IAM role using the AWS CLI
AWS Assuming a Role


Comments