LoginSignup
6
2

More than 3 years have passed since last update.

SAML Federated User で AWS CLI を使用するための便利スクリプト

Last updated at Posted at 2021-01-26

AWS マネジメントコンソールを SAML フェデレーションによる SSO で利用している場合、その権限で AWS CLI を利用するのは簡単ではない。

そもそも Role が一時的に割り当てられているだけであって IAM User を作成しているわけではないので Credentials を作成することができない。AWS CLI を利用するためには AssumeRoleWithSAML という API を使って一時的な Credentials を都度要求しなければならない。

詳しいことは以下に書いた。

SAML 認証による一時的な認証情報で boto3 を利用する - Qiita

上記は Python でやる場合の話だったが、今回は同じことを Bash でやれるようにスクリプトを書いたのでそれについてメモしておく。

スクリプト

aws コマンドと jq コマンドはあらかじめインストールしておく必要がある。

aws_assume_role_with_saml.sh
#!/bin/bash -eu

if !(type "aws" > /dev/null 2>&1) || !(type "jq" > /dev/null 2>&1); then
  echo "This script requires the 'aws' and 'jq' commands." 1>&2
  echo "Please install them." 1>&2
  exit 1
fi

SSO_AUTHENTICATION_URL=$(aws configure get sso_authentication_url || true)
if [ -n "${SSO_AUTHENTICATION_URL}" ]; then
  echo -e "Open this URL in your browser to get the SAML Response string.\n${SSO_AUTHENTICATION_URL}\n"
fi

read -n 8192 -p "SAML Response: " SAML_RESPONSE

CONFIG_PATH="${HOME}/.aws/assume-role-with-saml-config/${AWS_PROFILE:-default}.yml"
CREDENTIALS=$(aws sts assume-role-with-saml --cli-input-yaml "$(cat ${CONFIG_PATH})" --saml-assertion ${SAML_RESPONSE})

echo -e "\nSucceeded!\nAdd the below to '~/.aws/credentials'.\n"

echo "[${AWS_PROFILE:-default}]"
echo "aws_access_key_id = $(echo ${CREDENTIALS} | jq -r .Credentials.AccessKeyId)"
echo "aws_secret_access_key = $(echo ${CREDENTIALS} | jq -r .Credentials.SecretAccessKey)"
echo "aws_session_token = $(echo ${CREDENTIALS} | jq -r .Credentials.SessionToken)"

初期設定

~/.aws/assume-role-with-saml-config/<PROFILE>.yml に AssumeRoleWithSAML API で必要となる Role ARN や IdP ARN などを設定しておく。

~/.aws/assume-role-with-saml-config/myaccount.yml
RoleArn: arn:aws:iam::000000000000:role/Google-User
PrincipalArn: arn:aws:iam::000000000000:saml-provider/Google
DurationSeconds: 43200 # 12 hours

~/.aws/config に SSO の認証 URL を設定しておくと、スクリプト実行時に URL が表示されて便利。(設定しなくてもいい)

~/.aws/config
[profile myaccount]
region = ap-northeast-1
sso_authentication_url = https://accounts.google.com/o/saml2/initsso?idpid=xxxxxxxxx&spid=0000000000000&forceauthn=false

使い方

$ AWS_PROFILE=myaccount ./aws_assume_role_with_saml.sh
Open this URL in your browser to get the SAML Response string.
https://accounts.google.com/o/saml2/initsso?idpid=xxxxxxxxx&spid=0000000000000&forceauthn=false

SAML Response: (とても長い文字列を入力する)

Succeeded!
Write the following in '~/.aws/credentials'

[myaccount]
aws_access_key_id = ...
aws_secret_access_key = ... 
aws_session_token = ...

実行すると SAML Response の入力を要求されるので、Web ブラウザを使って SAML Response を取得して入力する。1

成功した場合は一時的な Credentials が表示されるので、これを ~/.aws/credentials に追記すれば AWS CLI が使えるようになる。

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