7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AWS CLIのアカウントを切り替えるためのコマンドを作成する

Last updated at Posted at 2020-01-19

はじめに

AWSのアカウントを個人用と会社用で切り替えて使うのが思いのほか面倒だったので変更用のコマンドを作成しました。

環境

macOS Catalina 10.15.2

AWSのアカウント情報の確認

AWSのアカウント情報は~/.aws/configにあります。
以下のような情報が入っています。

$ cat ~/.aws/config
[default]
output = json
region = ap-northeast-1

[profile s3deploy-user]
output = json
region = ap-northeast-1

[profile home-user]
output = json
region = ap-northeast-1

[profile lambada-user]
output = json
region = ap-northeast-1

認証情報は~/.aws/credentialsで確認できます。

アカウントの切り替えには以下のコマンドを実行する必要があります。

# shellを閉じるまで有効
export AWS_DEFAULT_PROFILE=test-user

# 実行時のみ
aws deploy create-application --application-name HelloWorld --profile test-user

コマンドの作成

chmod風にchawsというコマンドで作成することにします。

# chaws
TARGET_FILE=~/.aws/config

PROFILES=()

while read LINE
do
    if [[ $LINE =~ ^.*\[profile(.*)\].*$ ]]
    then
        PROFILES+=(`echo ${BASH_REMATCH[1]} | tr -d " "`)
    fi
done < $TARGET_FILE

select res in "${PROFILES[@]}"
do
  sed -i -e '/AWS_DEFAULT_PROFILE/d' ~/.zshrc
  echo export AWS_DEFAULT_PROFILE=$res >> ~/.zshrc
  break
done

これを適当につくったフォルダにいれてパスを通します。
今回は~/binフォルダに入れます。

cd ~/bin/

# 実行権限を付与
$ sudo chmod 755 chaws

# 環境変数を追加
$ echo export PATH='~/bin:$PATH' >> ~/.zshrc

# 読み込み
$ source ~/.zshrc

さっそく実行してみます。

$ chaws
1) s3deploy-user
2) home-user
3) lambada-user
# Enter 2

# 確認
$ source ~/.zshrc
$ echo $AWS_DEFAULT_PROFILE
home-user

ちゃんと切り替わりました。
bashを利用している人は、.zshrcのところを.bash_profileで動作すると思います。

参考記事

https://qiita.com/ryuzee/items/e3ce493f132f1981f57a
https://qiita.com/JJJJJJJJ/items/cc4357f5ba2a9eed809d

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?