AWS organization を利用して新しいAWS環境をゼロから作成する
AWSで新しい環境を作りたいけれど、「メールアドレスの新規作成やクレジットカードの登録が面倒だな……」と思ったことはありませんか?今回は、AWS Organizationsを活用して、完全新規のAWS環境をゼロから作成する手順を解説します。※新しいメールアドレスの用意や、カード情報の追加登録は一切不要です。
下記の流れで解説します。
- Organizations の作成
- アカウントの作成
- プロファイル設定
- ロールの作成
- ロールの切り替え
※ 操作はすべてAWS Python ライブラリ(boto3)を使用して実施します。
Organizations の作成
import boto3
from botocore.exceptions import ClientError
client = boto3.client('organizations', region_name='us-east-1')
try:
response = client.create_organization(
FeatureSet='ALL'
)
org_info = response['Organization']
print("✅ Organization created successfully.")
print(f"Management Account ID: {org_info['MasterAccountId']}")
except ClientError as e:
error_code = e.response['Error']['Code']
if error_code == 'AlreadyInOrganizationException':
print("❌ Error: This account is already a member or management account of an organization.")
elif error_code == 'ConcurrentModificationException':
print("❌ Error: Concurrent modification detected. Please retry after a few moments.")
else:
print(f"❌ Unexpected error occurred: {e}")
プラスメールアドレスについて
AWS organization を利用して新しいAWS環境を作成するにはメールアドレスの登録が必要なのですが、プラスメールアドレスを使えば新しいメールアドレスを都度取得する必要はありません。
プラスメールアドレスGmailやOutlook等は「ユーザー名+任意の文字列@メールドメイン」の形式で、事前設定なしにすぐプラスアドレスを利用できます。届いたメールはすべて元のアドレスの受信トレイに自動集約されます。
アカウントの作成
アカウントを作成します
このアカウントの作成が、新しいAWS環境を作ることに該当します。
ここでメールアドレスを指定する必要があるのですが、上記プラスメールアドレスを使用することで新しいメールアドレスを取得することなく、アカウントを作成できます。
下記例では、自分のメールアドレスがuser01@outleek.comだったとするとプラスメールアドレスでuser01+resources_dev_0808@outleek.comを指定します。
import boto3
import time
EMAIL_ADDRESS = 'user01+resources_dev_0808@outleek.com'
ACCOUNT_NAME = 'resources_dev_0808'
org_client = boto3.client('organizations', region_name='us-east-1')
print("Creating account...")
response = org_client.create_account(
Email=EMAIL_ADDRESS,
AccountName=ACCOUNT_NAME
)
request_id = response['CreateAccountStatus']['Id']
account_id = None
for _ in range(10):
status_response = org_client.describe_create_account_status(
CreateAccountRequestId=request_id
)
status = status_response['CreateAccountStatus']['State']
print(f"Current status: {status}")
if status == 'SUCCEEDED':
account_id = status_response['CreateAccountStatus']['AccountId']
print(f"Success! Account ID: {account_id}")
break
elif status == 'FAILED':
reason = status_response['CreateAccountStatus']['FailureReason']
print(f"Failed. Reason: {reason}")
break
time.sleep(10)
else:
print("Timeout waiting for account creation.")
プロフィルの設定
CLIで切り替えられるように%USERPROFILE%/.aws/configにprofile設定を追加します。
YOUR_ACCOUNT_IDはアカウントIDを指定してください。
%USERPROFILE%/.aws/config
[default]
region = ap-northeast-1
output = json
[profile resources_dev_admin]
role_arn = arn:aws:iam::YOUR_ACCOUNT_ID:role/OrganizationAccountAccessRole
source_profile = default