LoginSignup
2
2

概要

  • 仕事でAWSを使っているのですが、AWS CLIを使って複数のアカウントを切り替える方法でハマったのでメモ(かなり初歩的な内容です
  • 以下のような状況を想定
    • AWS CLIを使って複数のアカウントを切り替えたい

ユースケース

  • AWS環境が以下のような構成になっている
    • 本番環境(production
    • ステージング環境(staging)
    • 開発環境(development)
  • それぞれの環境に対して、AWS CLIを使って操作したい
  • AWS SSOアカウントが既に各環境に作成されている
    • AWS SSOアカウントには、それぞれの環境に対応したロールが作成されている
    • 例えば、本番環境に対応したロールは、arn:aws:iam::123456789012:role/production-adminのようなARNが割り当てられている
    • 詳しくは、AWS SSOのドキュメントを参照

それぞれの環境ごとのProfileを作成する

  • aws configureというコマンドを使って、それぞれの環境ごとのProfileを作成する
$ aws configure --profile production

img.png

  • 作成すると、~/.aws/credentialsに設定が保存される
$ cat ~/.aws/credentials

[default]
aws_access_key_id = AKIAxxxxxxxxxxxxxxx
aws_secret_access_key = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
[production]
aws_access_key_id = AKIAxxxxxxxxxxxxxxx
aws_secret_access_key = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
[staging]
aws_access_key_id = AKIAxxxxxxxxxxxxxxx
aws_secret_access_key = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
[development]
aws_access_key_id = AKIAxxxxxxxxxxxxxxx
aws_secret_access_key = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

複数のprofileを使用している場合にデフォルトで使用するprofileを変更する

  • 以下コマンドを実行すると、デフォルトで使用するprofileを変更できる
$ export AWS_PROFILE=production -- ここではproductionをデフォルトにする

profileを指定してコマンドを実行する

  • 以下のように、--profileオプションを使って、profileを指定してコマンドを実行することも可能
$ aws s3 ls --profile production

まとめ

  • aws configureコマンドを使って、それぞれの環境ごとのProfileを作成する
  • export AWS_PROFILE=productionコマンドを使って、デフォルトで使用するprofileを変更する
  • --profileオプションを使って、profileを指定してコマンドを実行することも可能
  • もっとAWS CLIを勉強しないとダメですね・・・

参考

2
2
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
2
2