4
4

More than 3 years have passed since last update.

terraformで二段階認証を使用する

Posted at

目的

  • terraform実行時、任意のロールに権限委譲したうえで、任意のユーザのMFAで生成されたワンタイムキーを要求させる

前提

  • Authenticatorを使用して2段階認証コードを生成している

環境

  • terraform
$ terraform version
Terraform v1.0.5
on darwin_amd64
  • MacOS
$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.15.7
BuildVersion:   19H2
  • awscli
$ aws --version
aws-cli/2.1.38 Python/3.8.8 Darwin/19.6.0 exe/x86_64 prompt/off

方法

  • terraformは標準でMFAをサポートしていないので、AWS VAULTを使用する

設定

install

$ brew install --cask aws-vault

Roles and MFA

  • ~/.aws/config
[profile <profile_name>]
region=<region-name>
source_profile=default
mfa_serial=arn:aws:iam::<account>:mfa/<user-name>
role_arn=arn:aws:iam::<account>:role/<role-name>

keychainに自分のIAMUSERのKEYを登録し、任意のパスワードを設定する

$ aws-vault add default
Enter Access Key ID: ********************
Enter Secret Access Key:****************************************
Added credentials to profile "default" in vault
  • 初期化
$ aws-vault exec <profile-name> -- terraform init
  • 登録したパスワードを入力
    スクリーンショット 2021-08-20 17.19.23.png

  • 生成されたトークンを入力

 $ aws-vault exec <profile-name> -- terraform init
Enter token for arn:aws:iam::<account>:mfa/<user-name>: ******
  • セッションの残時間などが可視化される
$ aws-vault list
Profile                      Credentials              Sessions
=======                      ===========              ========
<profile_name>                -                        sts.AssumeRole:59m56s

補足

  • aliasを作成し、引数としてterraformコマンドを渡す
~/.bash_profile
alias av='aws-vault exec terraform-mfa'
$ av -- terraform init
Enter token for arn:aws:iam::<account>:mfa/<user-name>: ******

Initializing the backend...

Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
- Using previously-installed hashicorp/aws v3.51.0

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4