0

How can I print aws_session_token from the following code?

    session = Session(aws_access_key_id=response['Credentials']['AccessKeyId'],
                      aws_secret_access_key=response['Credentials']['SecretAccessKey'],
                      aws_session_token=response['Credentials']['SessionToken'])

Full code:

import boto3
from boto3.session import Session


def assume_role(arn, session_name):
    """aws sts assume-role --role-arn arn:aws:iam::123456789:role/admin_role --role-session-name admin-role"""

    client = boto3.client('sts')
    account_id = client.get_caller_identity()["Account"]
    print(account_id)

    response = client.assume_role(RoleArn=arn, RoleSessionName=session_name)
    session = Session(aws_access_key_id=response['Credentials']['AccessKeyId'],
                      aws_secret_access_key=response['Credentials']['SecretAccessKey'],
                      aws_session_token=response['Credentials']['SessionToken'])

    client = session.client('sts')
    account_id = client.get_caller_identity()["Account"]
    print(account_id)


arn="arn:aws:iam::123456789:role/admin_role"
session_name="admin-role"

assume_role(arn, session_name)

Another example of the sessiontoken is in this answer. I want to print the session token.

user630702
  • 2,529
  • 5
  • 35
  • 98
  • I can't understand what you mean. The line of code that you highlight is a call to a third-party library. You don't get to change what that code does. Also, "received variable" isn't proper terminology and I'm not clear on what you mean by it. I also don't understand what you mean about printing "from" that code. – Karl Knechtel Dec 03 '21 at 05:13
  • Isn't it `response['Credentials']['SessionToken']`? – Yuri Ginsburg Dec 03 '21 at 05:13
  • I want to print the `aws_session_token=response['Credentials']['SessionToken'])` variable. Any idea how to do it? – user630702 Dec 03 '21 at 05:14
  • 1
    If you just want to know what value was passed as the `aws_session_token`, then that is just `response['Credentials']['SessionToken']`; that's what the `aws_session_token=response['Credentials']['SessionToken']` part means. – Karl Knechtel Dec 03 '21 at 05:14
  • 1
    "I want to print the aws_session_token=response['Credentials']['SessionToken']) variable. Any idea how to do it?" No, because that *isn't a variable*. – Karl Knechtel Dec 03 '21 at 05:14
  • I tried to print just `print(response['Credentials']['SessionToken'])` but that doesn't return anything – user630702 Dec 03 '21 at 05:14
  • Well, did you consider the possibility that `response['Credentials']['SessionToken']` is, for example, an empty string? – Karl Knechtel Dec 03 '21 at 05:15
  • No the script produces SessionToken. So I should be able to print it. It can't be empty – user630702 Dec 03 '21 at 05:16
  • @KarlKnechtel I've updated the question to show another example. – user630702 Dec 03 '21 at 05:19

0 Answers0