1
role_name = os.getenv('KINESIS_ROLE_ARN')
session_name = 'kinesis_session'
sts_client = boto3.client('sts')
auto_refresh_session = _create_refreshable_session()
kinesis_client = auto_refresh_session.client('kinesis')
kinesis_stream_name = "Log"

def _refresh_kinesis_role():
    params = {
        'RoleArn': role_name,
        'RoleSessionName': session_name,
        'DurationSeconds': 3600,
    }
    response = sts_client.assume_role(**params).get('Credentials')
    credentials = {
        'access_key': response.get('AccessKeyId'),
        'secret_key': response.get('SecretAccessKey'),
        'token': response.get('SessionToken'),
        'expiry_time': response.get('Expiration').isoformat(),
    }
    return credentials


def _create_refreshable_session():
    session_credentials = RefreshableCredentials.create_from_metadata(
        metadata=_refresh_kinesis_role(),
        refresh_using=_refresh_kinesis_role,
        method='sts-assume-role',
    )
    session = get_session()
    session._credentials = session_credentials
    autorefresh_session = boto3.Session(botocore_session=session)
    return autorefresh_session

I'm trying to create an auto refresh session to assume AWS role following this guide here: https://dev.to/li_chastina/auto-refresh-aws-tokens-using-iam-role-and-boto3-2cjf.

I'm getting an error of Unresolved reference on _create_refreshable_session() at line 4. I do see a similar question of this on stackoverflow but I don't quite understand the answer in that one. It seems like a problem of scope. That answer is basically saying that you need to define that function before you use it in top-level? Is there any way to solve this keeping the order of the code?

In the guide the author was using self for those two functions, but didn't seem to wrap them into any Class that confuses me as well so I removed the self part, I don't know if this is causing any error.

1 Answer 1

1

You've used that function before you defined it. You should move the _create_refreshable_session function to the top of the file.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.