All files / lib account.ts

98.14% Statements 53/54
95.45% Branches 21/22
100% Functions 4/4
98% Lines 49/50

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279                                3x 3x 3x 3x 3x 3x                                                                                                   3x 3x 3x 3x 3x           3x                           24x   24x   24x 24x 24x       24x 23x                         23x 23x   1x     1x                                 1x 1x       24x 24x 24x 24x 24x 24x 24x 24x                   24x                 105x               24x 24x 24x 24x   24x           24x   24x 24x                             24x                                           24x       24x 24x 1x             1x                                                                  
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 
Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License.
You may obtain a copy of the License at
 
    http://www.apache.org/licenses/LICENSE-2.0
 
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
 
import {Construct} from 'constructs';
import * as core from "aws-cdk-lib";
import { AccountProvider } from "./account-provider";
import * as cr from "aws-cdk-lib/custom-resources";
import * as ssm from "aws-cdk-lib/aws-ssm";
import { RemovalPolicy } from 'aws-cdk-lib';
 
/**
 * Properties of an AWS account
 */
export interface IAccountProps {
  /**
   * The email to use to create the AWS account
   */
  email: string;
  /**
   * The name of the AWS Account
   */
  name: string;
  /**
   * The account type
   */
  type?: AccountType;
  /**
   * The (optional) Stage name to be used in CI/CD pipeline
   */
  stageName?: string;
  /**
   * The (optional) Stage deployment order
   */
  stageOrder?: number;
  /**
   *  List of your services that will be hosted in this account. Set it to [ALL] if you don't plan to have dedicated account for each service.
   */
  hostedServices?: string[];
  /**
   * The potential Organizational Unit Id the account should be placed in
   */
  parentOrganizationalUnitId?: string;
  /**
   * The potential Organizational Unit Name the account should be placed in
   */
  parentOrganizationalUnitName?: string;
  /**
   * The AWS account Id
   */
  id?: string;
  /**
   * RemovalPolicy of the account. See https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-deletionpolicy.html#aws-attribute-deletionpolicy-options
   *
   * @default RemovalPolicy.RETAIN
   */
  removalPolicy?: RemovalPolicy;
}
 
export enum AccountType {
  CICD = "CICD",
  DNS = "DNS",
  STAGE = "STAGE",
  PLAYGROUND = "PLAYGROUND"
}
 
/**
 * An AWS Account
 */
export class Account extends Construct {
  /**
   * Constructor
   *
   * @param scope The parent Construct instantiating this account
   * @param id This instance name
   * @param accountProps Account properties
   */
  readonly accountName: string;
  readonly accountId: string;
  readonly accountStageName?: string;
  readonly accountStageOrder?: number;
 
