aws-cdk-lib#Stack TypeScript Examples

The following examples show how to use aws-cdk-lib#Stack. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AwsProvider.ts    From lift with MIT License 7 votes vote down vote up
constructor(private readonly serverless: Serverless) {
        this.stackName = serverless.getProvider("aws").naming.getStackName();
        this.app = new App();
        this.stack = new Stack(this.app, undefined, {
            synthesizer: new DefaultStackSynthesizer({
                generateBootstrapVersionRule: false,
            }),
        });
        this.legacyProvider = serverless.getProvider("aws");
        this.naming = this.legacyProvider.naming;
        this.region = serverless.getProvider("aws").getRegion();
        serverless.stack = this.stack;
    }
Example #2
Source File: global-rds.test.ts    From cdk-aurora-globaldatabase with Apache License 2.0 6 votes vote down vote up
test('test create Matser RDS', () => {
  const app = new App();
  const stack = new Stack(app, 'testing-stack', { env: envTokyo });
  new GlobalAuroraRDSMaster(stack, 'GlobalAuroraRDS');
  assertions.Template.fromStack(stack).findResources('AWS::RDS::DBCluster');
  assertions.Template.fromStack(stack).hasResourceProperties('AWS::RDS::DBClusterParameterGroup', {
    Family: 'aurora-mysql5.7',
    Parameters: {
      time_zone: 'UTC',
    },
  });
  assertions.Template.fromStack(stack).hasResourceProperties('AWS::RDS::DBInstance', {
    PubliclyAccessible: false,
  });
});
Example #3
Source File: CloudFormation.ts    From lift with MIT License 6 votes vote down vote up
export async function getStackOutput(aws: AwsProvider, output: CfnOutput): Promise<string | undefined> {
    const outputId = Stack.of(output.stack).resolve(output.logicalId) as string;
    const stackName = aws.stackName;

    getUtils().log.debug(`Fetching output "${outputId}" in stack "${stackName}"`);

    let data: DescribeStacksOutput;
    try {
        data = await aws.request<DescribeStacksInput, DescribeStacksOutput>("CloudFormation", "describeStacks", {
            StackName: stackName,
        });
    } catch (e) {
        if (e instanceof Error && e.message === `Stack with id ${stackName} does not exist`) {
            getUtils().log.debug(e.message);

            return undefined;
        }

        throw e;
    }
    if (!data.Stacks || !data.Stacks[0].Outputs) {
        return undefined;
    }
    for (const item of data.Stacks[0].Outputs) {
        if (item.OutputKey === outputId) {
            return item.OutputValue;
        }
    }

    return undefined;
}
Example #4
Source File: global-rds.test.ts    From cdk-aurora-globaldatabase with Apache License 2.0 6 votes vote down vote up
test('test change default dbUserName and default database Name', () => {
  const app = new App();
  const stack = new Stack(app, 'testing-stack', { env: envTokyo });;
  new GlobalAuroraRDSMaster(stack, 'GlobalAuroraRDS', {
    dbUserName: 'superuser',
    defaultDatabaseName: 'superdb',
    rdsPassword: '1qaz2wsx',
  });
  assertions.Template.fromStack(stack).hasResourceProperties('AWS::RDS::DBCluster', {
    Engine: 'aurora-mysql',
    DatabaseName: 'superdb',
    EngineVersion: '5.7.mysql_aurora.2.07.1',
    MasterUsername: 'superuser',
    MasterUserPassword: '1qaz2wsx',
  });
});
Example #5
Source File: index.ts    From cloudstructs with Apache License 2.0 6 votes vote down vote up
constructor(scope: Construct, id: string, props: EcsServiceRollerProps) {
    super(scope, id);

    const rule = props.trigger?.rule ?? new events.Rule(this, 'Rule', {
      schedule: props.trigger?.schedule ?? events.Schedule.cron({
        minute: '0',
        hour: '0',
      }),
    });


    rule.addTarget(new targets.AwsApi({
      service: 'ECS',
      action: 'updateService',
      parameters: {
        service: props.service.serviceName,
        cluster: props.cluster.clusterName,
        forceNewDeployment: true,
      } as AWS.ECS.UpdateServiceRequest,
      // https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-supported-iam-actions-resources.html
      // arn:aws:ecs:<region>:<account>:service/<cluster-name>/<service-name>
      policyStatement: new iam.PolicyStatement({
        actions: ['ecs:UpdateService'],
        resources: [Stack.of(this).formatArn({
          service: 'ecs',
          resource: 'service',
          resourceName: `${props.cluster.clusterName}/${props.service.serviceName}`,
        })],
      }),
    }));
  }
