Skip to content

Instantly share code, notes, and snippets.

@alex-phillips
Created August 31, 2023 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alex-phillips/b159fe70fd0e0c47da1c00556a6da821 to your computer and use it in GitHub Desktop.
Save alex-phillips/b159fe70fd0e0c47da1c00556a6da821 to your computer and use it in GitHub Desktop.
import boto3
import time
def create_new_session():
# Update these with your own values
role_arn = 'arn:aws:iam::YOUR_ACCOUNT_ID:role/YOUR_ROLE_NAME'
session_name = 'long-running-session'
sts_client = boto3.client('sts')
response = sts_client.assume_role(
RoleArn=role_arn,
RoleSessionName=session_name
)
return {
'access_key': response['Credentials']['AccessKeyId'],
'secret_key': response['Credentials']['SecretAccessKey'],
'session_token': response['Credentials']['SessionToken'],
'expiration': response['Credentials']['Expiration']
}
def main():
session = create_new_session()
while True:
current_time = time.time()
expiration_time = session['expiration'].timestamp()
if expiration_time - current_time <= 600: # Renew if less than 10 minutes left
print("Renewing session...")
session = create_new_session()
# Your code here: Use the session to interact with AWS services
# For example, you can create a new Boto3 client using the session credentials
s3_client = boto3.client('s3',
aws_access_key_id=session['access_key'],
aws_secret_access_key=session['secret_key'],
aws_session_token=session['session_token'])
# Perform your actions using the created client
time.sleep(300) # Wait for 5 minutes before checking again
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment