Skip to content

Instantly share code, notes, and snippets.

@justinclayton
Created December 6, 2018 23:03
Show Gist options
  • Save justinclayton/cb88ed06969533b1a453e24ac779e31a to your computer and use it in GitHub Desktop.
Save justinclayton/cb88ed06969533b1a453e24ac779e31a to your computer and use it in GitHub Desktop.
Create New AWS Account using AWS Organizations
#!/usr/bin/env bash -eio pipefail
ROOT_ID=$(aws organizations list-roots | jq -r '.Roots[0].Id')
name=$1
email=$2
ou_name=$3
create-account() {
aws organizations create-account --account-name $1 --email $2
}
wait-for-account-creation() {
while [[ $(aws organizations list-create-account-status --states IN_PROGRESS | jq '.CreateAccountStatuses | length') -gt 0 ]]; do sleep 2; done
}
move-account() {
local name=$1
local ou_name=$2
local ou_id=$(get-ou-id-for-ou-name ${ou_name})
local account_id=$(get-account-id-for-name ${name})
echo "account_id is $account_id"
aws organizations move-account --account ${account_id} \
--source-parent-id ${ROOT_ID} \
--destination-parent-id ${ou_id}
}
get-ou-id-for-ou-name() {
local ou_name=$1
aws organizations list-organizational-units-for-parent --parent-id ${ROOT_ID} | jq -r --arg ou ${ou_name} '.OrganizationalUnits[] | select(.Name == $ou) | .Id'
}
get-account-id-for-name() {
aws organizations list-accounts \
| jq -r --arg name ${name} '.Accounts[] | select(.Name == $name) | .Id'
}
write-config-for-account() {
local name=$1
local configpath=${2:-$HOME/.aws/config}
local account_id=$(get-account-id-for-name ${name})
sed -e "s/<<NAME>>/${name}/" -e "s/<<ACCOUNT>>/${account_id}/" >> ${configpath} <<EOF
[profile <<NAME>>]
role_arn = arn:aws:iam::<<ACCOUNT>>:role/OrganizationAccountAccessRole
account = <<ACCOUNT>>
source_profile = default
EOF
}
test-config-for-account() {
local name=$1
aws --profile $name sts get-caller-identity
}
create-account $name $email
echo "creating account..."
wait-for-account-creation
echo "assigning account $name to ou $ou_name..."
move-account $name $ou_name
echo "adding credentials to local ~/.aws/config..."
write-config-for-account $name
echo "testing credentials..."
test-config-for-account $name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment