Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Create New AWS Account using AWS Organizations
#!/usr/bin/env bash -eio pipefail
ROOT_ID=$(aws organizations list-roots | jq -r '.Roots[0].Id')
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
test-config-for-account() {
local name=$1
aws --profile $name sts get-caller-identity
create-account $name $email
echo "creating account..."
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