  constructor(scope: Construct, id: string, accountProps: IAccountProps) {
    super(scope, id);
 
    const accountProvider = AccountProvider.getOrCreate(this);
 
    let existingAccount = false;
    let accountId = accountProps.id;
    let hostedServices = accountProps.hostedServices ? accountProps.hostedServices.join(':') : undefined;
 
    // do not create account if we reuse one
    let account;
    if (!accountId) {
      account = new core.CustomResource(
        this,
        `Account-${accountProps.name}`,
        {
          serviceToken: accountProvider.provider.serviceToken,
          resourceType: "Custom::AccountCreation",
          properties: {
            Email: accountProps.email,
            AccountName: accountProps.name,
          },
          removalPolicy: accountProps.removalPolicy || RemovalPolicy.RETAIN
        },
      );
      accountId = account.getAtt("AccountId").toString();
      accountProps.id = accountId;
    } else {
      existingAccount = true;
 
      // retrieve existing account information (actual name and email) to update accountProps
      account = new cr.AwsCustomResource(this, "ExistingAccountCustomResource", {
        onUpdate: {
          service: "Organizations",
          action: "describeAccount",
          physicalResourceId: cr.PhysicalResourceId.fromResponse(
            "Account.Id"
          ),
          region: "us-east-1", //AWS Organizations API are only available in us-east-1 for root actions
          parameters: {
            AccountId: accountId
          }
        },
        policy: cr.AwsCustomResourcePolicy.fromSdkCalls({
          resources: cr.AwsCustomResourcePolicy.ANY_RESOURCE,
        })
      });
 
      accountProps.name = account.getResponseField("Account.Name");
      accountProps.email = account.getResponseField("Account.Email");
    }
 
    // add tags
    const tags: { Key: string; Value: any; }[] = [];
    tags.push({Key: 'Email', Value: accountProps.email});
    tags.push({Key: 'AccountName', Value: accountProps.name});
    if (accountProps.type != null) tags.push({Key: 'AccountType', Value: accountProps.type});
    if (accountProps.stageName != null) tags.push({Key: 'StageName', Value: accountProps.stageName});
    if (accountProps.stageOrder != null) tags.push({Key: 'StageOrder', Value: accountProps.stageOrder.toString()});
    if (hostedServices != null) tags.push({Key: 'HostedServices', Value: hostedServices});
    const tagAccount = {
      service: "Organizations",
      action: "tagResource",
      region: "us-east-1", //AWS Organizations API are only available in us-east-1 for root actions
      physicalResourceId: cr.PhysicalResourceId.of(`tags-${accountId}`),
      parameters: {
        ResourceId: accountId,
        Tags: tags
      }
    };
    new cr.AwsCustomResource(this, "TagAccountCustomResource", {
      onCreate: tagAccount,
      onUpdate: tagAccount,
      onDelete: {
        service: "Organizations",
        action: "untagResource",
        region: "us-east-1", //AWS Organizations API are only available in us-east-1 for root actions
        parameters: {
          ResourceId: accountId,
          TagKeys: tags.map(t => t.Key)
        }
      },
      policy: cr.AwsCustomResourcePolicy.fromSdkCalls({
        resources: cr.AwsCustomResourcePolicy.ANY_RESOURCE,
      })
    });
 
    this.accountName = accountProps.name;
    this.accountId = accountId;
    this.accountStageName = accountProps.stageName;
    this.accountStageOrder = accountProps.stageOrder;
 
    let ssmParam = new ssm.StringParameter(this, existingAccount?`${accountId}-AccountDetails`:`${accountProps.name}-AccountDetails`, {
      description: `Details of ${accountProps.name}`,
      parameterName: `/accounts/${accountProps.name}`,
      simpleName: false,
      stringValue: JSON.stringify(accountProps),
    });
    ssmParam.node.addDependency(account);
 
    if (accountProps.parentOrganizationalUnitId) {
      let parent = new cr.AwsCustomResource(this, "ListParentsCustomResource", {
        onUpdate: {
          service: "Organizations",
          action: "listParents",
          physicalResourceId: cr.PhysicalResourceId.of(`${accountProps.parentOrganizationalUnitId}-${accountId}`),
          region: "us-east-1", //AWS Organizations API are only available in us-east-1 for root actions
          parameters: {
            ChildId: accountId,
          },
        },
        policy: cr.AwsCustomResourcePolicy.fromSdkCalls({
          resources: cr.AwsCustomResourcePolicy.ANY_RESOURCE,
        }),
      });
 
      new cr.AwsCustomResource(this, "MoveAccountCustomResource",
        {
          onUpdate: {
            service: "Organizations",
            action: "moveAccount",
            physicalResourceId: cr.PhysicalResourceId.of(`move-${accountId}`),
            region: "us-east-1", //AWS Organizations API are only available in us-east-1 for root actions
            parameters: {
              AccountId: accountId,
              DestinationParentId: accountProps.parentOrganizationalUnitId,
              SourceParentId: parent.getResponseField("Parents.0.Id"),
            },
            ignoreErrorCodesMatching: 'DuplicateAccountException' // ignore if account is already there
          },
          policy: cr.AwsCustomResourcePolicy.fromSdkCalls({
            resources: cr.AwsCustomResourcePolicy.ANY_RESOURCE,
          }),
        }
      );
 
 
      // Enabling Organizations listAccounts call for auto resolution of stages and DNS accounts Ids and Names
      Iif (accountProps.type === AccountType.CICD) {
        this.registerAsDelegatedAdministrator(accountId, 'ssm.amazonaws.com');
      } else {
       // Switching to another principal to workaround the max number of delegated administrators (which is set to 3 by default).
       const needsToBeDelegatedForDNSZOneNameResolution = this.node.tryGetContext('domain_name') ?? false;
       if(needsToBeDelegatedForDNSZOneNameResolution)
        this.registerAsDelegatedAdministrator(accountId, 'config-multiaccountsetup.amazonaws.com');
      }
 
    }
  }
 
  registerAsDelegatedAdministrator(accountId: string, servicePrincipal: string) {
    new cr.AwsCustomResource(this,
      "registerDelegatedAdministrator",
      {
        onCreate: {
          service: 'Organizations',
          action: 'registerDelegatedAdministrator', // https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Organizations.html#registerDelegatedAdministrator-property
          physicalResourceId: cr.PhysicalResourceId.of('registerDelegatedAdministrator'),
          region: 'us-east-1', //AWS Organizations API are only available in us-east-1 for root actions
          parameters: {
            AccountId: accountId,
            ServicePrincipal: servicePrincipal
          }
        },
        onDelete: {
          service: 'Organizations',
          action: 'deregisterDelegatedAdministrator', // https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Organizations.html#deregisterDelegatedAdministrator-property
          physicalResourceId: cr.PhysicalResourceId.of('registerDelegatedAdministrator'),
          region: 'us-east-1', //AWS Organizations API are only available in us-east-1 for root actions
          parameters: {
            AccountId: accountId,
            ServicePrincipal: servicePrincipal
          }
        },
        installLatestAwsSdk: false,
        policy: cr.AwsCustomResourcePolicy.fromSdkCalls(
          {
            resources: cr.AwsCustomResourcePolicy.ANY_RESOURCE
          }
        )
      }
    );
  }
}