📝
CDK で AWS Organizations にアカウントを追加してみた
How to create an AWS Organization for your Account with the AWS CDK - DEV Community
At the time of writing there are different solutions out there to help you to manage your AWS Organization. AWS CloudFormation is missing and there is no support in the AWS CDK.
AWS Organizations へのアカウント追加については CDK ではネイティブにサポートされていないようなのでカスタムリソースで実現してみました。
前提
- 開発環境: Cloud9 (Amazon Linux 2023)
- 作業アカウント: AWS Organizations の管理アカウント
1. CDK プロジェクト作成
$ mkdir -p ~/.npm-global
$ npm config set prefix '~/.npm-global'
$ echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
$ source ~/.bashrc
$ npm install -g typescript
$ mkdir cdk-organizations-project
$ cd cdk-organizations-project
$ cdk init app --language typescript
$ mkdir lambda
$ touch lambda/create-account.js
2. CDK ファイル作成
lambda/create-account.js
const { OrganizationsClient, CreateAccountCommand } = require('@aws-sdk/client-organizations');
const client = new OrganizationsClient({ region: 'us-east-1' });
exports.handler = async (event) => {
console.log('Event:', JSON.stringify(event, null, 2));
const requestType = event.RequestType;
const properties = event.ResourceProperties;
try {
if (requestType === 'Create' || requestType === 'Update') {
const params = {
Email: properties.Email,
AccountName: properties.AccountName,
};
const command = new CreateAccountCommand(params);
const response = await client.send(command);
console.log('Create Account Response:', response);
return {
Status: 'SUCCESS',
PhysicalResourceId: response.CreateAccountStatus.Id,
Data: {
AccountId: response.CreateAccountStatus.Id,
},
};
} else if (requestType === 'Delete') {
return {
Status: 'SUCCESS',
PhysicalResourceId: event.PhysicalResourceId,
};
}
} catch (error) {
console.error('Error:', error);
return {
Status: 'FAILED',
PhysicalResourceId: event.PhysicalResourceId || 'unknown',
Reason: error.message,
};
}
};
2. CDK ファイル作成
lib/cdk-organizations-project-stack.ts
import * as cdk from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as cr from 'aws-cdk-lib/custom-resources';
import { Construct } from 'constructs';
import * as path from 'path';
export class CdkOrganizationsProjectStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const createAccountFunction = new lambda.Function(this, 'CreateAccountFunction', {
runtime: lambda.Runtime.NODEJS_18_X,
handler: 'create-account.handler',
code: lambda.Code.fromAsset(path.join(__dirname, '../lambda')),
});
createAccountFunction.addToRolePolicy(
new iam.PolicyStatement({
actions: ['organizations:CreateAccount'],
resources: ['*'],
})
);
const customResource = new cr.AwsCustomResource(this, 'CreateAccountCustomResource', {
onCreate: {
service: 'lambda',
action: 'invoke',
parameters: {
FunctionName: createAccountFunction.functionName,
Payload: JSON.stringify({
RequestType: 'Create',
ResourceProperties: {
Email: 'your-email-address',
AccountName: 'new-account-name',
},
}),
},
physicalResourceId: cr.PhysicalResourceId.of('CreateAccountResource'),
},
policy: cr.AwsCustomResourcePolicy.fromSdkCalls({
resources: cr.AwsCustomResourcePolicy.ANY_RESOURCE,
}),
});
createAccountFunction.grantInvoke(customResource);
}
}
3. デプロイ
$ cdk synth
$ cdk deploy
4. アカウントが追加されたことを確認
AWS Organizations のコンソールでアカウントが追加されたことを確認できれば OK です。

まとめ
今回は CDK で AWS Organizations にアカウントを追加してみました。
どなたかの参考になれば幸いです。
Discussion