Example #6
Source File: global-rds.test.ts    From cdk-aurora-globaldatabase with Apache License 2.0 6 votes vote down vote up
test('test update Parameter Group', () => {
  const app = new App();
  const stack = new Stack(app, 'testing-stack', { env: envTokyo });;
  new GlobalAuroraRDSMaster(stack, 'GlobalAuroraRDS', {
    parameters: {
      time_zone: MySQLtimeZone.ASIA_TAIPEI,
    },
  });
  assertions.Template.fromStack(stack).hasResourceProperties('AWS::RDS::DBClusterParameterGroup', {
    Parameters: {
      time_zone: 'Asia/Taipei',
    },
  });
});
Example #7
Source File: go-lambda-stack.ts    From cdk-examples with MIT License 6 votes vote down vote up
export class GoLambdaStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    // The code that defines your stack goes here
    new Function(this, 'goLambda', {
      runtime: Runtime.GO_1_X,
      handler: 'main',
      code: Code.fromAsset(`${__dirname}/../lambda-fns/hello-world/`, {
        bundling: {
          image: Runtime.GO_1_X.bundlingImage,
          user: 'root',
          command: [
            'bash', '-c', [
              'cd /asset-input',
              'go build -o main main.go',
              'mv /asset-input/main /asset-output/'
            ].join(' && ')
          ]
        }
      })
    })    
  }
}
Example #8
Source File: rds.test.ts    From bastion-host-forward with Apache License 2.0 6 votes vote down vote up
test('Bastion Host with own securityGroup', () => {
  const app = new App();
  const stack = new Stack(app, 'TestStack');
  const testVpc = new Vpc(stack, 'TestVpc');
  const securityGroup = new SecurityGroup(stack, 'SecurityGroup', {
    vpc: testVpc,
    allowAllOutbound: false,
    description: 'My test securityGroup description',
    securityGroupName: 'MyTestSecurityGroupName',
  });

  const testRds = new DatabaseInstance(stack, 'TestRDS', {
    engine: DatabaseInstanceEngine.POSTGRES,
    instanceType: InstanceType.of(InstanceClass.T3, InstanceSize.MICRO),
    vpc: testVpc,
  });

  // WHEN
  const bastionHost = new BastionHostRDSForward(stack, 'MyTestConstruct', {
    vpc: testVpc,
    name: 'MyBastion',
    rdsInstance: testRds,
    securityGroup,
  });
  const bastionHostSecurityGroup = bastionHost.securityGroup as SecurityGroup;

  assert.equal(securityGroup.securityGroupId, bastionHostSecurityGroup.securityGroupId);
  assert.equal(securityGroup.allowAllOutbound, bastionHostSecurityGroup.allowAllOutbound);
});
Example #9
Source File: ecs-service-roller.test.ts    From cloudstructs with Apache License 2.0 6 votes vote down vote up
beforeEach(() => {
  stack = new Stack();
  cluster = new ecs.Cluster(stack, 'Cluster');
  const taskDefinition = new ecs.FargateTaskDefinition(stack, 'TaskDef');
  taskDefinition.addContainer('Container', {
    image: ecs.ContainerImage.fromRegistry('my-image'),
  });
  service = new ecs.FargateService(stack, 'Service', {
    cluster,
    taskDefinition,
  });
});
Example #10
Source File: generic-bastion-host-forward.test.ts    From bastion-host-forward with Apache License 2.0 6 votes vote down vote up
test('Bastion Host with own securityGroup', () => {
  const app = new App();
  const stack = new Stack(app, 'TestStack');
  const testVpc = new Vpc(stack, 'TestVpc');
  const securityGroup = new SecurityGroup(stack, 'SecurityGroup', {
    vpc: testVpc,
    allowAllOutbound: false,
    description: 'My test securityGroup description',
    securityGroupName: 'MyTestSecurityGroupName',
  });

  // WHEN
  const bastionHost = new GenericBastionHostForward(stack, 'MyTestConstruct', {
    vpc: testVpc,
    name: 'MyRedShiftBastion',
    securityGroup,
    address: '127.0.0.1',
    port: '6379',
  });
  const bastionHostSecurityGroup = bastionHost.securityGroup as SecurityGroup;

  assert.equal(securityGroup.securityGroupId, bastionHostSecurityGroup.securityGroupId);
  assert.equal(securityGroup.allowAllOutbound, bastionHostSecurityGroup.allowAllOutbound);
});
Example #11
Source File: slack-app.integ.ts    From cloudstructs with Apache License 2.0 6 votes vote down vote up
class TestStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    const app = new SlackApp(this, 'MyApp', {
      configurationTokenSecret: secretsmanager.Secret.fromSecretNameV2(this, 'Secret', 'slack-app-config-token'),
      manifest: SlackAppManifestDefinition.fromManifest({
        name: 'My App',
        description: 'A very cool Slack App deployed with CDK',
      }),
    });

    new CfnOutput(this, 'AppId', {
      value: app.appId,
    });
  }
}
Example #12
Source File: ts-lambda-stack.ts    From cdk-examples with MIT License 6 votes vote down vote up
export class TsLambdaStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    // The code that defines your stack goes here

    new NodejsFunction(this, 'helloWorldFn', {
      runtime: Runtime.NODEJS_16_X,
      entry: `${__dirname}/../lambda-fns/hello-world/index.ts`,
      handler: 'myFunction',
      memorySize: 128,
      architecture: Architecture.ARM_64,
      bundling: {
        minify: true,
        // tsconfig: `${__dirname}/../lambda-fns/hello-world/tsconfig.json` // if you want to override defaults
      }
    })
  }
}
Example #13
Source File: certificate-stack.ts    From minwiz with BSD 2-Clause "Simplified" License 6 votes vote down vote up
export class CertificateStack extends Stack {
  public readonly websiteCert: DnsValidatedCertificate;
  public readonly hostedZone: IHostedZone;

  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    this.hostedZone = HostedZone.fromHostedZoneAttributes(
      this,
      "HostedZoneWithAttrs",
      {
        hostedZoneId,
        zoneName: website_domain,
      }
    );

