Skip to content

Instantly share code, notes, and snippets.

@kenzauros
Created April 25, 2023 02:52
Show Gist options
  • Save kenzauros/3db22b3b49db0e6e78155ac51f7b5509 to your computer and use it in GitHub Desktop.
Save kenzauros/3db22b3b49db0e6e78155ac51f7b5509 to your computer and use it in GitHub Desktop.
AWS SSO ユーザー登録&グループ追加
# Usage: ./register_sso_user.sh toyonaka@example.com toyonaka taro all
# arg1: Email (例: toyonaka@example.com)
# arg2: 氏 (例: toyonaka)
# arg3: 名 (例: taro)
# arg4: グループ名 (例: all)
set -xe
if (( $# != 4 )); then
echo "Usage: $0 <email> <family_name> <given_name> <group_name>"
exit 1
fi
# 引数を変数に代入
EMAIL=$1
FAMILY_NAME=${2^^} # 大文字
GIVEN_NAME=${3,,} # 小文字
GROUP_NAME=$4
# EMAIL がメールアドレスの形式でない場合はエラー
if [[ ! $EMAIL =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]]; then
echo "Email is not valid"
exit 1
fi
# FAMILY_NAME がアルファベット大文字のみでなければエラー
if [[ ! $FAMILY_NAME =~ ^[A-Z]+$ ]]; then
echo "Family name is not valid"
exit 1
fi
# GIVEN_NAME がアルファベット小文字のみでなければエラー
if [[ ! $GIVEN_NAME =~ ^[a-z]+$ ]]; then
echo "Given name is not valid"
exit 1
fi
# GROUP_NAME が英数字のみでなければエラー
if [[ ! $GROUP_NAME =~ ^[A-Za-z0-9]+$ ]]; then
echo "Group name is not valid"
exit 1
fi
# 名は先頭だけ大文字にする
GIVEN_NAME=${GIVEN_NAME^}
echo "Email: $EMAIL, Family name: $FAMILY_NAME, Given name: $GIVEN_NAME, Group name: $GROUP_NAME"
if [[ -z "$AWS_PROFILE" ]]; then
echo "AWS_PROFILE is not set"
exit 1
fi
if [[ -z "$AWS_REGION" ]]; then
echo "AWS_REGION is not set"
exit 1
fi
# exit 0
function get_id_store_id() {
aws sso-admin list-instances \
--query "Instances[0].IdentityStoreId" \
--output text
}
function get_group_id() {
# $1: グループ名
aws identitystore get-group-id \
--identity-store-id $ID_STORE_ID \
--alternate-identifier="{\"UniqueAttribute\":{\"AttributePath\":\"displayName\",\"AttributeValue\":\"$1\"}}" \
--query "GroupId" \
--output text
}
function create_user() {
# $1: Email
# $2: 氏
# $3: 名
aws identitystore create-user \
--identity-store-id $ID_STORE_ID \
--user-name $1 \
--name "FamilyName=$2,GivenName=$3" \
--display-name "$3 $2" \
--emails "Value=$1,Type=work,Primary=true" \
| jq -r '.UserId'
}
function addUserToGroup() {
# $1: USER_ID
# $2: GROUP_ID
aws identitystore create-group-membership \
--identity-store-id $ID_STORE_ID \
--group-id $2 \
--member-id "UserId=$1" \
| jq -r '.MembershipId'
}
# IdentityStoreId を取得
ID_STORE_ID=$(get_id_store_id)
echo "ID_STORE_ID: $ID_STORE_ID"
# グループ ID を取得
GROUP_ID=$(get_group_id $GROUP_NAME)
echo "GROUP_ID: $GROUP_ID"
# ユーザーを作成
USER_ID=$(create_user $EMAIL $FAMILY_NAME $GIVEN_NAME)
echo "USER_ID: $USER_ID"
# ユーザーをグループに追加
MEMBER_SHIP_ID=$(addUserToGroup $USER_ID $GROUP_ID)
echo "MEMBER_SHIP_ID: $MEMBER_SHIP_ID"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment