편하게 AWS CLI 계정 사용하기(aws vault, assume-role)

cli 환경에서 AWS 계정을 편하게 사용하기 위한 방법을 적은 글입니다
2021.10.28

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

안녕하세요 클래스메소드의 수재입니다.
제 환경에서는 IAM 역할의 권한과 MFA를 조합하여 AWS를 사용하고 있습니다.
그런데 이렇게 활용하니 테라폼을 설정할 때 너무나도 불편한 점이 많았습니다...
이 문제를 해결하기 위해 어떻게 했는지를 본 글에서 소개합니다.

무슨 일이 있었나

현재 aws의 config 파일은 다음과 같습니다.
sujae-test(이하 test)와 sujae-origin(이하 origin)이 가진 role_arn의 iam account가 다릅니다.

[profile sujae-origin]
source_profile = sujae-origin
role_arn = arn:aws:iam::++++:role/sujae
mfa_serial = arn:aws:iam::++++:mfa/sujae
region = ap-northeast-1

[profile sujae-test]
source_profile = sujae-origin
role_arn = arn:aws:iam::----:role/sujae
mfa_serial = arn:aws:iam::++++:mfa/sujae
region = ap-northeast-1

이러한 환경에서 test 프로필을 이용하여 테라폼의 plan을 해보니 다음과 같은 오류가 발생하였습니다.

Error: error configuring Terraform AWS Provider: Error creating AWS session: AssumeRoleTokenProviderNotSetError: assume role with MFA enabled, but AssumeRoleTokenProvider session option not set.

토큰을 이용하기 위해 get-session-token을 해보니 다음과 같은 오류가 발생합니다.

An error occurred (AccessDenied) when calling the GetSessionToken operation: Cannot call GetSessionToken with session credentials

찾아보면 해결할 수 있는 문제지만 시간이 없고 MFA를 해제할 수는 없는 노릇이기에 다른 방법을 찾아보았습니다.

AWS Vault

방법을 찾은 것 중에 하나가 바로 AWS Vault 입니다.
깃을 참고하니 각 OS 별로 다음과 같이 설치할 수 있었습니다.

You can install AWS Vault:

by downloading the latest release
on macOS with Homebrew Cask: brew install --cask aws-vault
on macOS with MacPorts: port install aws-vault
on Windows with Chocolatey: choco install aws-vault
on Windows with Scoop: scoop install aws-vault
on Linux with Homebrew on Linux: brew install aws-vault
on Arch Linux: pacman -S aws-vault
on FreeBSD: pkg install aws-vault
on OpenSUSE: enable devel:languages:go repo then zypper install aws-vault
with Nix: nix-env -i aws-vault
with asdf-vm: asdf plugin-add aws-vault https://github.com/karancode/asdf-aws-vault.git && asdf install aws-vault <version>

AWS Vault에서 제공하고 있는 격리용 서비스는 다음을 지원하고 있습니다.

The supported vaulting backends are:

macOS Keychain
Windows Credential Manager
Secret Service (Gnome Keyring, KWallet)
KWallet
Pass
Encrypted file

직접 해보기

저는 WSL에 brew로 패키지를 관리하기 때문에 brew를 이용하여 설치하였습니다.

$ brew install --cask aws-vault
$ aws-vault --version
6.3.1-Homebrew

이어서 유저를 추가해줍니다.

$ aws-vault add sujae-test
aws-vault: error: Specified keyring backend not available, try --help

macOS라면 키체인으로 연결되지만 WSL이기 때문에 backend를 따로 지정해주어야 합니다.
Pass 등을 설치할 수도 있지만 간단하게 파일로 관리하도록 하겠습니다.
그러면 다음과 같이 사용할 계정의 Access Key ID 와 Secret Access Key 그리고 해당 정보를 관리할 파일의 비밀번호를 설정합니다.

$ aws-vault --backend=file add sujae-test
Enter Access Key ID: 
Enter Secret Access Key: 
Enter passphrase to unlock /home/must012/.awsvault/keys/:

이후 생성한 프로필을 이용하여 plan을 해보니 다음과 같이 잘 작동하였습니다.

$ aws-vault --backend=file exec sujae-test -- terraform plan                                                          INT  1m 23s 
Enter token for arn:aws:iam::----:mfa/****: 
Enter passphrase to unlock /home/must012/.awsvault/keys/: 

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create
...
Plan: 1 to add, 0 to change, 0 to destroy.

해당 커맨드가 어떤 동작을 하는지 확인하고 싶다면 debug 옵션을 사용하면 됩니다.

$ aws-vault --backend=file --debug exec sujae-test -- terraform plan 
2021/10/27 17:12:56 aws-vault 6.3.1-Homebrew
2021/10/27 17:12:56 Loading config file /home/must012/.aws/config
2021/10/27 17:12:56 Parsing config file /home/must012/.aws/config
2021/10/27 17:12:56 [keyring] Considering backends: [file]
2021/10/27 17:12:56 Profile 'default' missing in config file
...

마지막으로 현재 저장된 계정의 목록을 확인하고 싶다면 list를 이용하시면 됩니다.
발행한 토큰의 유효 기간도 확인할 수 있으므로 필요에 따라 활용할 수 있습니다.

$ aws-vault list
Profile                  Credentials              Sessions                    
=======                  ===========              ========                    
sujae-origin                -                        -                           
sujae-test                 sujae-test                 sts.GetSessionToken:50m10s

이 외에

환경 변수를 지정하여 AWS Vault를 편하게 사용할 수 있습니다.

# backend 설정
export AWS_VAULT_BACKEND=file
# 파일의 비밀번호 설정
export AWS_VAULT_FILE_PASSPHRASE=0000

# 이후 커맨드를 입력할 때 해당 내용의 입력이 불필요해집니다.
aws-vault exec sujae-test -- terraform plan

이 외의 툴(remind101/assume-role)

AWS Vault 이외에 이전부터 제가 써오던 툴로는 assume-role이 있습니다.
마지막 커밋으로부터 4년이상이 지났지만 기능적으로는 문제없이 작동합니다.
기존에 사용하던 aws의 config / credential 파일의 수정 등의 작업 없이 단순히 설치하고 사용하면 됩니다.
딱히 사용방법에 대해 설명할 내용이 없기 때문에 깃을 참고해주세요.

긴 글 읽어주셔서 감사합니다.
내용 및 오탈자 피드백은 언제나 환영합니다. must01940 지메일로 보내주시면 감사합니다.

__참고자료__