    this.websiteCert = new DnsValidatedCertificate(this, "MinWizSSL", {
      domainName: website_domain,
      subjectAlternativeNames: [`www.${website_domain}`],
      hostedZone: this.hostedZone,
    });

    new CfnOutput(this, "WebsiteCertArn", {
      value: this.websiteCert.certificateArn,
    });
  }
}
Example #14
Source File: https-redirect-stack.ts    From cdk-examples with MIT License 6 votes vote down vote up
export class HttpsRedirectStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    // The code that defines your stack goes here

    const hostedZone = HostedZone.fromHostedZoneAttributes(this, 'HostedZoneWithAttrs', {
      hostedZoneId: 'myZoneId',
      zoneName: 'example.com'
    })

    new HttpsRedirect(this, 'wwwToNonWww', {
      recordNames: ['www.example.com'],
      targetDomain: 'example.com',
      zone: hostedZone
    })
  }
}
Example #15
Source File: global-rds.test.ts    From cdk-aurora-globaldatabase with Apache License 2.0 6 votes vote down vote up
test('test error Region', () => {
  const app = new App();
  const stack = new Stack(app, 'testing-stack', { env: envErrorRegion });
  expect(()=>{
    const globalmainstack = new GlobalAuroraRDSMaster(stack, 'GlobalAuroraRDS', {
      instanceType: InstanceTypeEnum.R5_LARGE,
      rdsPassword: '1qaz2wsx',
      engineVersion: _rds.DatabaseClusterEngine.auroraPostgres({ version: _rds.AuroraPostgresEngineVersion.VER_11_7 }),
      dbClusterpPG: new _rds.ParameterGroup(stack, 'dbClusterparametergroup', {
        engine: _rds.DatabaseClusterEngine.auroraPostgres({
          version: _rds.AuroraPostgresEngineVersion.VER_11_7,
        }),
      }),
    });

    globalmainstack.addRegionalCluster(stack, 'regional', {
      region: 'ap-southeast-1',
      dbSubnetGroupName: 'mock-db-subnet-group-name',
    });
  }).toThrowError(/This region sa-east-1 not Support Global RDS !!!/);
});
Example #16
Source File: lambda-local-stack.ts    From cdk-examples with MIT License 6 votes vote down vote up
export class LambdaLocalStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    // The code that defines your stack goes here

    const oneFn = new Function(this, 'oneFn', {
      runtime: Runtime.NODEJS_16_X,
      code: Code.fromAsset(`${__dirname}/../lambda-fns/one/deployment.zip`),
      handler: 'index.handler'
    })
  }
}
Example #17
Source File: global-rds.test.ts    From cdk-aurora-globaldatabase with Apache License 2.0 6 votes vote down vote up
test('test Create Custom Resource', () => {
  const app = new App();
  const stack = new Stack(app, 'testing-stack', { env: envTokyo });
  new GlobalAuroraRDSMaster(stack, 'GlobalAuroraRDS', {
    instanceType: InstanceTypeEnum.R5_LARGE,
    rdsPassword: '1qaz2wsx',
    engineVersion: _rds.DatabaseClusterEngine.auroraPostgres({ version: _rds.AuroraPostgresEngineVersion.VER_11_7 }),
    dbClusterpPG: new _rds.ParameterGroup(stack, 'dbClusterparametergroup', {
      engine: _rds.DatabaseClusterEngine.auroraPostgres({
        version: _rds.AuroraPostgresEngineVersion.VER_11_7,
      }),
    }),
  });
  assertions.Template.fromStack(stack).findResources('Custom::UpgradeGlobalClusterProvider');
});
Example #18
Source File: pipeline-stack.ts    From minwiz with BSD 2-Clause "Simplified" License 5 votes vote down vote up
export class PipelineStack extends Stack {
  constructor(app: App, id: string, props: PipelineStackProps) {
    super(app, id, props);

    const siteBuild = new PipelineProject(this, "MinWizBuild", {
      description: "minwiz.com site build",
      buildSpec: BuildSpec.fromObject({
        version: "0.2",
        phases: {
          install: {
            commands: ["npm ci"],
          },
          build: {
            commands: "npm run build",
          },
        },
        artifacts: {
          "base-directory": "dist",
          files: ["**/*"],
        },
      }),
      environment: {
        buildImage: LinuxBuildImage.STANDARD_5_0,
        computeType: ComputeType.SMALL,
      },
    });

    const siteBuildOutput = new Artifact("SiteBuildOutput");

    const sourceOutput = new Artifact("SrcOutput");

    const artifactBucket = new Bucket(this, "MinWizPipelineArtifacts", {
      removalPolicy: RemovalPolicy.DESTROY,
      encryption: BucketEncryption.S3_MANAGED,
      blockPublicAccess: BlockPublicAccess.BLOCK_ALL,
      autoDeleteObjects: true,
    });

    new Pipeline(this, "MinWiz", {
      restartExecutionOnUpdate: true,
      artifactBucket,
      stages: [
        {
          stageName: "Source",
          actions: [
            new GitHubSourceAction({
              actionName: "Checkout",
              output: sourceOutput,
              owner: "zeplia",
              repo: "minwiz",
              oauthToken: SecretValue.plainText(props.githubToken),
              trigger: GitHubTrigger.WEBHOOK,
            }),
          ],
        },
        {
          stageName: "Build",
          actions: [
            new CodeBuildAction({
              actionName: "Site_Build",
              project: siteBuild,
              input: sourceOutput,
              outputs: [siteBuildOutput],
            }),
          ],
        },
        {
          stageName: "Deploy",
          actions: [
            new S3DeployAction({
              actionName: "DeployStaticSite",
              input: siteBuildOutput,
              bucket: props.websiteBucket,
            }),
          ],
        },
      ],
    });
  }
}
Example #19
Source File: toolkit-cleaner.test.ts    From cloudstructs with Apache License 2.0 5 votes vote down vote up
stack: Stack
Example #20
Source File: cloudfront.ts    From minwiz with BSD 2-Clause "Simplified" License 5 votes vote down vote up
export class CloudfrontStack extends Stack {
  public readonly websiteBucket: Bucket;

  constructor(scope: Construct, id: string, props: CloudfrontStackProps) {
    super(scope, id, props);

    this.websiteBucket = new Bucket(this, "websiteBucket", {
      removalPolicy: RemovalPolicy.DESTROY,
      bucketName: website_domain,
      autoDeleteObjects: true,
    });

    new CfnOutput(this, "websiteBucketArn", {
      value: this.websiteBucket.bucketArn,
    });

    const cachePolicy = new CachePolicy(this, "MinWizPolicy", {
      defaultTtl: Duration.hours(24),
      minTtl: Duration.hours(24),
      maxTtl: Duration.hours(24),
      enableAcceptEncodingGzip: true,
      enableAcceptEncodingBrotli: true,
    });

    const distribution = new Distribution(this, "MinWizDistribution", {
      defaultBehavior: {
        origin: new S3Origin(this.websiteBucket),
        allowedMethods: AllowedMethods.ALLOW_GET_HEAD_OPTIONS,
        cachePolicy,
        compress: true,
        viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
      },
      domainNames: [website_domain /*, `www.${website_domain}`*/],
      certificate: props.websiteCert,
      minimumProtocolVersion: SecurityPolicyProtocol.TLS_V1_2_2019,
      defaultRootObject: "index.html",
      enableIpv6: true,
      enabled: true,
      httpVersion: HttpVersion.HTTP2,
      priceClass: PriceClass.PRICE_CLASS_ALL,
    });

    new ARecord(this, "aliasForCloudfront", {
      target: RecordTarget.fromAlias(new CloudFrontTarget(distribution)),
      zone: props.hostedZone,
      recordName: website_domain,
    });

    new HttpsRedirect(this, "wwwToNonWww", {
      recordNames: [`www.${website_domain}`],
      targetDomain: website_domain,
      zone: props.hostedZone,
    });
  }
}
Example #21
Source File: url-shortener.test.ts    From cloudstructs with Apache License 2.0 5 votes vote down vote up
stack: Stack
Example #22
Source File: global-rds.test.ts    From cdk-aurora-globaldatabase with Apache License 2.0 5 votes vote down vote up
test('test create Slave region vpc', () => {
  const app = new App();
  const stack = new Stack(app, 'testing-stack', { env: envTokyo });
  new GlobalAuroraRDSSlaveInfra(stack, 'GlobalAuroraRDS');
  assertions.Template.fromStack(stack).findResources('AWS::EC2::VPC');
});
Example #23
Source File: aurora-serverless.ts    From bastion-host-forward with Apache License 2.0 5 votes vote down vote up
/**
   * @returns the resource ARN for the the rds-db:connect action
   */
  private genDbUserArnFromRdsArn(dbIdentifier: string, dbUser: string): string {
    return `arn:aws:rds-db:${Stack.of(this).region}:${Stack.of(this).account}:dbuser:${dbIdentifier}/${dbUser}`;
  }
Example #24
Source File: static-website.test.ts    From cloudstructs with Apache License 2.0 5 votes vote down vote up
beforeEach(() => {
  app = new App();
  stack = new Stack(app, 'Stack', {
    env: { region: 'eu-west-1' },
  });
});
Example #25
Source File: aurora-serverless.test.ts    From bastion-host-forward with Apache License 2.0 5 votes vote down vote up
test('Bastion Host created for normal username/password access', () => {
  const app = new App();
  const stack = new Stack(app, 'TestStack');
  const testVpc = new Vpc(stack, 'TestVpc');
  const testAurora = new ServerlessCluster(stack, 'TestAurora', {
    engine: DatabaseClusterEngine.AURORA,
    vpc: testVpc,
  });

  // WHEN
  new BastionHostAuroraServerlessForward(stack, 'MyTestConstruct', {
    vpc: testVpc,
    name: 'MyBastion',
    serverlessCluster: testAurora,
    clientTimeout: 2,
    serverTimeout: 7,
  });

  const template = Template.fromStack(stack);

  // THEN
  template.hasResourceProperties('AWS::EC2::Instance', {
    UserData: {
      'Fn::Base64': {
        'Fn::Join': [
          '',
          [
            'Content-Type: multipart/mixed; boundary="//"\nMIME-Version: 1.0\n--//\nContent-Type: text/cloud-config; charset="us-ascii"\nMIME-Version: 1.0\nContent-Transfer-Encoding: 7bit\nContent-Disposition: attachment; filename="cloud-config.txt"\n#cloud-config\ncloud_final_modules:\n- [scripts-user, always]\n--//\nContent-Type: text/x-shellscript; charset="us-ascii"\nMIME-Version: 1.0\nContent-Transfer-Encoding: 7bit\nContent-Disposition: attachment; filename="userdata.txt"\n#!/bin/bash\nmount -o remount,rw,nosuid,nodev,noexec,relatime,hidepid=2 /proc\nyum install -y https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/linux_amd64/amazon-ssm-agent.rpm\nyum install -y haproxy\necho "listen database\n  bind 0.0.0.0:',
            {
              'Fn::GetAtt': ['TestAurora252434E9', 'Endpoint.Port'],
            },
            '\n  timeout connect 10s\n  timeout client 2m\n  timeout server 7m\n  mode tcp\n  server service ',
            {
              'Fn::GetAtt': ['TestAurora252434E9', 'Endpoint.Address'],
            },
            ':',
            {
              'Fn::GetAtt': ['TestAurora252434E9', 'Endpoint.Port'],
            },
            '\n" > /etc/haproxy/haproxy.cfg\nservice haproxy restart\n--//',
          ],
        ],
      },
    },
    Tags: [
      {
        Key: 'Name',
        Value: 'MyBastion',
      },
    ],
  });
});
Example #26
Source File: index.ts    From cdk-ssm-document with Apache License 2.0 5 votes vote down vote up
/**
   * Defines a new SSM document
   */
  constructor(scope: Construct, id: string, props: DocumentProps) {
    super(scope, id);

    this.tags = new TagManager(TagType.MAP, 'Custom::SSM-Document');
    this.tags.setTag(createdByTag, ID);

    const stack = Stack.of(this).stackName;
    this.lambda = this.ensureLambda();
    const name = this.fixDocumentName(props.name);

    if (name.length < 3 || name.length > 128) {
      Annotations.of(this).addError(
        `SSM Document name ${name} is invalid. The name must be between 3 and 128 characters.`
      );
      return;
    }

    let content = props.content;

    if (typeof content === 'string') {
      content = yaml.safeLoad(content) as DocumentContent;
    }

    const document = new CustomResource(this, `SSM-Document-${name}`, {
      serviceToken: this.lambda.functionArn,
      resourceType: resourceType,
      properties: {
        updateDefaultVersion: props.updateDefaultVersion || true,
        name: name,
        content: content,
        documentType: props.documentType || 'Command',
        targetType: props.targetType || '/',
        attachments: props.attachments,
        versionName: props.versionName,
        StackName: stack,
        tags: Lazy.any({
          produce: () => this.tags.renderTags(),
        }),
      },
      pascalCaseProperties: true,
    });

    this.name = document.getAttString('Name');
  }
