aws sts get-session-token 명령을 이용하면 수동으로 임시세션토큰을 발급 받을 수 있습니다.~/.aws/credentials 파일에 액세스 키, 시크릿 키, 세션 토큰을 모두 다시 넣어줘야 된다는 번거로움이 있습니다.파이썬 코드를 작성해서, 해당 계정의 OTP 6자리만 입력하면 임시세션토큰 발급부터 credentials 파일에 액세스 키, 시크릿 키, 세션 토큰 등록까지 자동화시킬 수 있습니다.
먼저 사전에 해당 계정에 대해 프로파일과 자격증명을 작성합니다.
[profile <프로파일 명>]
region = ap-northeast-2
mfa_serial = arn:aws:iam::<계정ID>:mfa/<IAM사용자계정>
[hyeob-policy-test]
aws_access_key_id = ABCDEFG
aws_secret_access_key = ABCDEFG
$ vim ./aws_mfa.py
#!/usr/bin/python3
import sys
import configparser
import json
import os
import getpass
from os.path import expanduser
if(len(sys.argv) <= 1 ):
exit("Need named profile")
home = expanduser("~")
requestedProfile = sys.argv[1]
awsConfig = configparser.ConfigParser()
awsCred = configparser.ConfigParser()
awsConfig.read("%s/.aws/config" % home)
awsCred.read('%s/.aws/credentials' % home)
try:
mfaARN = awsConfig["profile " + requestedProfile]['mfa_serial']
except KeyError:
try:
mfaARN = awsConfig['default']['mfa_serial']
except KeyError:
exit("Need MFA serial in config file")
profiles = set( awsCred.sections())
configprofiles = set( awsConfig.sections())
if( requestedProfile in profiles and "profile " + requestedProfile in configprofiles):
print("Updating %s profile" % requestedProfile)
else:
if( "profile " + requestedProfile in configprofiles):
print("Creating %s credentials profile" % requestedProfile)
awsCred.add_section(requestedProfile)
else:
exit("No such profile \"%s\" in config" % requestedProfile )
try:
OneTimeNumber = getpass.getpass("OTP from device: ")
except ValueError:
exit("OTP must be a number")
response = os.popen("aws --profile %s sts get-session-token --serial-number %s --token-code %s" % ( str(requestedProfile),
mfaARN,
str(OneTimeNumber).zfill(6))).read()
try:
myjson = json.loads(response)
except json.decoder.JSONDecodeError:
exit("AWS was not happy with that one")
awsCred[requestedProfile]['aws_access_key_id'] = myjson['Credentials']['AccessKeyId']
awsCred[requestedProfile]['aws_secret_access_key'] = myjson['Credentials']['SecretAccessKey']
awsCred[requestedProfile]['aws_session_token'] = myjson['Credentials']['SessionToken']
with open('%s/.aws/credentials' % home, 'w') as awsCredfile:
awsCred.write(awsCredfile)
그리고 해당 코드를 실행할 때 profile을 아규먼트로 넣으면 됩니다.
$ ./aws_mfa.py <profile>
profile 을 입력하면 아래와 같이 OTP를 입력해야합니다.

그럼 ~/.aws/credentials에 아래와 같이 입력됩니다.
(임시세션토큰을 발급 받으면 액세스 키와 시크릿 키도 새로 생성되어 값이 덮어씌워집니다)
[hyeob-policy-test]
aws_access_key_id = ABCD
aws_secret_access_key = ABCD
aws_session_token = IQoJb3JpZ2luX2VjELf//////////wEaDmFwLW5vcnRoZWFzdC0yIkYwRAIgQn3A4Nq2eiYMHMDfIFHkjTWlSdMKPC+++oUtz9s
이렇게 MFA를 인증하게 되면, AWS CLI에서 MFA를 인증해야만 수행할 수 있는 기능들을 수행할 수 있습니다.
(사용자와 연결되어 있는 정책에 해당 조건이 있어야 합니다)