I am trying to create a python script which will set aws temp credentials for me , rather than me having to manually run these following commands each time :
export AWS_PROFILE=terraformlive
aws sts get-session-token --serial-number "arn:aws:iam::595659205553:mfa/my-device" --token-code 123456
export AWS_ACCESS_KEY_ID=
export AWS_SECRET_ACCESS_KEY=
export AWS_DEFAULT_REGION=
export AWS_SESSION_TOKEN=
I have made a start on my python script but am not sure why I keep seeing this error , I have looked around on other solutions on stackoverflow but i really can't seem to figure out why my script is complaining and showing me the following error :
AttributeError: 'list' object has no attribute 'writelines'
import os
import boto3 as b
mfa_serial_number = "arn:aws:iam::595659205553:mfa/my-device"
mfa_otp = input("Enter your otp:" )
def get_sts(mfa_serial_number, mfa_otp):
session = b.Session(profile_name='terraformlive', region_name='eu-west-1')
sts = session.client('sts')
if mfa_serial_number is not None:
response = sts.get_session_token(
SerialNumber=mfa_serial_number, TokenCode=mfa_otp)
else:
response = sts.get_session_token()
temp_credentials = response['Credentials']
print(temp_credentials)
token_reponse = ["[temp-token] \n", "aws_access_key_id = " + temp_credentials["AccessKeyId"], "\n", "aws_secret_access_key = " + temp_credentials["SecretAccessKey"],"\n", "aws_session_token = " + temp_credentials["SessionToken"],"\n"]
# Look for the temp-token profile
pfile = "[temp-token]"
with open("/Users/mrdavado/.aws/credentials", "r") as credentials:
aws_credential_file = credentials.readlines()
#print(aws_credential_file)
for line in aws_credential_file:
if line.find(pfile) != -1:
print('Profile Exists!')
#Prints the line number where the word was found
profile_line = aws_credential_file.index(line)
new_aws_access_key_line_num = profile_line + 1
new_secret_access_key_line_num = profile_line + 2
new_session_token_key_line_num = profile_line + 3
print("its still working", profile_line)
print(new_aws_access_key_line_num)
else:
aws_credential_file.writelines([token_reponse])
credentials.close()
get_sts(mfa_serial_number, mfa_otp)
I have looked around on stackoverflow but cannot seem to find anything. I want my python script to be able to run aws sts get-session-token and set the temp credentials for me.
aws_credential_file.writelines([token_reponse])
.aws_credential_fiel
is a list object, containing the contents ofcredentials
.