Example #27
Source File: rds.test.ts    From bastion-host-forward with Apache License 2.0 5 votes vote down vote up
test('Bastion Host created for normal username/password access', () => {
  const app = new App();
  const stack = new Stack(app, 'TestStack');
  const testVpc = new Vpc(stack, 'TestVpc');
  const testRds = new DatabaseInstance(stack, 'TestRDS', {
    engine: DatabaseInstanceEngine.POSTGRES,
    instanceType: InstanceType.of(InstanceClass.T3, InstanceSize.MICRO),
    vpc: testVpc,
  });

  // WHEN
  new BastionHostRDSForward(stack, 'MyTestConstruct', {
    vpc: testVpc,
    name: 'MyBastion',
    rdsInstance: testRds,
    clientTimeout: 2,
    serverTimeout: 4,
  });

  const template = Template.fromStack(stack);

  // THEN
  template.hasResourceProperties('AWS::EC2::Instance', {
    UserData: {
      'Fn::Base64': {
        'Fn::Join': [
          '',
          [
            'Content-Type: multipart/mixed; boundary="//"\nMIME-Version: 1.0\n--//\nContent-Type: text/cloud-config; charset="us-ascii"\nMIME-Version: 1.0\nContent-Transfer-Encoding: 7bit\nContent-Disposition: attachment; filename="cloud-config.txt"\n#cloud-config\ncloud_final_modules:\n- [scripts-user, always]\n--//\nContent-Type: text/x-shellscript; charset="us-ascii"\nMIME-Version: 1.0\nContent-Transfer-Encoding: 7bit\nContent-Disposition: attachment; filename="userdata.txt"\n#!/bin/bash\nmount -o remount,rw,nosuid,nodev,noexec,relatime,hidepid=2 /proc\nyum install -y https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/linux_amd64/amazon-ssm-agent.rpm\nyum install -y haproxy\necho "listen database\n  bind 0.0.0.0:',
            {
              'Fn::GetAtt': ['TestRDSDF309CB7', 'Endpoint.Port'],
            },
            '\n  timeout connect 10s\n  timeout client 2m\n  timeout server 4m\n  mode tcp\n  server service ',
            {
              'Fn::GetAtt': ['TestRDSDF309CB7', 'Endpoint.Address'],
            },
            ':',
            {
              'Fn::GetAtt': ['TestRDSDF309CB7', 'Endpoint.Port'],
            },
            '\n" > /etc/haproxy/haproxy.cfg\nservice haproxy restart\n--//',
          ],
        ],
      },
    },
    Tags: [
      {
        Key: 'Name',
        Value: 'MyBastion',
      },
    ],
  });
});
Example #28
Source File: global-rds.test.ts    From cdk-aurora-globaldatabase with Apache License 2.0 5 votes vote down vote up
test('test error Region input addRegional Function', () => {
  const app = new App();
  const stack = new Stack(app, 'testing-stack', { env: envErrorRegion });
  expect(()=>{
    new GlobalAuroraRDSSlaveInfra(stack, 'GlobalAuroraRDS');
    assertions.Template.fromStack(stack).findResources('AWS::EC2::VPC');
  }).toThrowError(/This region sa-east-1 not Support Global RDS !!!/);
});
Example #29
Source File: dns-validated-domain-identity.ts    From aws-cdk-ses-domain-identity with MIT License 5 votes vote down vote up
public constructor(scope: Construct, id: string, props: DnsValidatedDomainIdentityProps) {
    super(scope, id);

    const stack = Stack.of(this);

    const region = props.region ?? stack.region;
    const accountId = stack.account;

    this.domainName = props.domainName;
    this.dkim = props.dkim ?? false;
    this.identityArn = `arn:aws:ses:${region}:${accountId}:identity/${this.domainName}`;
    this.normalizedZoneName = props.hostedZone.zoneName;
    // Remove trailing `.` from zone name
    if (this.normalizedZoneName.endsWith(".")) {
      this.normalizedZoneName = this.normalizedZoneName.substring(0, this.normalizedZoneName.length - 1);
    }

    // Remove any `/hostedzone/` prefix from the Hosted Zone ID
    this.hostedZoneId = props.hostedZone.hostedZoneId.replace(/^\/hostedzone\//, "");

    const requestorFunction = new lambda.Function(this, "DomainIdentityRequestorFunction", {
      code: lambda.Code.fromAsset(path.resolve(__dirname, "..", "lambda-packages", "dns-validated-domain-identity-handler", "dist")),
      handler: "index.identityRequestHandler",
      runtime: lambda.Runtime.NODEJS_14_X,
      memorySize: 128,
      timeout: Duration.minutes(15),
      role: props.customResourceRole,
    });
    requestorFunction.addToRolePolicy(new iam.PolicyStatement({
      actions: [
        "ses:GetIdentityVerificationAttributes",
        "ses:GetIdentityDkimAttributes",
        "ses:SetIdentityDkimEnabled",
        "ses:VerifyDomainIdentity",
        "ses:VerifyDomainDkim",
        "ses:ListIdentities",
        "ses:DeleteIdentity",
      ],
      resources: ["*"],
    }));
    requestorFunction.addToRolePolicy(new iam.PolicyStatement({
      actions: ["route53:GetChange"],
      resources: ["*"],
    }));
    requestorFunction.addToRolePolicy(new iam.PolicyStatement({
      actions: [
          "route53:changeResourceRecordSets",
          "route53:ListResourceRecordSets",
      ],
      resources: [`arn:${Stack.of(requestorFunction).partition}:route53:::hostedzone/${this.hostedZoneId}`],
    }));

    const identity = new CustomResource(this, "IdentityRequestorResource", {
      serviceToken: requestorFunction.functionArn,
      properties: {
        DomainName: this.domainName,
        HostedZoneId: this.hostedZoneId,
        Region: region,
        DKIM: props.dkim,
      },
    });

    this.node.addValidation({
      validate: (): string[] => {
        const errors: string[] = [];
        // Ensure the zone name is a parent zone of the certificate domain name
        if (!Token.isUnresolved(this.normalizedZoneName) &&
          this.domainName !== this.normalizedZoneName &&
          !this.domainName.endsWith("." + this.normalizedZoneName)) {
          errors.push(`DNS zone ${this.normalizedZoneName} is not authoritative for SES identity domain name ${this.domainName}`);
        }

        return errors;
      },
    });
  }