This assumes you are familar with the basic configurations needed to connect to Amazon Web Services (AWS) using Python boto3. If not, check out my article Python (Scripting) - Getting Started with Amazon Web Services (AWS) boto3.
Let's say you have a user that has not been granted permission to do something, such as listing secrets.
#!/usr/bin/python3
import boto3
session = boto3.Session(profile_name='johndoe')
client = session.client('secretsmanager')
secrets = client.list_secrets()
print(f"secrets = {secrets }")
Perhaps Access Denied is returned.
botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the secretsmanager:ListSecrets operation: User: arn:aws:iam::123456789012:user/johndoe is not authorized to perform: secretsmanager:ListSecrets
Security Token Service (STS) and Assume Role can be used to allow johndoe to list secrets. Let's say you create a role named my-role with the following Trust Relationship. In this example, user johndoe is allowed sts:AssumeRole.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Statement1",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::123456789012:user/johndoe"
},
"Action": "sts:AssumeRole"
}
]
}
And my-role has the following Permission Policy, allowing anyone in the AWS account to List Secrets.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "secretsmanager:ListSecrets",
"Resource": "arn:aws:sns:*:123456789012:*"
}
]
}
Here is how you can first authenticate as johndoe using Security Token Service (STS) and then Assume Role my-role and then uses the Access Key, Secret Key and Session Token returned by Assume Role in the request to List Secrets.
#!/usr/bin/python3
import boto3
import sys
session = boto3.Session(profile_name='johndoe')
client = boto3.client('sts')
response = client.assume_role(
RoleArn="arn:aws:iam::123456789012:role/my-role",
RoleSessionName="AssumeRoleSession1"
)
print(f"AccessKeyId = {response['Credentials']['AccessKeyId']}")
print(f"SecretAccessKey = {response['Credentials']['SecretAccessKey']}")
print(f"SessionToken = {response['Credentials']['SessionToken']}")
client = boto3.client(
'secretsmanager',
aws_access_key_id=response['Credentials']['AccessKeyId'],
aws_secret_access_key=response['Credentials']['SecretAccessKey'],
aws_session_token=response['Credentials']['SessionToken']
)
secrets = client.list_secrets()
print(f"secrets = {secrets }")
Did you find this article helpful?
If so, consider buying me a coffee over at