LoginSignup
12
1

More than 1 year has passed since last update.

Terraform(やその他CLIツール・コマンド)でMFA対応する

Last updated at Posted at 2019-12-18

TL:DR

  • AWSではMaster AccountにIAM Userでログインし、他のアカウント(OU)へアクセスできる権限をもったRoleへSwitch/AssumeRoleして必要な作業を行うケースが多いです。
  • ポリシーとしてSwitch/AssuemRoleの際に、"MFAが有効化"されていることを必須としていることも多いです。
  • terraformは公式にAssumeRoleへの対応をしていますが、MFAへの対応はされていません。
  • MFAまわりはaws-vaultでカバーしました。

aws-vaultでterraformをMFA対応させる

aws-vault
https://github.com/99designs/aws-vault

aws-vaultのインストール

リポジトリのREADMEにある通りに。

Macの場合
brew cask install aws-vault

aws-vaultでMFAするための設定

  • 事前に必要なもの

    • terraformが利用するIAM UserのAccess KeyとSecrets(A)
    • (A)に紐付いたMFAデバイスのARN(B)
      • こういうやつ → arn:aws:iam::xxxxxxxxxxxx:mfa/yourIAM
  • aws-vaultで使うprofile追加

$ aws-vault add hoge-prov
※Access KeyとSecretsを聞かれるので(A)を登録する
  • profileにmfa_deviceのARN(B)を追加登録
~/.aws/config
~(snip)~

[profile hoge-prov] ← 先程追加したprofileの項
mfa_serial = arn:aws:iam::xxxxxxxxxxxx:mfa/yourIAM ←ここに(B)を登録する

aws-vaultでMFAしつつterraformを実行してみる

$ aws-vault exec hoge-prov -- terraform plan -out=apply.plan -target=module.compute.aws_instance.hogefuga
Enter token for arn:aws:iam::xxxxxxxxxxxx:mfa/yourIAM: 
※^ MFAデバイスのTokenを入力してあげましょう

terraformの処理に時間がかかりすぎてセッション切れしちゃう場合

execの下記オプションでセッションの有効期限を変更できるようなのでお試しあれ

$ aws-vault exec --help
~(snip)~

  -t, --session-ttl=4h           Expiration time for aws session
      --assume-role-ttl=15m      Expiration time for aws assumed role

~(snip)~
12
1
3

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
12
1