# packages

pkgId: df7e8786841e8a567d9f27ca0c491236789e121f1d7f72523625e23f0ab4d75d
name: python-aws-cdk-lib
arch: src
version: 2.161.1
epoch: 0
release: 1
summary: Version 2 of the AWS Cloud Development Kit library
url: https://github.com/aws/aws-cdk
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk-lib-2.161.1-1.src.rpm
checksum_type: sha256
description:
  The AWS CDK construct library provides APIs to define your CDK application and add
  CDK constructs to the application.





  When upgrading from CDK 1.x, remove all dependencies to individual CDK packages
  from your dependencies file and follow the rest of the sections.



  To use this package, you need to declare this package and the `constructs` package as
  dependencies.

  According to the kind of project you are developing:

  For projects that are CDK libraries in NPM, declare them both under the `devDependencies` **and** `peerDependencies` sections.
  To make sure your library is compatible with the widest range of CDK versions: pick the minimum `aws-cdk-lib` version
  that your library requires; declare a range dependency with a caret on that version in peerDependencies, and declare a
  point version dependency on that version in devDependencies.

  For example, let's say the minimum version your library needs is `2.38.0`. Your `package.json` should look like this:

  ```javascript
  {
    "peerDependencies": {
      "aws-cdk-lib": "^2.38.0",
      "constructs": "^10.0.0"
    },
    "devDependencies": {
      /* Install the oldest version for testing so we don't accidentally use features from a newer version than we declare */
      "aws-cdk-lib": "2.38.0"
    }
  }
  ```

  For CDK apps, declare them under the `dependencies` section. Use a caret so you always get the latest version:

  ```json
  {
    "dependencies": {
      "aws-cdk-lib": "^2.38.0",
      "constructs": "^10.0.0"
    }
  }
  ```





  You can use a classic import to get access to each service namespaces:

  ```python
  from aws_cdk import Stack, App, aws_s3 as s3

  app = App()
  stack = Stack(app, "TestStack")

  s3.Bucket(stack, "TestBucket")
  ```



  Alternatively, you can use "barrel" imports:

  ```python
  from aws_cdk import App, Stack
  from aws_cdk.aws_s3 import Bucket

  app = App()
  stack = Stack(app, "TestStack")

  Bucket(stack, "TestBucket")
  ```

  <!--BEGIN CORE DOCUMENTATION-->



  A `Stack` is the smallest physical unit of deployment, and maps directly onto
  a CloudFormation Stack. You define a Stack by defining a subclass of `Stack`
  -- let's call it `MyStack` -- and instantiating the constructs that make up
  your application in `MyStack`'s constructor. You then instantiate this stack
  one or more times to define different instances of your application. For example,
  you can instantiate it once using few and cheap EC2 instances for testing,
  and once again using more and bigger EC2 instances for production.

  When your application grows, you may decide that it makes more sense to split it
  out across multiple `Stack` classes. This can happen for a number of reasons:

  * You could be starting to reach the maximum number of resources allowed in a single
    stack (this is currently 500).
  * You could decide you want to separate out stateful resources and stateless resources
    into separate stacks, so that it becomes easy to tear down and recreate the stacks
    that don't have stateful resources.
  * There could be a single stack with resources (like a VPC) that are shared
    between multiple instances of other stacks containing your applications.

  As soon as your conceptual application starts to encompass multiple stacks,
  it is convenient to wrap them in another construct that represents your
  logical application. You can then treat that new unit the same way you used
  to be able to treat a single stack: by instantiating it multiple times
  for different instances of your application.

  You can define a custom subclass of `Stage`, holding one or more
  `Stack`s, to represent a single logical instance of your application.

  As a final note: `Stack`s are not a unit of reuse. They describe physical
  deployment layouts, and as such are best left to application builders to
  organize their deployments with. If you want to vend a reusable construct,
  define it as a subclasses of `Construct`: the consumers of your construct
  will decide where to place it in their own stacks.



  Each Stack has a *synthesizer*, an object that determines how and where
  the Stack should be synthesized and deployed. The synthesizer controls
  aspects like:

  * How does the stack reference assets? (Either through CloudFormation
    parameters the CLI supplies, or because the Stack knows a predefined
    location where assets will be uploaded).
  * What roles are used to deploy the stack? These can be bootstrapped
    roles, roles created in some other way, or just the CLI's current
    credentials.

  The following synthesizers are available:

  * `DefaultStackSynthesizer`: recommended. Uses predefined asset locations and
    roles created by the modern bootstrap template. Access control is done by
    controlling who can assume the deploy role. This is the default stack
    synthesizer in CDKv2.
  * `LegacyStackSynthesizer`: Uses CloudFormation parameters to communicate
    asset locations, and the CLI's current permissions to deploy stacks. This
    is the default stack synthesizer in CDKv1.
  * `CliCredentialsStackSynthesizer`: Uses predefined asset locations, and the
    CLI's current permissions.

  Each of these synthesizers takes configuration arguments. To configure
  a stack with a synthesizer, pass it as one of its properties:

  ```python
  MyStack(app, "MyStack",
      synthesizer=DefaultStackSynthesizer(
          file_assets_bucket_name="my-orgs-asset-bucket"
      )
  )
  ```

  For more information on bootstrapping accounts and customizing synthesis,
  see [Bootstrapping in the CDK Developer Guide](https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html).



  [Nested stacks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html) are stacks created as part of other stacks. You create a nested stack within another stack by using the `NestedStack` construct.

  As your infrastructure grows, common patterns can emerge in which you declare the same components in multiple templates. You can separate out these common components and create dedicated templates for them. Then use the resource in your template to reference other templates, creating nested stacks.

  For example, assume that you have a load balancer configuration that you use for most of your stacks. Instead of copying and pasting the same configurations into your templates, you can create a dedicated template for the load balancer. Then, you just use the resource to reference that template from within other templates.

  The following example will define a single top-level stack that contains two nested stacks: each one with a single Amazon S3 bucket:

  ```python
  class MyNestedStack(cfn.NestedStack):
      def __init__(self, scope, id, *, parameters=None, timeout=None, notifications=None):
          super().__init__(scope, id, parameters=parameters, timeout=timeout, notifications=notifications)

          s3.Bucket(self, "NestedBucket")

  class MyParentStack(Stack):
      def __init__(self, scope, id, *, description=None, env=None, stackName=None, tags=None, notificationArns=None, synthesizer=None, terminationProtection=None, analyticsReporting=None, crossRegionReferences=None, permissionsBoundary=None, suppressTemplateIndentation=None):
          super().__init__(scope, id, description=description, env=env, stackName=stackName, tags=tags, notificationArns=notificationArns, synthesizer=synthesizer, terminationProtection=terminationProtection, analyticsReporting=analyticsReporting, crossRegionReferences=crossRegionReferences, permissionsBoundary=permissionsBoundary, suppressTemplateIndentation=suppressTemplateIndentation)

          MyNestedStack(self, "Nested1")
          MyNestedStack(self, "Nested2")
  ```

  Resources references across nested/parent boundaries (even with multiple levels of nesting) will be wired by the AWS CDK
  through CloudFormation parameters and outputs. When a resource from a parent stack is referenced by a nested stack,
  a CloudFormation parameter will automatically be added to the nested stack and assigned from the parent; when a resource
  from a nested stack is referenced by a parent stack, a CloudFormation output will be automatically be added to the
  nested stack and referenced using `Fn::GetAtt "Outputs.Xxx"` from the parent.

  Nested stacks also support the use of Docker image and file assets.



  You can access resources in a different stack, as long as they are in the
  same account and AWS Region (see [next section](#accessing-resources-in-a-different-stack-and-region) for an exception).
  The following example defines the stack `stack1`,
  which defines an Amazon S3 bucket. Then it defines a second stack, `stack2`,
  which takes the bucket from stack1 as a constructor property.

  ```python
  prod = {"account": "123456789012", "region": "us-east-1"}

  stack1 = StackThatProvidesABucket(app, "Stack1", env=prod)


  stack2 = StackThatExpectsABucket(app, "Stack2",
      bucket=stack1.bucket,
      env=prod
  )
  ```

  If the AWS CDK determines that the resource is in the same account and
  Region, but in a different stack, it automatically synthesizes AWS
  CloudFormation
  [Exports](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-exports.html)
  in the producing stack and an
  [Fn::ImportValue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html)
  in the consuming stack to transfer that information from one stack to the
  other.



  > **This feature is currently experimental**

  You can enable the Stack property `crossRegionReferences`
  in order to access resources in a different stack *and* region. With this feature flag
  enabled it is possible to do something like creating a CloudFront distribution in `us-east-2` and
  an ACM certificate in `us-east-1`.

  ```python
  stack1 = Stack(app, "Stack1",
      env=Environment(
          region="us-east-1"
      ),
      cross_region_references=True
  )
  cert = acm.Certificate(stack1, "Cert",
      domain_name="*.example.com",
      validation=acm.CertificateValidation.from_dns(route53.PublicHostedZone.from_hosted_zone_id(stack1, "Zone", "Z0329774B51CGXTDQV3X"))
  )

  stack2 = Stack(app, "Stack2",
      env=Environment(
          region="us-east-2"
      ),
      cross_region_references=True
  )
  cloudfront.Distribution(stack2, "Distribution",
      default_behavior=cloudfront.BehaviorOptions(
          origin=origins.HttpOrigin("example.com")
      ),
      domain_names=["dev.example.com"],
      certificate=cert
  )
  ```

  When the AWS CDK determines that the resource is in a different stack *and* is in a different
  region, it will "export" the value by creating a custom resource in the producing stack which
  creates SSM Parameters in the consuming region for each exported value. The parameters will be
  created with the name '/cdk/exports/${consumingStackName}/${export-name}'.
  In order to "import" the exports into the consuming stack a [SSM Dynamic reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#dynamic-references-ssm)
  is used to reference the SSM parameter which was created.

  In order to mimic strong references, a Custom Resource is also created in the consuming
  stack which marks the SSM parameters as being "imported". When a parameter has been successfully
  imported, the producing stack cannot update the value.

  > [!NOTE]
  > As a consequence of this feature being built on a Custom Resource, we are restricted to a
  > CloudFormation response body size limitation of [4096 bytes](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/crpg-ref-responses.html).
  > To prevent deployment errors related to the Custom Resource Provider response body being too
  > large, we recommend limiting the use of nested stacks and minimizing the length of stack names.
  > Doing this will prevent SSM parameter names from becoming too long which will reduce the size of the
  > response body.

  See the [adr](https://github.com/aws/aws-cdk/blob/main/packages/aws-cdk-lib/core/adr/cross-region-stack-references.md)
  for more details on this feature.



  The automatic references created by CDK when you use resources across stacks
  are convenient, but may block your deployments if you want to remove the
  resources that are referenced in this way. You will see an error like:

  ```text
  Export Stack1:ExportsOutputFnGetAtt-****** cannot be deleted as it is in use by Stack1
  ```

  Let's say there is a Bucket in the `stack1`, and the `stack2` references its
  `bucket.bucketName`. You now want to remove the bucket and run into the error above.

  It's not safe to remove `stack1.bucket` while `stack2` is still using it, so
  unblocking yourself from this is a two-step process. This is how it works:

  DEPLOYMENT 1: break the relationship

  * Make sure `stack2` no longer references `bucket.bucketName` (maybe the consumer
    stack now uses its own bucket, or it writes to an AWS DynamoDB table, or maybe you just
    remove the Lambda Function altogether).
  * In the `stack1` class, call `this.exportValue(this.bucket.bucketName)`. This
    will make sure the CloudFormation Export continues to exist while the relationship
    between the two stacks is being broken.
  * Deploy (this will effectively only change the `stack2`, but it's safe to deploy both).

  DEPLOYMENT 2: remove the resource

  * You are now free to remove the `bucket` resource from `stack1`.
  * Don't forget to remove the `exportValue()` call as well.
  * Deploy again (this time only the `stack1` will be changed -- the bucket will be deleted).



  To make specifications of time intervals unambiguous, a single class called
  `Duration` is used throughout the AWS Construct Library by all constructs
  that that take a time interval as a parameter (be it for a timeout, a
  rate, or something else).

  An instance of Duration is constructed by using one of the static factory
  methods on it:

  ```python
  Duration.seconds(300) # 5 minutes
  Duration.minutes(5) # 5 minutes
  Duration.hours(1) # 1 hour
  Duration.days(7) # 7 days
  Duration.parse("PT5M")
  ```

  Durations can be added or subtracted together:

  ```python
  Duration.minutes(1).plus(Duration.seconds(60)) # 2 minutes
  Duration.minutes(5).minus(Duration.seconds(10))
  ```



  To make specification of digital storage quantities unambiguous, a class called
  `Size` is available.

  An instance of `Size` is initialized through one of its static factory methods:

  ```python
  Size.kibibytes(200) # 200 KiB
  Size.mebibytes(5) # 5 MiB
  Size.gibibytes(40) # 40 GiB
  Size.tebibytes(200) # 200 TiB
  Size.pebibytes(3)
  ```

  Instances of `Size` created with one of the units can be converted into others.
  By default, conversion to a higher unit will fail if the conversion does not produce
  a whole number. This can be overridden by unsetting `integral` property.

  ```python
  Size.mebibytes(2).to_kibibytes() # yields 2048
  Size.kibibytes(2050).to_mebibytes(rounding=SizeRoundingBehavior.FLOOR)
  ```



  To help avoid accidental storage of secrets as plain text, we use the `SecretValue` type to
  represent secrets. Any construct that takes a value that should be a secret (such as
  a password or an access key) will take a parameter of type `SecretValue`.

  The best practice is to store secrets in AWS Secrets Manager and reference them using `SecretValue.secretsManager`:

  ```python
  secret = SecretValue.secrets_manager("secretId",
      json_field="password",  # optional: key of a JSON field to retrieve (defaults to all content),
      version_id="id",  # optional: id of the version (default AWSCURRENT)
      version_stage="stage"
  )
  ```

  Using AWS Secrets Manager is the recommended way to reference secrets in a CDK app.
  `SecretValue` also supports the following secret sources:

  * `SecretValue.unsafePlainText(secret)`: stores the secret as plain text in your app and the resulting template (not recommended).
  * `SecretValue.secretsManager(secret)`: refers to a secret stored in Secrets Manager
  * `SecretValue.ssmSecure(param, version)`: refers to a secret stored as a SecureString in the SSM
    Parameter Store. If you don't specify the exact version, AWS CloudFormation uses the latest
    version of the parameter.
  * `SecretValue.cfnParameter(param)`: refers to a secret passed through a CloudFormation parameter (must have `NoEcho: true`).
  * `SecretValue.cfnDynamicReference(dynref)`: refers to a secret described by a CloudFormation dynamic reference (used by `ssmSecure` and `secretsManager`).
  * `SecretValue.resourceAttribute(attr)`: refers to a secret returned from a CloudFormation resource creation.

  `SecretValue`s should only be passed to constructs that accept properties of type
  `SecretValue`. These constructs are written to ensure your secrets will not be
  exposed where they shouldn't be. If you try to use a `SecretValue` in a
  different location, an error about unsafe secret usage will be thrown at
  synthesis time.

  If you rotate the secret's value in Secrets Manager, you must also change at
  least one property on the resource where you are using the secret, to force
  CloudFormation to re-read the secret.

  `SecretValue.ssmSecure()` is only supported for a limited set of resources.
  [Click here for a list of supported resources and properties](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#template-parameters-dynamic-patterns-resources).



  Sometimes you will need to put together or pick apart Amazon Resource Names
  (ARNs). The functions `stack.formatArn()` and `stack.splitArn()` exist for
  this purpose.

  `formatArn()` can be used to build an ARN from components. It will automatically
  use the region and account of the stack you're calling it on:

  ```python




  stack.format_arn(
      service="lambda",
      resource="function",
      arn_format=ArnFormat.COLON_RESOURCE_NAME,
      resource_name="MyFunction"
  )
  ```

  `splitArn()` can be used to get a single component from an ARN. `splitArn()`
  will correctly deal with both literal ARNs and deploy-time values (tokens),
  but in case of a deploy-time value be aware that the result will be another
  deploy-time value which cannot be inspected in the CDK application.

  ```python




  arn_components = stack.split_arn(arn, ArnFormat.COLON_RESOURCE_NAME)
  function_name = arn_components.resource_name
  ```

  Note that the format of the resource separator depends on the service and
  may be any of the values supported by `ArnFormat`. When dealing with these
  functions, it is important to know the format of the ARN you are dealing with.

  For an exhaustive list of ARN formats used in AWS, see [AWS ARNs and
  Namespaces](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html)
  in the AWS General Reference.





  Sometimes AWS resources depend on other resources, and the creation of one
  resource must be completed before the next one can be started.

  In general, CloudFormation will correctly infer the dependency relationship
  between resources based on the property values that are used. In the cases where
  it doesn't, the AWS Construct Library will add the dependency relationship for
  you.

  If you need to add an ordering dependency that is not automatically inferred,
  you do so by adding a dependency relationship using
  `constructA.node.addDependency(constructB)`. This will add a dependency
  relationship between all resources in the scope of `constructA` and all
  resources in the scope of `constructB`.

  If you want a single object to represent a set of constructs that are not
  necessarily in the same scope, you can use a `DependencyGroup`. The
  following creates a single object that represents a dependency on two
  constructs, `constructB` and `constructC`:

  ```python

  b_and_c = DependencyGroup()
  b_and_c.add(construct_b)
  b_and_c.add(construct_c)


  construct_a.node.add_dependency(b_and_c)
  ```



  Two different stack instances can have a dependency on one another. This
  happens when an resource from one stack is referenced in another stack. In
  that case, CDK records the cross-stack referencing of resources,
  automatically produces the right CloudFormation primitives, and adds a
  dependency between the two stacks. You can also manually add a dependency
  between two stacks by using the `stackA.addDependency(stackB)` method.

  A stack dependency has the following implications:

  * Cyclic dependencies are not allowed, so if `stackA` is using resources from
    `stackB`, the reverse is not possible anymore.
  * Stacks with dependencies between them are treated specially by the CDK
    toolkit:

    * If `stackA` depends on `stackB`, running `cdk deploy stackA` will also
      automatically deploy `stackB`.
    * `stackB`'s deployment will be performed *before* `stackA`'s deployment.



  To make declaring dependencies between `CfnResource` objects easier, you can declare dependencies from one `CfnResource` object on another by using the `cfnResource1.addDependency(cfnResource2)` method. This method will work for resources both within the same stack and across stacks as it detects the relative location of the two resources and adds the dependency either to the resource or between the relevant stacks, as appropriate. If more complex logic is in needed, you can similarly remove, replace, or view dependencies between `CfnResource` objects with the `CfnResource` `removeDependency`, `replaceDependency`, and `obtainDependencies` methods, respectively.



  Custom Resources are CloudFormation resources that are implemented by arbitrary
  user code. They can do arbitrary lookups or modifications during a
  CloudFormation deployment.

  Custom resources are backed by *custom resource providers*. Commonly, these are
  Lambda Functions that are deployed in the same deployment as the one that
  defines the custom resource itself, but they can also be backed by Lambda
  Functions deployed previously, or code responding to SNS Topic events running on
  EC2 instances in a completely different account. For more information on custom
  resource providers, see the next section.

  Once you have a provider, each definition of a `CustomResource` construct
  represents one invocation. A single provider can be used for the implementation
  of arbitrarily many custom resource definitions. A single definition looks like
  this:

  ```python
  CustomResource(self, "MyMagicalResource",
      resource_type="Custom::MyCustomResource",  # must start with 'Custom::'

      
      properties={
          "Property1": "foo",
          "Property2": "bar"
      },

      
      
      
      service_token="ARN"
  )
  ```



  Custom resources are backed by a **custom resource provider** which can be
  implemented in one of the following ways. The following table compares the
  various provider types (ordered from low-level to high-level):

  | Provider                                                             | Compute Type | Error Handling | Submit to CloudFormation |   Max Timeout   | Language | Footprint |
  | -------------------------------------------------------------------- | :----------: | :------------: | :----------------------: | :-------------: | :------: | :-------: |
  | [sns.Topic](#amazon-sns-topic)                                       | Self-managed |     Manual     |          Manual          |    Unlimited    |   Any    |  Depends  |
  | [lambda.Function](#aws-lambda-function)                              |  AWS Lambda  |     Manual     |          Manual          |      15min      |   Any    |   Small   |
  | [core.CustomResourceProvider](#the-corecustomresourceprovider-class) |  AWS Lambda  |      Auto      |           Auto           |      15min      | Node.js  |   Small   |
  | [custom-resources.Provider](#the-custom-resource-provider-framework) |  AWS Lambda  |      Auto      |           Auto           | Unlimited Async |   Any    |   Large   |

  Legend:

  * **Compute type**: which type of compute can be used to execute the handler.
  * **Error Handling**: whether errors thrown by handler code are automatically
    trapped and a FAILED response is submitted to CloudFormation. If this is
    "Manual", developers must take care of trapping errors. Otherwise, events
    could cause stacks to hang.
  * **Submit to CloudFormation**: whether the framework takes care of submitting
    SUCCESS/FAILED responses to CloudFormation through the event's response URL.
  * **Max Timeout**: maximum allows/possible timeout.
  * **Language**: which programming languages can be used to implement handlers.
  * **Footprint**: how many resources are used by the provider framework itself.

  **A NOTE ABOUT SINGLETONS**

  When defining resources for a custom resource provider, you will likely want to
  define them as a *stack singleton* so that only a single instance of the
  provider is created in your stack and which is used by all custom resources of
  that type.

  Here is a basic pattern for defining stack singletons in the CDK. The following
  examples ensures that only a single SNS topic is defined:

  ```python
  def get_or_create(self, scope):
      stack = Stack.of(scope)
      uniqueid = "GloballyUniqueIdForSingleton" # For example, a UUID from `uuidgen`
      existing = stack.node.try_find_child(uniqueid)
      if existing:
          return existing
      return sns.Topic(stack, uniqueid)
  ```



  Every time a resource event occurs (CREATE/UPDATE/DELETE), an SNS notification
  is sent to the SNS topic. Users must process these notifications (e.g. through a
  fleet of worker hosts) and submit success/failure responses to the
  CloudFormation service.

  > You only need to use this type of provider if your custom resource cannot run on AWS Lambda, for reasons other than the 15
  > minute timeout. If you are considering using this type of provider because you want to write a custom resource provider that may need
  > to wait for more than 15 minutes for the API calls to stabilize, have a look at the [`custom-resources`](#the-custom-resource-provider-framework) module first.
  >
  > Refer to the [CloudFormation Custom Resource documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html) for information on the contract your custom resource needs to adhere to.

  Set `serviceToken` to `topic.topicArn`  in order to use this provider:

  ```python
  topic = sns.Topic(self, "MyProvider")

  CustomResource(self, "MyResource",
      service_token=topic.topic_arn
  )
  ```



  An AWS lambda function is called *directly* by CloudFormation for all resource
  events. The handler must take care of explicitly submitting a success/failure
  response to the CloudFormation service and handle various error cases.

  > **We do not recommend you use this provider type.** The CDK has wrappers around Lambda Functions that make them easier to work with.
  >
  > If you do want to use this provider, refer to the [CloudFormation Custom Resource documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html) for information on the contract your custom resource needs to adhere to.

  Set `serviceToken` to `lambda.functionArn` to use this provider:

  ```python
  fn = lambda_.SingletonFunction(self, "MyProvider", function_props)

  CustomResource(self, "MyResource",
      service_token=fn.function_arn
  )
  ```



  The class [`@aws-cdk/core.CustomResourceProvider`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CustomResourceProvider.html) offers a basic low-level
  framework designed to implement simple and slim custom resource providers. It
  currently only supports Node.js-based user handlers, represents permissions as raw
  JSON blobs instead of `iam.PolicyStatement` objects, and it does not have
  support for asynchronous waiting (handler cannot exceed the 15min lambda
  timeout). The `CustomResourceProviderRuntime` supports runtime `nodejs12.x`,
  `nodejs14.x`, `nodejs16.x`, `nodejs18.x`.

  > **As an application builder, we do not recommend you use this provider type.** This provider exists purely for custom resources that are part of the AWS Construct Library.
  >
  > The [`custom-resources`](#the-custom-resource-provider-framework) provider is more convenient to work with and more fully-featured.

  The provider has a built-in singleton method which uses the resource type as a
  stack-unique identifier and returns the service token:

  ```python
  service_token = CustomResourceProvider.get_or_create(self, "Custom::MyCustomResourceType",
      code_directory=f"{__dirname}/my-handler",
      runtime=CustomResourceProviderRuntime.NODEJS_18_X,
      description="Lambda function created by the custom resource provider"
  )

  CustomResource(self, "MyResource",
      resource_type="Custom::MyCustomResourceType",
      service_token=service_token
  )
  ```

  The directory (`my-handler` in the above example) must include an `index.js` file. It cannot import
  external dependencies or files outside this directory. It must export an async
  function named `handler`. This function accepts the CloudFormation resource
  event object and returns an object with the following structure:

  ```js
  exports.handler = async function(event) {
    const id = event.PhysicalResourceId; // only for "Update" and "Delete"
    const props = event.ResourceProperties;
    const oldProps = event.OldResourceProperties; // only for "Update"s

    switch (event.RequestType) {
      case "Create":
        // ...

      case "Update":
        // ...

        // if an error is thrown, a FAILED response will be submitted to CFN
        throw new Error('Failed!');

      case "Delete":
        // ...
    }

    return {
      // (optional) the value resolved from `resource.ref`
      // defaults to "event.PhysicalResourceId" or "event.RequestId"
      PhysicalResourceId: "REF",

      // (optional) calling `resource.getAtt("Att1")` on the custom resource in the CDK app
      // will return the value "BAR".
      Data: {
        Att1: "BAR",
        Att2: "BAZ"
      },

      // (optional) user-visible message
      Reason: "User-visible message",

      // (optional) hides values from the console
      NoEcho: true
    };
  }
  ```

  Here is an complete example of a custom resource that summarizes two numbers:

  `sum-handler/index.js`:

  ```js
  exports.handler = async (e) => {
    return {
      Data: {
        Result: e.ResourceProperties.lhs + e.ResourceProperties.rhs,
      },
    };
  };
  ```

  `sum.ts`:

  ```python
  from constructs import Construct
  from aws_cdk import CustomResource, CustomResourceProvider, CustomResourceProviderRuntime, Token

  class Sum(Construct):

      def __init__(self, scope, id, *, lhs, rhs):
          super().__init__(scope, id)

          resource_type = "Custom::Sum"
          service_token = CustomResourceProvider.get_or_create(self, resource_type,
              code_directory=f"{__dirname}/sum-handler",
              runtime=CustomResourceProviderRuntime.NODEJS_18_X
          )

          resource = CustomResource(self, "Resource",
              resource_type=resource_type,
              service_token=service_token,
              properties={
                  "lhs": lhs,
                  "rhs": rhs
              }
          )

          self.result = Token.as_number(resource.get_att("Result"))
  ```

  Usage will look like this:

  ```python
  sum = Sum(self, "MySum", lhs=40, rhs=2)
  CfnOutput(self, "Result", value=Token.as_string(sum.result))
  ```

  To access the ARN of the provider's AWS Lambda function role, use the `getOrCreateProvider()`
  built-in singleton method:

  ```python
  provider = CustomResourceProvider.get_or_create_provider(self, "Custom::MyCustomResourceType",
      code_directory=f"{__dirname}/my-handler",
      runtime=CustomResourceProviderRuntime.NODEJS_18_X
  )

  role_arn = provider.role_arn
  ```

  This role ARN can then be used in resource-based IAM policies.

  To add IAM policy statements to this role, use `addToRolePolicy()`:

  ```python
  provider = CustomResourceProvider.get_or_create_provider(self, "Custom::MyCustomResourceType",
      code_directory=f"{__dirname}/my-handler",
      runtime=CustomResourceProviderRuntime.NODEJS_18_X
  )
  provider.add_to_role_policy({
      "Effect": "Allow",
      "Action": "s3:GetObject",
      "Resource": "*"
  })
  ```

  Note that `addToRolePolicy()` uses direct IAM JSON policy blobs, *not* a
  `iam.PolicyStatement` object like you will see in the rest of the CDK.



  The [`@aws-cdk/custom-resources`](https://docs.aws.amazon.com/cdk/api/latest/docs/custom-resources-readme.html) module includes an advanced framework for
  implementing custom resource providers.

  Handlers are implemented as AWS Lambda functions, which means that they can be
  implemented in any Lambda-supported runtime. Furthermore, this provider has an
  asynchronous mode, which means that users can provide an `isComplete` lambda
  function which is called periodically until the operation is complete. This
  allows implementing providers that can take up to two hours to stabilize.

  Set `serviceToken` to `provider.serviceToken` to use this type of provider:

  ```python
  provider = customresources.Provider(self, "MyProvider",
      on_event_handler=on_event_handler,
      is_complete_handler=is_complete_handler
  )

  CustomResource(self, "MyResource",
      service_token=provider.service_token
  )
  ```

  See the [documentation](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.custom_resources-readme.html) for more details.



  A CDK stack synthesizes to an AWS CloudFormation Template. This section
  explains how this module allows users to access low-level CloudFormation
  features when needed.



  CloudFormation [stack outputs](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html) and exports are created using
  the `CfnOutput` class:

  ```python
  CfnOutput(self, "OutputName",
      value=my_bucket.bucket_name,
      description="The name of an S3 bucket",  # Optional
      export_name="TheAwesomeBucket"
  )
  ```



  CloudFormation templates support the use of [Parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) to
  customize a template. They enable CloudFormation users to input custom values to
  a template each time a stack is created or updated. While the CDK design
  philosophy favors using build-time parameterization, users may need to use
  CloudFormation in a number of cases (for example, when migrating an existing
  stack to the AWS CDK).

  Template parameters can be added to a stack by using the `CfnParameter` class:

  ```python
  CfnParameter(self, "MyParameter",
      type="Number",
      default=1337
  )
  ```

  The value of parameters can then be obtained using one of the `value` methods.
  As parameters are only resolved at deployment time, the values obtained are
  placeholder tokens for the real value (`Token.isUnresolved()` would return `true`
  for those):

  ```python
  param = CfnParameter(self, "ParameterName")


  param.value_as_string


  param.value_as_number


  param.value_as_list
  ```



  CloudFormation supports a number of [pseudo parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/pseudo-parameter-reference.html),
  which resolve to useful values at deployment time. CloudFormation pseudo
  parameters can be obtained from static members of the `Aws` class.

  It is generally recommended to access pseudo parameters from the scope's `stack`
  instead, which guarantees the values produced are qualifying the designated
  stack, which is essential in cases where resources are shared cross-stack:

  ```python

  stack = Stack.of(self)

  stack.account # Returns the AWS::AccountId for this stack (or the literal value if known)
  stack.region # Returns the AWS::Region for this stack (or the literal value if known)
  stack.partition
  ```



  CloudFormation resources can also specify [resource
  attributes](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-product-attribute-reference.html). The `CfnResource` class allows
  accessing those through the `cfnOptions` property:

  ```python
  raw_bucket = s3.CfnBucket(self, "Bucket")

  raw_bucket_alt = my_bucket.node.default_child


  raw_bucket.cfn_options.condition = CfnCondition(self, "EnableBucket")
  raw_bucket.cfn_options.metadata = {
      "metadata_key": "MetadataValue"
  }
  ```

  Resource dependencies (the `DependsOn` attribute) is modified using the
  `cfnResource.addDependency` method:

  ```python
  resource_a = CfnResource(self, "ResourceA", resource_props)
  resource_b = CfnResource(self, "ResourceB", resource_props)

  resource_b.add_dependency(resource_a)
  ```



  Some resources support a [CreationPolicy](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-creationpolicy.html) to be specified as a CfnOption.

  The creation policy is invoked only when AWS CloudFormation creates the associated resource. Currently, the only AWS CloudFormation resources that support creation policies are `CfnAutoScalingGroup`, `CfnInstance`, `CfnWaitCondition` and `CfnFleet`.

  The `CfnFleet` resource from the `aws-appstream` module supports specifying `startFleet` as
  a property of the creationPolicy on the resource options. Setting it to true will make AWS CloudFormation wait until the fleet is started before continuing with the creation of
  resources that depend on the fleet resource.

  ```python
  fleet = appstream.CfnFleet(self, "Fleet",
      instance_type="stream.standard.small",
      name="Fleet",
      compute_capacity=appstream.CfnFleet.ComputeCapacityProperty(
          desired_instances=1
      ),
      image_name="AppStream-AmazonLinux2-09-21-2022"
  )
  fleet.cfn_options.creation_policy = CfnCreationPolicy(
      start_fleet=True
  )
  ```

  The properties passed to the level 2 constructs `AutoScalingGroup` and `Instance` from the
  `aws-ec2` module abstract what is passed into the `CfnOption` properties `resourceSignal` and
  `autoScalingCreationPolicy`, but when using level 1 constructs you can specify these yourself.

  The CfnWaitCondition resource from the `aws-cloudformation` module suppports the `resourceSignal`.
  The format of the timeout is `PT#H#M#S`. In the example below AWS Cloudformation will wait for
  3 success signals to occur within 15 minutes before the status of the resource will be set to
  `CREATE_COMPLETE`.

  ```python



  resource.cfn_options.creation_policy = CfnCreationPolicy(
      resource_signal=CfnResourceSignal(
          count=3,
          timeout="PR15M"
      )
  )
  ```



  CloudFormation supports [intrinsic functions](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html). These functions
  can be accessed from the `Fn` class, which provides type-safe methods for each
  intrinsic function as well as condition expressions:

  ```python





  Fn.base64("SGVsbG8gQ0RLIQo=")


  environment_parameter = CfnParameter(self, "Environment")
  Fn.condition_and(
      
      Fn.condition_equals("Production", environment_parameter),
      
      Fn.condition_not(Fn.condition_equals("us-east-1", Aws.REGION)))


  Fn.to_json_string(my_object_or_array)


  Fn.len(Fn.split(",", my_array))
  ```

  When working with deploy-time values (those for which `Token.isUnresolved`
  returns `true`), idiomatic conditionals from the programming language cannot be
  used (the value will not be known until deployment time). When conditional logic
  needs to be expressed with un-resolved values, it is necessary to use
  CloudFormation conditions by means of the `CfnCondition` class:

  ```python
  environment_parameter = CfnParameter(self, "Environment")
  is_prod = CfnCondition(self, "IsProduction",
      expression=Fn.condition_equals("Production", environment_parameter)
  )


  stage = Fn.condition_if(is_prod.logical_id, "Beta", "Prod").to_string()



  bucket = s3.Bucket(self, "Bucket")
  cfn_bucket = my_bucket.node.default_child
  cfn_bucket.cfn_options.condition = is_prod
  ```



  CloudFormation [mappings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/mappings-section-structure.html) are created and queried using the
  `CfnMappings` class:

  ```python
  region_table = CfnMapping(self, "RegionTable",
      mapping={
          "us-east-1": {
              "region_name": "US East (N. Virginia)"
          },
          "us-east-2": {
              "region_name": "US East (Ohio)"
          }
      }
  )

  region_table.find_in_map(Aws.REGION, "regionName")
  ```

  This will yield the following template:

  ```yaml
  Mappings:
    RegionTable:
      us-east-1:
        regionName: US East (N. Virginia)
      us-east-2:
        regionName: US East (Ohio)
  ```

  Mappings can also be synthesized "lazily"; lazy mappings will only render a "Mappings"
  section in the synthesized CloudFormation template if some `findInMap` call is unable to
  immediately return a concrete value due to one or both of the keys being unresolved tokens
  (some value only available at deploy-time).

  For example, the following code will not produce anything in the "Mappings" section. The
  call to `findInMap` will be able to resolve the value during synthesis and simply return
  `'US East (Ohio)'`.

  ```python
  region_table = CfnMapping(self, "RegionTable",
      mapping={
          "us-east-1": {
              "region_name": "US East (N. Virginia)"
          },
          "us-east-2": {
              "region_name": "US East (Ohio)"
          }
      },
      lazy=True
  )

  region_table.find_in_map("us-east-2", "regionName")
  ```

  On the other hand, the following code will produce the "Mappings" section shown above,
  since the top-level key is an unresolved token. The call to `findInMap` will return a token that resolves to
  `{ "Fn::FindInMap": [ "RegionTable", { "Ref": "AWS::Region" }, "regionName" ] }`.

  ```python



  region_table.find_in_map(Aws.REGION, "regionName")
  ```

  An optional default value can also be passed to `findInMap`. If either key is not found in the map and the mapping is lazy, `findInMap` will return the default value and not render the mapping.
  If the mapping is not lazy or either key is an unresolved token, the call to `findInMap` will return a token that resolves to
  `{ "Fn::FindInMap": [ "MapName", "TopLevelKey", "SecondLevelKey", { "DefaultValue": "DefaultValue" } ] }`, and the mapping will be rendered.
  Note that the `AWS::LanguageExtentions` transform is added to enable the default value functionality.

  For example, the following code will again not produce anything in the "Mappings" section. The
  call to `findInMap` will be able to resolve the value during synthesis and simply return
  `'Region not found'`.

  ```python
  region_table = CfnMapping(self, "RegionTable",
      mapping={
          "us-east-1": {
              "region_name": "US East (N. Virginia)"
          },
          "us-east-2": {
              "region_name": "US East (Ohio)"
          }
      },
      lazy=True
  )

  region_table.find_in_map("us-west-1", "regionName", "Region not found")
  ```



  CloudFormation supports [dynamically resolving](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html) values
  for SSM parameters (including secure strings) and Secrets Manager. Encoding such
  references is done using the `CfnDynamicReference` class:

  ```python
  CfnDynamicReference(CfnDynamicReferenceService.SECRETS_MANAGER, "secret-id:secret-string:json-key:version-stage:version-id")
  ```



  CloudFormation templates support a number of options, including which Macros or
  [Transforms](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-section-structure.html) to use when deploying the stack. Those can be
  configured using the `stack.templateOptions` property:

  ```python
  stack = Stack(app, "StackName")

  stack.template_options.description = "This will appear in the AWS console"
  stack.template_options.transforms = ["AWS::Serverless-2016-10-31"]
  stack.template_options.metadata = {
      "metadata_key": "MetadataValue"
  }
  ```



  The `CfnResource` class allows emitting arbitrary entries in the
  [Resources](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html) section of the CloudFormation template.

  ```python
  CfnResource(self, "ResourceId",
      type="AWS::S3::Bucket",
      properties={
          "BucketName": "bucket-name"
      }
  )
  ```

  As for any other resource, the logical ID in the CloudFormation template will be
  generated by the AWS CDK, but the type and properties will be copied verbatim in
  the synthesized template.



  When migrating a CloudFormation stack to the AWS CDK, it can be useful to
  include fragments of an existing template verbatim in the synthesized template.
  This can be achieved using the `CfnInclude` class.

  ```python
  CfnInclude(self, "ID",
      template={
          "Resources": {
              "Bucket": {
                  "Type": "AWS::S3::Bucket",
                  "Properties": {
                      "BucketName": "my-shiny-bucket"
                  }
              }
          }
      }
  )
  ```



  You can prevent a stack from being accidentally deleted by enabling termination
  protection on the stack. If a user attempts to delete a stack with termination
  protection enabled, the deletion fails and the stack--including its status--remains
  unchanged. Enabling or disabling termination protection on a stack sets it for any
  nested stacks belonging to that stack as well. You can enable termination protection
  on a stack by setting the `terminationProtection` prop to `true`.

  ```python
  stack = Stack(app, "StackName",
      termination_protection=True
  )
  ```

  You can also set termination protection with the setter after you've instantiated the stack.

  ```python
  stack = Stack(app, "StackName")
  stack.termination_protection = True
  ```

  By default, termination protection is disabled.



  You can add a description of the stack in the same way as `StackProps`.

  ```python
  stack = Stack(app, "StackName",
      description="This is a description."
  )
  ```



  `CfnJson` allows you to postpone the resolution of a JSON blob from
  deployment-time. This is useful in cases where the CloudFormation JSON template
  cannot express a certain value.

  A common example is to use `CfnJson` in order to render a JSON map which needs
  to use intrinsic functions in keys. Since JSON map keys must be strings, it is
  impossible to use intrinsics in keys and `CfnJson` can help.

  The following example defines an IAM role which can only be assumed by
  principals that are tagged with a specific tag.

  ```python
  tag_param = CfnParameter(self, "TagName")

  string_equals = CfnJson(self, "ConditionJson",
      value={
          "f"aws:PrincipalTag/{tagParam.valueAsString}"": True
      }
  )

  principal = iam.AccountRootPrincipal().with_conditions({
      "StringEquals": string_equals
  })

  iam.Role(self, "MyRole", assumed_by=principal)
  ```

  **Explanation**: since in this example we pass the tag name through a parameter, it
  can only be resolved during deployment. The resolved value can be represented in
  the template through a `{ "Ref": "TagName" }`. However, since we want to use
  this value inside a [`aws:PrincipalTag/TAG-NAME`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principaltag)
  IAM operator, we need it in the *key* of a `StringEquals` condition. JSON keys
  *must be* strings, so to circumvent this limitation, we use `CfnJson`
  to "delay" the rendition of this template section to deploy-time. This means
  that the value of `StringEquals` in the template will be `{ "Fn::GetAtt": [ "ConditionJson", "Value" ] }`, and will only "expand" to the operator we synthesized during deployment.



  When deploying to AWS CloudFormation, it needs to keep in check the amount of resources being added inside a Stack. Currently it's possible to check the limits in the [AWS CloudFormation quotas](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html) page.

  It's possible to synthesize the project with more Resources than the allowed (or even reduce the number of Resources).

  Set the context key `@aws-cdk/core:stackResourceLimit` with the proper value, being 0 for disable the limit of resources.



  The AWS CloudFormation templates generated by CDK include indentation by default.
  Indentation makes the templates more readable, but also increases their size,
  and CloudFormation templates cannot exceed 1MB.

  It's possible to reduce the size of your templates by suppressing indentation.

  To do this for all templates, set the context key `@aws-cdk/core:suppressTemplateIndentation` to `true`.

  To do this for a specific stack, add a `suppressTemplateIndentation: true` property to the
  stack's `StackProps` parameter. You can also set this property to `false` to override
  the context key setting.



  [Context values](https://docs.aws.amazon.com/cdk/v2/guide/context.html) are key-value pairs that can be associated with an app, stack, or construct.
  One common use case for context is to use it for enabling/disabling [feature flags](https://docs.aws.amazon.com/cdk/v2/guide/featureflags.html). There are several places
  where context can be specified. They are listed below in the order they are evaluated (items at the
  top take precedence over those below).

  * The `node.setContext()` method
  * The `postCliContext` prop when you create an `App`
  * The CLI via the `--context` CLI argument
  * The `cdk.json` file via the `context` key:
  * The `cdk.context.json` file:
  * The `~/.cdk.json` file via the `context` key:
  * The `context` prop when you create an `App`



  ```python
  App(
      context={
          "@aws-cdk/core:newStyleStackSynthesis": True
      }
  )
  ```

  ```python
  app = App()
  app.node.set_context("@aws-cdk/core:newStyleStackSynthesis", True)
  ```

  ```python
  App(
      post_cli_context={
          "@aws-cdk/core:newStyleStackSynthesis": True
      }
  )
  ```

  ```console
  cdk synth --context @aws-cdk/core:newStyleStackSynthesis=true
  ```

  *cdk.json*

  ```json
  {
    "context": {
      "@aws-cdk/core:newStyleStackSynthesis": true
    }
  }
  ```

  *cdk.context.json*

  ```json
  {
    "@aws-cdk/core:newStyleStackSynthesis": true
  }
  ```

  *~/.cdk.json*

  ```json
  {
    "context": {
      "@aws-cdk/core:newStyleStackSynthesis": true
    }
  }
  ```



  It is possible to apply an [IAM permissions boundary](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html)
  to all roles within a specific construct scope. The most common use case would
  be to apply a permissions boundary at the `Stage` level.

  ```python
  prod_stage = Stage(app, "ProdStage",
      permissions_boundary=PermissionsBoundary.from_name("cdk-${Qualifier}-PermissionsBoundary")
  )
  ```

  Any IAM Roles or Users created within this Stage will have the default
  permissions boundary attached.

  For more details see the [Permissions Boundary](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam-readme.html#permissions-boundaries) section in the IAM guide.



  If you or your organization use (or would like to use) any policy validation tool, such as
  [CloudFormation
  Guard](https://docs.aws.amazon.com/cfn-guard/latest/ug/what-is-guard.html) or
  [OPA](https://www.openpolicyagent.org/), to define constraints on your
  CloudFormation template, you can incorporate them into the CDK application.
  By using the appropriate plugin, you can make the CDK application check the
  generated CloudFormation templates against your policies immediately after
  synthesis. If there are any violations, the synthesis will fail and a report
  will be printed to the console or to a file (see below).

  > **Note**
  > This feature is considered experimental, and both the plugin API and the
  > format of the validation report are subject to change in the future.



  To use one or more validation plugins in your application, use the
  `policyValidationBeta1` property of `Stage`:

  ```python

  app = App(
      policy_validation_beta1=[
          
          ThirdPartyPluginX(),
          ThirdPartyPluginY()
      ]
  )


  prod_stage = Stage(app, "ProdStage",
      policy_validation_beta1=[
          ThirdPartyPluginX()
      ]
  )
  ```

  Immediately after synthesis, all plugins registered this way will be invoked to
  validate all the templates generated in the scope you defined. In particular, if
  you register the templates in the `App` object, all templates will be subject to
  validation.

  > **Warning**
  > Other than modifying the cloud assembly, plugins can do anything that your CDK
  > application can. They can read data from the filesystem, access the network
  > etc. It's your responsibility as the consumer of a plugin to verify that it is
  > secure to use.

  By default, the report will be printed in a human readable format. If you want a
  report in JSON format, enable it using the `@aws-cdk/core:validationReportJson`
  context passing it directly to the application:

  ```python
  app = App(
      context={"@aws-cdk/core:validationReportJson": True}
  )
  ```

  Alternatively, you can set this context key-value pair using the `cdk.json` or
  `cdk.context.json` files in your project directory (see
  [Runtime context](https://docs.aws.amazon.com/cdk/v2/guide/context.html)).

  If you choose the JSON format, the CDK will print the policy validation report
  to a file called `policy-validation-report.json` in the cloud assembly
  directory. For the default, human-readable format, the report will be printed to
  the standard output.



  The communication protocol between the CDK core module and your policy tool is
  defined by the `IPolicyValidationPluginBeta1` interface. To create a new plugin you must
  write a class that implements this interface. There are two things you need to
  implement: the plugin name (by overriding the `name` property), and the
  `validate()` method.

  The framework will call `validate()`, passing an `IPolicyValidationContextBeta1` object.
  The location of the templates to be validated is given by `templatePaths`. The
  plugin should return an instance of `PolicyValidationPluginReportBeta1`. This object
  represents the report that the user wil receive at the end of the synthesis.

  ```python
  @jsii.implements(IPolicyValidationPluginBeta1)
  class MyPlugin:

      def validate(self, context):
          

          
          
          return PolicyValidationPluginReportBeta1(
              success=False,
              violations=[PolicyViolationBeta1(
                  rule_name="CKV_AWS_117",
                  description="Ensure that AWS Lambda function is configured inside a VPC",
                  fix="https://docs.bridgecrew.io/docs/ensure-that-aws-lambda-function-is-configured-inside-a-vpc-1",
                  violating_resources=[PolicyViolatingResourceBeta1(
                      resource_logical_id="MyFunction3BAA72D1",
                      template_path="/home/johndoe/myapp/cdk.out/MyService.template.json",
                      locations=["Properties/VpcConfig"]
                  )]
              )]
          )
  ```

  In addition to the name, plugins may optionally report their version (`version`
  property ) and a list of IDs of the rules they are going to evaluate (`ruleIds`
  property).

  Note that plugins are not allowed to modify anything in the cloud assembly. Any
  attempt to do so will result in synthesis failure.

  If your plugin depends on an external tool, keep in mind that some developers may
  not have that tool installed in their workstations yet. To minimize friction, we
  highly recommend that you provide some installation script along with your
  plugin package, to automate the whole process. Better yet, run that script as
  part of the installation of your package. With `npm`, for example, you can run
  add it to the `postinstall`
  [script](https://docs.npmjs.com/cli/v9/using-npm/scripts) in the `package.json`
  file.



  Construct authors can add annotations to constructs to report at three different
  levels: `ERROR`, `WARN`, `INFO`.

  Typically warnings are added for things that are important for the user to be
  aware of, but will not cause deployment errors in all cases. Some common
  scenarios are (non-exhaustive list):

  * Warn when the user needs to take a manual action, e.g. IAM policy should be
    added to an referenced resource.
  * Warn if the user configuration might not follow best practices (but is still
    valid)
  * Warn if the user is using a deprecated API



  If you would like to run with `--strict` mode enabled (warnings will throw
  errors) it is possible to `acknowledge` warnings to make the warning go away.

  For example, if > 10 IAM managed policies are added to an IAM Group, a warning
  will be created:

  ```text
  IAM:Group:MaxPoliciesExceeded: You added 11 to IAM Group my-group. The maximum number of managed policies attached to an IAM group is 10.
  ```

  If you have requested a [quota increase](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html#reference_iam-quotas-entities)
  you may have the ability to add > 10 managed policies which means that this
  warning does not apply to you. You can acknowledge this by `acknowledging` the
  warning by the `id`.

  ```python
  Annotations.of(self).acknowledge_warning("IAM:Group:MaxPoliciesExceeded", "Account has quota increased to 20")
  ```

  <!--END CORE DOCUMENTATION-->


pkgId: 44890abbfde85c8c948ef2f6135ad9f998fe282b662736f038e69daf920e5bc4
name: python-aws-cdk-lib
arch: src
version: 2.167.0
epoch: 0
release: 1
summary: Version 2 of the AWS Cloud Development Kit library
url: https://github.com/aws/aws-cdk
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk-lib-2.167.0-1.src.rpm
checksum_type: sha256
description:
  The AWS CDK construct library provides APIs to define your CDK application and add
  CDK constructs to the application.





  When upgrading from CDK 1.x, remove all dependencies to individual CDK packages
  from your dependencies file and follow the rest of the sections.



  To use this package, you need to declare this package and the `constructs` package as
  dependencies.

  According to the kind of project you are developing:

  For projects that are CDK libraries in NPM, declare them both under the `devDependencies` **and** `peerDependencies` sections.
  To make sure your library is compatible with the widest range of CDK versions: pick the minimum `aws-cdk-lib` version
  that your library requires; declare a range dependency with a caret on that version in peerDependencies, and declare a
  point version dependency on that version in devDependencies.

  For example, let's say the minimum version your library needs is `2.38.0`. Your `package.json` should look like this:

  ```javascript
  {
    "peerDependencies": {
      "aws-cdk-lib": "^2.38.0",
      "constructs": "^10.0.0"
    },
    "devDependencies": {
      /* Install the oldest version for testing so we don't accidentally use features from a newer version than we declare */
      "aws-cdk-lib": "2.38.0"
    }
  }
  ```

  For CDK apps, declare them under the `dependencies` section. Use a caret so you always get the latest version:

  ```json
  {
    "dependencies": {
      "aws-cdk-lib": "^2.38.0",
      "constructs": "^10.0.0"
    }
  }
  ```





  You can use a classic import to get access to each service namespaces:

  ```python
  from aws_cdk import Stack, App, aws_s3 as s3

  app = App()
  stack = Stack(app, "TestStack")

  s3.Bucket(stack, "TestBucket")
  ```



  Alternatively, you can use "barrel" imports:

  ```python
  from aws_cdk import App, Stack
  from aws_cdk.aws_s3 import Bucket

  app = App()
  stack = Stack(app, "TestStack")

  Bucket(stack, "TestBucket")
  ```

  <!--BEGIN CORE DOCUMENTATION-->



  A `Stack` is the smallest physical unit of deployment, and maps directly onto
  a CloudFormation Stack. You define a Stack by defining a subclass of `Stack`
  -- let's call it `MyStack` -- and instantiating the constructs that make up
  your application in `MyStack`'s constructor. You then instantiate this stack
  one or more times to define different instances of your application. For example,
  you can instantiate it once using few and cheap EC2 instances for testing,
  and once again using more and bigger EC2 instances for production.

  When your application grows, you may decide that it makes more sense to split it
  out across multiple `Stack` classes. This can happen for a number of reasons:

  * You could be starting to reach the maximum number of resources allowed in a single
    stack (this is currently 500).
  * You could decide you want to separate out stateful resources and stateless resources
    into separate stacks, so that it becomes easy to tear down and recreate the stacks
    that don't have stateful resources.
  * There could be a single stack with resources (like a VPC) that are shared
    between multiple instances of other stacks containing your applications.

  As soon as your conceptual application starts to encompass multiple stacks,
  it is convenient to wrap them in another construct that represents your
  logical application. You can then treat that new unit the same way you used
  to be able to treat a single stack: by instantiating it multiple times
  for different instances of your application.

  You can define a custom subclass of `Stage`, holding one or more
  `Stack`s, to represent a single logical instance of your application.

  As a final note: `Stack`s are not a unit of reuse. They describe physical
  deployment layouts, and as such are best left to application builders to
  organize their deployments with. If you want to vend a reusable construct,
  define it as a subclasses of `Construct`: the consumers of your construct
  will decide where to place it in their own stacks.



  Each Stack has a *synthesizer*, an object that determines how and where
  the Stack should be synthesized and deployed. The synthesizer controls
  aspects like:

  * How does the stack reference assets? (Either through CloudFormation
    parameters the CLI supplies, or because the Stack knows a predefined
    location where assets will be uploaded).
  * What roles are used to deploy the stack? These can be bootstrapped
    roles, roles created in some other way, or just the CLI's current
    credentials.

  The following synthesizers are available:

  * `DefaultStackSynthesizer`: recommended. Uses predefined asset locations and
    roles created by the modern bootstrap template. Access control is done by
    controlling who can assume the deploy role. This is the default stack
    synthesizer in CDKv2.
  * `LegacyStackSynthesizer`: Uses CloudFormation parameters to communicate
    asset locations, and the CLI's current permissions to deploy stacks. This
    is the default stack synthesizer in CDKv1.
  * `CliCredentialsStackSynthesizer`: Uses predefined asset locations, and the
    CLI's current permissions.

  Each of these synthesizers takes configuration arguments. To configure
  a stack with a synthesizer, pass it as one of its properties:

  ```python
  MyStack(app, "MyStack",
      synthesizer=DefaultStackSynthesizer(
          file_assets_bucket_name="amzn-s3-demo-bucket"
      )
  )
  ```

  For more information on bootstrapping accounts and customizing synthesis,
  see [Bootstrapping in the CDK Developer Guide](https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html).



  [Nested stacks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html) are stacks created as part of other stacks. You create a nested stack within another stack by using the `NestedStack` construct.

  As your infrastructure grows, common patterns can emerge in which you declare the same components in multiple templates. You can separate out these common components and create dedicated templates for them. Then use the resource in your template to reference other templates, creating nested stacks.

  For example, assume that you have a load balancer configuration that you use for most of your stacks. Instead of copying and pasting the same configurations into your templates, you can create a dedicated template for the load balancer. Then, you just use the resource to reference that template from within other templates.

  The following example will define a single top-level stack that contains two nested stacks: each one with a single Amazon S3 bucket:

  ```python
  class MyNestedStack(cfn.NestedStack):
      def __init__(self, scope, id, *, parameters=None, timeout=None, notifications=None):
          super().__init__(scope, id, parameters=parameters, timeout=timeout, notifications=notifications)

          s3.Bucket(self, "NestedBucket")

  class MyParentStack(Stack):
      def __init__(self, scope, id, *, description=None, env=None, stackName=None, tags=None, notificationArns=None, synthesizer=None, terminationProtection=None, analyticsReporting=None, crossRegionReferences=None, permissionsBoundary=None, suppressTemplateIndentation=None):
          super().__init__(scope, id, description=description, env=env, stackName=stackName, tags=tags, notificationArns=notificationArns, synthesizer=synthesizer, terminationProtection=terminationProtection, analyticsReporting=analyticsReporting, crossRegionReferences=crossRegionReferences, permissionsBoundary=permissionsBoundary, suppressTemplateIndentation=suppressTemplateIndentation)

          MyNestedStack(self, "Nested1")
          MyNestedStack(self, "Nested2")
  ```

  Resources references across nested/parent boundaries (even with multiple levels of nesting) will be wired by the AWS CDK
  through CloudFormation parameters and outputs. When a resource from a parent stack is referenced by a nested stack,
  a CloudFormation parameter will automatically be added to the nested stack and assigned from the parent; when a resource
  from a nested stack is referenced by a parent stack, a CloudFormation output will be automatically be added to the
  nested stack and referenced using `Fn::GetAtt "Outputs.Xxx"` from the parent.

  Nested stacks also support the use of Docker image and file assets.



  You can access resources in a different stack, as long as they are in the
  same account and AWS Region (see [next section](#accessing-resources-in-a-different-stack-and-region) for an exception).
  The following example defines the stack `stack1`,
  which defines an Amazon S3 bucket. Then it defines a second stack, `stack2`,
  which takes the bucket from stack1 as a constructor property.

  ```python
  prod = {"account": "123456789012", "region": "us-east-1"}

  stack1 = StackThatProvidesABucket(app, "Stack1", env=prod)


  stack2 = StackThatExpectsABucket(app, "Stack2",
      bucket=stack1.bucket,
      env=prod
  )
  ```

  If the AWS CDK determines that the resource is in the same account and
  Region, but in a different stack, it automatically synthesizes AWS
  CloudFormation
  [Exports](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-exports.html)
  in the producing stack and an
  [Fn::ImportValue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html)
  in the consuming stack to transfer that information from one stack to the
  other.



  > **This feature is currently experimental**

  You can enable the Stack property `crossRegionReferences`
  in order to access resources in a different stack *and* region. With this feature flag
  enabled it is possible to do something like creating a CloudFront distribution in `us-east-2` and
  an ACM certificate in `us-east-1`.

  ```python
  stack1 = Stack(app, "Stack1",
      env=Environment(
          region="us-east-1"
      ),
      cross_region_references=True
  )
  cert = acm.Certificate(stack1, "Cert",
      domain_name="*.example.com",
      validation=acm.CertificateValidation.from_dns(route53.PublicHostedZone.from_hosted_zone_id(stack1, "Zone", "Z0329774B51CGXTDQV3X"))
  )

  stack2 = Stack(app, "Stack2",
      env=Environment(
          region="us-east-2"
      ),
      cross_region_references=True
  )
  cloudfront.Distribution(stack2, "Distribution",
      default_behavior=cloudfront.BehaviorOptions(
          origin=origins.HttpOrigin("example.com")
      ),
      domain_names=["dev.example.com"],
      certificate=cert
  )
  ```

  When the AWS CDK determines that the resource is in a different stack *and* is in a different
  region, it will "export" the value by creating a custom resource in the producing stack which
  creates SSM Parameters in the consuming region for each exported value. The parameters will be
  created with the name '/cdk/exports/${consumingStackName}/${export-name}'.
  In order to "import" the exports into the consuming stack a [SSM Dynamic reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#dynamic-references-ssm)
  is used to reference the SSM parameter which was created.

  In order to mimic strong references, a Custom Resource is also created in the consuming
  stack which marks the SSM parameters as being "imported". When a parameter has been successfully
  imported, the producing stack cannot update the value.

  > [!NOTE]
  > As a consequence of this feature being built on a Custom Resource, we are restricted to a
  > CloudFormation response body size limitation of [4096 bytes](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/crpg-ref-responses.html).
  > To prevent deployment errors related to the Custom Resource Provider response body being too
  > large, we recommend limiting the use of nested stacks and minimizing the length of stack names.
  > Doing this will prevent SSM parameter names from becoming too long which will reduce the size of the
  > response body.

  See the [adr](https://github.com/aws/aws-cdk/blob/main/packages/aws-cdk-lib/core/adr/cross-region-stack-references.md)
  for more details on this feature.



  The automatic references created by CDK when you use resources across stacks
  are convenient, but may block your deployments if you want to remove the
  resources that are referenced in this way. You will see an error like:

  ```text
  Export Stack1:ExportsOutputFnGetAtt-****** cannot be deleted as it is in use by Stack1
  ```

  Let's say there is a Bucket in the `stack1`, and the `stack2` references its
  `bucket.bucketName`. You now want to remove the bucket and run into the error above.

  It's not safe to remove `stack1.bucket` while `stack2` is still using it, so
  unblocking yourself from this is a two-step process. This is how it works:

  DEPLOYMENT 1: break the relationship

  * Make sure `stack2` no longer references `bucket.bucketName` (maybe the consumer
    stack now uses its own bucket, or it writes to an AWS DynamoDB table, or maybe you just
    remove the Lambda Function altogether).
  * In the `stack1` class, call `this.exportValue(this.bucket.bucketName)`. This
    will make sure the CloudFormation Export continues to exist while the relationship
    between the two stacks is being broken.
  * Deploy (this will effectively only change the `stack2`, but it's safe to deploy both).

  DEPLOYMENT 2: remove the resource

  * You are now free to remove the `bucket` resource from `stack1`.
  * Don't forget to remove the `exportValue()` call as well.
  * Deploy again (this time only the `stack1` will be changed -- the bucket will be deleted).



  To make specifications of time intervals unambiguous, a single class called
  `Duration` is used throughout the AWS Construct Library by all constructs
  that that take a time interval as a parameter (be it for a timeout, a
  rate, or something else).

  An instance of Duration is constructed by using one of the static factory
  methods on it:

  ```python
  Duration.seconds(300) # 5 minutes
  Duration.minutes(5) # 5 minutes
  Duration.hours(1) # 1 hour
  Duration.days(7) # 7 days
  Duration.parse("PT5M")
  ```

  Durations can be added or subtracted together:

  ```python
  Duration.minutes(1).plus(Duration.seconds(60)) # 2 minutes
  Duration.minutes(5).minus(Duration.seconds(10))
  ```



  To make specification of digital storage quantities unambiguous, a class called
  `Size` is available.

  An instance of `Size` is initialized through one of its static factory methods:

  ```python
  Size.kibibytes(200) # 200 KiB
  Size.mebibytes(5) # 5 MiB
  Size.gibibytes(40) # 40 GiB
  Size.tebibytes(200) # 200 TiB
  Size.pebibytes(3)
  ```

  Instances of `Size` created with one of the units can be converted into others.
  By default, conversion to a higher unit will fail if the conversion does not produce
  a whole number. This can be overridden by unsetting `integral` property.

  ```python
  Size.mebibytes(2).to_kibibytes() # yields 2048
  Size.kibibytes(2050).to_mebibytes(rounding=SizeRoundingBehavior.FLOOR)
  ```



  To help avoid accidental storage of secrets as plain text, we use the `SecretValue` type to
  represent secrets. Any construct that takes a value that should be a secret (such as
  a password or an access key) will take a parameter of type `SecretValue`.

  The best practice is to store secrets in AWS Secrets Manager and reference them using `SecretValue.secretsManager`:

  ```python
  secret = SecretValue.secrets_manager("secretId",
      json_field="password",  # optional: key of a JSON field to retrieve (defaults to all content),
      version_id="id",  # optional: id of the version (default AWSCURRENT)
      version_stage="stage"
  )
  ```

  Using AWS Secrets Manager is the recommended way to reference secrets in a CDK app.
  `SecretValue` also supports the following secret sources:

  * `SecretValue.unsafePlainText(secret)`: stores the secret as plain text in your app and the resulting template (not recommended).
  * `SecretValue.secretsManager(secret)`: refers to a secret stored in Secrets Manager
  * `SecretValue.ssmSecure(param, version)`: refers to a secret stored as a SecureString in the SSM
    Parameter Store. If you don't specify the exact version, AWS CloudFormation uses the latest
    version of the parameter.
  * `SecretValue.cfnParameter(param)`: refers to a secret passed through a CloudFormation parameter (must have `NoEcho: true`).
  * `SecretValue.cfnDynamicReference(dynref)`: refers to a secret described by a CloudFormation dynamic reference (used by `ssmSecure` and `secretsManager`).
  * `SecretValue.resourceAttribute(attr)`: refers to a secret returned from a CloudFormation resource creation.

  `SecretValue`s should only be passed to constructs that accept properties of type
  `SecretValue`. These constructs are written to ensure your secrets will not be
  exposed where they shouldn't be. If you try to use a `SecretValue` in a
  different location, an error about unsafe secret usage will be thrown at
  synthesis time.

  If you rotate the secret's value in Secrets Manager, you must also change at
  least one property on the resource where you are using the secret, to force
  CloudFormation to re-read the secret.

  `SecretValue.ssmSecure()` is only supported for a limited set of resources.
  [Click here for a list of supported resources and properties](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#template-parameters-dynamic-patterns-resources).



  Sometimes you will need to put together or pick apart Amazon Resource Names
  (ARNs). The functions `stack.formatArn()` and `stack.splitArn()` exist for
  this purpose.

  `formatArn()` can be used to build an ARN from components. It will automatically
  use the region and account of the stack you're calling it on:

  ```python




  stack.format_arn(
      service="lambda",
      resource="function",
      arn_format=ArnFormat.COLON_RESOURCE_NAME,
      resource_name="MyFunction"
  )
  ```

  `splitArn()` can be used to get a single component from an ARN. `splitArn()`
  will correctly deal with both literal ARNs and deploy-time values (tokens),
  but in case of a deploy-time value be aware that the result will be another
  deploy-time value which cannot be inspected in the CDK application.

  ```python




  arn_components = stack.split_arn(arn, ArnFormat.COLON_RESOURCE_NAME)
  function_name = arn_components.resource_name
  ```

  Note that the format of the resource separator depends on the service and
  may be any of the values supported by `ArnFormat`. When dealing with these
  functions, it is important to know the format of the ARN you are dealing with.

  For an exhaustive list of ARN formats used in AWS, see [AWS ARNs and
  Namespaces](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html)
  in the AWS General Reference.





  Sometimes AWS resources depend on other resources, and the creation of one
  resource must be completed before the next one can be started.

  In general, CloudFormation will correctly infer the dependency relationship
  between resources based on the property values that are used. In the cases where
  it doesn't, the AWS Construct Library will add the dependency relationship for
  you.

  If you need to add an ordering dependency that is not automatically inferred,
  you do so by adding a dependency relationship using
  `constructA.node.addDependency(constructB)`. This will add a dependency
  relationship between all resources in the scope of `constructA` and all
  resources in the scope of `constructB`.

  If you want a single object to represent a set of constructs that are not
  necessarily in the same scope, you can use a `DependencyGroup`. The
  following creates a single object that represents a dependency on two
  constructs, `constructB` and `constructC`:

  ```python

  b_and_c = DependencyGroup()
  b_and_c.add(construct_b)
  b_and_c.add(construct_c)


  construct_a.node.add_dependency(b_and_c)
  ```



  Two different stack instances can have a dependency on one another. This
  happens when an resource from one stack is referenced in another stack. In
  that case, CDK records the cross-stack referencing of resources,
  automatically produces the right CloudFormation primitives, and adds a
  dependency between the two stacks. You can also manually add a dependency
  between two stacks by using the `stackA.addDependency(stackB)` method.

  A stack dependency has the following implications:

  * Cyclic dependencies are not allowed, so if `stackA` is using resources from
    `stackB`, the reverse is not possible anymore.
  * Stacks with dependencies between them are treated specially by the CDK
    toolkit:

    * If `stackA` depends on `stackB`, running `cdk deploy stackA` will also
      automatically deploy `stackB`.
    * `stackB`'s deployment will be performed *before* `stackA`'s deployment.



  To make declaring dependencies between `CfnResource` objects easier, you can declare dependencies from one `CfnResource` object on another by using the `cfnResource1.addDependency(cfnResource2)` method. This method will work for resources both within the same stack and across stacks as it detects the relative location of the two resources and adds the dependency either to the resource or between the relevant stacks, as appropriate. If more complex logic is in needed, you can similarly remove, replace, or view dependencies between `CfnResource` objects with the `CfnResource` `removeDependency`, `replaceDependency`, and `obtainDependencies` methods, respectively.



  Custom Resources are CloudFormation resources that are implemented by arbitrary
  user code. They can do arbitrary lookups or modifications during a
  CloudFormation deployment.

  Custom resources are backed by *custom resource providers*. Commonly, these are
  Lambda Functions that are deployed in the same deployment as the one that
  defines the custom resource itself, but they can also be backed by Lambda
  Functions deployed previously, or code responding to SNS Topic events running on
  EC2 instances in a completely different account. For more information on custom
  resource providers, see the next section.

  Once you have a provider, each definition of a `CustomResource` construct
  represents one invocation. A single provider can be used for the implementation
  of arbitrarily many custom resource definitions. A single definition looks like
  this:

  ```python
  CustomResource(self, "MyMagicalResource",
      resource_type="Custom::MyCustomResource",  # must start with 'Custom::'

      
      properties={
          "Property1": "foo",
          "Property2": "bar"
      },

      
      
      
      service_token="ARN"
  )
  ```



  Custom resources are backed by a **custom resource provider** which can be
  implemented in one of the following ways. The following table compares the
  various provider types (ordered from low-level to high-level):

  | Provider                                                             | Compute Type | Error Handling | Submit to CloudFormation |   Max Timeout   | Language | Footprint |
  | -------------------------------------------------------------------- | :----------: | :------------: | :----------------------: | :-------------: | :------: | :-------: |
  | [sns.Topic](#amazon-sns-topic)                                       | Self-managed |     Manual     |          Manual          |    Unlimited    |   Any    |  Depends  |
  | [lambda.Function](#aws-lambda-function)                              |  AWS Lambda  |     Manual     |          Manual          |      15min      |   Any    |   Small   |
  | [core.CustomResourceProvider](#the-corecustomresourceprovider-class) |  AWS Lambda  |      Auto      |           Auto           |      15min      | Node.js  |   Small   |
  | [custom-resources.Provider](#the-custom-resource-provider-framework) |  AWS Lambda  |      Auto      |           Auto           | Unlimited Async |   Any    |   Large   |

  Legend:

  * **Compute type**: which type of compute can be used to execute the handler.
  * **Error Handling**: whether errors thrown by handler code are automatically
    trapped and a FAILED response is submitted to CloudFormation. If this is
    "Manual", developers must take care of trapping errors. Otherwise, events
    could cause stacks to hang.
  * **Submit to CloudFormation**: whether the framework takes care of submitting
    SUCCESS/FAILED responses to CloudFormation through the event's response URL.
  * **Max Timeout**: maximum allows/possible timeout.
  * **Language**: which programming languages can be used to implement handlers.
  * **Footprint**: how many resources are used by the provider framework itself.

  **A NOTE ABOUT SINGLETONS**

  When defining resources for a custom resource provider, you will likely want to
  define them as a *stack singleton* so that only a single instance of the
  provider is created in your stack and which is used by all custom resources of
  that type.

  Here is a basic pattern for defining stack singletons in the CDK. The following
  examples ensures that only a single SNS topic is defined:

  ```python
  def get_or_create(self, scope):
      stack = Stack.of(scope)
      uniqueid = "GloballyUniqueIdForSingleton" # For example, a UUID from `uuidgen`
      existing = stack.node.try_find_child(uniqueid)
      if existing:
          return existing
      return sns.Topic(stack, uniqueid)
  ```



  Every time a resource event occurs (CREATE/UPDATE/DELETE), an SNS notification
  is sent to the SNS topic. Users must process these notifications (e.g. through a
  fleet of worker hosts) and submit success/failure responses to the
  CloudFormation service.

  > You only need to use this type of provider if your custom resource cannot run on AWS Lambda, for reasons other than the 15
  > minute timeout. If you are considering using this type of provider because you want to write a custom resource provider that may need
  > to wait for more than 15 minutes for the API calls to stabilize, have a look at the [`custom-resources`](#the-custom-resource-provider-framework) module first.
  >
  > Refer to the [CloudFormation Custom Resource documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html) for information on the contract your custom resource needs to adhere to.

  Set `serviceToken` to `topic.topicArn`  in order to use this provider:

  ```python
  topic = sns.Topic(self, "MyProvider")

  CustomResource(self, "MyResource",
      service_token=topic.topic_arn
  )
  ```



  An AWS lambda function is called *directly* by CloudFormation for all resource
  events. The handler must take care of explicitly submitting a success/failure
  response to the CloudFormation service and handle various error cases.

  > **We do not recommend you use this provider type.** The CDK has wrappers around Lambda Functions that make them easier to work with.
  >
  > If you do want to use this provider, refer to the [CloudFormation Custom Resource documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html) for information on the contract your custom resource needs to adhere to.

  Set `serviceToken` to `lambda.functionArn` to use this provider:

  ```python
  fn = lambda_.SingletonFunction(self, "MyProvider", function_props)

  CustomResource(self, "MyResource",
      service_token=fn.function_arn
  )
  ```



  The class [`@aws-cdk/core.CustomResourceProvider`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.CustomResourceProvider.html) offers a basic low-level
  framework designed to implement simple and slim custom resource providers. It
  currently only supports Node.js-based user handlers, represents permissions as raw
  JSON blobs instead of `iam.PolicyStatement` objects, and it does not have
  support for asynchronous waiting (handler cannot exceed the 15min lambda
  timeout). The `CustomResourceProviderRuntime` supports runtime `nodejs12.x`,
  `nodejs14.x`, `nodejs16.x`, `nodejs18.x`.

  > **As an application builder, we do not recommend you use this provider type.** This provider exists purely for custom resources that are part of the AWS Construct Library.
  >
  > The [`custom-resources`](#the-custom-resource-provider-framework) provider is more convenient to work with and more fully-featured.

  The provider has a built-in singleton method which uses the resource type as a
  stack-unique identifier and returns the service token:

  ```python
  service_token = CustomResourceProvider.get_or_create(self, "Custom::MyCustomResourceType",
      code_directory=f"{__dirname}/my-handler",
      runtime=CustomResourceProviderRuntime.NODEJS_18_X,
      description="Lambda function created by the custom resource provider"
  )

  CustomResource(self, "MyResource",
      resource_type="Custom::MyCustomResourceType",
      service_token=service_token
  )
  ```

  The directory (`my-handler` in the above example) must include an `index.js` file. It cannot import
  external dependencies or files outside this directory. It must export an async
  function named `handler`. This function accepts the CloudFormation resource
  event object and returns an object with the following structure:

  ```js
  exports.handler = async function(event) {
    const id = event.PhysicalResourceId; // only for "Update" and "Delete"
    const props = event.ResourceProperties;
    const oldProps = event.OldResourceProperties; // only for "Update"s

    switch (event.RequestType) {
      case "Create":
        // ...

      case "Update":
        // ...

        // if an error is thrown, a FAILED response will be submitted to CFN
        throw new Error('Failed!');

      case "Delete":
        // ...
    }

    return {
      // (optional) the value resolved from `resource.ref`
      // defaults to "event.PhysicalResourceId" or "event.RequestId"
      PhysicalResourceId: "REF",

      // (optional) calling `resource.getAtt("Att1")` on the custom resource in the CDK app
      // will return the value "BAR".
      Data: {
        Att1: "BAR",
        Att2: "BAZ"
      },

      // (optional) user-visible message
      Reason: "User-visible message",

      // (optional) hides values from the console
      NoEcho: true
    };
  }
  ```

  Here is an complete example of a custom resource that summarizes two numbers:

  `sum-handler/index.js`:

  ```js
  exports.handler = async (e) => {
    return {
      Data: {
        Result: e.ResourceProperties.lhs + e.ResourceProperties.rhs,
      },
    };
  };
  ```

  `sum.ts`:

  ```python
  from constructs import Construct
  from aws_cdk import CustomResource, CustomResourceProvider, CustomResourceProviderRuntime, Token

  class Sum(Construct):

      def __init__(self, scope, id, *, lhs, rhs):
          super().__init__(scope, id)

          resource_type = "Custom::Sum"
          service_token = CustomResourceProvider.get_or_create(self, resource_type,
              code_directory=f"{__dirname}/sum-handler",
              runtime=CustomResourceProviderRuntime.NODEJS_18_X
          )

          resource = CustomResource(self, "Resource",
              resource_type=resource_type,
              service_token=service_token,
              properties={
                  "lhs": lhs,
                  "rhs": rhs
              }
          )

          self.result = Token.as_number(resource.get_att("Result"))
  ```

  Usage will look like this:

  ```python
  sum = Sum(self, "MySum", lhs=40, rhs=2)
  CfnOutput(self, "Result", value=Token.as_string(sum.result))
  ```

  To access the ARN of the provider's AWS Lambda function role, use the `getOrCreateProvider()`
  built-in singleton method:

  ```python
  provider = CustomResourceProvider.get_or_create_provider(self, "Custom::MyCustomResourceType",
      code_directory=f"{__dirname}/my-handler",
      runtime=CustomResourceProviderRuntime.NODEJS_18_X
  )

  role_arn = provider.role_arn
  ```

  This role ARN can then be used in resource-based IAM policies.

  To add IAM policy statements to this role, use `addToRolePolicy()`:

  ```python
  provider = CustomResourceProvider.get_or_create_provider(self, "Custom::MyCustomResourceType",
      code_directory=f"{__dirname}/my-handler",
      runtime=CustomResourceProviderRuntime.NODEJS_18_X
  )
  provider.add_to_role_policy({
      "Effect": "Allow",
      "Action": "s3:GetObject",
      "Resource": "*"
  })
  ```

  Note that `addToRolePolicy()` uses direct IAM JSON policy blobs, *not* a
  `iam.PolicyStatement` object like you will see in the rest of the CDK.



  The [`@aws-cdk/custom-resources`](https://docs.aws.amazon.com/cdk/api/latest/docs/custom-resources-readme.html) module includes an advanced framework for
  implementing custom resource providers.

  Handlers are implemented as AWS Lambda functions, which means that they can be
  implemented in any Lambda-supported runtime. Furthermore, this provider has an
  asynchronous mode, which means that users can provide an `isComplete` lambda
  function which is called periodically until the operation is complete. This
  allows implementing providers that can take up to two hours to stabilize.

  Set `serviceToken` to `provider.serviceToken` to use this type of provider:

  ```python
  provider = customresources.Provider(self, "MyProvider",
      on_event_handler=on_event_handler,
      is_complete_handler=is_complete_handler
  )

  CustomResource(self, "MyResource",
      service_token=provider.service_token
  )
  ```

  See the [documentation](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.custom_resources-readme.html) for more details.



  A CDK stack synthesizes to an AWS CloudFormation Template. This section
  explains how this module allows users to access low-level CloudFormation
  features when needed.



  CloudFormation [stack outputs](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html) and exports are created using
  the `CfnOutput` class:

  ```python
  CfnOutput(self, "OutputName",
      value=my_bucket.bucket_name,
      description="The name of an S3 bucket",  # Optional
      export_name="TheAwesomeBucket"
  )
  ```



  CloudFormation templates support the use of [Parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) to
  customize a template. They enable CloudFormation users to input custom values to
  a template each time a stack is created or updated. While the CDK design
  philosophy favors using build-time parameterization, users may need to use
  CloudFormation in a number of cases (for example, when migrating an existing
  stack to the AWS CDK).

  Template parameters can be added to a stack by using the `CfnParameter` class:

  ```python
  CfnParameter(self, "MyParameter",
      type="Number",
      default=1337
  )
  ```

  The value of parameters can then be obtained using one of the `value` methods.
  As parameters are only resolved at deployment time, the values obtained are
  placeholder tokens for the real value (`Token.isUnresolved()` would return `true`
  for those):

  ```python
  param = CfnParameter(self, "ParameterName")


  param.value_as_string


  param.value_as_number


  param.value_as_list
  ```



  CloudFormation supports a number of [pseudo parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/pseudo-parameter-reference.html),
  which resolve to useful values at deployment time. CloudFormation pseudo
  parameters can be obtained from static members of the `Aws` class.

  It is generally recommended to access pseudo parameters from the scope's `stack`
  instead, which guarantees the values produced are qualifying the designated
  stack, which is essential in cases where resources are shared cross-stack:

  ```python

  stack = Stack.of(self)

  stack.account # Returns the AWS::AccountId for this stack (or the literal value if known)
  stack.region # Returns the AWS::Region for this stack (or the literal value if known)
  stack.partition
  ```



  CloudFormation resources can also specify [resource
  attributes](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-product-attribute-reference.html). The `CfnResource` class allows
  accessing those through the `cfnOptions` property:

  ```python
  raw_bucket = s3.CfnBucket(self, "Bucket")

  raw_bucket_alt = my_bucket.node.default_child


  raw_bucket.cfn_options.condition = CfnCondition(self, "EnableBucket")
  raw_bucket.cfn_options.metadata = {
      "metadata_key": "MetadataValue"
  }
  ```

  Resource dependencies (the `DependsOn` attribute) is modified using the
  `cfnResource.addDependency` method:

  ```python
  resource_a = CfnResource(self, "ResourceA", resource_props)
  resource_b = CfnResource(self, "ResourceB", resource_props)

  resource_b.add_dependency(resource_a)
  ```



  Some resources support a [CreationPolicy](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-creationpolicy.html) to be specified as a CfnOption.

  The creation policy is invoked only when AWS CloudFormation creates the associated resource. Currently, the only AWS CloudFormation resources that support creation policies are `CfnAutoScalingGroup`, `CfnInstance`, `CfnWaitCondition` and `CfnFleet`.

  The `CfnFleet` resource from the `aws-appstream` module supports specifying `startFleet` as
  a property of the creationPolicy on the resource options. Setting it to true will make AWS CloudFormation wait until the fleet is started before continuing with the creation of
  resources that depend on the fleet resource.

  ```python
  fleet = appstream.CfnFleet(self, "Fleet",
      instance_type="stream.standard.small",
      name="Fleet",
      compute_capacity=appstream.CfnFleet.ComputeCapacityProperty(
          desired_instances=1
      ),
      image_name="AppStream-AmazonLinux2-09-21-2022"
  )
  fleet.cfn_options.creation_policy = CfnCreationPolicy(
      start_fleet=True
  )
  ```

  The properties passed to the level 2 constructs `AutoScalingGroup` and `Instance` from the
  `aws-ec2` module abstract what is passed into the `CfnOption` properties `resourceSignal` and
  `autoScalingCreationPolicy`, but when using level 1 constructs you can specify these yourself.

  The CfnWaitCondition resource from the `aws-cloudformation` module suppports the `resourceSignal`.
  The format of the timeout is `PT#H#M#S`. In the example below AWS Cloudformation will wait for
  3 success signals to occur within 15 minutes before the status of the resource will be set to
  `CREATE_COMPLETE`.

  ```python



  resource.cfn_options.creation_policy = CfnCreationPolicy(
      resource_signal=CfnResourceSignal(
          count=3,
          timeout="PR15M"
      )
  )
  ```



  CloudFormation supports [intrinsic functions](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html). These functions
  can be accessed from the `Fn` class, which provides type-safe methods for each
  intrinsic function as well as condition expressions:

  ```python





  Fn.base64("SGVsbG8gQ0RLIQo=")


  environment_parameter = CfnParameter(self, "Environment")
  Fn.condition_and(
      
      Fn.condition_equals("Production", environment_parameter),
      
      Fn.condition_not(Fn.condition_equals("us-east-1", Aws.REGION)))


  Fn.to_json_string(my_object_or_array)


  Fn.len(Fn.split(",", my_array))
  ```

  When working with deploy-time values (those for which `Token.isUnresolved`
  returns `true`), idiomatic conditionals from the programming language cannot be
  used (the value will not be known until deployment time). When conditional logic
  needs to be expressed with un-resolved values, it is necessary to use
  CloudFormation conditions by means of the `CfnCondition` class:

  ```python
  environment_parameter = CfnParameter(self, "Environment")
  is_prod = CfnCondition(self, "IsProduction",
      expression=Fn.condition_equals("Production", environment_parameter)
  )


  stage = Fn.condition_if(is_prod.logical_id, "Beta", "Prod").to_string()



  bucket = s3.Bucket(self, "Bucket")
  cfn_bucket = my_bucket.node.default_child
  cfn_bucket.cfn_options.condition = is_prod
  ```



  CloudFormation [mappings](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/mappings-section-structure.html) are created and queried using the
  `CfnMappings` class:

  ```python
  region_table = CfnMapping(self, "RegionTable",
      mapping={
          "us-east-1": {
              "region_name": "US East (N. Virginia)"
          },
          "us-east-2": {
              "region_name": "US East (Ohio)"
          }
      }
  )

  region_table.find_in_map(Aws.REGION, "regionName")
  ```

  This will yield the following template:

  ```yaml
  Mappings:
    RegionTable:
      us-east-1:
        regionName: US East (N. Virginia)
      us-east-2:
        regionName: US East (Ohio)
  ```

  Mappings can also be synthesized "lazily"; lazy mappings will only render a "Mappings"
  section in the synthesized CloudFormation template if some `findInMap` call is unable to
  immediately return a concrete value due to one or both of the keys being unresolved tokens
  (some value only available at deploy-time).

  For example, the following code will not produce anything in the "Mappings" section. The
  call to `findInMap` will be able to resolve the value during synthesis and simply return
  `'US East (Ohio)'`.

  ```python
  region_table = CfnMapping(self, "RegionTable",
      mapping={
          "us-east-1": {
              "region_name": "US East (N. Virginia)"
          },
          "us-east-2": {
              "region_name": "US East (Ohio)"
          }
      },
      lazy=True
  )

  region_table.find_in_map("us-east-2", "regionName")
  ```

  On the other hand, the following code will produce the "Mappings" section shown above,
  since the top-level key is an unresolved token. The call to `findInMap` will return a token that resolves to
  `{ "Fn::FindInMap": [ "RegionTable", { "Ref": "AWS::Region" }, "regionName" ] }`.

  ```python



  region_table.find_in_map(Aws.REGION, "regionName")
  ```

  An optional default value can also be passed to `findInMap`. If either key is not found in the map and the mapping is lazy, `findInMap` will return the default value and not render the mapping.
  If the mapping is not lazy or either key is an unresolved token, the call to `findInMap` will return a token that resolves to
  `{ "Fn::FindInMap": [ "MapName", "TopLevelKey", "SecondLevelKey", { "DefaultValue": "DefaultValue" } ] }`, and the mapping will be rendered.
  Note that the `AWS::LanguageExtentions` transform is added to enable the default value functionality.

  For example, the following code will again not produce anything in the "Mappings" section. The
  call to `findInMap` will be able to resolve the value during synthesis and simply return
  `'Region not found'`.

  ```python
  region_table = CfnMapping(self, "RegionTable",
      mapping={
          "us-east-1": {
              "region_name": "US East (N. Virginia)"
          },
          "us-east-2": {
              "region_name": "US East (Ohio)"
          }
      },
      lazy=True
  )

  region_table.find_in_map("us-west-1", "regionName", "Region not found")
  ```



  CloudFormation supports [dynamically resolving](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html) values
  for SSM parameters (including secure strings) and Secrets Manager. Encoding such
  references is done using the `CfnDynamicReference` class:

  ```python
  CfnDynamicReference(CfnDynamicReferenceService.SECRETS_MANAGER, "secret-id:secret-string:json-key:version-stage:version-id")
  ```



  CloudFormation templates support a number of options, including which Macros or
  [Transforms](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-section-structure.html) to use when deploying the stack. Those can be
  configured using the `stack.templateOptions` property:

  ```python
  stack = Stack(app, "StackName")

  stack.template_options.description = "This will appear in the AWS console"
  stack.template_options.transforms = ["AWS::Serverless-2016-10-31"]
  stack.template_options.metadata = {
      "metadata_key": "MetadataValue"
  }
  ```



  The `CfnResource` class allows emitting arbitrary entries in the
  [Resources](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html) section of the CloudFormation template.

  ```python
  CfnResource(self, "ResourceId",
      type="AWS::S3::Bucket",
      properties={
          "BucketName": "amzn-s3-demo-bucket"
      }
  )
  ```

  As for any other resource, the logical ID in the CloudFormation template will be
  generated by the AWS CDK, but the type and properties will be copied verbatim in
  the synthesized template.



  When migrating a CloudFormation stack to the AWS CDK, it can be useful to
  include fragments of an existing template verbatim in the synthesized template.
  This can be achieved using the `CfnInclude` class.

  ```python
  CfnInclude(self, "ID",
      template={
          "Resources": {
              "Bucket": {
                  "Type": "AWS::S3::Bucket",
                  "Properties": {
                      "BucketName": "amzn-s3-demo-bucket"
                  }
              }
          }
      }
  )
  ```



  You can prevent a stack from being accidentally deleted by enabling termination
  protection on the stack. If a user attempts to delete a stack with termination
  protection enabled, the deletion fails and the stack--including its status--remains
  unchanged. Enabling or disabling termination protection on a stack sets it for any
  nested stacks belonging to that stack as well. You can enable termination protection
  on a stack by setting the `terminationProtection` prop to `true`.

  ```python
  stack = Stack(app, "StackName",
      termination_protection=True
  )
  ```

  You can also set termination protection with the setter after you've instantiated the stack.

  ```python
  stack = Stack(app, "StackName")
  stack.termination_protection = True
  ```

  By default, termination protection is disabled.



  You can add a description of the stack in the same way as `StackProps`.

  ```python
  stack = Stack(app, "StackName",
      description="This is a description."
  )
  ```



  `CfnJson` allows you to postpone the resolution of a JSON blob from
  deployment-time. This is useful in cases where the CloudFormation JSON template
  cannot express a certain value.

  A common example is to use `CfnJson` in order to render a JSON map which needs
  to use intrinsic functions in keys. Since JSON map keys must be strings, it is
  impossible to use intrinsics in keys and `CfnJson` can help.

  The following example defines an IAM role which can only be assumed by
  principals that are tagged with a specific tag.

  ```python
  tag_param = CfnParameter(self, "TagName")

  string_equals = CfnJson(self, "ConditionJson",
      value={
          "f"aws:PrincipalTag/{tagParam.valueAsString}"": True
      }
  )

  principal = iam.AccountRootPrincipal().with_conditions({
      "StringEquals": string_equals
  })

  iam.Role(self, "MyRole", assumed_by=principal)
  ```

  **Explanation**: since in this example we pass the tag name through a parameter, it
  can only be resolved during deployment. The resolved value can be represented in
  the template through a `{ "Ref": "TagName" }`. However, since we want to use
  this value inside a [`aws:PrincipalTag/TAG-NAME`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principaltag)
  IAM operator, we need it in the *key* of a `StringEquals` condition. JSON keys
  *must be* strings, so to circumvent this limitation, we use `CfnJson`
  to "delay" the rendition of this template section to deploy-time. This means
  that the value of `StringEquals` in the template will be `{ "Fn::GetAtt": [ "ConditionJson", "Value" ] }`, and will only "expand" to the operator we synthesized during deployment.



  When deploying to AWS CloudFormation, it needs to keep in check the amount of resources being added inside a Stack. Currently it's possible to check the limits in the [AWS CloudFormation quotas](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html) page.

  It's possible to synthesize the project with more Resources than the allowed (or even reduce the number of Resources).

  Set the context key `@aws-cdk/core:stackResourceLimit` with the proper value, being 0 for disable the limit of resources.



  The AWS CloudFormation templates generated by CDK include indentation by default.
  Indentation makes the templates more readable, but also increases their size,
  and CloudFormation templates cannot exceed 1MB.

  It's possible to reduce the size of your templates by suppressing indentation.

  To do this for all templates, set the context key `@aws-cdk/core:suppressTemplateIndentation` to `true`.

  To do this for a specific stack, add a `suppressTemplateIndentation: true` property to the
  stack's `StackProps` parameter. You can also set this property to `false` to override
  the context key setting.



  [Context values](https://docs.aws.amazon.com/cdk/v2/guide/context.html) are key-value pairs that can be associated with an app, stack, or construct.
  One common use case for context is to use it for enabling/disabling [feature flags](https://docs.aws.amazon.com/cdk/v2/guide/featureflags.html). There are several places
  where context can be specified. They are listed below in the order they are evaluated (items at the
  top take precedence over those below).

  * The `node.setContext()` method
  * The `postCliContext` prop when you create an `App`
  * The CLI via the `--context` CLI argument
  * The `cdk.json` file via the `context` key:
  * The `cdk.context.json` file:
  * The `~/.cdk.json` file via the `context` key:
  * The `context` prop when you create an `App`



  ```python
  App(
      context={
          "@aws-cdk/core:newStyleStackSynthesis": True
      }
  )
  ```

  ```python
  app = App()
  app.node.set_context("@aws-cdk/core:newStyleStackSynthesis", True)
  ```

  ```python
  App(
      post_cli_context={
          "@aws-cdk/core:newStyleStackSynthesis": True
      }
  )
  ```

  ```console
  cdk synth --context @aws-cdk/core:newStyleStackSynthesis=true
  ```

  *cdk.json*

  ```json
  {
    "context": {
      "@aws-cdk/core:newStyleStackSynthesis": true
    }
  }
  ```

  *cdk.context.json*

  ```json
  {
    "@aws-cdk/core:newStyleStackSynthesis": true
  }
  ```

  *~/.cdk.json*

  ```json
  {
    "context": {
      "@aws-cdk/core:newStyleStackSynthesis": true
    }
  }
  ```



  It is possible to apply an [IAM permissions boundary](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html)
  to all roles within a specific construct scope. The most common use case would
  be to apply a permissions boundary at the `Stage` level.

  ```python
  prod_stage = Stage(app, "ProdStage",
      permissions_boundary=PermissionsBoundary.from_name("cdk-${Qualifier}-PermissionsBoundary")
  )
  ```

  Any IAM Roles or Users created within this Stage will have the default
  permissions boundary attached.

  For more details see the [Permissions Boundary](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_iam-readme.html#permissions-boundaries) section in the IAM guide.



  If you or your organization use (or would like to use) any policy validation tool, such as
  [CloudFormation
  Guard](https://docs.aws.amazon.com/cfn-guard/latest/ug/what-is-guard.html) or
  [OPA](https://www.openpolicyagent.org/), to define constraints on your
  CloudFormation template, you can incorporate them into the CDK application.
  By using the appropriate plugin, you can make the CDK application check the
  generated CloudFormation templates against your policies immediately after
  synthesis. If there are any violations, the synthesis will fail and a report
  will be printed to the console or to a file (see below).

  > **Note**
  > This feature is considered experimental, and both the plugin API and the
  > format of the validation report are subject to change in the future.



  To use one or more validation plugins in your application, use the
  `policyValidationBeta1` property of `Stage`:

  ```python

  app = App(
      policy_validation_beta1=[
          
          ThirdPartyPluginX(),
          ThirdPartyPluginY()
      ]
  )


  prod_stage = Stage(app, "ProdStage",
      policy_validation_beta1=[
          ThirdPartyPluginX()
      ]
  )
  ```

  Immediately after synthesis, all plugins registered this way will be invoked to
  validate all the templates generated in the scope you defined. In particular, if
  you register the templates in the `App` object, all templates will be subject to
  validation.

  > **Warning**
  > Other than modifying the cloud assembly, plugins can do anything that your CDK
  > application can. They can read data from the filesystem, access the network
  > etc. It's your responsibility as the consumer of a plugin to verify that it is
  > secure to use.

  By default, the report will be printed in a human readable format. If you want a
  report in JSON format, enable it using the `@aws-cdk/core:validationReportJson`
  context passing it directly to the application:

  ```python
  app = App(
      context={"@aws-cdk/core:validationReportJson": True}
  )
  ```

  Alternatively, you can set this context key-value pair using the `cdk.json` or
  `cdk.context.json` files in your project directory (see
  [Runtime context](https://docs.aws.amazon.com/cdk/v2/guide/context.html)).

  If you choose the JSON format, the CDK will print the policy validation report
  to a file called `policy-validation-report.json` in the cloud assembly
  directory. For the default, human-readable format, the report will be printed to
  the standard output.



  The communication protocol between the CDK core module and your policy tool is
  defined by the `IPolicyValidationPluginBeta1` interface. To create a new plugin you must
  write a class that implements this interface. There are two things you need to
  implement: the plugin name (by overriding the `name` property), and the
  `validate()` method.

  The framework will call `validate()`, passing an `IPolicyValidationContextBeta1` object.
  The location of the templates to be validated is given by `templatePaths`. The
  plugin should return an instance of `PolicyValidationPluginReportBeta1`. This object
  represents the report that the user wil receive at the end of the synthesis.

  ```python
  @jsii.implements(IPolicyValidationPluginBeta1)
  class MyPlugin:

      def validate(self, context):
          

          
          
          return PolicyValidationPluginReportBeta1(
              success=False,
              violations=[PolicyViolationBeta1(
                  rule_name="CKV_AWS_117",
                  description="Ensure that AWS Lambda function is configured inside a VPC",
                  fix="https://docs.bridgecrew.io/docs/ensure-that-aws-lambda-function-is-configured-inside-a-vpc-1",
                  violating_resources=[PolicyViolatingResourceBeta1(
                      resource_logical_id="MyFunction3BAA72D1",
                      template_path="/home/johndoe/myapp/cdk.out/MyService.template.json",
                      locations=["Properties/VpcConfig"]
                  )]
              )]
          )
  ```

  In addition to the name, plugins may optionally report their version (`version`
  property ) and a list of IDs of the rules they are going to evaluate (`ruleIds`
  property).

  Note that plugins are not allowed to modify anything in the cloud assembly. Any
  attempt to do so will result in synthesis failure.

  If your plugin depends on an external tool, keep in mind that some developers may
  not have that tool installed in their workstations yet. To minimize friction, we
  highly recommend that you provide some installation script along with your
  plugin package, to automate the whole process. Better yet, run that script as
  part of the installation of your package. With `npm`, for example, you can run
  add it to the `postinstall`
  [script](https://docs.npmjs.com/cli/v9/using-npm/scripts) in the `package.json`
  file.



  Construct authors can add annotations to constructs to report at three different
  levels: `ERROR`, `WARN`, `INFO`.

  Typically warnings are added for things that are important for the user to be
  aware of, but will not cause deployment errors in all cases. Some common
  scenarios are (non-exhaustive list):

  * Warn when the user needs to take a manual action, e.g. IAM policy should be
    added to an referenced resource.
  * Warn if the user configuration might not follow best practices (but is still
    valid)
  * Warn if the user is using a deprecated API



  If you would like to run with `--strict` mode enabled (warnings will throw
  errors) it is possible to `acknowledge` warnings to make the warning go away.

  For example, if > 10 IAM managed policies are added to an IAM Group, a warning
  will be created:

  ```text
  IAM:Group:MaxPoliciesExceeded: You added 11 to IAM Group my-group. The maximum number of managed policies attached to an IAM group is 10.
  ```

  If you have requested a [quota increase](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html#reference_iam-quotas-entities)
  you may have the ability to add > 10 managed policies which means that this
  warning does not apply to you. You can acknowledge this by `acknowledging` the
  warning by the `id`.

  ```python
  Annotations.of(self).acknowledge_warning("IAM:Group:MaxPoliciesExceeded", "Account has quota increased to 20")
  ```

  <!--END CORE DOCUMENTATION-->


pkgId: b810c89736d5c605d4c119e92d2b2daaa12eaf71f91f9fe53ee91f9e92f41fc2
name: python-aws-cdk-microservice
arch: src
version: 0.0.19
epoch: 0
release: 1
summary: @smallcase/aws-cdk-microservice
url: https://github.com/smallcase/aws-cdk-microservice.git
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk-microservice-0.0.19-1.src.rpm
checksum_type: sha256
description:
  aws-cdk-microservice construct library is an open-source extension of the AWS Cloud Development Kit (AWS CDK) to deploy configurable microservice infra and its individual components in less than 50 lines of code and human readable configuration which can be managed by pull requests!



  ![Architecture diagram](static/microservice.png)

  Using cdk a microservice can be deployed using the following sample code snippet:

  ```python
  import { Stack, StackProps } from '@aws-cdk/core';
  import { Construct } from 'constructs';
  import { MicroService } from '@smallcase/aws-cdk-microservice';
  import { App } from '@aws-cdk/core';

  export class UnknownAPIStackDev extends Stack {
   constructor(scope: Construct, id: string, props?: StackProps) {
     super(scope, id, props);
     new MicroService(this, 'test', {
       appName: 'test',
       env: 'prod',
       asgMaxSize: '1',
       asgMinSize: '1',
       diskSize: 20,
       instanceLabels: [
         {
           key: 'SUDOERS_GROUPS_TAG',
           propagateAtLaunch: true,
           value: 'Developers',
         },
       ],
       instanceType: 't3.micro',
       vpc: 'vpc-1234567',
       role: {
         type: 'existing',
         roleArn: 'arn:aws:iam::123456789233:instance-profile/API-DEV',
       },
       sshKey: 'master-dev',
       subnets: ['subnet-12345678', 'subnet-123456789'],
       tcpRules: [
         {
           sourceSG: 'sg-12345678',
           description: 'ssh rule',
           port: 22,
         },
         {
           sourceSG: 'sg-987654321',
           description: 'from load balancer',
           port: 8000,
         },
       ],
       networkProps: [
         {
           healthCheckPath: '/health',
           host: 'abc-test-123.smallcase.com',
           lbArn: 'arn:aws:elasticloadbalancing:ap-south-1:123456789233:loadbalancer/app/API-DEV-External',
           sslEnabled: false,
           port: 8000,
           protocol: 'HTTP',
           zoneName: 'smallcase.com',
           zoneId: '1234567891011'
         },
       ],
       createCodedeployApplication: true,
     });
   }
  }

  new UnknownAPIStackDev(app, 'UnknownAPIStackDev', {
   env: { account: '12345678910', region: 'ap-south-1' },
  });

  app.synth()
  ```

  Please refer [here](/API.md) to check how to use individual resource constructs.

  Install using NPM:

  ```
  npm install @smallcase/aws-cdk-microservice
  ```

  Using yarn

  ```
  yarn add @smallcase/aws-cdk-microservice
  ```

  Configuration helper
  | **Property**                 | **Type**                                  | **Default** | **Description**                                                                                                                                                                                                                                                 |
  |------------------------------|-------------------------------------------|-------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
  | appName                      | string                                    |             | Name of the application to be deployed                                                                                                                                                                                                                          |
  | applicationType?              | string                                    | new         | Type of application, new or existing, if existing, codedeploy will skip it's application creation and create a deployment group in existing application.                                                                                                        |
  | asgMaxSize?                  | number                                    | 2           | Max ASG scale size                                                                                                                                                                                                                                              |
  | asgMinSize?                  | number                                    | 1           | Min ASG scale size                                                                                                                                                                                                                                              |
  | env?                         | string                                    | development | Application environment name                                                                                                                                                                                                                                    |
  | instanceLabels?              | CfnAutoScalingGroup.TagPropertyProperty[] | []          | Tags to apply to the stack                                                                                                                                                                                                                                      |
  | healthCheckPath?             | string                                    | /health     | Health check path for target group                                                                                                                                                                                                                              |
  | port?                        | number                                    | undefined   | Port on which application is running. If not passed, target group will not be created                                                                                                                                                                           |
  | protocol?                    | string (HTTP/HTTPS/GRPC)                  | HTTP        | Service protocol                                                                                                                                                                                                                                                |
  | diskSize?                    | number                                    | 8GB         | Size of root volume for launch template                                                                                                                                                                                                                         |
  | vpc                          | string                                    |             | VPC in which application infra is to be deployed                                                                                                                                                                                                                |
  | role?                        | string                                    |             | Role ARN which is to be used with launch template                                                                                                                                                                                                               |
  | tcpRules                     | IngressRule[]                             | []          | TCP Rules which are to be applied to the security group                                                                                                                                                                                                         |
  | subnets                      | string[]                                  |             | Subnets in which subnets are to be deployed                                                                                                                                                                                                                     |
  | sslEnabled?                  | boolean                                   | false       | Whether to use HTTPS ALB listener, or HTTP ALB listener                                                                                                                                                                                                         |
  | host?                        | string                                    |             | DNS name, for example abc.xyz.com. Won't be created if TG is not created,                                                                                                                                                                                       |
  | lbArn?                       | string                                    |             | Load balancer arn for application load balancing                                                                                                                                                                                                                |
  | sshKey                       | string                                    |             | The ssh key pair name which is to be used                                                                                                                                                                                                                       |
  | diskType?                    | string (GP2/GP3/IO1/IO2)                  | GP3         | Type of disk to be used                                                                                                                                                                                                                                         |
  | createCodedeployApplication? | boolean                                   | false       | Whether to create a codedeploy application and a deployment group for current ENV passed, if applicationType is new, this will not create an application but will create a new deployment group in the same application name, will throw an error if not found. |
  | deploymentPolicies?          | string[]                                  | []          | Deployment group policies which are to be passed, there are major policies already attached which will allow usage of S3 and triggering codedeploy agents on instances.                                                                                         |

  Bootstrap the environment

  ```
  cdk bootstrap
  ```

  Check the changed which are to be deployed

  ```
  ~ -> cdk diff
  Stack my-stack-dev
  ...
  IAM Policy Changes
  ┌───┬──────────────────────────────────────────────────────────────────────────────┬────────────────────────────────────────────────────────────────────┐
  │   │ Resource                                                                     │ Managed Policy ARN                                                 │
  ├───┼──────────────────────────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────────────────┤
  │ + │ ${UnknownAPI/development-UnknownAPI-as/development-UnknownAPI-ASG-stackRole} │ arn:aws:iam::aws:policy/service-role/AmazonEC2SpotFleetTaggingRole │
  │ + │ ${UnknownAPI/development-UnknownAPI-as/development-UnknownAPI-ASG-stackRole} │ arn:aws:iam::aws:policy/ReadOnlyAccess                             │
  │ + │ ${UnknownAPI/development-UnknownAPI-as/development-UnknownAPI-ASG-stackRole} │ arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM           │
  │ + │ ${UnknownAPI/development-UnknownAPI-as/development-UnknownAPI-ASG-stackRole} │ arn:aws:iam::aws:policy/AmazonEC2FullAccess                        │
  └───┴──────────────────────────────────────────────────────────────────────────────┴────────────────────────────────────────────────────────────────────┘
  Security Group Changes
  ┌───┬─────────────────────────────────────────────────────────────────────────────────────┬─────┬────────────┬─────────────────┐
  │   │ Group                                                                               │ Dir │ Protocol   │ Peer            │
  ├───┼─────────────────────────────────────────────────────────────────────────────────────┼─────┼────────────┼─────────────────┤
  │ + │ ${UnknownAPI/development-UnknownAPI-as/development-UnknownAPI-ASG-stack-sg.GroupId} │ In  │ TCP 22     │ sg-12346578     │
  │ + │ ${UnknownAPI/development-UnknownAPI-as/development-UnknownAPI-ASG-stack-sg.GroupId} │ Out │ Everything │ Everyone (IPv4) │
  └───┴─────────────────────────────────────────────────────────────────────────────────────┴─────┴────────────┴─────────────────┘
  (NOTE: There may be security-related changes not in this list. See https://github.com/aws/aws-cdk/issues/1299)

  Resources
  [+] AWS::EC2::SecurityGroup UnknownAPI/development-UnknownAPI-as/development-UnknownAPI-ASG-stack-sg UnknownAPIdevelopmentUnknownAPIasdevelopmentUnknownAPIASGstacksg858F9DBC
  [+] AWS::EC2::SecurityGroupIngress UnknownAPI/development-UnknownAPI-as/development-UnknownAPI-ASG-stack-sg/from mystackdevUnknownAPIdevelopmentUnknownAPIassgf9c56492221D098D02:22 UnknownAPIdevelopmentUnknownAPIasdevelopmentUnknownAPIASGstacksgfrommystackdevUnknownAPIdevelopmentUnknownAPIassgf9c56492221D098D0222498F0E3E
  [+] AWS::IAM::Role UnknownAPI/development-UnknownAPI-as/development-UnknownAPI-ASG-stackRole UnknownAPIdevelopmentUnknownAPIasdevelopmentUnknownAPIASGstackRole3CEFE0B7
  [+] AWS::IAM::Policy UnknownAPI/development-UnknownAPI-as/development-UnknownAPI-ASG-stackRole/DefaultPolicy UnknownAPIdevelopmentUnknownAPIasdevelopmentUnknownAPIASGstackRoleDefaultPolicy8F61E954
  [+] AWS::IAM::InstanceProfile UnknownAPI/development-UnknownAPI-as/development-UnknownAPI-LT/Profile UnknownAPIdevelopmentUnknownAPIasdevelopmentUnknownAPILTProfileC84DF85A
  [+] AWS::EC2::LaunchTemplate UnknownAPI/development-UnknownAPI-as/development-UnknownAPI-LT UnknownAPIdevelopmentUnknownAPIasdevelopmentUnknownAPILT3B54AB26
  [+] AWS::ElasticLoadBalancingV2::TargetGroup UnknownAPI/development-UnknownAPI-as/development-UnknownAPI-TG UnknownAPIdevelopmentUnknownAPIasdevelopmentUnknownAPITG141FD907
  [+] AWS::AutoScaling::AutoScalingGroup UnknownAPI/development-UnknownAPI-as/development-UnknownAPI-ASG UnknownAPIdevelopmentUnknownAPIasdevelopmentUnknownAPIASGEC1B4F9C
  [+] AWS::IAM::Role UnknownAPI/UnknownAPI-deployment-group-role UnknownAPIUnknownAPIdeploymentgrouprole6E048442
  [+] AWS::IAM::Policy UnknownAPI/UnknownAPI-deployment-group-role/DefaultPolicy UnknownAPIUnknownAPIdeploymentgrouproleDefaultPolicy176FEC37
  [+] AWS::CodeDeploy::Application UnknownAPI/development-UnknownAPI-cd/UnknownAPI-development UnknownAPIdevelopmentUnknownAPIcdUnknownAPIdevelopment72A04EEC
  [+] AWS::CodeDeploy::DeploymentGroup UnknownAPI/development-UnknownAPI-cd/development UnknownAPIdevelopmentUnknownAPIcddevelopmentC502CFAD
  ```

  this is a trimmed output.

  Deploy using

  ```
  ~ -> cdk deploy
  ```


pkgId: 7db894014d80cc8a5a624cd378bba7b4971b25b929dbae74b3b20e2e4ffc94bd
name: python-aws-cdk.app-staging-synthesizer-alpha
arch: src
version: 2.163.0a0
epoch: 0
release: 1
summary: Cdk synthesizer for with app-scoped staging stack
url: https://github.com/aws/aws-cdk
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk.app-staging-synthesizer-alpha-2.163.0a0-1.src.rpm
checksum_type: sha256
description:
  <!--END STABILITY BANNER-->
  This library includes constructs aimed at replacing the current model of bootstrapping and providing
  greater control of the bootstrap experience to the CDK user. The important constructs in this library
  are as follows:
  * the `IStagingResources` interface: a framework for an app-level bootstrap stack that handles
    file assets and docker assets.
  * the `DefaultStagingStack`, which is a works-out-of-the-box implementation of the `IStagingResources`
    interface.
  * the `AppStagingSynthesizer`, a new CDK synthesizer that will synthesize CDK applications with
    the staging resources provided.
  > As this library is `experimental`, there are features that are not yet implemented. Please look
  > at the list of [Known Limitations](#known-limitations) before getting started.
  To get started, update your CDK App with a new `defaultStackSynthesizer`:
  ```python
  from aws_cdk.aws_s3 import BucketEncryption
  app = App(
      default_stack_synthesizer=AppStagingSynthesizer.default_resources(
          app_id="my-app-id",  # put a unique id here
          staging_bucket_encryption=BucketEncryption.S3_MANAGED
      )
  )
  ```
  This will introduce a `DefaultStagingStack` in your CDK App and staging assets of your App
  will live in the resources from that stack rather than the CDK Bootstrap stack.
  If you are migrating from a different version of synthesis your updated CDK App will target
  the resources in the `DefaultStagingStack` and no longer be tied to the bootstrapped resources
  in your account.

  In our default bootstrapping process, when you run `cdk bootstrap aws://<account>/<region>`, the following
  resources are created:
  * It creates Roles to assume for cross-account deployments and for Pipeline deployments;
  * It creates staging resources: a global S3 bucket and global ECR repository to hold CDK assets;
  * It creates Roles to write to the S3 bucket and ECR repository;
  Because the bootstrapping resources include regional resources, you need to bootstrap
  every region you plan to deploy to individually. All assets of all CDK apps deploying
  to that account and region will be written to the single S3 Bucket and ECR repository.
  By using the synthesizer in this library, instead of the
  `DefaultStackSynthesizer`, a different set of staging resources will be created
  for every CDK application, and they will be created automatically as part of a
  regular deployment, in a separate Stack that is deployed before your application
  Stacks. The staging resources will be one S3 bucket, and *one ECR repository per
  image*, and Roles necessary to access those buckets and ECR repositories. The
  Roles from the default bootstrap stack are still used (though their use can be
  turned off).
  This has the following advantages:
  * Because staging resources are now application-specific, they can be fully cleaned up when you clean up
    the application.
  * Because there is now one ECR repository per image instead of one ECR repository for all images, it is
    possible to effectively use ECR life cycle rules (for example, retain only the most recent 5 images)
    to cut down on storage costs.
  * Resources between separate CDK Apps are separated so they can be cleaned up and lifecycle
    controlled individually.
  * Because the only shared bootstrapping resources required are Roles, which are global resources,
    you now only need to bootstrap every account in one Region (instead of every Region). This makes it
    easier to do with CloudFormation StackSets.
  For the deployment roles, this synthesizer still uses the Roles from the default
  bootstrap stack, and nothing else. The staging resources from that bootstrap
  stack will be unused. You can customize the template to remove those resources
  if you prefer.  In the future, we will provide a bootstrap stack template with
  only those Roles, specifically for use with this synthesizer.

  The most common use case will be to use the built-in default resources. In this scenario, the
  synthesizer will create a new Staging Stack in each environment the CDK App is deployed to store
  its staging resources. To use this kind of synthesizer, use `AppStagingSynthesizer.defaultResources()`.
  ```python
  from aws_cdk.aws_s3 import BucketEncryption
  app = App(
      default_stack_synthesizer=AppStagingSynthesizer.default_resources(
          app_id="my-app-id",
          staging_bucket_encryption=BucketEncryption.S3_MANAGED,
          
          
          deployment_identities=DeploymentIdentities.default_bootstrap_roles(bootstrap_region="us-east-1")
      )
  )
  ```
  Every CDK App that uses the `DefaultStagingStack` must include an `appId`. This should
  be an identifier unique to the app and is used to differentiate staging resources associated
  with the app.

  The Default Staging Stack includes all the staging resources necessary for CDK Assets. The below example
  is of a CDK App using the `AppStagingSynthesizer` and creating a file asset for the Lambda Function
  source code. As part of the `DefaultStagingStack`, an S3 bucket and IAM role will be created that will be
  used to upload the asset to S3.
  ```python
  from aws_cdk.aws_s3 import BucketEncryption
  app = App(
      default_stack_synthesizer=AppStagingSynthesizer.default_resources(
          app_id="my-app-id",
          staging_bucket_encryption=BucketEncryption.S3_MANAGED
      )
  )
  stack = Stack(app, "my-stack")
  lambda_.Function(stack, "lambda",
      code=lambda_.AssetCode.from_asset(path.join(__dirname, "assets")),
      handler="index.handler",
      runtime=lambda_.Runtime.PYTHON_3_9
  )
  app.synth()
  ```

  You can customize some or all of the roles you'd like to use in the synthesizer as well,
  if all you need is to supply custom roles (and not change anything else in the `DefaultStagingStack`):
  ```python
  from aws_cdk.aws_s3 import BucketEncryption
  app = App(
      default_stack_synthesizer=AppStagingSynthesizer.default_resources(
          app_id="my-app-id",
          staging_bucket_encryption=BucketEncryption.S3_MANAGED,
          deployment_identities=DeploymentIdentities.specify_roles(
              cloud_formation_execution_role=BootstrapRole.from_role_arn("arn:aws:iam::123456789012:role/Execute"),
              deployment_role=BootstrapRole.from_role_arn("arn:aws:iam::123456789012:role/Deploy"),
              lookup_role=BootstrapRole.from_role_arn("arn:aws:iam::123456789012:role/Lookup")
          )
      )
  )
  ```
  Or, you can ask to use the CLI credentials that exist at deploy-time.
  These credentials must have the ability to perform CloudFormation calls,
  lookup resources in your account, and perform CloudFormation deployment.
  For a full list of what is necessary, see `LookupRole`, `DeploymentActionRole`,
  and `CloudFormationExecutionRole` in the
  [bootstrap template](https://github.com/aws/aws-cdk/blob/main/packages/aws-cdk/lib/api/bootstrap/bootstrap-template.yaml).
  ```python
  from aws_cdk.aws_s3 import BucketEncryption
  app = App(
      default_stack_synthesizer=AppStagingSynthesizer.default_resources(
          app_id="my-app-id",
          staging_bucket_encryption=BucketEncryption.S3_MANAGED,
          deployment_identities=DeploymentIdentities.cli_credentials()
      )
  )
  ```
  The default staging stack will create roles to publish to the S3 bucket and ECR repositories,
  assumable by the deployment role. You can also specify an existing IAM role for the
  `fileAssetPublishingRole` or `imageAssetPublishingRole`:
  ```python
  from aws_cdk.aws_s3 import BucketEncryption
  app = App(
      default_stack_synthesizer=AppStagingSynthesizer.default_resources(
          app_id="my-app-id",
          staging_bucket_encryption=BucketEncryption.S3_MANAGED,
          file_asset_publishing_role=BootstrapRole.from_role_arn("arn:aws:iam::123456789012:role/S3Access"),
          image_asset_publishing_role=BootstrapRole.from_role_arn("arn:aws:iam::123456789012:role/ECRAccess")
      )
  )
  ```

  There are two types of assets:
  * Assets used only during deployment. These are used to hand off a large piece of data to another
    service, that will make a private copy of that data. After deployment, the asset is only necessary for
    a potential future rollback.
  * Assets accessed throughout the running life time of the application.
  Examples of assets that are only used at deploy time are CloudFormation Templates and Lambda Code
  bundles. Examples of assets accessed throughout the life time of the application are script files
  downloaded to run in a CodeBuild Project, or on EC2 instance startup. ECR images are always application
  life-time assets. S3 deploy time assets are stored with a `deploy-time/` prefix, and a lifecycle rule will collect them after a configurable number of days.
  Lambda assets are by default marked as deploy time assets:
  ```python

  lambda_.Function(stack, "lambda",
      code=lambda_.AssetCode.from_asset(path.join(__dirname, "assets")),  # lambda marks deployTime = true
      handler="index.handler",
      runtime=lambda_.Runtime.PYTHON_3_9
  )
  ```
  Or, if you want to create your own deploy time asset:
  ```python
  from aws_cdk.aws_s3_assets import Asset

  asset = Asset(stack, "deploy-time-asset",
      deploy_time=True,
      path=path.join(__dirname, "deploy-time-asset")
  )
  ```
  By default, we store deploy time assets for 30 days, but you can change this number by specifying
  `deployTimeFileAssetLifetime`. The number you specify here is how long you will be able to roll back
  to a previous version of an application just by doing a CloudFormation deployment with the old
  template, without rebuilding and republishing assets.
  ```python
  from aws_cdk.aws_s3 import BucketEncryption
  app = App(
      default_stack_synthesizer=AppStagingSynthesizer.default_resources(
          app_id="my-app-id",
          staging_bucket_encryption=BucketEncryption.S3_MANAGED,
          deploy_time_file_asset_lifetime=Duration.days(100)
      )
  )
  ```

  By default, we store a maximum of 3 revisions of a particular docker image asset. This allows
  for smooth faciliation of rollback scenarios where we may reference previous versions of an
  image. When more than 3 revisions of an asset exist in the ECR repository, the oldest one is
  purged.
  To change the number of revisions stored, use `imageAssetVersionCount`:
  ```python
  from aws_cdk.aws_s3 import BucketEncryption
  app = App(
      default_stack_synthesizer=AppStagingSynthesizer.default_resources(
          app_id="my-app-id",
          staging_bucket_encryption=BucketEncryption.S3_MANAGED,
          image_asset_version_count=10
      )
  )
  ```

  By default, the staging resources will be cleaned up on stack deletion. That means that the
  S3 Bucket and ECR Repositories are set to `RemovalPolicy.DESTROY` and have `autoDeleteObjects`
  or `emptyOnDelete` turned on. This creates custom resources under the hood to facilitate
  cleanup. To turn this off, specify `autoDeleteStagingAssets: false`.
  ```python
  from aws_cdk.aws_s3 import BucketEncryption
  app = App(
      default_stack_synthesizer=AppStagingSynthesizer.default_resources(
          app_id="my-app-id",
          staging_bucket_encryption=BucketEncryption.S3_MANAGED,
          auto_delete_staging_assets=False
      )
  )
  ```

  You must explicitly specify the encryption type for the staging bucket via the `stagingBucketEncryption` property. In
  future versions of this package, the default will be `BucketEncryption.S3_MANAGED`.
  In previous versions of this package, the default was to use KMS encryption for the staging bucket. KMS keys cost
  $1/month, which could result in unexpected costs for users who are not aware of this. As we stabilize this module
  we intend to make the default S3-managed encryption, which is free. However, the migration path from KMS to S3
  managed encryption for existing buckets is not straightforward. Therefore, for now, this property is required.
  If you have an existing staging bucket encrypted with a KMS key, you will likely want to set this property to
  `BucketEncryption.KMS`. If you are creating a new staging bucket, you can set this property to
  `BucketEncryption.S3_MANAGED` to avoid the cost of a KMS key.
  You can learn more about choosing a bucket encryption type in the
  [S3 documentation](https://docs.aws.amazon.com/AmazonS3/latest/userguide/serv-side-encryption.html).

  If you want to customize some behavior that is not configurable via properties,
  you can implement your own class that implements `IStagingResources`. To get a head start,
  you can subclass `DefaultStagingStack`.
  ```python
  class CustomStagingStack(DefaultStagingStack):
      pass
  ```
  Or you can roll your own staging resources from scratch, as long as it implements `IStagingResources`.
  ```python
  @jsii.implements(IStagingResources)
  class CustomStagingStack(Stack):
      def __init__(self, scope, id, *, description=None, env=None, stackName=None, tags=None, notificationArns=None, synthesizer=None, terminationProtection=None, analyticsReporting=None, crossRegionReferences=None, permissionsBoundary=None, suppressTemplateIndentation=None):
          super().__init__(scope, id, description=description, env=env, stackName=stackName, tags=tags, notificationArns=notificationArns, synthesizer=synthesizer, terminationProtection=terminationProtection, analyticsReporting=analyticsReporting, crossRegionReferences=crossRegionReferences, permissionsBoundary=permissionsBoundary, suppressTemplateIndentation=suppressTemplateIndentation)
      def add_file(self, *, sourceHash, executable=None, fileName=None, packaging=None, deployTime=None):
          return FileStagingLocation(
              bucket_name="amzn-s3-demo-bucket",
              assume_role_arn="myArn",
              dependency_stack=self
          )
      def add_docker_image(self, *, sourceHash, executable=None, directoryName=None, dockerBuildArgs=None, dockerBuildSecrets=None, dockerBuildSsh=None, dockerBuildTarget=None, dockerFile=None, repositoryName=None, networkMode=None, platform=None, dockerOutputs=None, assetName=None, dockerCacheFrom=None, dockerCacheTo=None, dockerCacheDisabled=None):
          return ImageStagingLocation(
              repo_name="myRepo",
              assume_role_arn="myArn",
              dependency_stack=self
          )
  ```
  Using your custom staging resources means implementing a `CustomFactory` class and calling the
  `AppStagingSynthesizer.customFactory()` static method. This has the benefit of providing a
  custom Staging Stack that can be created in every environment the CDK App is deployed to.
  ```python
  @jsii.implements(IStagingResourcesFactory)
  class CustomFactory:
      def obtain_staging_resources(self, stack, *, environmentString, deployRoleArn=None, qualifier):
          my_app = App.of(stack)
          return CustomStagingStack(my_app, f"CustomStagingStack-{context.environmentString}")
  app = App(
      default_stack_synthesizer=AppStagingSynthesizer.custom_factory(
          factory=CustomFactory(),
          once_per_env=True
      )
  )
  ```

  Use `AppStagingSynthesizer.customResources()` to supply an existing stack as the Staging Stack.
  Make sure that the custom stack you provide implements `IStagingResources`.
  ```python
  resource_app = App()
  resources = CustomStagingStack(resource_app, "CustomStagingStack")
  app = App(
      default_stack_synthesizer=AppStagingSynthesizer.custom_resources(
          resources=resources
      )
  )
  ```

  Since this module is experimental, there are some known limitations:
  * Currently this module does not support CDK Pipelines. You must deploy CDK Apps using this
    synthesizer via `cdk deploy`. Please upvote [this issue](https://github.com/aws/aws-cdk/issues/26118)
    to indicate you want this.
  * This synthesizer only needs a bootstrap stack with Roles, without staging resources. We
    haven't written such a bootstrap stack yet; at the moment you can use the existing modern
    bootstrap stack, the staging resources in them will just go unused. You can customize the
    template to remove them if desired.
  * Due to limitations on the CloudFormation template size, CDK Applications can have
    at most 20 independent ECR images. Please upvote [this issue](https://github.com/aws/aws-cdk/issues/26119)
    if you need more than this.


pkgId: 26f450ba642cd540d6a79e1ad6040af0bb575d289dcea8b5d3236fe624ba8b74
name: python-aws-cdk.asset-awscli-v2
arch: src
version: 2.0.124
epoch: 0
release: 1
summary: An Asset construct that contains the AWS CLI, for use in Lambda Layers
url: https://github.com/cdklabs/awscdk-asset-awscli#readme
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk.asset-awscli-v2-2.0.124-1.src.rpm
checksum_type: sha256
description:
  > This library is currently under development. Do not use!
  <!--END STABILITY BANNER-->
  This module exports a single class called `AwsCliAsset` which is an `s3_assets.Asset` that bundles the AWS CLI v2.
  Usage:
  ```python

  from aws_cdk.asset_awscli_v2 import AwsCliAsset
  import aws_cdk.aws_lambda as lambda_
  import aws_cdk.aws_s3_assets as s3_assets
  from aws_cdk import FileSystem

  awscli = AwsCliAsset(self, "AwsCliCode")
  fn.add_layers(lambda_.LayerVersion(self, "AwsCliLayer",
      code=lambda_.Code.from_bucket(awscli.bucket, awscli.s3_object_key)
  ))
  ```
  The CLI will be installed under `/opt/awscli/aws`.


pkgId: f4240c32e55f0298f33ed4f375af3a88e79e47763432acac67995993a66398ff
name: python-aws-cdk.aws-amplify-alpha
arch: src
version: 2.162.1a0
epoch: 0
release: 1
summary: The CDK Construct Library for AWS::Amplify
url: https://github.com/aws/aws-cdk
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk.aws-amplify-alpha-2.162.1a0-1.src.rpm
checksum_type: sha256
description:
  <!--END STABILITY BANNER-->
  The AWS Amplify Console provides a Git-based workflow for deploying and hosting fullstack serverless web applications. A fullstack serverless app consists of a backend built with cloud resources such as GraphQL or REST APIs, file and data storage, and a frontend built with single page application frameworks such as React, Angular, Vue, or Gatsby.

  To set up an Amplify Console app, define an `App`:
  ```python
  import aws_cdk.aws_codebuild as codebuild
  amplify_app = amplify.App(self, "MyApp",
      source_code_provider=amplify.GitHubSourceCodeProvider(
          owner="<user>",
          repository="<repo>",
          oauth_token=SecretValue.secrets_manager("my-github-token")
      ),
      build_spec=codebuild.BuildSpec.from_object_to_yaml({
          
          "version": "1.0",
          "frontend": {
              "phases": {
                  "pre_build": {
                      "commands": ["yarn"
                      ]
                  },
                  "build": {
                      "commands": ["yarn build"
                      ]
                  }
              },
              "artifacts": {
                  "base_directory": "public",
                  "files": -"**/*"
              }
          }
      })
  )
  ```
  To connect your `App` to GitLab, use the `GitLabSourceCodeProvider`:
  ```python
  amplify_app = amplify.App(self, "MyApp",
      source_code_provider=amplify.GitLabSourceCodeProvider(
          owner="<user>",
          repository="<repo>",
          oauth_token=SecretValue.secrets_manager("my-gitlab-token")
      )
  )
  ```
  To connect your `App` to CodeCommit, use the `CodeCommitSourceCodeProvider`:
  ```python
  import aws_cdk.aws_codecommit as codecommit
  repository = codecommit.Repository(self, "Repo",
      repository_name="my-repo"
  )
  amplify_app = amplify.App(self, "App",
      source_code_provider=amplify.CodeCommitSourceCodeProvider(repository=repository)
  )
  ```
  The IAM role associated with the `App` will automatically be granted the permission
  to pull the CodeCommit repository.
  Add branches:
  ```python

  main = amplify_app.add_branch("main") # `id` will be used as repo branch name
  dev = amplify_app.add_branch("dev",
      performance_mode=True
  )
  dev.add_environment("STAGE", "dev")
  ```
  Auto build and pull request preview are enabled by default.
  Add custom rules for redirection:
  ```python

  amplify_app.add_custom_rule({
      "source": "/docs/specific-filename.html",
      "target": "/documents/different-filename.html",
      "status": amplify.RedirectStatus.TEMPORARY_REDIRECT
  })
  ```
  When working with a single page application (SPA), use the
  `CustomRule.SINGLE_PAGE_APPLICATION_REDIRECT` to set up a 200
  rewrite for all files to `index.html` except for the following
  file extensions: css, gif, ico, jpg, js, png, txt, svg, woff,
  ttf, map, json, webmanifest.
  ```python

  my_single_page_app.add_custom_rule(amplify.CustomRule.SINGLE_PAGE_APPLICATION_REDIRECT)
  ```
  Add a domain and map sub domains to branches:
  ```python



  domain = amplify_app.add_domain("example.com",
      enable_auto_subdomain=True,  # in case subdomains should be auto registered for branches
      auto_subdomain_creation_patterns=["*", "pr*"]
  )
  domain.map_root(main) # map main branch to domain root
  domain.map_sub_domain(main, "www")
  domain.map_sub_domain(dev)
  ```
  To specify a custom certificate for your custom domain use the `customCertificate` property:
  ```python


  domain = amplify_app.add_domain("example.com",
      custom_certificate=custom_certificate
  )
  ```

  Password protect the app with basic auth by specifying the `basicAuth` prop.
  Use `BasicAuth.fromCredentials` when referencing an existing secret:
  ```python
  amplify_app = amplify.App(self, "MyApp",
      source_code_provider=amplify.GitHubSourceCodeProvider(
          owner="<user>",
          repository="<repo>",
          oauth_token=SecretValue.secrets_manager("my-github-token")
      ),
      basic_auth=amplify.BasicAuth.from_credentials("username", SecretValue.secrets_manager("my-github-token"))
  )
  ```
  Use `BasicAuth.fromGeneratedPassword` to generate a password in Secrets Manager:
  ```python
  amplify_app = amplify.App(self, "MyApp",
      source_code_provider=amplify.GitHubSourceCodeProvider(
          owner="<user>",
          repository="<repo>",
          oauth_token=SecretValue.secrets_manager("my-github-token")
      ),
      basic_auth=amplify.BasicAuth.from_generated_password("username")
  )
  ```
  Basic auth can be added to specific branches:
  ```python

  amplify_app.add_branch("feature/next",
      basic_auth=amplify.BasicAuth.from_generated_password("username")
  )
  ```

  Use the `autoBranchCreation` and `autoBranchDeletion` props to control creation/deletion
  of branches:
  ```python
  amplify_app = amplify.App(self, "MyApp",
      source_code_provider=amplify.GitHubSourceCodeProvider(
          owner="<user>",
          repository="<repo>",
          oauth_token=SecretValue.secrets_manager("my-github-token")
      ),
      auto_branch_creation=amplify.AutoBranchCreation( # Automatically connect branches that match a pattern set
          patterns=["feature/*", "test/*"]),
      auto_branch_deletion=True
  )
  ```

  Use the `customResponseHeaders` prop to configure custom response headers for an Amplify app:
  ```python
  amplify_app = amplify.App(self, "App",
      source_code_provider=amplify.GitHubSourceCodeProvider(
          owner="<user>",
          repository="<repo>",
          oauth_token=SecretValue.secrets_manager("my-github-token")
      ),
      custom_response_headers=[amplify.CustomResponseHeader(
          pattern="*.json",
          headers={
              "custom-header-name-1": "custom-header-value-1",
              "custom-header-name-2": "custom-header-value-2"
          }
      ), amplify.CustomResponseHeader(
          pattern="/path/*",
          headers={
              "custom-header-name-1": "custom-header-value-2"
          }
      )
      ]
  )
  ```

  Setting the `platform` field on the Amplify `App` construct can be used to control whether the app will host only static assets or server side rendered assets in addition to static. By default, the value is set to `WEB` (static only), however, server side rendering can be turned on by setting to `WEB_COMPUTE` as follows:
  ```python
  amplify_app = amplify.App(self, "MyApp",
      platform=amplify.Platform.WEB_COMPUTE
  )
  ```

  Amplify uses Amazon CloudFront to manage the caching configuration for your hosted applications. A cache configuration is applied to each app to optimize for the best performance.
  Setting the `cacheConfigType` field on the Amplify `App` construct can be used to control cache configguration. By default, the value is set to `AMPLIFY_MANAGED`. If you want to exclude all cookies from the cache key, set `AMPLIFY_MANAGED_NO_COOKIES`.
  For more information, see [Managing the cache configuration for an app](https://docs.aws.amazon.com/amplify/latest/userguide/caching.html).
  ```python
  amplify_app = amplify.App(self, "MyApp",
      cache_config_type=amplify.CacheConfigType.AMPLIFY_MANAGED_NO_COOKIES
  )
  ```

  `sourceCodeProvider` is optional; when this is not specified the Amplify app can be deployed to using `.zip` packages. The `asset` property can be used to deploy S3 assets to Amplify as part of the CDK:
  ```python
  import aws_cdk.aws_s3_assets as assets


  branch = amplify_app.add_branch("dev", asset=asset)
  ```


pkgId: 1757350867a5894974a01a3656dcc080d27e1b5f2fc6bd2ba50ea1ca12836e0f
name: python-aws-cdk.aws-apigatewayv2-alpha
arch: src
version: 2.114.1a0
epoch: 0
release: 1
summary: This module is deprecated. All constructs are now available under aws-cdk-lib/aws-apigatewayv2
url: https://github.com/aws/aws-cdk
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk.aws-apigatewayv2-alpha-2.114.1a0-1.src.rpm
checksum_type: sha256
description:
  <!--END STABILITY BANNER-->
  All constructs moved to aws-cdk-lib/aws-apigatewayv2.

  * [Introduction](#introduction)
  * [HTTP API](#http-api)
    * [Defining HTTP APIs](#defining-http-apis)
    * [Cross Origin Resource Sharing (CORS)](#cross-origin-resource-sharing-cors)
    * [Publishing HTTP APIs](#publishing-http-apis)
    * [Custom Domain](#custom-domain)
    * [Mutual TLS](#mutual-tls-mtls)
    * [Managing access to HTTP APIs](#managing-access-to-http-apis)
    * [Metrics](#metrics)
    * [VPC Link](#vpc-link)
    * [Private Integration](#private-integration)
  * [WebSocket API](#websocket-api)
    * [Manage Connections Permission](#manage-connections-permission)
    * [Managing access to WebSocket APIs](#managing-access-to-websocket-apis)

  Amazon API Gateway is an AWS service for creating, publishing, maintaining, monitoring, and securing REST, HTTP, and WebSocket
  APIs at any scale. API developers can create APIs that access AWS or other web services, as well as data stored in the AWS Cloud.
  As an API Gateway API developer, you can create APIs for use in your own client applications. Read the
  [Amazon API Gateway Developer Guide](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html).
  This module supports features under [API Gateway v2](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/AWS_ApiGatewayV2.html)
  that lets users set up Websocket and HTTP APIs.
  REST APIs can be created using the `aws-cdk-lib/aws-apigateway` module.
  HTTP and Websocket APIs use the same CloudFormation resources under the hood. However, this module separates them into two separate constructs for a more efficient abstraction since there are a number of CloudFormation properties that specifically apply only to each type of API.

  HTTP APIs enable creation of RESTful APIs that integrate with AWS Lambda functions, known as Lambda proxy integration,
  or to any routable HTTP endpoint, known as HTTP proxy integration.

  HTTP APIs have two fundamental concepts - Routes and Integrations.
  Routes direct incoming API requests to backend resources. Routes consist of two parts: an HTTP method and a resource
  path, such as, `GET /books`. Learn more at [Working with
  routes](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-routes.html). Use the `ANY` method
  to match any methods for a route that are not explicitly defined.
  Integrations define how the HTTP API responds when a client reaches a specific Route. HTTP APIs support Lambda proxy
  integration, HTTP proxy integration and, AWS service integrations, also known as private integrations. Learn more at
  [Configuring integrations](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations.html).
  Integrations are available at the `aws-apigatewayv2-integrations` module and more information is available in that module.
  As an early example, we have a website for a bookstore where the following code snippet configures a route `GET /books` with an HTTP proxy integration. All other HTTP method calls to `/books` route to a default lambda proxy for the bookstore.
  ```python
  from aws_cdk.aws_apigatewayv2_integrations_alpha import HttpUrlIntegration, HttpLambdaIntegration

  get_books_integration = HttpUrlIntegration("GetBooksIntegration", "https://get-books-proxy.example.com")
  book_store_default_integration = HttpLambdaIntegration("BooksIntegration", book_store_default_fn)
  http_api = apigwv2.HttpApi(self, "HttpApi")
  http_api.add_routes(
      path="/books",
      methods=[apigwv2.HttpMethod.GET],
      integration=get_books_integration
  )
  http_api.add_routes(
      path="/books",
      methods=[apigwv2.HttpMethod.ANY],
      integration=book_store_default_integration
  )
  ```
  The URL to the endpoint can be retrieved via the `apiEndpoint` attribute. By default this URL is enabled for clients. Use `disableExecuteApiEndpoint` to disable it.
  ```python
  http_api = apigwv2.HttpApi(self, "HttpApi",
      disable_execute_api_endpoint=True
  )
  ```
  The `defaultIntegration` option while defining HTTP APIs lets you create a default catch-all integration that is
  matched when a client reaches a route that is not explicitly defined.
  ```python
  from aws_cdk.aws_apigatewayv2_integrations_alpha import HttpUrlIntegration
  apigwv2.HttpApi(self, "HttpProxyApi",
      default_integration=HttpUrlIntegration("DefaultIntegration", "https://example.com")
  )
  ```

  [Cross-origin resource sharing (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) is a browser security
  feature that restricts HTTP requests that are initiated from scripts running in the browser. Enabling CORS will allow
  requests to your API from a web application hosted in a domain different from your API domain.
  When configured CORS for an HTTP API, API Gateway automatically sends a response to preflight `OPTIONS` requests, even
  if there isn't an `OPTIONS` route configured. Note that, when this option is used, API Gateway will ignore CORS headers
  returned from your backend integration. Learn more about [Configuring CORS for an HTTP
  API](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-cors.html).
  The `corsPreflight` option lets you specify a CORS configuration for an API.
  ```python
  apigwv2.HttpApi(self, "HttpProxyApi",
      cors_preflight=apigwv2.CorsPreflightOptions(
          allow_headers=["Authorization"],
          allow_methods=[apigwv2.CorsHttpMethod.GET, apigwv2.CorsHttpMethod.HEAD, apigwv2.CorsHttpMethod.OPTIONS, apigwv2.CorsHttpMethod.POST
          ],
          allow_origins=["*"],
          max_age=Duration.days(10)
      )
  )
  ```

  A Stage is a logical reference to a lifecycle state of your API (for example, `dev`, `prod`, `beta`, or `v2`). API
  stages are identified by their stage name. Each stage is a named reference to a deployment of the API made available for
  client applications to call.
  Use `HttpStage` to create a Stage resource for HTTP APIs. The following code sets up a Stage, whose URL is available at
  `https://{api_id}.execute-api.{region}.amazonaws.com/beta`.
  ```python

  apigwv2.HttpStage(self, "Stage",
      http_api=api,
      stage_name="beta"
  )
  ```
  If you omit the `stageName` will create a `$default` stage. A `$default` stage is one that is served from the base of
  the API's URL - `https://{api_id}.execute-api.{region}.amazonaws.com/`.
  Note that, `HttpApi` will always creates a `$default` stage, unless the `createDefaultStage` property is unset.

  Custom domain names are simpler and more intuitive URLs that you can provide to your API users. Custom domain name are associated to API stages.
  The code snippet below creates a custom domain and configures a default domain mapping for your API that maps the
  custom domain to the `$default` stage of the API.
  ```python
  import aws_cdk.aws_certificatemanager as acm
  from aws_cdk.aws_apigatewayv2_integrations_alpha import HttpLambdaIntegration

  cert_arn = "arn:aws:acm:us-east-1:111111111111:certificate"
  domain_name = "example.com"
  dn = apigwv2.DomainName(self, "DN",
      domain_name=domain_name,
      certificate=acm.Certificate.from_certificate_arn(self, "cert", cert_arn)
  )
  api = apigwv2.HttpApi(self, "HttpProxyProdApi",
      default_integration=HttpLambdaIntegration("DefaultIntegration", handler),
      
      default_domain_mapping=apigwv2.DomainMappingOptions(
          domain_name=dn,
          mapping_key="foo"
      )
  )
  ```
  To migrate a domain endpoint from one type to another, you can add a new endpoint configuration via `addEndpoint()`
  and then configure DNS records to route traffic to the new endpoint. After that, you can remove the previous endpoint configuration.
  Learn more at [Migrating a custom domain name](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-regional-api-custom-domain-migrate.html)
  To associate a specific `Stage` to a custom domain mapping -
  ```python


  api.add_stage("beta",
      stage_name="beta",
      auto_deploy=True,
      
      domain_mapping=apigwv2.DomainMappingOptions(
          domain_name=dn,
          mapping_key="bar"
      )
  )
  ```
  The same domain name can be associated with stages across different `HttpApi` as so -
  ```python
  from aws_cdk.aws_apigatewayv2_integrations_alpha import HttpLambdaIntegration


  api_demo = apigwv2.HttpApi(self, "DemoApi",
      default_integration=HttpLambdaIntegration("DefaultIntegration", handler),
      
      default_domain_mapping=apigwv2.DomainMappingOptions(
          domain_name=dn,
          mapping_key="demo"
      )
  )
  ```
  The `mappingKey` determines the base path of the URL with the custom domain. Each custom domain is only allowed
  to have one API mapping with undefined `mappingKey`. If more than one API mappings are specified, `mappingKey` will be required for all of them. In the sample above, the custom domain is associated
  with 3 API mapping resources across different APIs and Stages.
  |        API     |     Stage   |   URL  |
  | :------------: | :---------: | :----: |
  | api | $default  |   `https://${domainName}/foo`  |
  | api | beta  |   `https://${domainName}/bar`  |
  | apiDemo | $default  |   `https://${domainName}/demo`  |
  You can retrieve the full domain URL with mapping key using the `domainUrl` property as so -
  ```python

  demo_domain_url = api_demo.default_stage.domain_url
  ```

  Mutual TLS can be configured to limit access to your API based by using client certificates instead of (or as an extension of) using authorization headers.
  ```python
  import aws_cdk.aws_s3 as s3
  import aws_cdk.aws_certificatemanager as acm

  cert_arn = "arn:aws:acm:us-east-1:111111111111:certificate"
  domain_name = "example.com"
  apigwv2.DomainName(self, "DomainName",
      domain_name=domain_name,
      certificate=acm.Certificate.from_certificate_arn(self, "cert", cert_arn),
      mtls=apigwv2.MTLSConfig(
          bucket=bucket,
          key="someca.pem",
          version="version"
      )
  )
  ```
  Instructions for configuring your trust store can be found [here](https://aws.amazon.com/blogs/compute/introducing-mutual-tls-authentication-for-amazon-api-gateway/)

  API Gateway supports multiple mechanisms for [controlling and managing access to your HTTP
  API](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-access-control.html) through authorizers.
  These authorizers can be found in the [APIGatewayV2-Authorizers](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-apigatewayv2-authorizers-readme.html) constructs library.

  The API Gateway v2 service sends metrics around the performance of HTTP APIs to Amazon CloudWatch.
  These metrics can be referred to using the metric APIs available on the `HttpApi` construct.
  The APIs with the `metric` prefix can be used to get reference to specific metrics for this API. For example,
  the method below refers to the client side errors metric for this API.
  ```python
  api = apigwv2.HttpApi(self, "my-api")
  client_error_metric = api.metric_client_error()
  ```
  Please note that this will return a metric for all the stages defined in the api. It is also possible to refer to metrics for a specific Stage using
  the `metric` methods from the `Stage` construct.
  ```python
  api = apigwv2.HttpApi(self, "my-api")
  stage = apigwv2.HttpStage(self, "Stage",
      http_api=api
  )
  client_error_metric = stage.metric_client_error()
  ```

  Private integrations let HTTP APIs connect with AWS resources that are placed behind a VPC. These are usually Application
  Load Balancers, Network Load Balancers or a Cloud Map service. The `VpcLink` construct enables this integration.
  The following code creates a `VpcLink` to a private VPC.
  ```python
  import aws_cdk.aws_ec2 as ec2
  import aws_cdk.aws_elasticloadbalancingv2 as elb
  from aws_cdk.aws_apigatewayv2_integrations_alpha import HttpAlbIntegration
  vpc = ec2.Vpc(self, "VPC")
  alb = elb.ApplicationLoadBalancer(self, "AppLoadBalancer", vpc=vpc)
  vpc_link = apigwv2.VpcLink(self, "VpcLink", vpc=vpc)

  alb_integration = HttpAlbIntegration("ALBIntegration", alb.listeners[0])
  ```
  Any existing `VpcLink` resource can be imported into the CDK app via the `VpcLink.fromVpcLinkAttributes()`.
  ```python
  import aws_cdk.aws_ec2 as ec2

  awesome_link = apigwv2.VpcLink.from_vpc_link_attributes(self, "awesome-vpc-link",
      vpc_link_id="us-east-1_oiuR12Abd",
      vpc=vpc
  )
  ```

  Private integrations enable integrating an HTTP API route with private resources in a VPC, such as Application Load Balancers or
  Amazon ECS container-based applications.  Using private integrations, resources in a VPC can be exposed for access by
  clients outside of the VPC.
  These integrations can be found in the [aws-apigatewayv2-integrations](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-apigatewayv2-integrations-readme.html) constructs library.

  A WebSocket API in API Gateway is a collection of WebSocket routes that are integrated with backend HTTP endpoints,
  Lambda functions, or other AWS services. You can use API Gateway features to help you with all aspects of the API
  lifecycle, from creation through monitoring your production APIs. [Read more](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-overview.html)
  WebSocket APIs have two fundamental concepts - Routes and Integrations.
  WebSocket APIs direct JSON messages to backend integrations based on configured routes. (Non-JSON messages are directed
  to the configured `$default` route.)
  Integrations define how the WebSocket API behaves when a client reaches a specific Route. Learn more at
  [Configuring integrations](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-integration-requests.html).
  Integrations are available in the `aws-apigatewayv2-integrations` module and more information is available in that module.
  To add the default WebSocket routes supported by API Gateway (`$connect`, `$disconnect` and `$default`), configure them as part of api props:
  ```python
  from aws_cdk.aws_apigatewayv2_integrations_alpha import WebSocketLambdaIntegration



  web_socket_api = apigwv2.WebSocketApi(self, "mywsapi",
      connect_route_options=apigwv2.WebSocketRouteOptions(integration=WebSocketLambdaIntegration("ConnectIntegration", connect_handler)),
      disconnect_route_options=apigwv2.WebSocketRouteOptions(integration=WebSocketLambdaIntegration("DisconnectIntegration", disconnect_handler)),
      default_route_options=apigwv2.WebSocketRouteOptions(integration=WebSocketLambdaIntegration("DefaultIntegration", default_handler))
  )
  apigwv2.WebSocketStage(self, "mystage",
      web_socket_api=web_socket_api,
      stage_name="dev",
      auto_deploy=True
  )
  ```
  To retrieve a websocket URL and a callback URL:
  ```python

  web_socket_uRL = web_socket_stage.url

  callback_uRL = web_socket_stage.callback_url
  ```
  To add any other route:
  ```python
  from aws_cdk.aws_apigatewayv2_integrations_alpha import WebSocketLambdaIntegration

  web_socket_api = apigwv2.WebSocketApi(self, "mywsapi")
  web_socket_api.add_route("sendmessage",
      integration=WebSocketLambdaIntegration("SendMessageIntegration", message_handler)
  )
  ```
  To add a route that can return a result:
  ```python
  from aws_cdk.aws_apigatewayv2_integrations_alpha import WebSocketLambdaIntegration

  web_socket_api = apigwv2.WebSocketApi(self, "mywsapi")
  web_socket_api.add_route("sendmessage",
      integration=WebSocketLambdaIntegration("SendMessageIntegration", message_handler),
      return_response=True
  )
  ```
  To import an existing WebSocketApi:
  ```python
  web_socket_api = apigwv2.WebSocketApi.from_web_socket_api_attributes(self, "mywsapi", web_socket_id="api-1234")
  ```

  Grant permission to use API Gateway Management API of a WebSocket API by calling the `grantManageConnections` API.
  You can use Management API to send a callback message to a connected client, get connection information, or disconnect the client. Learn more at [Use @connections commands in your backend service](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-how-to-call-websocket-api-connections.html).
  ```python

  web_socket_api = apigwv2.WebSocketApi(self, "mywsapi")
  stage = apigwv2.WebSocketStage(self, "mystage",
      web_socket_api=web_socket_api,
      stage_name="dev"
  )

  stage.grant_management_api_access(fn)

  web_socket_api.grant_manage_connections(fn)
  ```

  API Gateway supports multiple mechanisms for [controlling and managing access to a WebSocket API](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-control-access.html) through authorizers.
  These authorizers can be found in the [APIGatewayV2-Authorizers](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-apigatewayv2-authorizers-readme.html) constructs library.

  Websocket APIs also support usage of API Keys. An API Key is a key that is used to grant access to an API. These are useful for controlling and tracking access to an API, when used together with [usage plans](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-usage-plans.html). These together allow you to configure controls around API access such as quotas and throttling, along with per-API Key metrics on usage.
  To require an API Key when accessing the Websocket API:
  ```python
  web_socket_api = apigwv2.WebSocketApi(self, "mywsapi",
      api_key_selection_expression=apigwv2.WebSocketApiKeySelectionExpression.HEADER_X_API_KEY
  )
  ```


pkgId: fe6654c4276de0f2a93bf5130dea6d66bc584422c1b867ce7fe2a68feb637b9d
name: python-aws-cdk.aws-apprunner-alpha
arch: src
version: 2.162.1a0
epoch: 0
release: 1
summary: The CDK Construct Library for AWS::AppRunner
url: https://github.com/aws/aws-cdk
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk.aws-apprunner-alpha-2.162.1a0-1.src.rpm
checksum_type: sha256
description:
  <!--END STABILITY BANNER-->
  This module is part of the [AWS Cloud Development Kit](https://github.com/aws/aws-cdk) project.
  ```python
  import aws_cdk.aws_apprunner_alpha as apprunner
  ```

  AWS App Runner is a fully managed service that makes it easy for developers to quickly deploy containerized web applications and APIs, at scale and with no prior infrastructure experience required. Start with your source code or a container image. App Runner automatically builds and deploys the web application and load balances traffic with encryption. App Runner also scales up or down automatically to meet your traffic needs. With App Runner, rather than thinking about servers or scaling, you have more time to focus on your applications.

  The `Service` construct allows you to create AWS App Runner services with `ECR Public`, `ECR` or `Github` with the `source` property in the following scenarios:
  * `Source.fromEcr()` - To define the source repository from `ECR`.
  * `Source.fromEcrPublic()` - To define the source repository from `ECR Public`.
  * `Source.fromGitHub()` - To define the source repository from the `Github repository`.
  * `Source.fromAsset()` - To define the source from local asset directory.
  The `Service` construct implements `IGrantable`.

  To create a `Service` with ECR Public:
  ```python
  apprunner.Service(self, "Service",
      source=apprunner.Source.from_ecr_public(
          image_configuration=apprunner.ImageConfiguration(port=8000),
          image_identifier="public.ecr.aws/aws-containers/hello-app-runner:latest"
      )
  )
  ```

  To create a `Service` from an existing ECR repository:
  ```python
  import aws_cdk.aws_ecr as ecr
  apprunner.Service(self, "Service",
      source=apprunner.Source.from_ecr(
          image_configuration=apprunner.ImageConfiguration(port=80),
          repository=ecr.Repository.from_repository_name(self, "NginxRepository", "nginx"),
          tag_or_digest="latest"
      )
  )
  ```
  To create a `Service` from local docker image asset directory built and pushed to Amazon ECR:
  You can specify whether to enable continuous integration from the source repository with the `autoDeploymentsEnabled` flag.
  ```python
  import aws_cdk.aws_ecr_assets as assets
  image_asset = assets.DockerImageAsset(self, "ImageAssets",
      directory=path.join(__dirname, "docker.assets")
  )
  apprunner.Service(self, "Service",
      source=apprunner.Source.from_asset(
          image_configuration=apprunner.ImageConfiguration(port=8000),
          asset=image_asset
      ),
      auto_deployments_enabled=True
  )
  ```

  To create a `Service` from the GitHub repository, you need to specify an existing App Runner `Connection`.
  See [Managing App Runner connections](https://docs.aws.amazon.com/apprunner/latest/dg/manage-connections.html) for more details.
  ```python
  apprunner.Service(self, "Service",
      source=apprunner.Source.from_git_hub(
          repository_url="https://github.com/aws-containers/hello-app-runner",
          branch="main",
          configuration_source=apprunner.ConfigurationSourceType.REPOSITORY,
          connection=apprunner.GitHubConnection.from_connection_arn("CONNECTION_ARN")
      )
  )
  ```
  Use `codeConfigurationValues` to override configuration values with the `API` configuration source type.
  ```python
  apprunner.Service(self, "Service",
      source=apprunner.Source.from_git_hub(
          repository_url="https://github.com/aws-containers/hello-app-runner",
          branch="main",
          configuration_source=apprunner.ConfigurationSourceType.API,
          code_configuration_values=apprunner.CodeConfigurationValues(
              runtime=apprunner.Runtime.PYTHON_3,
              port="8000",
              start_command="python app.py",
              build_command="yum install -y pycairo && pip install -r requirements.txt"
          ),
          connection=apprunner.GitHubConnection.from_connection_arn("CONNECTION_ARN")
      )
  )
  ```

  You are allowed to define `instanceRole` and `accessRole` for the `Service`.
  `instanceRole` - The IAM role that provides permissions to your App Runner service. These are permissions that
  your code needs when it calls any AWS APIs. If not defined, a new instance role will be generated
  when required.
  To add IAM policy statements to this role, use `addToRolePolicy()`:
  ```python
  import aws_cdk.aws_iam as iam
  service = apprunner.Service(self, "Service",
      source=apprunner.Source.from_ecr_public(
          image_configuration=apprunner.ImageConfiguration(port=8000),
          image_identifier="public.ecr.aws/aws-containers/hello-app-runner:latest"
      )
  )
  service.add_to_role_policy(iam.PolicyStatement(
      effect=iam.Effect.ALLOW,
      actions=["s3:GetObject"],
      resources=["*"]
  ))
  ```
  `accessRole` - The IAM role that grants the App Runner service access to a source repository. It's required for
  ECR image repositories (but not for ECR Public repositories). If not defined, a new access role will be generated
  when required.
  See [App Runner IAM Roles](https://docs.aws.amazon.com/apprunner/latest/dg/security_iam_service-with-iam.html#security_iam_service-with-iam-roles) for more details.

  To associate an App Runner service with a custom Auto Scaling Configuration, define `autoScalingConfiguration` for the service.
  ```python
  auto_scaling_configuration = apprunner.AutoScalingConfiguration(self, "AutoScalingConfiguration",
      auto_scaling_configuration_name="MyAutoScalingConfiguration",
      max_concurrency=150,
      max_size=20,
      min_size=5
  )
  apprunner.Service(self, "DemoService",
      source=apprunner.Source.from_ecr_public(
          image_configuration=apprunner.ImageConfiguration(port=8000),
          image_identifier="public.ecr.aws/aws-containers/hello-app-runner:latest"
      ),
      auto_scaling_configuration=auto_scaling_configuration
  )
  ```

  To associate an App Runner service with a custom VPC, define `vpcConnector` for the service.
  ```python
  import aws_cdk.aws_ec2 as ec2
  vpc = ec2.Vpc(self, "Vpc",
      ip_addresses=ec2.IpAddresses.cidr("10.0.0.0/16")
  )
  vpc_connector = apprunner.VpcConnector(self, "VpcConnector",
      vpc=vpc,
      vpc_subnets=vpc.select_subnets(subnet_type=ec2.SubnetType.PUBLIC),
      vpc_connector_name="MyVpcConnector"
  )
  apprunner.Service(self, "Service",
      source=apprunner.Source.from_ecr_public(
          image_configuration=apprunner.ImageConfiguration(port=8000),
          image_identifier="public.ecr.aws/aws-containers/hello-app-runner:latest"
      ),
      vpc_connector=vpc_connector
  )
  ```

  To use dual stack (IPv4 and IPv6) for your incoming public network configuration, set `ipAddressType` to `IpAddressType.DUAL_STACK`.
  ```python
  apprunner.Service(self, "Service",
      source=apprunner.Source.from_ecr_public(
          image_configuration=apprunner.ImageConfiguration(port=8000),
          image_identifier="public.ecr.aws/aws-containers/hello-app-runner:latest"
      ),
      ip_address_type=apprunner.IpAddressType.DUAL_STACK
  )
  ```
  **Note**: Currently, App Runner supports dual stack for only Public endpoint.
  Only IPv4 is supported for Private endpoint.
  If you update a service that's using dual-stack Public endpoint to a Private endpoint,
  your App Runner service will default to support only IPv4 for Private endpoint and fail
  to receive traffic originating from IPv6 endpoint.

  To include environment variables integrated with AWS Secrets Manager, use the `environmentSecrets` attribute.
  You can use the `addSecret` method from the App Runner `Service` class to include secrets from outside the
  service definition.
  ```python
  import aws_cdk.aws_secretsmanager as secretsmanager
  import aws_cdk.aws_ssm as ssm

  secret = secretsmanager.Secret(stack, "Secret")
  parameter = ssm.StringParameter.from_secure_string_parameter_attributes(stack, "Parameter",
      parameter_name="/name",
      version=1
  )
  service = apprunner.Service(stack, "Service",
      source=apprunner.Source.from_ecr_public(
          image_configuration=apprunner.ImageConfiguration(
              port=8000,
              environment_secrets={
                  "SECRET": apprunner.Secret.from_secrets_manager(secret),
                  "PARAMETER": apprunner.Secret.from_ssm_parameter(parameter),
                  "SECRET_ID": apprunner.Secret.from_secrets_manager_version(secret, version_id="version-id"),
                  "SECRET_STAGE": apprunner.Secret.from_secrets_manager_version(secret, version_stage="version-stage")
              }
          ),
          image_identifier="public.ecr.aws/aws-containers/hello-app-runner:latest"
      )
  )
  service.add_secret("LATER_SECRET", apprunner.Secret.from_secrets_manager(secret, "field"))
  ```

  To use a customer managed key for your source encryption, use the `kmsKey` attribute.
  ```python
  import aws_cdk.aws_kms as kms

  apprunner.Service(self, "Service",
      source=apprunner.Source.from_ecr_public(
          image_configuration=apprunner.ImageConfiguration(port=8000),
          image_identifier="public.ecr.aws/aws-containers/hello-app-runner:latest"
      ),
      kms_key=kms_key
  )
  ```

  To configure the health check for the service, use the `healthCheck` attribute.
  You can specify it by static methods `HealthCheck.http` or `HealthCheck.tcp`.
  ```python
  apprunner.Service(self, "Service",
      source=apprunner.Source.from_ecr_public(
          image_configuration=apprunner.ImageConfiguration(port=8000),
          image_identifier="public.ecr.aws/aws-containers/hello-app-runner:latest"
      ),
      health_check=apprunner.HealthCheck.http(
          healthy_threshold=5,
          interval=Duration.seconds(10),
          path="/",
          timeout=Duration.seconds(10),
          unhealthy_threshold=10
      )
  )
  ```

  To associate an App Runner service with a custom observability configuration, use the `observabilityConfiguration` property.
  ```python
  observability_configuration = apprunner.ObservabilityConfiguration(self, "ObservabilityConfiguration",
      observability_configuration_name="MyObservabilityConfiguration",
      trace_configuration_vendor=apprunner.TraceConfigurationVendor.AWSXRAY
  )
  apprunner.Service(self, "DemoService",
      source=apprunner.Source.from_ecr_public(
          image_configuration=apprunner.ImageConfiguration(port=8000),
          image_identifier="public.ecr.aws/aws-containers/hello-app-runner:latest"
      ),
      observability_configuration=observability_configuration
  )
  ```


pkgId: 15861f6ce4d564d56e4817f3599880627d001b7a30a625c920d8cfb2c694addf
name: python-aws-cdk.aws-apprunner-alpha
arch: src
version: 2.167.0a0
epoch: 0
release: 1
summary: The CDK Construct Library for AWS::AppRunner
url: https://github.com/aws/aws-cdk
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk.aws-apprunner-alpha-2.167.0a0-1.src.rpm
checksum_type: sha256
description:
  <!--END STABILITY BANNER-->
  This module is part of the [AWS Cloud Development Kit](https://github.com/aws/aws-cdk) project.
  ```python
  import aws_cdk.aws_apprunner_alpha as apprunner
  ```

  AWS App Runner is a fully managed service that makes it easy for developers to quickly deploy containerized web applications and APIs, at scale and with no prior infrastructure experience required. Start with your source code or a container image. App Runner automatically builds and deploys the web application and load balances traffic with encryption. App Runner also scales up or down automatically to meet your traffic needs. With App Runner, rather than thinking about servers or scaling, you have more time to focus on your applications.

  The `Service` construct allows you to create AWS App Runner services with `ECR Public`, `ECR` or `Github` with the `source` property in the following scenarios:
  * `Source.fromEcr()` - To define the source repository from `ECR`.
  * `Source.fromEcrPublic()` - To define the source repository from `ECR Public`.
  * `Source.fromGitHub()` - To define the source repository from the `Github repository`.
  * `Source.fromAsset()` - To define the source from local asset directory.
  The `Service` construct implements `IGrantable`.

  To create a `Service` with ECR Public:
  ```python
  apprunner.Service(self, "Service",
      source=apprunner.Source.from_ecr_public(
          image_configuration=apprunner.ImageConfiguration(port=8000),
          image_identifier="public.ecr.aws/aws-containers/hello-app-runner:latest"
      )
  )
  ```

  To create a `Service` from an existing ECR repository:
  ```python
  import aws_cdk.aws_ecr as ecr
  apprunner.Service(self, "Service",
      source=apprunner.Source.from_ecr(
          image_configuration=apprunner.ImageConfiguration(port=80),
          repository=ecr.Repository.from_repository_name(self, "NginxRepository", "nginx"),
          tag_or_digest="latest"
      )
  )
  ```
  To create a `Service` from local docker image asset directory built and pushed to Amazon ECR:
  You can specify whether to enable continuous integration from the source repository with the `autoDeploymentsEnabled` flag.
  ```python
  import aws_cdk.aws_ecr_assets as assets
  image_asset = assets.DockerImageAsset(self, "ImageAssets",
      directory=path.join(__dirname, "docker.assets")
  )
  apprunner.Service(self, "Service",
      source=apprunner.Source.from_asset(
          image_configuration=apprunner.ImageConfiguration(port=8000),
          asset=image_asset
      ),
      auto_deployments_enabled=True
  )
  ```

  To create a `Service` from the GitHub repository, you need to specify an existing App Runner `Connection`.
  See [Managing App Runner connections](https://docs.aws.amazon.com/apprunner/latest/dg/manage-connections.html) for more details.
  ```python
  apprunner.Service(self, "Service",
      source=apprunner.Source.from_git_hub(
          repository_url="https://github.com/aws-containers/hello-app-runner",
          branch="main",
          configuration_source=apprunner.ConfigurationSourceType.REPOSITORY,
          connection=apprunner.GitHubConnection.from_connection_arn("CONNECTION_ARN")
      )
  )
  ```
  Use `codeConfigurationValues` to override configuration values with the `API` configuration source type.
  ```python
  apprunner.Service(self, "Service",
      source=apprunner.Source.from_git_hub(
          repository_url="https://github.com/aws-containers/hello-app-runner",
          branch="main",
          configuration_source=apprunner.ConfigurationSourceType.API,
          code_configuration_values=apprunner.CodeConfigurationValues(
              runtime=apprunner.Runtime.PYTHON_3,
              port="8000",
              start_command="python app.py",
              build_command="yum install -y pycairo && pip install -r requirements.txt"
          ),
          connection=apprunner.GitHubConnection.from_connection_arn("CONNECTION_ARN")
      )
  )
  ```

  You are allowed to define `instanceRole` and `accessRole` for the `Service`.
  `instanceRole` - The IAM role that provides permissions to your App Runner service. These are permissions that
  your code needs when it calls any AWS APIs. If not defined, a new instance role will be generated
  when required.
  To add IAM policy statements to this role, use `addToRolePolicy()`:
  ```python
  import aws_cdk.aws_iam as iam
  service = apprunner.Service(self, "Service",
      source=apprunner.Source.from_ecr_public(
          image_configuration=apprunner.ImageConfiguration(port=8000),
          image_identifier="public.ecr.aws/aws-containers/hello-app-runner:latest"
      )
  )
  service.add_to_role_policy(iam.PolicyStatement(
      effect=iam.Effect.ALLOW,
      actions=["s3:GetObject"],
      resources=["*"]
  ))
  ```
  `accessRole` - The IAM role that grants the App Runner service access to a source repository. It's required for
  ECR image repositories (but not for ECR Public repositories). If not defined, a new access role will be generated
  when required.
  See [App Runner IAM Roles](https://docs.aws.amazon.com/apprunner/latest/dg/security_iam_service-with-iam.html#security_iam_service-with-iam-roles) for more details.

  To associate an App Runner service with a custom Auto Scaling Configuration, define `autoScalingConfiguration` for the service.
  ```python
  auto_scaling_configuration = apprunner.AutoScalingConfiguration(self, "AutoScalingConfiguration",
      auto_scaling_configuration_name="MyAutoScalingConfiguration",
      max_concurrency=150,
      max_size=20,
      min_size=5
  )
  apprunner.Service(self, "DemoService",
      source=apprunner.Source.from_ecr_public(
          image_configuration=apprunner.ImageConfiguration(port=8000),
          image_identifier="public.ecr.aws/aws-containers/hello-app-runner:latest"
      ),
      auto_scaling_configuration=auto_scaling_configuration
  )
  ```

  To associate an App Runner service with a custom VPC, define `vpcConnector` for the service.
  ```python
  import aws_cdk.aws_ec2 as ec2
  vpc = ec2.Vpc(self, "Vpc",
      ip_addresses=ec2.IpAddresses.cidr("10.0.0.0/16")
  )
  vpc_connector = apprunner.VpcConnector(self, "VpcConnector",
      vpc=vpc,
      vpc_subnets=vpc.select_subnets(subnet_type=ec2.SubnetType.PUBLIC),
      vpc_connector_name="MyVpcConnector"
  )
  apprunner.Service(self, "Service",
      source=apprunner.Source.from_ecr_public(
          image_configuration=apprunner.ImageConfiguration(port=8000),
          image_identifier="public.ecr.aws/aws-containers/hello-app-runner:latest"
      ),
      vpc_connector=vpc_connector
  )
  ```

  To make your App Runner service private and only accessible from within a VPC use the `isPubliclyAccessible` property and associate it to a `VpcIngressConnection` resource.
  To set up a `VpcIngressConnection`, specify a VPC, a VPC Interface Endpoint, and the App Runner service.
  Also you must set `isPubliclyAccessible` property in ther `Service` to `false`.
  For more information, see [Enabling Private endpoint for incoming traffic](https://docs.aws.amazon.com/apprunner/latest/dg/network-pl.html).
  ```python
  import aws_cdk.aws_ec2 as ec2

  interface_vpc_endpoint = ec2.InterfaceVpcEndpoint(self, "MyVpcEndpoint",
      vpc=vpc,
      service=ec2.InterfaceVpcEndpointAwsService.APP_RUNNER_REQUESTS,
      private_dns_enabled=False
  )
  service = apprunner.Service(self, "Service",
      source=apprunner.Source.from_ecr_public(
          image_configuration=apprunner.ImageConfiguration(
              port=8000
          ),
          image_identifier="public.ecr.aws/aws-containers/hello-app-runner:latest"
      ),
      is_publicly_accessible=False
  )
  apprunner.VpcIngressConnection(self, "VpcIngressConnection",
      vpc=vpc,
      interface_vpc_endpoint=interface_vpc_endpoint,
      service=service
  )
  ```

  To use dual stack (IPv4 and IPv6) for your incoming public network configuration, set `ipAddressType` to `IpAddressType.DUAL_STACK`.
  ```python
  apprunner.Service(self, "Service",
      source=apprunner.Source.from_ecr_public(
          image_configuration=apprunner.ImageConfiguration(port=8000),
          image_identifier="public.ecr.aws/aws-containers/hello-app-runner:latest"
      ),
      ip_address_type=apprunner.IpAddressType.DUAL_STACK
  )
  ```
  **Note**: Currently, App Runner supports dual stack for only Public endpoint.
  Only IPv4 is supported for Private endpoint.
  If you update a service that's using dual-stack Public endpoint to a Private endpoint,
  your App Runner service will default to support only IPv4 for Private endpoint and fail
  to receive traffic originating from IPv6 endpoint.

  To include environment variables integrated with AWS Secrets Manager, use the `environmentSecrets` attribute.
  You can use the `addSecret` method from the App Runner `Service` class to include secrets from outside the
  service definition.
  ```python
  import aws_cdk.aws_secretsmanager as secretsmanager
  import aws_cdk.aws_ssm as ssm

  secret = secretsmanager.Secret(stack, "Secret")
  parameter = ssm.StringParameter.from_secure_string_parameter_attributes(stack, "Parameter",
      parameter_name="/name",
      version=1
  )
  service = apprunner.Service(stack, "Service",
      source=apprunner.Source.from_ecr_public(
          image_configuration=apprunner.ImageConfiguration(
              port=8000,
              environment_secrets={
                  "SECRET": apprunner.Secret.from_secrets_manager(secret),
                  "PARAMETER": apprunner.Secret.from_ssm_parameter(parameter),
                  "SECRET_ID": apprunner.Secret.from_secrets_manager_version(secret, version_id="version-id"),
                  "SECRET_STAGE": apprunner.Secret.from_secrets_manager_version(secret, version_stage="version-stage")
              }
          ),
          image_identifier="public.ecr.aws/aws-containers/hello-app-runner:latest"
      )
  )
  service.add_secret("LATER_SECRET", apprunner.Secret.from_secrets_manager(secret, "field"))
  ```

  To use a customer managed key for your source encryption, use the `kmsKey` attribute.
  ```python
  import aws_cdk.aws_kms as kms

  apprunner.Service(self, "Service",
      source=apprunner.Source.from_ecr_public(
          image_configuration=apprunner.ImageConfiguration(port=8000),
          image_identifier="public.ecr.aws/aws-containers/hello-app-runner:latest"
      ),
      kms_key=kms_key
  )
  ```

  To configure the health check for the service, use the `healthCheck` attribute.
  You can specify it by static methods `HealthCheck.http` or `HealthCheck.tcp`.
  ```python
  apprunner.Service(self, "Service",
      source=apprunner.Source.from_ecr_public(
          image_configuration=apprunner.ImageConfiguration(port=8000),
          image_identifier="public.ecr.aws/aws-containers/hello-app-runner:latest"
      ),
      health_check=apprunner.HealthCheck.http(
          healthy_threshold=5,
          interval=Duration.seconds(10),
          path="/",
          timeout=Duration.seconds(10),
          unhealthy_threshold=10
      )
  )
  ```

  To associate an App Runner service with a custom observability configuration, use the `observabilityConfiguration` property.
  ```python
  observability_configuration = apprunner.ObservabilityConfiguration(self, "ObservabilityConfiguration",
      observability_configuration_name="MyObservabilityConfiguration",
      trace_configuration_vendor=apprunner.TraceConfigurationVendor.AWSXRAY
  )
  apprunner.Service(self, "DemoService",
      source=apprunner.Source.from_ecr_public(
          image_configuration=apprunner.ImageConfiguration(port=8000),
          image_identifier="public.ecr.aws/aws-containers/hello-app-runner:latest"
      ),
      observability_configuration=observability_configuration
  )
  ```


pkgId: 17716099e239d33527e71bc637dd324c4165f8c0769f0a6fba58d171304608ab
name: python-aws-cdk.aws-appsync-alpha
arch: src
version: 2.59.0a0
epoch: 0
release: 1
summary: The CDK Construct Library for AWS::AppSync
url: https://github.com/aws/aws-cdk
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk.aws-appsync-alpha-2.59.0a0-1.src.rpm
checksum_type: sha256
description:
  <!--END STABILITY BANNER-->
  The `@aws-cdk/aws-appsync` package contains constructs for building flexible
  APIs that use GraphQL.
  ```python
  import aws_cdk.aws_appsync_alpha as appsync
  ```


  Example of a GraphQL API with `AWS_IAM` [authorization](#authorization) resolving into a DynamoDb
  backend data source.
  GraphQL schema file `schema.graphql`:
  ```gql
  type demo {
    id: String!
    version: String!
  }
  type Query {
    getDemos: [ demo! ]
  }
  input DemoInput {
    version: String!
  }
  type Mutation {
    addDemo(input: DemoInput!): demo
  }
  ```
  CDK stack file `app-stack.ts`:
  ```python
  api = appsync.GraphqlApi(self, "Api",
      name="demo",
      schema=appsync.SchemaFile.from_asset(path.join(__dirname, "schema.graphql")),
      authorization_config=appsync.AuthorizationConfig(
          default_authorization=appsync.AuthorizationMode(
              authorization_type=appsync.AuthorizationType.IAM
          )
      ),
      xray_enabled=True
  )
  demo_table = dynamodb.Table(self, "DemoTable",
      partition_key=dynamodb.Attribute(
          name="id",
          type=dynamodb.AttributeType.STRING
      )
  )
  demo_dS = api.add_dynamo_db_data_source("demoDataSource", demo_table)



  demo_dS.create_resolver("QueryGetDemosResolver",
      type_name="Query",
      field_name="getDemos",
      request_mapping_template=appsync.MappingTemplate.dynamo_db_scan_table(),
      response_mapping_template=appsync.MappingTemplate.dynamo_db_result_list()
  )

  demo_dS.create_resolver("MutationAddDemoResolver",
      type_name="Mutation",
      field_name="addDemo",
      request_mapping_template=appsync.MappingTemplate.dynamo_db_put_item(
          appsync.PrimaryKey.partition("id").auto(),
          appsync.Values.projecting("input")),
      response_mapping_template=appsync.MappingTemplate.dynamo_db_result_item()
  )

  demo_dS.create_resolver("QueryGetDemosConsistentResolver",
      type_name="Query",
      field_name="getDemosConsistent",
      request_mapping_template=appsync.MappingTemplate.dynamo_db_scan_table(True),
      response_mapping_template=appsync.MappingTemplate.dynamo_db_result_list()
  )
  ```

  AppSync provides a data source for executing SQL commands against Amazon Aurora
  Serverless clusters. You can use AppSync resolvers to execute SQL statements
  against the Data API with GraphQL queries, mutations, and subscriptions.
  ```python



  secret = rds.DatabaseSecret(self, "AuroraSecret",
      username="clusteradmin"
  )

  vpc = ec2.Vpc(self, "AuroraVpc")

  cluster = rds.ServerlessCluster(self, "AuroraCluster",
      engine=rds.DatabaseClusterEngine.AURORA_MYSQL,
      vpc=vpc,
      credentials={"username": "clusteradmin"},
      cluster_identifier="db-endpoint-test",
      default_database_name="demos"
  )
  rds_dS = api.add_rds_data_source("rds", cluster, secret, "demos")

  rds_dS.create_resolver("QueryGetDemosRdsResolver",
      type_name="Query",
      field_name="getDemosRds",
      request_mapping_template=appsync.MappingTemplate.from_string("""
            {
              "version": "2018-05-29",
              "statements": [
                "SELECT * FROM demos"
              ]
            }
            """),
      response_mapping_template=appsync.MappingTemplate.from_string("""
              $utils.toJson($utils.rds.toJsonObject($ctx.result)[0])
            """)
  )

  rds_dS.create_resolver("MutationAddDemoRdsResolver",
      type_name="Mutation",
      field_name="addDemoRds",
      request_mapping_template=appsync.MappingTemplate.from_string("""
            {
              "version": "2018-05-29",
              "statements": [
                "INSERT INTO demos VALUES (:id, :version)",
                "SELECT * WHERE id = :id"
              ],
              "variableMap": {
                ":id": $util.toJson($util.autoId()),
                ":version": $util.toJson($ctx.args.version)
              }
            }
            """),
      response_mapping_template=appsync.MappingTemplate.from_string("""
              $utils.toJson($utils.rds.toJsonObject($ctx.result)[1][0])
            """)
  )
  ```

  GraphQL schema file `schema.graphql`:
  ```gql
  type job {
    id: String!
    version: String!
  }
  input DemoInput {
    version: String!
  }
  type Mutation {
    callStepFunction(input: DemoInput!): job
  }
  ```
  GraphQL request mapping template `request.vtl`:
  ```json
  {
    "version": "2018-05-29",
    "method": "POST",
    "resourcePath": "/",
    "params": {
      "headers": {
        "content-type": "application/x-amz-json-1.0",
        "x-amz-target":"AWSStepFunctions.StartExecution"
      },
      "body": {
        "stateMachineArn": "<your step functions arn>",
        "input": "{ \"id\": \"$context.arguments.id\" }"
      }
    }
  }
  ```
  GraphQL response mapping template `response.vtl`:
  ```json
  {
    "id": "${context.result.id}"
  }
  ```
  CDK stack file `app-stack.ts`:
  ```python
  api = appsync.GraphqlApi(self, "api",
      name="api",
      schema=appsync.SchemaFile.from_asset(path.join(__dirname, "schema.graphql"))
  )
  http_ds = api.add_http_data_source("ds", "https://states.amazonaws.com",
      name="httpDsWithStepF",
      description="from appsync to StepFunctions Workflow",
      authorization_config=appsync.AwsIamConfig(
          signing_region="us-east-1",
          signing_service_name="states"
      )
  )
  http_ds.create_resolver("MutationCallStepFunctionResolver",
      type_name="Mutation",
      field_name="callStepFunction",
      request_mapping_template=appsync.MappingTemplate.from_file("request.vtl"),
      response_mapping_template=appsync.MappingTemplate.from_file("response.vtl")
  )
  ```

  AppSync has builtin support for Amazon OpenSearch Service (successor to Amazon
  Elasticsearch Service) from domains that are provisioned through your AWS account. You can
  use AppSync resolvers to perform GraphQL operations such as queries, mutations, and
  subscriptions.
  ```python
  import aws_cdk.aws_opensearchservice as opensearch

  user = iam.User(self, "User")
  domain = opensearch.Domain(self, "Domain",
      version=opensearch.EngineVersion.OPENSEARCH_1_3,
      removal_policy=RemovalPolicy.DESTROY,
      fine_grained_access_control=opensearch.AdvancedSecurityOptions(master_user_arn=user.user_arn),
      encryption_at_rest=opensearch.EncryptionAtRestOptions(enabled=True),
      node_to_node_encryption=True,
      enforce_https=True
  )
  ds = api.add_open_search_data_source("ds", domain)
  ds.create_resolver("QueryGetTestsResolver",
      type_name="Query",
      field_name="getTests",
      request_mapping_template=appsync.MappingTemplate.from_string(JSON.stringify({
          "version": "2017-02-28",
          "operation": "GET",
          "path": "/id/post/_search",
          "params": {
              "headers": {},
              "query_string": {},
              "body": {"from": 0, "size": 50}
          }
      })),
      response_mapping_template=appsync.MappingTemplate.from_string("""[
              
              
              $utils.toJson($entry.get("_source"))
              
            ]""")
  )
  ```

  For many use cases you may want to associate a custom domain name with your
  GraphQL API. This can be done during the API creation.
  ```python
  import aws_cdk.aws_certificatemanager as acm
  import aws_cdk.aws_route53 as route53


  zone_name = "example.com"
  my_domain_name = "api.example.com"
  certificate = acm.Certificate(self, "cert", domain_name=my_domain_name)
  schema = appsync.SchemaFile(file_path="mySchemaFile")
  api = appsync.GraphqlApi(self, "api",
      name="myApi",
      schema=schema,
      domain_name=appsync.DomainOptions(
          certificate=certificate,
          domain_name=my_domain_name
      )
  )

  zone = route53.HostedZone.from_hosted_zone_attributes(self, "HostedZone",
      hosted_zone_id=hosted_zone_id,
      zone_name=zone_name
  )

  route53.CnameRecord(self, "CnameApiRecord",
      record_name="api",
      zone=zone,
      domain_name=api.app_sync_domain_name
  )
  ```

  AppSync automatically create a log group with the name `/aws/appsync/apis/<graphql_api_id>` upon deployment with
  log data set to never expire. If you want to set a different expiration period, use the `logConfig.retention` property.
  To obtain the GraphQL API's log group as a `logs.ILogGroup` use the `logGroup` property of the
  `GraphqlApi` construct.
  ```python
  import aws_cdk.aws_logs as logs
  log_config = appsync.LogConfig(
      retention=logs.RetentionDays.ONE_WEEK
  )
  appsync.GraphqlApi(self, "api",
      authorization_config=appsync.AuthorizationConfig(),
      name="myApi",
      schema=appsync.SchemaFile.from_asset(path.join(__dirname, "myApi.graphql")),
      log_config=log_config
  )
  ```

  You can define a schema using from a local file using `SchemaFile.fromAsset`
  ```python
  api = appsync.GraphqlApi(self, "api",
      name="myApi",
      schema=appsync.SchemaFile.from_asset(path.join(__dirname, "schema.graphl"))
  )
  ```

  Alternative schema sources can be defined by implementing the `ISchema`
  interface. An example of this is the `CodeFirstSchema` class provided in
  [awscdk-appsync-utils](https://github.com/cdklabs/awscdk-appsync-utils)

  Any GraphQL Api that has been created outside the stack can be imported from
  another stack into your CDK app. Utilizing the `fromXxx` function, you have
  the ability to add data sources and resolvers through a `IGraphqlApi` interface.
  ```python


  imported_api = appsync.GraphqlApi.from_graphql_api_attributes(self, "IApi",
      graphql_api_id=api.api_id,
      graphql_api_arn=api.arn
  )
  imported_api.add_dynamo_db_data_source("TableDataSource", table)
  ```
  If you don't specify `graphqlArn` in `fromXxxAttributes`, CDK will autogenerate
  the expected `arn` for the imported api, given the `apiId`. For creating data
  sources and resolvers, an `apiId` is sufficient.

  There are multiple authorization types available for GraphQL API to cater to different
  access use cases. They are:
  * API Keys (`AuthorizationType.API_KEY`)
  * Amazon Cognito User Pools (`AuthorizationType.USER_POOL`)
  * OpenID Connect (`AuthorizationType.OPENID_CONNECT`)
  * AWS Identity and Access Management (`AuthorizationType.AWS_IAM`)
  * AWS Lambda (`AuthorizationType.AWS_LAMBDA`)
  These types can be used simultaneously in a single API, allowing different types of clients to
  access data. When you specify an authorization type, you can also specify the corresponding
  authorization mode to finish defining your authorization. For example, this is a GraphQL API
  with AWS Lambda Authorization.
  ```python
  import aws_cdk.aws_lambda as lambda_

  appsync.GraphqlApi(self, "api",
      name="api",
      schema=appsync.SchemaFile.from_asset(path.join(__dirname, "appsync.test.graphql")),
      authorization_config=appsync.AuthorizationConfig(
          default_authorization=appsync.AuthorizationMode(
              authorization_type=appsync.AuthorizationType.LAMBDA,
              lambda_authorizer_config=appsync.LambdaAuthorizerConfig(
                  handler=auth_function
              )
          )
      )
  )
  ```

  When using `AWS_IAM` as the authorization type for GraphQL API, an IAM Role
  with correct permissions must be used for access to API.
  When configuring permissions, you can specify specific resources to only be
  accessible by `IAM` authorization. For example, if you want to only allow mutability
  for `IAM` authorized access you would configure the following.
  In `schema.graphql`:
  ```gql
  type Mutation {
    updateExample(...): ...
      @aws_iam
  }
  ```
  In `IAM`:
  ```json
  {
    "Version": "2012-10-17",
    "Statement": [
      {
        "Effect": "Allow",
        "Action": [
          "appsync:GraphQL"
        ],
        "Resource": [
          "arn:aws:appsync:REGION:ACCOUNT_ID:apis/GRAPHQL_ID/types/Mutation/fields/updateExample"
        ]
      }
    ]
  }
  ```
  See [documentation](https://docs.aws.amazon.com/appsync/latest/devguide/security.html#aws-iam-authorization) for more details.
  To make this easier, CDK provides `grant` API.
  Use the `grant` function for more granular authorization.
  ```python

  role = iam.Role(self, "Role",
      assumed_by=iam.ServicePrincipal("lambda.amazonaws.com")
  )
  api.grant(role, appsync.IamResource.custom("types/Mutation/fields/updateExample"), "appsync:GraphQL")
  ```

  In order to use the `grant` functions, you need to use the class `IamResource`.
  * `IamResource.custom(...arns)` permits custom ARNs and requires an argument.
  * `IamResouce.ofType(type, ...fields)` permits ARNs for types and their fields.
  * `IamResource.all()` permits ALL resources.

  Alternatively, you can use more generic `grant` functions to accomplish the same usage.
  These include:
  * grantMutation (use to grant access to Mutation fields)
  * grantQuery (use to grant access to Query fields)
  * grantSubscription (use to grant access to Subscription fields)
  ```python



  api.grant_mutation(role, "updateExample")

  api.grant(role, appsync.IamResource.of_type("Mutation", "updateExample"), "appsync:GraphQL")
  ```

  AppSync Functions are local functions that perform certain operations onto a
  backend data source. Developers can compose operations (Functions) and execute
  them in sequence with Pipeline Resolvers.
  ```python

  appsync_function = appsync.AppsyncFunction(self, "function",
      name="appsync_function",
      api=api,
      data_source=api.add_none_data_source("none"),
      request_mapping_template=appsync.MappingTemplate.from_file("request.vtl"),
      response_mapping_template=appsync.MappingTemplate.from_file("response.vtl")
  )
  ```
  AppSync Functions are used in tandem with pipeline resolvers to compose multiple
  operations.
  ```python


  pipeline_resolver = appsync.Resolver(self, "pipeline",
      api=api,
      data_source=api.add_none_data_source("none"),
      type_name="typeName",
      field_name="fieldName",
      request_mapping_template=appsync.MappingTemplate.from_file("beforeRequest.vtl"),
      pipeline_config=[appsync_function],
      response_mapping_template=appsync.MappingTemplate.from_file("afterResponse.vtl")
  )
  ```
  Learn more about Pipeline Resolvers and AppSync Functions [here](https://docs.aws.amazon.com/appsync/latest/devguide/pipeline-resolvers.html).


pkgId: a0bc38472cddfdd3941f777d08465b41db69dfd3f30010d546478184149f10c2
name: python-aws-cdk.aws-batch-alpha
arch: src
version: 2.95.1a0
epoch: 0
release: 1
summary: The CDK Construct Library for AWS::Batch
url: https://github.com/aws/aws-cdk
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk.aws-batch-alpha-2.95.1a0-1.src.rpm
checksum_type: sha256
description:
  <!--END STABILITY BANNER-->
  This module is part of the [AWS Cloud Development Kit](https://github.com/aws/aws-cdk) project.
  AWS Batch is a batch processing tool for efficiently running hundreds of thousands computing jobs in AWS.
  Batch can dynamically provision [Amazon EC2](https://aws.amazon.com/ec2/) Instances to meet the resource requirements of submitted jobs
  and simplifies the planning, scheduling, and executions of your batch workloads. Batch achieves this through four different resources:
  * ComputeEnvironments: Contain the resources used to execute Jobs
  * JobDefinitions: Define a type of Job that can be submitted
  * JobQueues: Route waiting Jobs to ComputeEnvironments
  * SchedulingPolicies: Applied to Queues to control how and when Jobs exit the JobQueue and enter the ComputeEnvironment
  `ComputeEnvironment`s can be managed or unmanaged. Batch will automatically provision EC2 Instances in a managed `ComputeEnvironment` and will
  not provision any Instances in an unmanaged `ComputeEnvironment`. Managed `ComputeEnvironment`s can use ECS, Fargate, or EKS resources to spin up
  EC2 Instances in (ensure your EKS Cluster has [been configured](https://docs.aws.amazon.com/batch/latest/userguide/getting-started-eks.html)
  to support a Batch ComputeEnvironment before linking it). You can use Launch Templates and Placement Groups to configure exactly how these resources
  will be provisioned.
  `JobDefinition`s can use either ECS resources or EKS resources. ECS `JobDefinition`s can use multiple containers to execute distributed workloads.
  EKS `JobDefinition`s can only execute a single container. Submitted Jobs use `JobDefinition`s as templates.
  `JobQueue`s must link at least one `ComputeEnvironment`. Jobs exit the Queue in FIFO order unless a `SchedulingPolicy` is specified.
  `SchedulingPolicy`s tell the Scheduler how to choose which Jobs should be executed next by the ComputeEnvironment.



  Spot instances are significantly discounted EC2 instances that can be reclaimed at any time by AWS.
  Workloads that are fault-tolerant or stateless can take advantage of spot pricing.
  To use spot spot instances, set `spot` to `true` on a managed Ec2 or Fargate Compute Environment:
  ```python
  vpc = ec2.Vpc(self, "VPC")
  batch.FargateComputeEnvironment(self, "myFargateComputeEnv",
      vpc=vpc,
      spot=True
  )
  ```
  Batch allows you to specify the percentage of the on-demand instance that the current spot price
  must be to provision the instance using the `spotBidPercentage`.
  This defaults to 100%, which is the recommended value.
  This value cannot be specified for `FargateComputeEnvironment`s
  and only applies to `ManagedEc2EcsComputeEnvironment`s.
  The following code configures a Compute Environment to only use spot instances that
  are at most 20% the price of the on-demand instance price:
  ```python
  vpc = ec2.Vpc(self, "VPC")
  batch.ManagedEc2EcsComputeEnvironment(self, "myEc2ComputeEnv",
      vpc=vpc,
      spot=True,
      spot_bid_percentage=20
  )
  ```
  For stateful or otherwise non-interruption-tolerant workflows, omit `spot` or set it to `false` to only provision on-demand instances.

  Batch allows you to choose the instance types or classes that will run your workload.
  This example configures your `ComputeEnvironment` to use only the `M5AD.large` instance:
  ```python
  vpc = ec2.Vpc(self, "VPC")
  batch.ManagedEc2EcsComputeEnvironment(self, "myEc2ComputeEnv",
      vpc=vpc,
      instance_types=[ec2.InstanceType.of(ec2.InstanceClass.M5AD, ec2.InstanceSize.LARGE)]
  )
  ```
  Batch allows you to specify only the instance class and to let it choose the size, which you can do like this:
  ```python

  vpc = ec2.Vpc(self, "VPC")
  compute_env.add_instance_class(ec2.InstanceClass.M5AD)

  batch.ManagedEc2EcsComputeEnvironment(self, "myEc2ComputeEnv",
      vpc=vpc,
      instance_classes=[ec2.InstanceClass.R4]
  )
  ```
  Unless you explicitly specify `useOptimalInstanceClasses: false`, this compute environment will use `'optimal'` instances,
  which tells Batch to pick an instance from the C4, M4, and R4 instance families.
  *Note*: Batch does not allow specifying instance types or classes with different architectures.
  For example, `InstanceClass.A1` cannot be specified alongside `'optimal'`,
  because `A1` uses ARM and `'optimal'` uses x86_64.
  You can specify both `'optimal'` alongside several different instance types in the same compute environment:
  ```python

  compute_env = batch.ManagedEc2EcsComputeEnvironment(self, "myEc2ComputeEnv",
      instance_types=[ec2.InstanceType.of(ec2.InstanceClass.M5AD, ec2.InstanceSize.LARGE)],
      use_optimal_instance_classes=True,  # default
      vpc=vpc
  )

  compute_env.add_instance_type(ec2.InstanceType.of(ec2.InstanceClass.M5AD, ec2.InstanceSize.LARGE))
  compute_env.add_instance_class(ec2.InstanceClass.C4)
  compute_env.add_instance_class(ec2.InstanceClass.M4)
  compute_env.add_instance_class(ec2.InstanceClass.R4)
  ```

  | Allocation Strategy           | Optimized for              | Downsides                     |
  | -----------------------       | -------------              | ----------------------------- |
  | BEST_FIT                      | Cost                       | May limit throughput          |
  | BEST_FIT_PROGRESSIVE          | Throughput                 | May increase cost             |
  | SPOT_CAPACITY_OPTIMIZED       | Least interruption         | Only useful on Spot instances |
  | SPOT_PRICE_CAPACITY_OPTIMIZED | Least interruption + Price | Only useful on Spot instances |
  Batch provides different Allocation Strategies to help it choose which instances to provision.
  If your workflow tolerates interruptions, you should enable `spot` on your `ComputeEnvironment`
  and use `SPOT_PRICE_CAPACITY_OPTIMIZED` (this is the default if `spot` is enabled).
  This will tell Batch to choose the instance types from the ones you’ve specified that have
  the most spot capacity available to minimize the chance of interruption and have the lowest price.
  To get the most benefit from your spot instances,
  you should allow Batch to choose from as many different instance types as possible.
  If you only care about minimal interruptions and not want Batch to optimize for cost, use
  `SPOT_CAPACITY_OPTIMIZED`. `SPOT_PRICE_CAPACITY_OPTIMIZED` is recommended over `SPOT_CAPACITY_OPTIMIZED`
  for most use cases.
  If your workflow does not tolerate interruptions and you want to minimize your costs at the expense
  of potentially longer waiting times, use `AllocationStrategy.BEST_FIT`.
  This will choose the lowest-cost instance type that fits all the jobs in the queue.
  If instances of that type are not available,
  the queue will not choose a new type; instead, it will wait for the instance to become available.
  This can stall your `Queue`, with your compute environment only using part of its max capacity
  (or none at all) until the `BEST_FIT` instance becomes available.
  If you are running a workflow that does not tolerate interruptions and you want to maximize throughput,
  you can use `AllocationStrategy.BEST_FIT_PROGRESSIVE`.
  This is the default Allocation Strategy if `spot` is `false` or unspecified.
  This strategy will examine the Jobs in the queue and choose whichever instance type meets the requirements
  of the jobs in the queue and with the lowest cost per vCPU, just as `BEST_FIT`.
  However, if not all of the capacity can be filled with this instance type,
  it will choose a new next-best instance type to run any jobs that couldn’t fit into the `BEST_FIT` capacity.
  To make the most use of this allocation strategy,
  it is recommended to use as many instance classes as is feasible for your workload.
  This example shows a `ComputeEnvironment` that uses `BEST_FIT_PROGRESSIVE`
  with `'optimal'` and `InstanceClass.M5` instance types:
  ```python

  compute_env = batch.ManagedEc2EcsComputeEnvironment(self, "myEc2ComputeEnv",
      vpc=vpc,
      instance_classes=[ec2.InstanceClass.M5]
  )
  ```
  This example shows a `ComputeEnvironment` that uses `BEST_FIT` with `'optimal'` instances:
  ```python

  compute_env = batch.ManagedEc2EcsComputeEnvironment(self, "myEc2ComputeEnv",
      vpc=vpc,
      allocation_strategy=batch.AllocationStrategy.BEST_FIT
  )
  ```
  *Note*: `allocationStrategy` cannot be specified on Fargate Compute Environments.

  You can specify the maximum and minimum vCPUs a managed `ComputeEnvironment` can have at any given time.
  Batch will *always* maintain `minvCpus` worth of instances in your ComputeEnvironment, even if it is not executing any jobs,
  and even if it is disabled. Batch will scale the instances up to `maxvCpus` worth of instances as
  jobs exit the JobQueue and enter the ComputeEnvironment. If you use `AllocationStrategy.BEST_FIT_PROGRESSIVE`,
  `AllocationStrategy.SPOT_PRICE_CAPACITY_OPTIMIZED`, or `AllocationStrategy.SPOT_CAPACITY_OPTIMIZED`,
  batch may exceed `maxvCpus`; it will never exceed `maxvCpus` by more than a single instance type. This example configures a
  `minvCpus` of 10 and a `maxvCpus` of 100:
  ```python

  batch.ManagedEc2EcsComputeEnvironment(self, "myEc2ComputeEnv",
      vpc=vpc,
      instance_classes=[ec2.InstanceClass.R4],
      minv_cpus=10,
      maxv_cpus=100
  )
  ```

  You can tag any instances launched by your managed EC2 ComputeEnvironments by using the CDK `Tags` API:
  ```python
  from aws_cdk import Tags

  tag_cE = batch.ManagedEc2EcsComputeEnvironment(self, "CEThatMakesTaggedInstnaces",
      vpc=vpc
  )
  Tags.of(tag_cE).add("super", "salamander")
  ```
  Unmanaged `ComputeEnvironment`s do not support `maxvCpus` or `minvCpus` because you must provision and manage the instances yourself;
  that is, Batch will not scale them up and down as needed.

  Multiple `JobQueue`s can share the same `ComputeEnvironment`.
  If multiple Queues are attempting to submit Jobs to the same `ComputeEnvironment`,
  Batch will pick the Job from the Queue with the highest priority.
  This example creates two `JobQueue`s that share a `ComputeEnvironment`:
  ```python

  shared_compute_env = batch.FargateComputeEnvironment(self, "spotEnv",
      vpc=vpc,
      spot=True
  )
  low_priority_queue = batch.JobQueue(self, "JobQueue",
      priority=1
  )
  high_priority_queue = batch.JobQueue(self, "JobQueue",
      priority=10
  )
  low_priority_queue.add_compute_environment(shared_compute_env, 1)
  high_priority_queue.add_compute_environment(shared_compute_env, 1)
  ```

  Batch `JobQueue`s execute Jobs submitted to them in FIFO order unless you specify a `SchedulingPolicy`.
  FIFO queuing can cause short-running jobs to be starved while long-running jobs fill the compute environment.
  To solve this, Jobs can be associated with a share.
  Shares consist of a `shareIdentifier` and a `weightFactor`, which is inversely correlated with the vCPU allocated to that share identifier.
  When submitting a Job, you can specify its `shareIdentifier` to associate that particular job with that share.
  Let's see how the scheduler uses this information to schedule jobs.
  For example, if there are two shares defined as follows:
  | Share Identifier | Weight Factor |
  | ---------------- | ------------- |
  | A                | 1             |
  | B                | 1             |
  The weight factors share the following relationship:
  ```math
  A_{vCpus} / A_{Weight} = B_{vCpus} / B_{Weight}
  ```
  where `BvCpus` is the number of vCPUs allocated to jobs with share identifier `'B'`, and `B_weight` is the weight factor of `B`.
  The total number of vCpus allocated to a share is equal to the amount of jobs in that share times the number of vCpus necessary for every job.
  Let's say that each A job needs 32 VCpus (`A_requirement` = 32) and each B job needs 64 vCpus (`B_requirement` = 64):
  ```math
  A_{vCpus} = A_{Jobs} * A_{Requirement}
  ```
  ```math
  B_{vCpus} = B_{Jobs} * B_{Requirement}
  ```
  We have:
  ```math
  A_{vCpus} / A_{Weight} = B_{vCpus} / B_{Weight}
  ```
  ```math
  A_{Jobs} * A_{Requirement} / A_{Weight} = B_{Jobs} * B_{Requirement} / B_{Weight}
  ```
  ```math
  A_{Jobs} * 32 / 1 = B_{Jobs} * 64 / 1
  ```
  ```math
  A_{Jobs} * 32 = B_{Jobs} * 64
  ```
  ```math
  A_{Jobs} = B_{Jobs} * 2
  ```
  Thus the scheduler will schedule two `'A'` jobs for each `'B'` job.
  You can control the weight factors to change these ratios, but note that
  weight factors are inversely correlated with the vCpus allocated to the corresponding share.
  This example would be configured like this:
  ```python
  fairshare_policy = batch.FairshareSchedulingPolicy(self, "myFairsharePolicy")
  fairshare_policy.add_share(
      share_identifier="A",
      weight_factor=1
  )
  fairshare_policy.add_share(
      share_identifier="B",
      weight_factor=1
  )
  batch.JobQueue(self, "JobQueue",
      scheduling_policy=fairshare_policy
  )
  ```
  *Note*: The scheduler will only consider the current usage of the compute environment unless you specify `shareDecay`.
  For example, a `shareDecay` of 5 minutes in the above example means that at any given point in time, twice as many `'A'` jobs
  will be scheduled for each `'B'` job, but only for the past 5 minutes. If `'B'` jobs run longer than 5 minutes, then
  the scheduler is allowed to put more than two `'A'` jobs for each `'B'` job, because the usage of those long-running
  `'B'` jobs will no longer be considered after 5 minutes. `shareDecay` linearly decreases the usage of
  long running jobs for calculation purposes. For example if share decay is 60 seconds,
  then jobs that run for 30 seconds have their usage considered to be only 50% of what it actually is,
  but after a whole minute the scheduler pretends they don't exist for fairness calculations.
  The following code specifies a `shareDecay` of 5 minutes:
  ```python
  import aws_cdk as cdk
  fairshare_policy = batch.FairshareSchedulingPolicy(self, "myFairsharePolicy",
      share_decay=cdk.Duration.minutes(5)
  )
  ```
  If you have high priority jobs that should always be executed as soon as they arrive,
  you can define a `computeReservation` to specify the percentage of the
  maximum vCPU capacity that should be reserved for shares that are *not in the queue*.
  The actual reserved percentage is defined by Batch as:
  ```math
   (\frac{computeReservation}{100}) ^ {ActiveFairShares}
  ```
  where `ActiveFairShares` is the number of shares for which there exists
  at least one job in the queue with a unique share identifier.
  This is best illustrated with an example.
  Suppose there are three shares with share identifiers `A`, `B` and `C` respectively
  and we specify the `computeReservation` to be 75%. The queue is currently empty,
  and no other shares exist.
  There are no active fair shares, since the queue is empty.
  Thus (75/100)^0 = 1 = 100% of the maximum vCpus are reserved for all shares.
  A job with identifier `A` enters the queue.
  The number of active fair shares is now 1, hence
  (75/100)^1 = .75 = 75% of the maximum vCpus are reserved for all shares that do not have the identifier `A`;
  for this example, this is `B` and `C`,
  (but if jobs are submitted with a share identifier not covered by this fairshare policy, those would be considered just as `B` and `C` are).
  Now a `B` job enters the queue. The number of active fair shares is now 2,
  so (75/100)^2 = .5625 = 56.25% of the maximum vCpus are reserved for all shares that do not have the identifier `A` or `B`.
  Now a second `A` job enters the queue. The number of active fair shares is still 2,
  so the percentage reserved is still 56.25%
  Now a `C` job enters the queue. The number of active fair shares is now 3,
  so (75/100)^3 = .421875 = 42.1875% of the maximum vCpus are reserved for all shares that do not have the identifier `A`, `B`, or `C`.
  If there are no other shares that your jobs can specify, this means that 42.1875% of your capacity will never be used!
  Now, `A`, `B`, and `C` can only consume 100% - 42.1875% = 57.8125% of the maximum vCpus.
  Note that the this percentage is **not** split between `A`, `B`, and `C`.
  Instead, the scheduler will use their `weightFactor`s to decide which jobs to schedule;
  the only difference is that instead of competing for 100% of the max capacity, jobs compete for 57.8125% of the max capacity.
  This example specifies a `computeReservation` of 75% that will behave as explained in the example above:
  ```python
  batch.FairshareSchedulingPolicy(self, "myFairsharePolicy",
      compute_reservation=75,
      shares=[batch.Share(weight_factor=1, share_identifier="A"), batch.Share(weight_factor=0.5, share_identifier="B"), batch.Share(weight_factor=2, share_identifier="C")
      ]
  )
  ```
  You can specify a `priority` on your `JobDefinition`s to tell the scheduler to prioritize certain jobs that share the same share identifier.

  Certain workflows may result in Jobs failing due to intermittent issues.
  Jobs can specify retry policies to respond to different failures with different actions.
  There are three different ways information about the way a Job exited can be conveyed;
  * `exitCode`: the exit code returned from the process executed by the container. Will only match non-zero exit codes.
  * `reason`: any middleware errors, like your Docker registry being down.
  * `statusReason`: infrastructure errors, most commonly your spot instance being reclaimed.
  For most use cases, only one of these will be associated with a particular action at a time.
  To specify common `exitCode`s, `reason`s, or `statusReason`s, use the corresponding value from
  the `Reason` class. This example shows some common failure reasons:
  ```python
  import aws_cdk as cdk
  job_defn = batch.EcsJobDefinition(self, "JobDefn",
      container=batch.EcsEc2ContainerDefinition(self, "containerDefn",
          image=ecs.ContainerImage.from_registry("public.ecr.aws/amazonlinux/amazonlinux:latest"),
          memory=cdk.Size.mebibytes(2048),
          cpu=256
      ),
      retry_attempts=5,
      retry_strategies=[
          batch.RetryStrategy.of(batch.Action.EXIT, batch.Reason.CANNOT_PULL_CONTAINER)
      ]
  )
  job_defn.add_retry_strategy(
      batch.RetryStrategy.of(batch.Action.EXIT, batch.Reason.SPOT_INSTANCE_RECLAIMED))
  job_defn.add_retry_strategy(
      batch.RetryStrategy.of(batch.Action.EXIT, batch.Reason.CANNOT_PULL_CONTAINER))
  job_defn.add_retry_strategy(
      batch.RetryStrategy.of(batch.Action.EXIT, batch.Reason.custom(
          on_exit_code="40*",
          on_reason="some reason"
      )))
  ```
  When specifying a custom reason,
  you can specify a glob string to match each of these and react to different failures accordingly.
  Up to five different retry strategies can be configured for each Job,
  and each strategy can match against some or all of `exitCode`, `reason`, and `statusReason`.
  You can optionally configure the number of times a job will be retried,
  but you cannot configure different retry counts for different strategies; they all share the same count.
  If multiple conditions are specified in a given retry strategy,
  they must all match for the action to be taken; the conditions are ANDed together, not ORed.

  Batch can run jobs on ECS or EKS. ECS jobs can be defined as single container or multinode.
  This example creates a `JobDefinition` that runs a single container with ECS:
  ```python
  import aws_cdk as cdk
  import aws_cdk.aws_iam as iam
  import aws_cdk.aws_efs as efs


  my_file_system.grant_read(my_job_role)
  job_defn = batch.EcsJobDefinition(self, "JobDefn",
      container=batch.EcsEc2ContainerDefinition(self, "containerDefn",
          image=ecs.ContainerImage.from_registry("public.ecr.aws/amazonlinux/amazonlinux:latest"),
          memory=cdk.Size.mebibytes(2048),
          cpu=256,
          volumes=[batch.EcsVolume.efs(
              name="myVolume",
              file_system=my_file_system,
              container_path="/Volumes/myVolume",
              use_job_role=True
          )],
          job_role=my_job_role
      )
  )
  ```
  For workflows that need persistent storage, batch supports mounting `Volume`s to the container.
  You can both provision the volume and mount it to the container in a single operation:
  ```python
  import aws_cdk.aws_efs as efs


  job_defn.container.add_volume(batch.EcsVolume.efs(
      name="myVolume",
      file_system=my_file_system,
      container_path="/Volumes/myVolume"
  ))
  ```

  You can expose SecretsManager Secret ARNs or SSM Parameters to your container as environment variables.
  The following example defines the `MY_SECRET_ENV_VAR` environment variable that contains the
  ARN of the Secret defined by `mySecret`:
  ```python
  import aws_cdk as cdk

  job_defn = batch.EcsJobDefinition(self, "JobDefn",
      container=batch.EcsEc2ContainerDefinition(self, "containerDefn",
          image=ecs.ContainerImage.from_registry("public.ecr.aws/amazonlinux/amazonlinux:latest"),
          memory=cdk.Size.mebibytes(2048),
          cpu=256,
          secrets={
              "MY_SECRET_ENV_VAR": batch.Secret.from_secrets_manager(my_secret)
          }
      )
  )
  ```

  Batch also supports running workflows on EKS. The following example creates a `JobDefinition` that runs on EKS:
  ```python
  import aws_cdk as cdk
  job_defn = batch.EksJobDefinition(self, "eksf2",
      container=batch.EksContainerDefinition(self, "container",
          image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
          volumes=[batch.EksVolume.empty_dir(
              name="myEmptyDirVolume",
              mount_path="/mount/path",
              medium=batch.EmptyDirMediumType.MEMORY,
              readonly=True,
              size_limit=cdk.Size.mebibytes(2048)
          )]
      )
  )
  ```
  You can mount `Volume`s to these containers in a single operation:
  ```python

  job_defn.container.add_volume(batch.EksVolume.empty_dir(
      name="emptyDir",
      mount_path="/Volumes/emptyDir"
  ))
  job_defn.container.add_volume(batch.EksVolume.host_path(
      name="hostPath",
      host_path="/sys",
      mount_path="/Volumes/hostPath"
  ))
  job_defn.container.add_volume(batch.EksVolume.secret(
      name="secret",
      optional=True,
      mount_path="/Volumes/secret",
      secret_name="mySecret"
  ))
  ```

  Some workflows benefit from parallellization and are most powerful when run in a distributed environment,
  such as certain numerical calculations or simulations. Batch offers `MultiNodeJobDefinition`s,
  which allow a single job to run on multiple instances in parallel, for this purpose.
  Message Passing Interface (MPI) is often used with these workflows.
  You must configure your containers to use MPI properly,
  but Batch allows different nodes running different containers to communicate easily with one another.
  You must configure your containers to use certain environment variables that Batch will provide them,
  which lets them know which one is the main node, among other information.
  For an in-depth example on using MPI to perform numerical computations on Batch,
  see this [blog post](https://aws.amazon.com/blogs/compute/building-a-tightly-coupled-molecular-dynamics-workflow-with-multi-node-parallel-jobs-in-aws-batch/)
  In particular, the environment variable that tells the containers which one is the main node can be configured on your `MultiNodeJobDefinition` as follows:
  ```python
  import aws_cdk as cdk
  multi_node_job = batch.MultiNodeJobDefinition(self, "JobDefinition",
      instance_type=ec2.InstanceType.of(ec2.InstanceClass.R4, ec2.InstanceSize.LARGE),
      containers=[batch.MultiNodeContainer(
          container=batch.EcsEc2ContainerDefinition(self, "mainMPIContainer",
              image=ecs.ContainerImage.from_registry("yourregsitry.com/yourMPIImage:latest"),
              cpu=256,
              memory=cdk.Size.mebibytes(2048)
          ),
          start_node=0,
          end_node=5
      )]
  )

  multi_node_job.add_container(
      start_node=6,
      end_node=10,
      container=batch.EcsEc2ContainerDefinition(self, "multiContainer",
          image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
          cpu=256,
          memory=cdk.Size.mebibytes(2048)
      )
  )
  ```
  If you need to set the control node to an index other than 0, specify it in directly:
  ```python
  multi_node_job = batch.MultiNodeJobDefinition(self, "JobDefinition",
      main_node=5,
      instance_type=ec2.InstanceType.of(ec2.InstanceClass.R4, ec2.InstanceSize.LARGE)
  )
  ```

  Batch allows you define parameters in your `JobDefinition`, which can be referenced in the container command. For example:
  ```python
  import aws_cdk as cdk
  batch.EcsJobDefinition(self, "JobDefn",
      parameters={"echo_param": "foobar"},
      container=batch.EcsEc2ContainerDefinition(self, "containerDefn",
          image=ecs.ContainerImage.from_registry("public.ecr.aws/amazonlinux/amazonlinux:latest"),
          memory=cdk.Size.mebibytes(2048),
          cpu=256,
          command=["echo", "Ref::echoParam"
          ]
      )
  )
  ```

  AWS Batch uses an [allocation strategy](https://docs.aws.amazon.com/batch/latest/userguide/allocation-strategies.html) to determine what compute resource will efficiently handle incoming job requests. By default, **BEST_FIT** will pick an available compute instance based on vCPU requirements. If none exist, the job will wait until resources become available. However, with this strategy, you may have jobs waiting in the queue unnecessarily despite having more powerful instances available. Below is an example of how that situation might look like:
  ```plaintext
  Compute Environment:
  1. m5.xlarge => 4 vCPU
  2. m5.2xlarge => 8 vCPU
  ```
  ```plaintext


pkgId: f23518cd3e4325216af2055c55b0ed3eec6f03fe3ce20cc1b3586f17ec7bc05a
name: python-aws-cdk.aws-cloud9-alpha
arch: src
version: 2.162.1a0
epoch: 0
release: 1
summary: The CDK Construct Library for AWS::Cloud9
url: https://github.com/aws/aws-cdk
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk.aws-cloud9-alpha-2.162.1a0-1.src.rpm
checksum_type: sha256
description:
  <!--END STABILITY BANNER-->
  This module is part of the [AWS Cloud Development Kit](https://github.com/aws/aws-cdk) project.
  AWS Cloud9 is a cloud-based integrated development environment (IDE) that lets you write, run, and debug your code with just a
  browser. It includes a code editor, debugger, and terminal. Cloud9 comes prepackaged with essential tools for popular
  programming languages, including JavaScript, Python, PHP, and more, so you don’t need to install files or configure your
  development machine to start new projects. Since your Cloud9 IDE is cloud-based, you can work on your projects from your
  office, home, or anywhere using an internet-connected machine. Cloud9 also provides a seamless experience for developing
  serverless applications enabling you to easily define resources, debug, and switch between local and remote execution of
  serverless applications. With Cloud9, you can quickly share your development environment with your team, enabling you to pair
  program and track each other's inputs in real time.

  EC2 Environments are defined with `Ec2Environment`. To create an EC2 environment in the private subnet, specify
  `subnetSelection` with private `subnetType`.
  ```python

  vpc = ec2.Vpc(self, "VPC", max_azs=3)
  cloud9.Ec2Environment(self, "Cloud9Env", vpc=vpc, image_id=cloud9.ImageId.AMAZON_LINUX_2)

  default_vpc = ec2.Vpc.from_lookup(self, "DefaultVPC", is_default=True)
  cloud9.Ec2Environment(self, "Cloud9Env2",
      vpc=default_vpc,
      instance_type=ec2.InstanceType("t3.large"),
      image_id=cloud9.ImageId.AMAZON_LINUX_2
  )

  c9env = cloud9.Ec2Environment(self, "Cloud9Env3",
      vpc=vpc,
      subnet_selection=ec2.SubnetSelection(
          subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS
      ),
      image_id=cloud9.ImageId.AMAZON_LINUX_2
  )

  CfnOutput(self, "URL", value=c9env.ide_url)
  ```

  Use `imageId` to specify the EC2 AMI image to be used:
  ```python
  default_vpc = ec2.Vpc.from_lookup(self, "DefaultVPC", is_default=True)
  cloud9.Ec2Environment(self, "Cloud9Env2",
      vpc=default_vpc,
      instance_type=ec2.InstanceType("t3.large"),
      image_id=cloud9.ImageId.UBUNTU_18_04
  )
  ```

  Use `clonedRepositories` to clone one or multiple AWS Codecommit repositories into the environment:
  ```python
  import aws_cdk.aws_codecommit as codecommit



  repo_new = codecommit.Repository(self, "RepoNew",
      repository_name="new-repo"
  )

  repo_existing = codecommit.Repository.from_repository_name(self, "RepoExisting", "existing-repo")
  cloud9.Ec2Environment(self, "C9Env",
      vpc=vpc,
      cloned_repositories=[
          cloud9.CloneRepository.from_code_commit(repo_new, "/src/new-repo"),
          cloud9.CloneRepository.from_code_commit(repo_existing, "/src/existing-repo")
      ],
      image_id=cloud9.ImageId.AMAZON_LINUX_2
  )
  ```

  Every Cloud9 Environment has an **owner**. An owner has full control over the environment, and can invite additional members to the environment for collaboration purposes. For more information, see [Working with shared environments in AWS Cloud9](https://docs.aws.amazon.com/cloud9/latest/user-guide/share-environment.html)).
  By default, the owner will be the identity that creates the Environment, which is most likely your CloudFormation Execution Role when the Environment is created using CloudFormation. Provider a value for the `owner` property to assign a different owner, either a specific IAM User or the AWS Account Root User.
  `Owner` is an IAM entity that owns a Cloud9 environment. `Owner` has their own access permissions, and resources. You can specify an `Owner`in an EC2 environment which could be of the following types:
  1. Account Root
  2. IAM User
  3. IAM Federated User
  4. IAM Assumed Role
  The ARN of the owner must satisfy the following regular expression: `^arn:(aws|aws-cn|aws-us-gov|aws-iso|aws-iso-b):(iam|sts)::\d+:(root|(user\/[\w+=/:,.@-]{1,64}|federated-user\/[\w+=/:,.@-]{2,32}|assumed-role\/[\w+=:,.@-]{1,64}\/[\w+=,.@-]{1,64}))$`
  Note: Using the account root user is not recommended, see [environment sharing best practices](https://docs.aws.amazon.com/cloud9/latest/user-guide/share-environment.html#share-environment-best-practices).
  To specify the AWS Account Root User as the environment owner, use `Owner.accountRoot()`
  ```python

  cloud9.Ec2Environment(self, "C9Env",
      vpc=vpc,
      image_id=cloud9.ImageId.AMAZON_LINUX_2,
      owner=cloud9.Owner.account_root("111111111")
  )
  ```
  To specify a specific IAM User as the environment owner, use `Owner.user()`. The user should have the `AWSCloud9Administrator` managed policy
  The user should have the `AWSCloud9User` (preferred) or `AWSCloud9Administrator` managed policy attached.
  ```python
  import aws_cdk.aws_iam as iam

  user = iam.User(self, "user")
  user.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name("AWSCloud9Administrator"))
  cloud9.Ec2Environment(self, "C9Env",
      vpc=vpc,
      image_id=cloud9.ImageId.AMAZON_LINUX_2,
      owner=cloud9.Owner.user(user)
  )
  ```
  To specify a specific IAM Federated User as the environment owner, use `Owner.federatedUser(accountId, userName)`.
  The user should have the `AWSCloud9User` (preferred) or `AWSCloud9Administrator` managed policy attached.
  ```python
  import aws_cdk.aws_iam as iam

  cloud9.Ec2Environment(self, "C9Env",
      vpc=vpc,
      image_id=cloud9.ImageId.AMAZON_LINUX_2,
      owner=cloud9.Owner.federated_user(Stack.of(self).account, "Admin/johndoe")
  )
  ```
  To specify an IAM Assumed Role as the environment owner, use `Owner.assumedRole(accountId: string, roleName: string)`.
  The role should have the `AWSCloud9User` (preferred) or `AWSCloud9Administrator` managed policy attached.
  ```python
  import aws_cdk.aws_iam as iam

  cloud9.Ec2Environment(self, "C9Env",
      vpc=vpc,
      image_id=cloud9.ImageId.AMAZON_LINUX_2,
      owner=cloud9.Owner.assumed_role(Stack.of(self).account, "Admin/johndoe-role")
  )
  ```

  A Cloud9 environment can automatically start and stop the associated EC2 instance to reduce costs.
  Use `automaticStop` to specify the number of minutes until the running instance is shut down after the environment was last used.
  ```python
  default_vpc = ec2.Vpc.from_lookup(self, "DefaultVPC", is_default=True)
  cloud9.Ec2Environment(self, "Cloud9Env2",
      vpc=default_vpc,
      image_id=cloud9.ImageId.AMAZON_LINUX_2,
      automatic_stop=Duration.minutes(30)
  )
  ```


pkgId: 9a52069177753859ad17331b7b5ea6a54b514bed606b5cabe5d4fb8bb28f7fb8
name: python-aws-cdk.aws-codestar-alpha
arch: src
version: 2.162.1a0
epoch: 0
release: 1
summary: The CDK Construct Library for AWS::CodeStar
url: https://github.com/aws/aws-cdk
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk.aws-codestar-alpha-2.162.1a0-1.src.rpm
checksum_type: sha256
description:
  <!--END STABILITY BANNER-->

  To create a new GitHub Repository and commit the assets from S3 bucket into the repository after it is created:
  ```python
  import aws_cdk.aws_codestar_alpha as codestar
  import aws_cdk.aws_s3 as s3
  codestar.GitHubRepository(self, "GitHubRepo",
      owner="aws",
      repository_name="aws-cdk",
      access_token=SecretValue.secrets_manager("my-github-token",
          json_field="token"
      ),
      contents_bucket=s3.Bucket.from_bucket_name(self, "Bucket", "amzn-s3-demo-bucket"),
      contents_key="import.zip"
  )
  ```

  At this moment, updates to the `GitHubRepository` are not supported and the repository will not be deleted upon the deletion of the CloudFormation stack. You will need to update or delete the GitHub repository manually.


pkgId: 9b05d7c87ae3214e6a21534249448829f4268ea9b480ae873d89e0b7f125a2d2
name: python-aws-cdk.aws-cognito-identitypool-alpha
arch: src
version: 2.162.1a0
epoch: 0
release: 1
summary: The CDK Construct Library for AWS::Cognito Identity Pools
url: https://github.com/aws/aws-cdk
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk.aws-cognito-identitypool-alpha-2.162.1a0-1.src.rpm
checksum_type: sha256
description:
  <!--END STABILITY BANNER-->
  [Amazon Cognito Identity Pools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html) enable you to grant your users access to other AWS services.
  Identity Pools are one of the two main components of [Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html), which provides authentication, authorization, and
  user management for your web and mobile apps. Your users can sign in through a a trusted identity provider, like a user
  pool or a SAML 2.0 service, as well as with third party providers such as Facebook, Amazon, Google or Apple.
  The other main component in Amazon Cognito is [user pools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html). User Pools are user directories that provide sign-up and
  sign-in options for your app users.
  This module is part of the [AWS Cloud Development Kit](https://github.com/aws/aws-cdk) project.
  ```python
  from aws_cdk.aws_cognito_identitypool_alpha import IdentityPool, UserPoolAuthenticationProvider
  ```

  * [Identity Pools](#identity-pools)
    * [Authenticated and Unauthenticated Identities](#authenticated-and-unauthenticated-identities)
    * [Authentication Providers](#authentication-providers)
      * [User Pool Authentication Provider](#user-pool-authentication-provider)
      * [Server Side Token Check](#server-side-token-check)
      * [Associating an External Provider Directly](#associating-an-external-provider-directly)
      * [OpenIdConnect and Saml](#openid-connect-and-saml)
      * [Custom Providers](#custom-providers)
    * [Role Mapping](#role-mapping)
      * [Provider Urls](#provider-urls)
    * [Authentication Flow](#authentication-flow)
    * [Cognito Sync](#cognito-sync)
    * [Importing Identity Pools](#importing-identity-pools)

  Identity pools provide temporary AWS credentials for users who are guests (unauthenticated) and for users who have
  authenticated by presenting a token from another identity provider. An identity pool is a store of user identity data
  specific to an account.
  Identity pools can be used in conjunction with Cognito User Pools or by accessing external federated identity providers
  directly. Learn more at [Amazon Cognito Identity Pools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html).

  Identity pools define two types of identities: authenticated(`user`) and unauthenticated (`guest`). Every identity in
  an identity pool is either authenticated or unauthenticated. Each identity pool has a default role for authenticated
  identities, and a default role for unauthenticated identities. Absent other overriding rules (see below), these are the
  roles that will be assumed by the corresponding users in the authentication process.
  A basic Identity Pool with minimal configuration has no required props, with default authenticated (user) and
  unauthenticated (guest) roles applied to the identity pool:
  ```python
  IdentityPool(self, "myIdentityPool")
  ```
  By default, both the authenticated and unauthenticated roles will have no permissions attached. Grant permissions
  to roles using the public `authenticatedRole` and `unauthenticatedRole` properties:
  ```python
  import aws_cdk.aws_dynamodb as dynamodb

  identity_pool = IdentityPool(self, "myIdentityPool")

  table.grant_read_write_data(identity_pool.authenticated_role)

  table.grant_read_data(identity_pool.unauthenticated_role)

  identity_pool.authenticated_role.add_to_principal_policy(iam.PolicyStatement(
      effect=iam.Effect.ALLOW,
      actions=["dynamodb:*"],
      resources=["*"]
  ))
  ```
  The default roles can also be supplied in `IdentityPoolProps`:
  ```python
  stack = Stack()
  authenticated_role = iam.Role(self, "authRole",
      assumed_by=iam.ServicePrincipal("service.amazonaws.com")
  )
  unauthenticated_role = iam.Role(self, "unauthRole",
      assumed_by=iam.ServicePrincipal("service.amazonaws.com")
  )
  identity_pool = IdentityPool(self, "TestIdentityPoolActions",
      authenticated_role=authenticated_role,
      unauthenticated_role=unauthenticated_role
  )
  ```

  Authenticated identities belong to users who are authenticated by a public login provider (Amazon Cognito user pools,
  Login with Amazon, Sign in with Apple, Facebook, Google, SAML, or any OpenID Connect Providers) or a developer provider
  (your own backend authentication process).
  [Authentication providers](https://docs.aws.amazon.com/cognito/latest/developerguide/external-identity-providers.html) can be associated with an Identity Pool by first associating them with a Cognito User Pool or by
  associating the provider directly with the identity pool.

  In order to attach a user pool to an identity pool as an authentication provider, the identity pool needs properties
  from both the user pool and the user pool client. For this reason identity pools use a `UserPoolAuthenticationProvider`
  to gather the necessary properties from the user pool constructs.
  ```python
  user_pool = cognito.UserPool(self, "Pool")
  IdentityPool(self, "myidentitypool",
      identity_pool_name="myidentitypool",
      authentication_providers=IdentityPoolAuthenticationProviders(
          user_pools=[UserPoolAuthenticationProvider(user_pool=user_pool)]
      )
  )
  ```
  User pools can also be associated with an identity pool after instantiation. The Identity Pool's `addUserPoolAuthentication` method
  returns the User Pool Client that has been created:
  ```python

  user_pool = cognito.UserPool(self, "Pool")
  user_pool_client = identity_pool.add_user_pool_authentication(UserPoolAuthenticationProvider(
      user_pool=user_pool
  ))
  ```

  With the `IdentityPool` CDK Construct, by default the pool is configured to check with the integrated user pools to
  make sure that the user has not been globally signed out or deleted before the identity pool provides an OIDC token or
  AWS credentials for the user.
  If the user is signed out or deleted, the identity pool will return a 400 Not Authorized error. This setting can be
  disabled, however, in several ways.
  Setting `disableServerSideTokenCheck` to true will change the default behavior to no server side token check. Learn
  more [here](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_CognitoIdentityProvider.html#CognitoIdentity-Type-CognitoIdentityProvider-ServerSideTokenCheck):
  ```python

  user_pool = cognito.UserPool(self, "Pool")
  identity_pool.add_user_pool_authentication(UserPoolAuthenticationProvider(
      user_pool=user_pool,
      disable_server_side_token_check=True
  ))
  ```

  One or more [external identity providers](https://docs.aws.amazon.com/cognito/latest/developerguide/external-identity-providers.html) can be associated with an identity pool directly using
  `authenticationProviders`:
  ```python
  IdentityPool(self, "myidentitypool",
      identity_pool_name="myidentitypool",
      authentication_providers=IdentityPoolAuthenticationProviders(
          amazon=IdentityPoolAmazonLoginProvider(
              app_id="amzn1.application.12312k3j234j13rjiwuenf"
          ),
          facebook=IdentityPoolFacebookLoginProvider(
              app_id="1234567890123"
          ),
          google=IdentityPoolGoogleLoginProvider(
              client_id="12345678012.apps.googleusercontent.com"
          ),
          apple=IdentityPoolAppleLoginProvider(
              services_id="com.myappleapp.auth"
          ),
          twitter=IdentityPoolTwitterLoginProvider(
              consumer_key="my-twitter-id",
              consumer_secret="my-twitter-secret"
          )
      )
  )
  ```
  To associate more than one provider of the same type with the identity pool, use User
  Pools, OpenIdConnect, or SAML. Only one provider per external service can be attached directly to the identity pool.

  [OpenID Connect](https://docs.aws.amazon.com/cognito/latest/developerguide/open-id.html) is an open standard for
  authentication that is supported by a number of login providers. Amazon Cognito supports linking of identities with
  OpenID Connect providers that are configured through [AWS Identity and Access Management](http://aws.amazon.com/iam/).
  An identity provider that supports [Security Assertion Markup Language 2.0 (SAML 2.0)](https://docs.aws.amazon.com/cognito/latest/developerguide/saml-identity-provider.html) can be used to provide a simple
  onboarding flow for users. The SAML-supporting identity provider specifies the IAM roles that can be assumed by users
  so that different users can be granted different sets of permissions. Associating an OpenId Connect or Saml provider
  with an identity pool:
  ```python


  IdentityPool(self, "myidentitypool",
      identity_pool_name="myidentitypool",
      authentication_providers=IdentityPoolAuthenticationProviders(
          open_id_connect_providers=[open_id_connect_provider],
          saml_providers=[saml_provider]
      )
  )
  ```

  The identity pool's behavior can be customized further using custom [developer authenticated identities](https://docs.aws.amazon.com/cognito/latest/developerguide/developer-authenticated-identities.html).
  With developer authenticated identities, users can be registered and authenticated via an existing authentication
  process while still using Amazon Cognito to synchronize user data and access AWS resources.
  Like the supported external providers, though, only one custom provider can be directly associated with the identity
  pool.
  ```python

  IdentityPool(self, "myidentitypool",
      identity_pool_name="myidentitypool",
      authentication_providers=IdentityPoolAuthenticationProviders(
          google=IdentityPoolGoogleLoginProvider(
              client_id="12345678012.apps.googleusercontent.com"
          ),
          open_id_connect_providers=[open_id_connect_provider],
          custom_provider="my-custom-provider.example.com"
      )
  )
  ```

  In addition to setting default roles for authenticated and unauthenticated users, identity pools can also be used to
  define rules to choose the role for each user based on claims in the user's ID token by using Role Mapping. When using
  role mapping, it's important to be aware of some of the permissions the role will need. An in depth
  review of roles and role mapping can be found [here](https://docs.aws.amazon.com/cognito/latest/developerguide/role-based-access-control.html).
  Using a [token-based approach](https://docs.aws.amazon.com/cognito/latest/developerguide/role-based-access-control.html#using-tokens-to-assign-roles-to-users) to role mapping will allow mapped roles to be passed through the `cognito:roles` or
  `cognito:preferred_role` claims from the identity provider:
  ```python
  from aws_cdk.aws_cognito_identitypool_alpha import IdentityPoolProviderUrl
  IdentityPool(self, "myidentitypool",
      identity_pool_name="myidentitypool",
      role_mappings=[IdentityPoolRoleMapping(
          provider_url=IdentityPoolProviderUrl.AMAZON,
          use_token=True
      )]
  )
  ```
  Using a rule-based approach to role mapping allows roles to be assigned based on custom claims passed from the identity provider:
  ```python
  from aws_cdk.aws_cognito_identitypool_alpha import IdentityPoolProviderUrl, RoleMappingMatchType


  IdentityPool(self, "myidentitypool",
      identity_pool_name="myidentitypool",
      
      role_mappings=[IdentityPoolRoleMapping(
          provider_url=IdentityPoolProviderUrl.AMAZON,
          rules=[RoleMappingRule(
              claim="custom:admin",
              claim_value="admin",
              mapped_role=admin_role
          ), RoleMappingRule(
              claim="custom:admin",
              claim_value="admin",
              match_type=RoleMappingMatchType.NOTEQUAL,
              mapped_role=non_admin_role
          )
          ]
      )]
  )
  ```
  Role mappings can also be added after instantiation with the Identity Pool's `addRoleMappings` method:
  ```python
  from aws_cdk.aws_cognito_identitypool_alpha import IdentityPoolRoleMapping




  identity_pool.add_role_mappings(my_added_role_mapping1, my_added_role_mapping2, my_added_role_mapping3)
  ```

  Role mappings must be associated with the url of an Identity Provider which can be supplied
  `IdentityPoolProviderUrl`. Supported Providers have static Urls that can be used:
  ```python
  from aws_cdk.aws_cognito_identitypool_alpha import IdentityPoolProviderUrl
  IdentityPool(self, "myidentitypool",
      identity_pool_name="myidentitypool",
      role_mappings=[IdentityPoolRoleMapping(
          provider_url=IdentityPoolProviderUrl.FACEBOOK,
          use_token=True
      )]
  )
  ```
  For identity providers that don't have static Urls, a custom Url can be supplied:
  ```python
  from aws_cdk.aws_cognito_identitypool_alpha import IdentityPoolProviderUrl
  IdentityPool(self, "myidentitypool",
      identity_pool_name="myidentitypool",
      role_mappings=[IdentityPoolRoleMapping(
          provider_url=IdentityPoolProviderUrl.custom("my-custom-provider.com"),
          use_token=True
      )
      ]
  )
  ```
  If a provider URL is a CDK Token, as it will be if you are trying to use a previously defined Cognito User Pool, you will need to also provide a mappingKey.
  This is because by default, the key in the Cloudformation role mapping hash is the providerUrl, and Cloudformation map keys must be concrete strings, they
  cannot be references. For example:
  ```python
  from aws_cdk.aws_cognito import UserPool, UserPoolClient
  from aws_cdk.aws_cognito_identitypool_alpha import IdentityPoolProviderUrl


  IdentityPool(self, "myidentitypool",
      identity_pool_name="myidentitypool",
      role_mappings=[IdentityPoolRoleMapping(
          mapping_key="cognito",
          provider_url=IdentityPoolProviderUrl.user_pool(user_pool, user_pool_client),
          use_token=True
      )]
  )
  ```
  See [here](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypoolroleattachment-rolemapping.html#cfn-cognito-identitypoolroleattachment-rolemapping-identityprovider) for more information.

  Identity Pool [Authentication Flow](https://docs.aws.amazon.com/cognito/latest/developerguide/authentication-flow.html) defaults to the enhanced, simplified flow. The Classic (basic) Authentication Flow
  can also be implemented using `allowClassicFlow`:
  ```python
  IdentityPool(self, "myidentitypool",
      identity_pool_name="myidentitypool",
      allow_classic_flow=True
  )
  ```

  It's now recommended to integrate [AWS AppSync](https://aws.amazon.com/appsync/) for synchronizing app data across devices, so
  Cognito Sync features like `PushSync`, `CognitoEvents`, and `CognitoStreams` are not a part of `IdentityPool`. More
  information can be found [here](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-sync.html).

  You can import existing identity pools into your stack using Identity Pool static methods with the Identity Pool Id or
  Arn:
  ```python
  IdentityPool.from_identity_pool_id(self, "my-imported-identity-pool", "us-east-1:dj2823ryiwuhef937")
  IdentityPool.from_identity_pool_arn(self, "my-imported-identity-pool", "arn:aws:cognito-identity:us-east-1:123456789012:identitypool/us-east-1:dj2823ryiwuhef937")
  ```


pkgId: c186129efab6599d45d0e8c7501a8cf7ce5503dec6d6f6bf8483a73968b3ed54
name: python-aws-cdk.aws-cognito-identitypool-alpha
arch: src
version: 2.166.0a0
epoch: 0
release: 1
summary: The CDK Construct Library for AWS::Cognito Identity Pools
url: https://github.com/aws/aws-cdk
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk.aws-cognito-identitypool-alpha-2.166.0a0-1.src.rpm
checksum_type: sha256
description:
  <!--END STABILITY BANNER-->
  > **Identity Pools are in a separate module while the API is being stabilized. Once we stabilize the module, they will**
  > **be included into the stable [aws-cognito](../aws-cognito) library. Please provide feedback on this experience by**
  > **creating an [issue here](https://github.com/aws/aws-cdk/issues/new/choose)**
  [Amazon Cognito Identity Pools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html) enable you to grant your users access to other AWS services.
  Identity Pools are one of the two main components of [Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html), which provides authentication, authorization, and
  user management for your web and mobile apps. Your users can sign in through a a trusted identity provider, like a user
  pool or a SAML 2.0 service, as well as with third party providers such as Facebook, Amazon, Google or Apple.
  The other main component in Amazon Cognito is [user pools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html). User Pools are user directories that provide sign-up and
  sign-in options for your app users.
  This module is part of the [AWS Cloud Development Kit](https://github.com/aws/aws-cdk) project.
  ```python
  from aws_cdk.aws_cognito_identitypool_alpha import IdentityPool, UserPoolAuthenticationProvider
  ```

  * [Identity Pools](#identity-pools)
    * [Authenticated and Unauthenticated Identities](#authenticated-and-unauthenticated-identities)
    * [Authentication Providers](#authentication-providers)
      * [User Pool Authentication Provider](#user-pool-authentication-provider)
      * [Server Side Token Check](#server-side-token-check)
      * [Associating an External Provider Directly](#associating-an-external-provider-directly)
      * [OpenIdConnect and Saml](#openid-connect-and-saml)
      * [Custom Providers](#custom-providers)
    * [Role Mapping](#role-mapping)
      * [Provider Urls](#provider-urls)
    * [Authentication Flow](#authentication-flow)
    * [Cognito Sync](#cognito-sync)
    * [Importing Identity Pools](#importing-identity-pools)

  Identity pools provide temporary AWS credentials for users who are guests (unauthenticated) and for users who have
  authenticated by presenting a token from another identity provider. An identity pool is a store of user identity data
  specific to an account.
  Identity pools can be used in conjunction with Cognito User Pools or by accessing external federated identity providers
  directly. Learn more at [Amazon Cognito Identity Pools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html).

  Identity pools define two types of identities: authenticated(`user`) and unauthenticated (`guest`). Every identity in
  an identity pool is either authenticated or unauthenticated. Each identity pool has a default role for authenticated
  identities, and a default role for unauthenticated identities. Absent other overriding rules (see below), these are the
  roles that will be assumed by the corresponding users in the authentication process.
  A basic Identity Pool with minimal configuration has no required props, with default authenticated (user) and
  unauthenticated (guest) roles applied to the identity pool:
  ```python
  IdentityPool(self, "myIdentityPool")
  ```
  By default, both the authenticated and unauthenticated roles will have no permissions attached. When granting permissions,
  you should ensure that you are granting the least privileged permissions required for your use case. Grant permissions
  to roles using the public `authenticatedRole` and `unauthenticatedRole` properties:
  ```python
  import aws_cdk.aws_dynamodb as dynamodb

  identity_pool = IdentityPool(self, "myIdentityPool")

  table.grant_read_write_data(identity_pool.authenticated_role)

  table.grant_read_data(identity_pool.unauthenticated_role)

  identity_pool.authenticated_role.add_to_principal_policy(iam.PolicyStatement(
      effect=iam.Effect.ALLOW,
      actions=["dynamodb:UpdateItem"],
      resources=[table.table_arn]
  ))
  ```
  The default roles can also be supplied in `IdentityPoolProps`:
  ```python
  stack = Stack()
  authenticated_role = iam.Role(self, "authRole",
      assumed_by=iam.ServicePrincipal("service.amazonaws.com")
  )
  unauthenticated_role = iam.Role(self, "unauthRole",
      assumed_by=iam.ServicePrincipal("service.amazonaws.com")
  )
  identity_pool = IdentityPool(self, "TestIdentityPoolActions",
      authenticated_role=authenticated_role,
      unauthenticated_role=unauthenticated_role
  )
  ```

  Authenticated identities belong to users who are authenticated by a public login provider (Amazon Cognito user pools,
  Login with Amazon, Sign in with Apple, Facebook, Google, SAML, or any OpenID Connect Providers) or a developer provider
  (your own backend authentication process).
  [Authentication providers](https://docs.aws.amazon.com/cognito/latest/developerguide/external-identity-providers.html) can be associated with an Identity Pool by first associating them with a Cognito User Pool or by
  associating the provider directly with the identity pool.

  In order to attach a user pool to an identity pool as an authentication provider, the identity pool needs properties
  from both the user pool and the user pool client. For this reason identity pools use a `UserPoolAuthenticationProvider`
  to gather the necessary properties from the user pool constructs.
  ```python
  user_pool = cognito.UserPool(self, "Pool")
  IdentityPool(self, "myidentitypool",
      identity_pool_name="myidentitypool",
      authentication_providers=IdentityPoolAuthenticationProviders(
          user_pools=[UserPoolAuthenticationProvider(user_pool=user_pool)]
      )
  )
  ```
  User pools can also be associated with an identity pool after instantiation. The Identity Pool's `addUserPoolAuthentication` method
  returns the User Pool Client that has been created:
  ```python

  user_pool = cognito.UserPool(self, "Pool")
  user_pool_client = identity_pool.add_user_pool_authentication(UserPoolAuthenticationProvider(
      user_pool=user_pool
  ))
  ```

  With the `IdentityPool` CDK Construct, by default the pool is configured to check with the integrated user pools to
  make sure that the user has not been globally signed out or deleted before the identity pool provides an OIDC token or
  AWS credentials for the user.
  If the user is signed out or deleted, the identity pool will return a 400 Not Authorized error. This setting can be
  disabled, however, in several ways.
  Setting `disableServerSideTokenCheck` to true will change the default behavior to no server side token check. Learn
  more [here](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_CognitoIdentityProvider.html#CognitoIdentity-Type-CognitoIdentityProvider-ServerSideTokenCheck):
  ```python

  user_pool = cognito.UserPool(self, "Pool")
  identity_pool.add_user_pool_authentication(UserPoolAuthenticationProvider(
      user_pool=user_pool,
      disable_server_side_token_check=True
  ))
  ```

  One or more [external identity providers](https://docs.aws.amazon.com/cognito/latest/developerguide/external-identity-providers.html) can be associated with an identity pool directly using
  `authenticationProviders`:
  ```python
  IdentityPool(self, "myidentitypool",
      identity_pool_name="myidentitypool",
      authentication_providers=IdentityPoolAuthenticationProviders(
          amazon=IdentityPoolAmazonLoginProvider(
              app_id="amzn1.application.12312k3j234j13rjiwuenf"
          ),
          facebook=IdentityPoolFacebookLoginProvider(
              app_id="1234567890123"
          ),
          google=IdentityPoolGoogleLoginProvider(
              client_id="12345678012.apps.googleusercontent.com"
          ),
          apple=IdentityPoolAppleLoginProvider(
              services_id="com.myappleapp.auth"
          ),
          twitter=IdentityPoolTwitterLoginProvider(
              consumer_key="my-twitter-id",
              consumer_secret="my-twitter-secret"
          )
      )
  )
  ```
  To associate more than one provider of the same type with the identity pool, use User
  Pools, OpenIdConnect, or SAML. Only one provider per external service can be attached directly to the identity pool.

  [OpenID Connect](https://docs.aws.amazon.com/cognito/latest/developerguide/open-id.html) is an open standard for
  authentication that is supported by a number of login providers. Amazon Cognito supports linking of identities with
  OpenID Connect providers that are configured through [AWS Identity and Access Management](http://aws.amazon.com/iam/).
  An identity provider that supports [Security Assertion Markup Language 2.0 (SAML 2.0)](https://docs.aws.amazon.com/cognito/latest/developerguide/saml-identity-provider.html) can be used to provide a simple
  onboarding flow for users. The SAML-supporting identity provider specifies the IAM roles that can be assumed by users
  so that different users can be granted different sets of permissions. Associating an OpenId Connect or Saml provider
  with an identity pool:
  ```python


  IdentityPool(self, "myidentitypool",
      identity_pool_name="myidentitypool",
      authentication_providers=IdentityPoolAuthenticationProviders(
          open_id_connect_providers=[open_id_connect_provider],
          saml_providers=[saml_provider]
      )
  )
  ```

  The identity pool's behavior can be customized further using custom [developer authenticated identities](https://docs.aws.amazon.com/cognito/latest/developerguide/developer-authenticated-identities.html).
  With developer authenticated identities, users can be registered and authenticated via an existing authentication
  process while still using Amazon Cognito to synchronize user data and access AWS resources.
  Like the supported external providers, though, only one custom provider can be directly associated with the identity
  pool.
  ```python

  IdentityPool(self, "myidentitypool",
      identity_pool_name="myidentitypool",
      authentication_providers=IdentityPoolAuthenticationProviders(
          google=IdentityPoolGoogleLoginProvider(
              client_id="12345678012.apps.googleusercontent.com"
          ),
          open_id_connect_providers=[open_id_connect_provider],
          custom_provider="my-custom-provider.example.com"
      )
  )
  ```

  In addition to setting default roles for authenticated and unauthenticated users, identity pools can also be used to
  define rules to choose the role for each user based on claims in the user's ID token by using Role Mapping. When using
  role mapping, it's important to be aware of some of the permissions the role will need, and that the least privileged
  roles necessary are given for your specific use case. An in depth
  review of roles and role mapping can be found [here](https://docs.aws.amazon.com/cognito/latest/developerguide/role-based-access-control.html).
  Using a [token-based approach](https://docs.aws.amazon.com/cognito/latest/developerguide/role-based-access-control.html#using-tokens-to-assign-roles-to-users) to role mapping will allow mapped roles to be passed through the `cognito:roles` or
  `cognito:preferred_role` claims from the identity provider:
  ```python
  from aws_cdk.aws_cognito_identitypool_alpha import IdentityPoolProviderUrl
  IdentityPool(self, "myidentitypool",
      identity_pool_name="myidentitypool",
      role_mappings=[IdentityPoolRoleMapping(
          provider_url=IdentityPoolProviderUrl.AMAZON,
          use_token=True
      )]
  )
  ```
  Using a rule-based approach to role mapping allows roles to be assigned based on custom claims passed from the identity provider:
  ```python
  from aws_cdk.aws_cognito_identitypool_alpha import IdentityPoolProviderUrl, RoleMappingMatchType


  IdentityPool(self, "myidentitypool",
      identity_pool_name="myidentitypool",
      
      role_mappings=[IdentityPoolRoleMapping(
          provider_url=IdentityPoolProviderUrl.AMAZON,
          rules=[RoleMappingRule(
              claim="custom:admin",
              claim_value="admin",
              mapped_role=admin_role
          ), RoleMappingRule(
              claim="custom:admin",
              claim_value="admin",
              match_type=RoleMappingMatchType.NOTEQUAL,
              mapped_role=non_admin_role
          )
          ]
      )]
  )
  ```
  Role mappings can also be added after instantiation with the Identity Pool's `addRoleMappings` method:
  ```python
  from aws_cdk.aws_cognito_identitypool_alpha import IdentityPoolRoleMapping




  identity_pool.add_role_mappings(my_added_role_mapping1, my_added_role_mapping2, my_added_role_mapping3)
  ```

  Role mappings must be associated with the url of an Identity Provider which can be supplied
  `IdentityPoolProviderUrl`. Supported Providers have static Urls that can be used:
  ```python
  from aws_cdk.aws_cognito_identitypool_alpha import IdentityPoolProviderUrl
  IdentityPool(self, "myidentitypool",
      identity_pool_name="myidentitypool",
      role_mappings=[IdentityPoolRoleMapping(
          provider_url=IdentityPoolProviderUrl.FACEBOOK,
          use_token=True
      )]
  )
  ```
  For identity providers that don't have static Urls, a custom Url can be supplied:
  ```python
  from aws_cdk.aws_cognito_identitypool_alpha import IdentityPoolProviderUrl
  IdentityPool(self, "myidentitypool",
      identity_pool_name="myidentitypool",
      role_mappings=[IdentityPoolRoleMapping(
          provider_url=IdentityPoolProviderUrl.custom("my-custom-provider.com"),
          use_token=True
      )
      ]
  )
  ```
  If a provider URL is a CDK Token, as it will be if you are trying to use a previously defined Cognito User Pool, you will need to also provide a mappingKey.
  This is because by default, the key in the Cloudformation role mapping hash is the providerUrl, and Cloudformation map keys must be concrete strings, they
  cannot be references. For example:
  ```python
  from aws_cdk.aws_cognito import UserPool, UserPoolClient
  from aws_cdk.aws_cognito_identitypool_alpha import IdentityPoolProviderUrl


  IdentityPool(self, "myidentitypool",
      identity_pool_name="myidentitypool",
      role_mappings=[IdentityPoolRoleMapping(
          mapping_key="cognito",
          provider_url=IdentityPoolProviderUrl.user_pool(user_pool, user_pool_client),
          use_token=True
      )]
  )
  ```
  See [here](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypoolroleattachment-rolemapping.html#cfn-cognito-identitypoolroleattachment-rolemapping-identityprovider) for more information.

  Identity Pool [Authentication Flow](https://docs.aws.amazon.com/cognito/latest/developerguide/authentication-flow.html) defaults to the enhanced, simplified flow. The Classic (basic) Authentication Flow
  can also be implemented using `allowClassicFlow`:
  ```python
  IdentityPool(self, "myidentitypool",
      identity_pool_name="myidentitypool",
      allow_classic_flow=True
  )
  ```

  It's now recommended to integrate [AWS AppSync](https://aws.amazon.com/appsync/) for synchronizing app data across devices, so
  Cognito Sync features like `PushSync`, `CognitoEvents`, and `CognitoStreams` are not a part of `IdentityPool`. More
  information can be found [here](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-sync.html).

  You can import existing identity pools into your stack using Identity Pool static methods with the Identity Pool Id or
  Arn:
  ```python
  IdentityPool.from_identity_pool_id(self, "my-imported-identity-pool", "us-east-1:dj2823ryiwuhef937")
  IdentityPool.from_identity_pool_arn(self, "my-imported-identity-pool", "arn:aws:cognito-identity:us-east-1:123456789012:identitypool/us-east-1:dj2823ryiwuhef937")
  ```


pkgId: 6a543e3b450e4e6f54b506b3cc2fb6ffce9180ef1f5a8ef334997c16e40cc2c5
name: python-aws-cdk.aws-ec2-alpha
arch: src
version: 2.167.0a0
epoch: 0
release: 1
summary: The CDK construct library for VPC V2
url: https://github.com/aws/aws-cdk
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk.aws-ec2-alpha-2.167.0a0-1.src.rpm
checksum_type: sha256
description:
  <!--END STABILITY BANNER-->

  `VpcV2` is a re-write of the [`ec2.Vpc`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Vpc.html) construct. This new construct enables higher level of customization
  on the VPC being created. `VpcV2` implements the existing [`IVpc`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.IVpc.html), therefore,
  `VpcV2` is compatible with other constructs that accepts `IVpc` (e.g. [`ApplicationLoadBalancer`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_elasticloadbalancingv2.ApplicationLoadBalancer.html#construct-props)).
  To create a VPC with both IPv4 and IPv6 support:
  ```python
  stack = Stack()
  VpcV2(self, "Vpc",
      primary_address_block=IpAddresses.ipv4("10.0.0.0/24"),
      secondary_address_blocks=[
          IpAddresses.amazon_provided_ipv6(cidr_block_name="AmazonProvidedIpv6")
      ]
  )
  ```
  `VpcV2` does not automatically create subnets or allocate IP addresses, which is different from the `Vpc` construct.

  `SubnetV2` is a re-write of the [`ec2.Subnet`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Subnet.html) construct.
  This new construct can be used to add subnets to a `VpcV2` instance:
  ```python
  stack = Stack()
  my_vpc = VpcV2(self, "Vpc",
      secondary_address_blocks=[
          IpAddresses.amazon_provided_ipv6(cidr_block_name="AmazonProvidedIp")
      ]
  )
  SubnetV2(self, "subnetA",
      vpc=my_vpc,
      availability_zone="us-east-1a",
      ipv4_cidr_block=IpCidr("10.0.0.0/24"),
      ipv6_cidr_block=IpCidr("2a05:d02c:25:4000::/60"),
      subnet_type=SubnetType.PRIVATE_ISOLATED
  )
  ```

  By default `VpcV2` uses `10.0.0.0/16` as the primary CIDR if none is defined.
  Additional CIDRs can be adding to the VPC via the `secondaryAddressBlocks` prop.
  The following example illustrates the different options of defining the address blocks:
  ```python
  stack = Stack()
  ipam = Ipam(self, "Ipam",
      operating_region=["us-west-1"]
  )
  ipam_public_pool = ipam.public_scope.add_pool("PublicPoolA",
      address_family=AddressFamily.IP_V6,
      aws_service=AwsServiceName.EC2,
      locale="us-west-1",
      public_ip_source=IpamPoolPublicIpSource.AMAZON
  )
  ipam_public_pool.provision_cidr("PublicPoolACidrA", netmask_length=52)
  ipam_private_pool = ipam.private_scope.add_pool("PrivatePoolA",
      address_family=AddressFamily.IP_V4
  )
  ipam_private_pool.provision_cidr("PrivatePoolACidrA", netmask_length=8)
  VpcV2(self, "Vpc",
      primary_address_block=IpAddresses.ipv4("10.0.0.0/24"),
      secondary_address_blocks=[
          IpAddresses.amazon_provided_ipv6(cidr_block_name="AmazonIpv6"),
          IpAddresses.ipv6_ipam(
              ipam_pool=ipam_public_pool,
              netmask_length=52,
              cidr_block_name="ipv6Ipam"
          ),
          IpAddresses.ipv4_ipam(
              ipam_pool=ipam_private_pool,
              netmask_length=8,
              cidr_block_name="ipv4Ipam"
          )
      ]
  )
  ```
  Since `VpcV2` does not create subnets automatically, users have full control over IP addresses allocation across subnets.

  `RouteTable` is a new construct that allows for route tables to be customized in a variety of ways. For instance, the following example shows how a custom route table can be created and appended to a subnet:
  ```python
  my_vpc = VpcV2(self, "Vpc")
  route_table = RouteTable(self, "RouteTable",
      vpc=my_vpc
  )
  subnet = SubnetV2(self, "Subnet",
      vpc=my_vpc,
      route_table=route_table,
      availability_zone="eu-west-2a",
      ipv4_cidr_block=IpCidr("10.0.0.0/24"),
      subnet_type=SubnetType.PRIVATE_ISOLATED
  )
  ```
  `Routes` can be created to link subnets to various different AWS services via gateways and endpoints. Each unique route target has its own dedicated construct that can be routed to a given subnet via the `Route` construct. An example using the `InternetGateway` construct can be seen below:
  ```python
  stack = Stack()
  my_vpc = VpcV2(self, "Vpc")
  route_table = RouteTable(self, "RouteTable",
      vpc=my_vpc
  )
  subnet = SubnetV2(self, "Subnet",
      vpc=my_vpc,
      availability_zone="eu-west-2a",
      ipv4_cidr_block=IpCidr("10.0.0.0/24"),
      subnet_type=SubnetType.PRIVATE_ISOLATED
  )
  igw = InternetGateway(self, "IGW",
      vpc=my_vpc
  )
  Route(self, "IgwRoute",
      route_table=route_table,
      destination="0.0.0.0/0",
      target={"gateway": igw}
  )
  ```
  Alternatively, `Routes` can also be created via method `addRoute` in the `RouteTable` class. An example using the `EgressOnlyInternetGateway` construct can be seen below:
  Note: `EgressOnlyInternetGateway` can only be used to set up outbound IPv6 routing.
  ```python
  stack = Stack()
  my_vpc = VpcV2(self, "Vpc",
      primary_address_block=IpAddresses.ipv4("10.1.0.0/16"),
      secondary_address_blocks=[IpAddresses.amazon_provided_ipv6(
          cidr_block_name="AmazonProvided"
      )]
  )
  eigw = EgressOnlyInternetGateway(self, "EIGW",
      vpc=my_vpc
  )
  route_table = RouteTable(self, "RouteTable",
      vpc=my_vpc
  )
  route_table.add_route("EIGW", "::/0", {"gateway": eigw})
  ```
  Other route targets may require a deeper set of parameters to set up properly. For instance, the example below illustrates how to set up a `NatGateway`:
  ```python
  my_vpc = VpcV2(self, "Vpc")
  route_table = RouteTable(self, "RouteTable",
      vpc=my_vpc
  )
  subnet = SubnetV2(self, "Subnet",
      vpc=my_vpc,
      availability_zone="eu-west-2a",
      ipv4_cidr_block=IpCidr("10.0.0.0/24"),
      subnet_type=SubnetType.PRIVATE_ISOLATED
  )
  natgw = NatGateway(self, "NatGW",
      subnet=subnet,
      vpc=my_vpc,
      connectivity_type=NatConnectivityType.PRIVATE,
      private_ip_address="10.0.0.42"
  )
  Route(self, "NatGwRoute",
      route_table=route_table,
      destination="0.0.0.0/0",
      target={"gateway": natgw}
  )
  ```
  It is also possible to set up endpoints connecting other AWS services. For instance, the example below illustrates the linking of a Dynamo DB endpoint via the existing `ec2.GatewayVpcEndpoint` construct as a route target:
  ```python
  stack = Stack()
  my_vpc = VpcV2(self, "Vpc")
  route_table = RouteTable(self, "RouteTable",
      vpc=my_vpc
  )
  subnet = SubnetV2(self, "Subnet",
      vpc=my_vpc,
      availability_zone="eu-west-2a",
      ipv4_cidr_block=IpCidr("10.0.0.0/24"),
      subnet_type=SubnetType.PRIVATE
  )
  dynamo_endpoint = ec2.GatewayVpcEndpoint(self, "DynamoEndpoint",
      service=ec2.GatewayVpcEndpointAwsService.DYNAMODB,
      vpc=my_vpc,
      subnets=[subnet]
  )
  Route(self, "DynamoDBRoute",
      route_table=route_table,
      destination="0.0.0.0/0",
      target={"endpoint": dynamo_endpoint}
  )
  ```

  An egress-only internet gateway is a horizontally scaled, redundant, and highly available VPC component that allows outbound communication over IPv6 from instances in your VPC to the internet, and prevents the internet from initiating an IPv6 connection with your instances.
  For more information see [Enable outbound IPv6 traffic using an egress-only internet gateway](https://docs.aws.amazon.com/vpc/latest/userguide/egress-only-internet-gateway.html).
  VpcV2 supports adding an egress only internet gateway to VPC using the `addEgressOnlyInternetGateway` method.
  By default, this method sets up a route to all outbound IPv6 address ranges, unless a specific destination is provided by the user. It can only be configured for IPv6-enabled VPCs.
  The `Subnets` parameter accepts a `SubnetFilter`, which can be based on a `SubnetType` in VpcV2. A new route will be added to the route tables of all subnets that match this filter.
  ```python
  stack = Stack()
  my_vpc = VpcV2(self, "Vpc",
      primary_address_block=IpAddresses.ipv4("10.1.0.0/16"),
      secondary_address_blocks=[IpAddresses.amazon_provided_ipv6(
          cidr_block_name="AmazonProvided"
      )]
  )
  route_table = RouteTable(self, "RouteTable",
      vpc=my_vpc
  )
  subnet = SubnetV2(self, "Subnet",
      vpc=my_vpc,
      availability_zone="eu-west-2a",
      ipv4_cidr_block=IpCidr("10.0.0.0/24"),
      ipv6_cidr_block=IpCidr("2001:db8:1::/64"),
      subnet_type=SubnetType.PRIVATE
  )
  my_vpc.add_egress_only_internet_gateway(
      subnets=[ec2.SubnetSelection(subnet_type=SubnetType.PRIVATE)],
      destination="::/60"
  )
  ```

  A NAT gateway is a Network Address Translation (NAT) service.You can use a NAT gateway so that instances in a private subnet can connect to services outside your VPC but external services cannot initiate a connection with those instances.
  For more information, see [NAT gateway basics](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html).
  When you create a NAT gateway, you specify one of the following connectivity types:
  **Public – (Default)**: Instances in private subnets can connect to the internet through a public NAT gateway, but cannot receive unsolicited inbound connections from the internet
  **Private**: Instances in private subnets can connect to other VPCs or your on-premises network through a private NAT gateway.
  To define the NAT gateway connectivity type as `ConnectivityType.Public`, you need to ensure that there is an IGW(Internet Gateway) attached to the subnet's VPC.
  Since a NATGW is associated with a particular subnet, providing `subnet` field in the input props is mandatory.
  Additionally, you can set up a route in any route table with the target set to the NAT Gateway. The function `addNatGateway` returns a `NATGateway` object that you can reference later.
  The code example below provides the definition for adding a NAT gateway to your subnet:
  ```python
  stack = Stack()
  my_vpc = VpcV2(self, "Vpc")
  route_table = RouteTable(self, "RouteTable",
      vpc=my_vpc
  )
  subnet = SubnetV2(self, "Subnet",
      vpc=my_vpc,
      availability_zone="eu-west-2a",
      ipv4_cidr_block=IpCidr("10.0.0.0/24"),
      subnet_type=SubnetType.PUBLIC
  )
  my_vpc.add_internet_gateway()
  my_vpc.add_nat_gateway(
      subnet=subnet,
      connectivity_type=NatConnectivityType.PUBLIC
  )
  ```

  A virtual private gateway is the endpoint on the VPC side of your VPN connection.
  For more information, see [What is AWS Site-to-Site VPN?](https://docs.aws.amazon.com/vpn/latest/s2svpn/VPC_VPN.html).
  VPN route propagation is a feature in Amazon Web Services (AWS) that automatically updates route tables in your Virtual Private Cloud (VPC) with routes learned from a VPN connection.
  To enable VPN route propogation, use the `vpnRoutePropagation` property to specify the subnets as an input to the function. VPN route propagation will then be enabled for each subnet with the corresponding route table IDs.
  Additionally, you can set up a route in any route table with the target set to the VPN Gateway. The function `enableVpnGatewayV2` returns a `VPNGatewayV2` object that you can reference later.
  The code example below provides the definition for setting up a VPN gateway with `vpnRoutePropogation` enabled:
  ```python
  stack = Stack()
  my_vpc = VpcV2(self, "Vpc")
  vpn_gateway = my_vpc.enable_vpn_gateway_v2(
      vpn_route_propagation=[ec2.SubnetSelection(subnet_type=SubnetType.PUBLIC)],
      type=VpnConnectionType.IPSEC_1
  )
  route_table = RouteTable(stack, "routeTable",
      vpc=my_vpc
  )
  Route(stack, "route",
      destination="172.31.0.0/24",
      target={"gateway": vpn_gateway},
      route_table=route_table
  )
  ```

  An internet gateway is a horizontally scaled, redundant, and highly available VPC component that allows communication between your VPC and the internet. It supports both IPv4 and IPv6 traffic.
  For more information, see [Enable VPC internet access using internet gateways](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-igw-internet-access.html).
  You can add an internet gateway to a VPC using `addInternetGateway` method. By default, this method creates a route in all Public Subnets with outbound destination set to `0.0.0.0` for IPv4 and `::0` for IPv6 enabled VPC.
  Instead of using the default settings, you can configure a custom destinatation range by providing an optional input `destination` to the method.
  The code example below shows how to add an internet gateway with a custom outbound destination IP range:
  ```python
  stack = Stack()
  my_vpc = VpcV2(self, "Vpc")
  subnet = SubnetV2(self, "Subnet",
      vpc=my_vpc,
      availability_zone="eu-west-2a",
      ipv4_cidr_block=IpCidr("10.0.0.0/24"),
      subnet_type=SubnetType.PUBLIC
  )
  my_vpc.add_internet_gateway(
      ipv4_destination="192.168.0.0/16"
  )
  ```

  You can import an existing VPC and its subnets using the `VpcV2.fromVpcV2Attributes()` method or an individual subnet using `SubnetV2.fromSubnetV2Attributes()` method.

  To import an existing VPC, use the `VpcV2.fromVpcV2Attributes()` method. You'll need to provide the VPC ID, primary CIDR block, and information about the subnets. You can import secondary address as well created through IPAM, BYOIP(IPv4) or enabled through Amazon Provided IPv6. You must provide VPC Id and its primary CIDR block for importing it.
  If you wish to add a new subnet to imported VPC, new subnet's IP range(IPv4) will be validated against provided secondary and primary address block to confirm that it is within the the range of VPC.
  Here's an example of importing a VPC with only the required parameters
  ```python
  stack = Stack()
  imported_vpc = VpcV2.from_vpc_v2_attributes(stack, "ImportedVpc",
      vpc_id="mockVpcID",
      vpc_cidr_block="10.0.0.0/16"
  )
  ```
  In case of cross account or cross region VPC, its recommended to provide region and ownerAccountId so that these values for the VPC can be used to populate correct arn value for the VPC. If a VPC region and account ID is not provided, then region and account configured in the stack will be used. Furthermore, these fields will be referenced later while setting up VPC peering connection, so its necessary to set these fields to a correct value.
  Below is an example of importing a cross region and cross acount VPC, VPC arn for this case would be 'arn:aws:ec2:us-west-2:123456789012:vpc/mockVpcID'
  ```python
  stack = Stack()

  imported_vpc = VpcV2.from_vpc_v2_attributes(stack, "ImportedVpc",
      vpc_id="mockVpcID",
      vpc_cidr_block="10.0.0.0/16",
      owner_account_id="123456789012",
      region="us-west-2"
  )
  ```
  Here's an example of how to import a VPC with multiple CIDR blocks, IPv6 support, and different subnet types:
  In this example, we're importing a VPC with:
  * A primary CIDR block (10.1.0.0/16)
  * One secondary IPv4 CIDR block (10.2.0.0/16)
  * Two secondary address using IPAM pool (IPv4 and IPv6)
  * VPC has Amazon-provided IPv6 CIDR enabled
  * An isolated subnet in us-west-2a
  * A public subnet in us-west-2b
  ```python
  stack = Stack()
  imported_vpc = VpcV2.from_vpc_v2_attributes(self, "ImportedVPC",
      vpc_id="vpc-XXX",
      vpc_cidr_block="10.1.0.0/16",
      secondary_cidr_blocks=[VPCCidrBlockattributes(
          cidr_block="10.2.0.0/16",
          cidr_block_name="ImportedBlock1"
      ), VPCCidrBlockattributes(
          ipv6_ipam_pool_id="ipam-pool-XXX",
          ipv6_netmask_length=52,
          cidr_block_name="ImportedIpamIpv6"
      ), VPCCidrBlockattributes(
          ipv4_ipam_pool_id="ipam-pool-XXX",
          ipv4_ipam_provisioned_cidrs=["10.2.0.0/16"],
          cidr_block_name="ImportedIpamIpv4"
      ), VPCCidrBlockattributes(
          amazon_provided_ipv6_cidr_block=True
      )
      ],
      subnets=[SubnetV2Attributes(
          subnet_name="IsolatedSubnet2",
          subnet_id="subnet-03cd773c0fe08ed26",
          subnet_type=SubnetType.PRIVATE_ISOLATED,
          availability_zone="us-west-2a",
          ipv4_cidr_block="10.2.0.0/24",
          route_table_id="rtb-0871c310f98da2cbb"
      ), SubnetV2Attributes(
          subnet_id="subnet-0fa477e01db27d820",
          subnet_type=SubnetType.PUBLIC,
          availability_zone="us-west-2b",
          ipv4_cidr_block="10.3.0.0/24",
          route_table_id="rtb-014f3043098fe4b96"
      )]
  )


  imported_subnet = SubnetV2(self, "NewSubnet",
      availability_zone="us-west-2a",
      ipv4_cidr_block=IpCidr("10.2.2.0/24"),
      vpc=imported_vpc,
      subnet_type=SubnetType.PUBLIC
  )

  imported_vpc.add_internet_gateway()
  imported_vpc.add_nat_gateway(subnet=imported_subnet)
  imported_vpc.add_egress_only_internet_gateway()
  ```
  You can add more subnets as needed by including additional entries in the `isolatedSubnets`, `publicSubnets`, or other subnet type arrays (e.g., `privateSubnets`).

  You can also import individual subnets using the `SubnetV2.fromSubnetV2Attributes()` method. This is useful when you need to work with specific subnets independently of a VPC.
  Here's an example of how to import a subnet:
  ```python
  SubnetV2.from_subnet_v2_attributes(self, "ImportedSubnet",
      subnet_id="subnet-0123456789abcdef0",
      availability_zone="us-west-2a",
      ipv4_cidr_block="10.2.0.0/24",
      route_table_id="rtb-0871c310f98da2cbb",
      subnet_type=SubnetType.PRIVATE_ISOLATED
  )
  ```
  By importing existing VPCs and subnets, you can easily integrate your existing AWS infrastructure with new resources created through CDK. This is particularly useful when you need to work with pre-existing network configurations or when you're migrating existing infrastructure to CDK.


pkgId: 53cf16ac84fb047cd4c23fc6752d61dadce0f8e5e818dc312086b76b55faa6fc
name: python-aws-cdk.aws-ec2-alpha
arch: src
version: 2.170.0a0
epoch: 0
release: 1
summary: The CDK construct library for VPC V2
url: https://github.com/aws/aws-cdk
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk.aws-ec2-alpha-2.170.0a0-1.src.rpm
checksum_type: sha256
description:
  <!--END STABILITY BANNER-->

  `VpcV2` is a re-write of the [`ec2.Vpc`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Vpc.html) construct. This new construct enables higher level of customization
  on the VPC being created. `VpcV2` implements the existing [`IVpc`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.IVpc.html), therefore,
  `VpcV2` is compatible with other constructs that accepts `IVpc` (e.g. [`ApplicationLoadBalancer`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_elasticloadbalancingv2.ApplicationLoadBalancer.html#construct-props)).
  To create a VPC with both IPv4 and IPv6 support:
  ```python
  stack = Stack()
  VpcV2(self, "Vpc",
      primary_address_block=IpAddresses.ipv4("10.0.0.0/24"),
      secondary_address_blocks=[
          IpAddresses.amazon_provided_ipv6(cidr_block_name="AmazonProvidedIpv6")
      ]
  )
  ```
  `VpcV2` does not automatically create subnets or allocate IP addresses, which is different from the `Vpc` construct.

  `SubnetV2` is a re-write of the [`ec2.Subnet`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Subnet.html) construct.
  This new construct can be used to add subnets to a `VpcV2` instance:
  ```python
  stack = Stack()
  my_vpc = VpcV2(self, "Vpc",
      secondary_address_blocks=[
          IpAddresses.amazon_provided_ipv6(cidr_block_name="AmazonProvidedIp")
      ]
  )
  SubnetV2(self, "subnetA",
      vpc=my_vpc,
      availability_zone="us-east-1a",
      ipv4_cidr_block=IpCidr("10.0.0.0/24"),
      ipv6_cidr_block=IpCidr("2a05:d02c:25:4000::/60"),
      subnet_type=SubnetType.PRIVATE_ISOLATED
  )
  ```

  By default `VpcV2` uses `10.0.0.0/16` as the primary CIDR if none is defined.
  Additional CIDRs can be adding to the VPC via the `secondaryAddressBlocks` prop.
  The following example illustrates the different options of defining the address blocks:
  ```python
  stack = Stack()
  ipam = Ipam(self, "Ipam",
      operating_region=["us-west-1"]
  )
  ipam_public_pool = ipam.public_scope.add_pool("PublicPoolA",
      address_family=AddressFamily.IP_V6,
      aws_service=AwsServiceName.EC2,
      locale="us-west-1",
      public_ip_source=IpamPoolPublicIpSource.AMAZON
  )
  ipam_public_pool.provision_cidr("PublicPoolACidrA", netmask_length=52)
  ipam_private_pool = ipam.private_scope.add_pool("PrivatePoolA",
      address_family=AddressFamily.IP_V4
  )
  ipam_private_pool.provision_cidr("PrivatePoolACidrA", netmask_length=8)
  VpcV2(self, "Vpc",
      primary_address_block=IpAddresses.ipv4("10.0.0.0/24"),
      secondary_address_blocks=[
          IpAddresses.amazon_provided_ipv6(cidr_block_name="AmazonIpv6"),
          IpAddresses.ipv6_ipam(
              ipam_pool=ipam_public_pool,
              netmask_length=52,
              cidr_block_name="ipv6Ipam"
          ),
          IpAddresses.ipv4_ipam(
              ipam_pool=ipam_private_pool,
              netmask_length=8,
              cidr_block_name="ipv4Ipam"
          )
      ]
  )
  ```
  Since `VpcV2` does not create subnets automatically, users have full control over IP addresses allocation across subnets.

  `RouteTable` is a new construct that allows for route tables to be customized in a variety of ways. For instance, the following example shows how a custom route table can be created and appended to a subnet:
  ```python
  my_vpc = VpcV2(self, "Vpc")
  route_table = RouteTable(self, "RouteTable",
      vpc=my_vpc
  )
  subnet = SubnetV2(self, "Subnet",
      vpc=my_vpc,
      route_table=route_table,
      availability_zone="eu-west-2a",
      ipv4_cidr_block=IpCidr("10.0.0.0/24"),
      subnet_type=SubnetType.PRIVATE_ISOLATED
  )
  ```
  `Routes` can be created to link subnets to various different AWS services via gateways and endpoints. Each unique route target has its own dedicated construct that can be routed to a given subnet via the `Route` construct. An example using the `InternetGateway` construct can be seen below:
  ```python
  stack = Stack()
  my_vpc = VpcV2(self, "Vpc")
  route_table = RouteTable(self, "RouteTable",
      vpc=my_vpc
  )
  subnet = SubnetV2(self, "Subnet",
      vpc=my_vpc,
      availability_zone="eu-west-2a",
      ipv4_cidr_block=IpCidr("10.0.0.0/24"),
      subnet_type=SubnetType.PRIVATE_ISOLATED
  )
  igw = InternetGateway(self, "IGW",
      vpc=my_vpc
  )
  Route(self, "IgwRoute",
      route_table=route_table,
      destination="0.0.0.0/0",
      target={"gateway": igw}
  )
  ```
  Alternatively, `Routes` can also be created via method `addRoute` in the `RouteTable` class. An example using the `EgressOnlyInternetGateway` construct can be seen below:
  Note: `EgressOnlyInternetGateway` can only be used to set up outbound IPv6 routing.
  ```python
  stack = Stack()
  my_vpc = VpcV2(self, "Vpc",
      primary_address_block=IpAddresses.ipv4("10.1.0.0/16"),
      secondary_address_blocks=[IpAddresses.amazon_provided_ipv6(
          cidr_block_name="AmazonProvided"
      )]
  )
  eigw = EgressOnlyInternetGateway(self, "EIGW",
      vpc=my_vpc
  )
  route_table = RouteTable(self, "RouteTable",
      vpc=my_vpc
  )
  route_table.add_route("EIGW", "::/0", {"gateway": eigw})
  ```
  Other route targets may require a deeper set of parameters to set up properly. For instance, the example below illustrates how to set up a `NatGateway`:
  ```python
  my_vpc = VpcV2(self, "Vpc")
  route_table = RouteTable(self, "RouteTable",
      vpc=my_vpc
  )
  subnet = SubnetV2(self, "Subnet",
      vpc=my_vpc,
      availability_zone="eu-west-2a",
      ipv4_cidr_block=IpCidr("10.0.0.0/24"),
      subnet_type=SubnetType.PRIVATE_ISOLATED
  )
  natgw = NatGateway(self, "NatGW",
      subnet=subnet,
      vpc=my_vpc,
      connectivity_type=NatConnectivityType.PRIVATE,
      private_ip_address="10.0.0.42"
  )
  Route(self, "NatGwRoute",
      route_table=route_table,
      destination="0.0.0.0/0",
      target={"gateway": natgw}
  )
  ```
  It is also possible to set up endpoints connecting other AWS services. For instance, the example below illustrates the linking of a Dynamo DB endpoint via the existing `ec2.GatewayVpcEndpoint` construct as a route target:
  ```python
  stack = Stack()
  my_vpc = VpcV2(self, "Vpc")
  route_table = RouteTable(self, "RouteTable",
      vpc=my_vpc
  )
  subnet = SubnetV2(self, "Subnet",
      vpc=my_vpc,
      availability_zone="eu-west-2a",
      ipv4_cidr_block=IpCidr("10.0.0.0/24"),
      subnet_type=SubnetType.PRIVATE
  )
  dynamo_endpoint = ec2.GatewayVpcEndpoint(self, "DynamoEndpoint",
      service=ec2.GatewayVpcEndpointAwsService.DYNAMODB,
      vpc=my_vpc,
      subnets=[subnet]
  )
  Route(self, "DynamoDBRoute",
      route_table=route_table,
      destination="0.0.0.0/0",
      target={"endpoint": dynamo_endpoint}
  )
  ```

  VPC peering connection allows you to connect two VPCs and route traffic between them using private IP addresses. The VpcV2 construct supports creating VPC peering connections through the `VPCPeeringConnection` construct from the `route` module.
  Peering Connection cannot be established between two VPCs with overlapping CIDR ranges. Please make sure the two VPC CIDRs do not overlap with each other else it will throw an error.
  For more information, see [What is VPC peering?](https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html).
  The following show examples of how to create a peering connection between two VPCs for all possible combinations of same-account or cross-account, and same-region or cross-region configurations.
  Note: You cannot create a VPC peering connection between VPCs that have matching or overlapping CIDR blocks
  **Case 1: Same Account and Same Region Peering Connection**
  ```python
  stack = Stack()
  vpc_a = VpcV2(self, "VpcA",
      primary_address_block=IpAddresses.ipv4("10.0.0.0/16")
  )
  vpc_b = VpcV2(self, "VpcB",
      primary_address_block=IpAddresses.ipv4("10.1.0.0/16")
  )
  peering_connection = vpc_a.create_peering_connection("sameAccountSameRegionPeering",
      acceptor_vpc=vpc_b
  )
  ```
  **Case 2: Same Account and Cross Region Peering Connection**
  There is no difference from Case 1 when calling `createPeeringConnection`. The only change is that one of the VPCs are created in another stack with a different region. To establish cross region VPC peering connection, acceptorVpc needs to be imported to the requestor VPC stack using `fromVpcV2Attributes` method.
  ```python
  app = App()
  stack_a = Stack(app, "VpcStackA", env=Environment(account="000000000000", region="us-east-1"))
  stack_b = Stack(app, "VpcStackB", env=Environment(account="000000000000", region="us-west-2"))
  vpc_a = VpcV2(stack_a, "VpcA",
      primary_address_block=IpAddresses.ipv4("10.0.0.0/16")
  )
  VpcV2(stack_b, "VpcB",
      primary_address_block=IpAddresses.ipv4("10.1.0.0/16")
  )
  vpc_b = VpcV2.from_vpc_v2_attributes(stack_a, "ImportedVpcB",
      vpc_id="MockVpcBid",
      vpc_cidr_block="10.1.0.0/16",
      region="us-west-2",
      owner_account_id="000000000000"
  )
  peering_connection = vpc_a.create_peering_connection("sameAccountCrossRegionPeering",
      acceptor_vpc=vpc_b
  )
  ```
  **Case 3: Cross Account Peering Connection**
  For cross-account connections, the acceptor account needs an IAM role that grants the requestor account permission to initiate the connection. Create a new IAM role in the acceptor account using method `createAcceptorVpcRole` to provide the necessary permissions.
  Once role is created in account, provide role arn for field `peerRoleArn` under method `createPeeringConnection`
  ```python
  stack = Stack()
  acceptor_vpc = VpcV2(self, "VpcA",
      primary_address_block=IpAddresses.ipv4("10.0.0.0/16")
  )
  acceptor_role_arn = acceptor_vpc.create_acceptor_vpc_role("000000000000")
  ```
  After creating an IAM role in the acceptor account, we can initiate the peering connection request from the requestor VPC. Import accpeptorVpc to the stack using `fromVpcV2Attributes` method, it is recommended to specify owner account id of the acceptor VPC in case of cross account peering connection, if acceptor VPC is hosted in different region provide region value for import as well.
  The following code snippet demonstrates how to set up VPC peering between two VPCs in different AWS accounts using CDK:
  ```python
  stack = Stack()
  acceptor_vpc = VpcV2.from_vpc_v2_attributes(self, "acceptorVpc",
      vpc_id="vpc-XXXX",
      vpc_cidr_block="10.0.0.0/16",
      region="us-east-2",
      owner_account_id="111111111111"
  )
  acceptor_role_arn = "arn:aws:iam::111111111111:role/VpcPeeringRole"
  requestor_vpc = VpcV2(self, "VpcB",
      primary_address_block=IpAddresses.ipv4("10.1.0.0/16")
  )
  peering_connection = requestor_vpc.create_peering_connection("crossAccountCrossRegionPeering",
      acceptor_vpc=acceptor_vpc,
      peer_role_arn=acceptor_role_arn
  )
  ```

  After establishing the VPC peering connection, routes must be added to the respective route tables in the VPCs to enable traffic flow. If a route is added to the requestor stack, information will be able to flow from the requestor VPC to the acceptor VPC, but not in the reverse direction. For bi-directional communication, routes need to be added in both VPCs from their respective stacks.
  For more information, see [Update your route tables for a VPC peering connection](https://docs.aws.amazon.com/vpc/latest/peering/vpc-peering-routing.html).
  ```python
  stack = Stack()
  acceptor_vpc = VpcV2(self, "VpcA",
      primary_address_block=IpAddresses.ipv4("10.0.0.0/16")
  )
  requestor_vpc = VpcV2(self, "VpcB",
      primary_address_block=IpAddresses.ipv4("10.1.0.0/16")
  )
  peering_connection = requestor_vpc.create_peering_connection("peeringConnection",
      acceptor_vpc=acceptor_vpc
  )
  route_table = RouteTable(self, "RouteTable",
      vpc=requestor_vpc
  )
  route_table.add_route("vpcPeeringRoute", "10.0.0.0/16", {"gateway": peering_connection})
  ```
  This can also be done using AWS CLI. For more information, see [create-route](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-route.html).
  ```bash

  aws ec2 create-route --route-table-id rtb-requestor --destination-cidr-block 10.0.0.0/16 --vpc-peering-connection-id pcx-xxxxxxxx

  aws ec2 create-route --route-table-id rtb-acceptor --destination-cidr-block 10.1.0.0/16 --vpc-peering-connection-id pcx-xxxxxxxx
  ```

  To delete a VPC peering connection, use the following command:
  ```bash
  aws ec2 delete-vpc-peering-connection --vpc-peering-connection-id pcx-xxxxxxxx
  ```
  For more information, see [Delete a VPC peering connection](https://docs.aws.amazon.com/vpc/latest/peering/create-vpc-peering-connection.html#delete-vpc-peering-connection).

  An egress-only internet gateway is a horizontally scaled, redundant, and highly available VPC component that allows outbound communication over IPv6 from instances in your VPC to the internet, and prevents the internet from initiating an IPv6 connection with your instances.
  For more information see [Enable outbound IPv6 traffic using an egress-only internet gateway](https://docs.aws.amazon.com/vpc/latest/userguide/egress-only-internet-gateway.html).
  VpcV2 supports adding an egress only internet gateway to VPC using the `addEgressOnlyInternetGateway` method.
  By default, this method sets up a route to all outbound IPv6 address ranges, unless a specific destination is provided by the user. It can only be configured for IPv6-enabled VPCs.
  The `Subnets` parameter accepts a `SubnetFilter`, which can be based on a `SubnetType` in VpcV2. A new route will be added to the route tables of all subnets that match this filter.
  ```python
  stack = Stack()
  my_vpc = VpcV2(self, "Vpc",
      primary_address_block=IpAddresses.ipv4("10.1.0.0/16"),
      secondary_address_blocks=[IpAddresses.amazon_provided_ipv6(
          cidr_block_name="AmazonProvided"
      )]
  )
  route_table = RouteTable(self, "RouteTable",
      vpc=my_vpc
  )
  subnet = SubnetV2(self, "Subnet",
      vpc=my_vpc,
      availability_zone="eu-west-2a",
      ipv4_cidr_block=IpCidr("10.0.0.0/24"),
      ipv6_cidr_block=IpCidr("2001:db8:1::/64"),
      subnet_type=SubnetType.PRIVATE
  )
  my_vpc.add_egress_only_internet_gateway(
      subnets=[ec2.SubnetSelection(subnet_type=SubnetType.PRIVATE)],
      destination="::/60"
  )
  ```

  A NAT gateway is a Network Address Translation (NAT) service.You can use a NAT gateway so that instances in a private subnet can connect to services outside your VPC but external services cannot initiate a connection with those instances.
  For more information, see [NAT gateway basics](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html).
  When you create a NAT gateway, you specify one of the following connectivity types:
  **Public – (Default)**: Instances in private subnets can connect to the internet through a public NAT gateway, but cannot receive unsolicited inbound connections from the internet
  **Private**: Instances in private subnets can connect to other VPCs or your on-premises network through a private NAT gateway.
  To define the NAT gateway connectivity type as `ConnectivityType.Public`, you need to ensure that there is an IGW(Internet Gateway) attached to the subnet's VPC.
  Since a NATGW is associated with a particular subnet, providing `subnet` field in the input props is mandatory.
  Additionally, you can set up a route in any route table with the target set to the NAT Gateway. The function `addNatGateway` returns a `NATGateway` object that you can reference later.
  The code example below provides the definition for adding a NAT gateway to your subnet:
  ```python
  stack = Stack()
  my_vpc = VpcV2(self, "Vpc")
  route_table = RouteTable(self, "RouteTable",
      vpc=my_vpc
  )
  subnet = SubnetV2(self, "Subnet",
      vpc=my_vpc,
      availability_zone="eu-west-2a",
      ipv4_cidr_block=IpCidr("10.0.0.0/24"),
      subnet_type=SubnetType.PUBLIC
  )
  my_vpc.add_internet_gateway()
  my_vpc.add_nat_gateway(
      subnet=subnet,
      connectivity_type=NatConnectivityType.PUBLIC
  )
  ```

  A virtual private gateway is the endpoint on the VPC side of your VPN connection.
  For more information, see [What is AWS Site-to-Site VPN?](https://docs.aws.amazon.com/vpn/latest/s2svpn/VPC_VPN.html).
  VPN route propagation is a feature in Amazon Web Services (AWS) that automatically updates route tables in your Virtual Private Cloud (VPC) with routes learned from a VPN connection.
  To enable VPN route propogation, use the `vpnRoutePropagation` property to specify the subnets as an input to the function. VPN route propagation will then be enabled for each subnet with the corresponding route table IDs.
  Additionally, you can set up a route in any route table with the target set to the VPN Gateway. The function `enableVpnGatewayV2` returns a `VPNGatewayV2` object that you can reference later.
  The code example below provides the definition for setting up a VPN gateway with `vpnRoutePropogation` enabled:
  ```python
  stack = Stack()
  my_vpc = VpcV2(self, "Vpc")
  vpn_gateway = my_vpc.enable_vpn_gateway_v2(
      vpn_route_propagation=[ec2.SubnetSelection(subnet_type=SubnetType.PUBLIC)],
      type=VpnConnectionType.IPSEC_1
  )
  route_table = RouteTable(stack, "routeTable",
      vpc=my_vpc
  )
  Route(stack, "route",
      destination="172.31.0.0/24",
      target={"gateway": vpn_gateway},
      route_table=route_table
  )
  ```

  An internet gateway is a horizontally scaled, redundant, and highly available VPC component that allows communication between your VPC and the internet. It supports both IPv4 and IPv6 traffic.
  For more information, see [Enable VPC internet access using internet gateways](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-igw-internet-access.html).
  You can add an internet gateway to a VPC using `addInternetGateway` method. By default, this method creates a route in all Public Subnets with outbound destination set to `0.0.0.0` for IPv4 and `::0` for IPv6 enabled VPC.
  Instead of using the default settings, you can configure a custom destinatation range by providing an optional input `destination` to the method.
  The code example below shows how to add an internet gateway with a custom outbound destination IP range:
  ```python
  stack = Stack()
  my_vpc = VpcV2(self, "Vpc")
  subnet = SubnetV2(self, "Subnet",
      vpc=my_vpc,
      availability_zone="eu-west-2a",
      ipv4_cidr_block=IpCidr("10.0.0.0/24"),
      subnet_type=SubnetType.PUBLIC
  )
  my_vpc.add_internet_gateway(
      ipv4_destination="192.168.0.0/16"
  )
  ```

  You can import an existing VPC and its subnets using the `VpcV2.fromVpcV2Attributes()` method or an individual subnet using `SubnetV2.fromSubnetV2Attributes()` method.

  To import an existing VPC, use the `VpcV2.fromVpcV2Attributes()` method. You'll need to provide the VPC ID, primary CIDR block, and information about the subnets. You can import secondary address as well created through IPAM, BYOIP(IPv4) or enabled through Amazon Provided IPv6. You must provide VPC Id and its primary CIDR block for importing it.
  If you wish to add a new subnet to imported VPC, new subnet's IP range(IPv4) will be validated against provided secondary and primary address block to confirm that it is within the the range of VPC.
  Here's an example of importing a VPC with only the required parameters
  ```python
  stack = Stack()
  imported_vpc = VpcV2.from_vpc_v2_attributes(stack, "ImportedVpc",
      vpc_id="mockVpcID",
      vpc_cidr_block="10.0.0.0/16"
  )
  ```
  In case of cross account or cross region VPC, its recommended to provide region and ownerAccountId so that these values for the VPC can be used to populate correct arn value for the VPC. If a VPC region and account ID is not provided, then region and account configured in the stack will be used. Furthermore, these fields will be referenced later while setting up VPC peering connection, so its necessary to set these fields to a correct value.
  Below is an example of importing a cross region and cross acount VPC, VPC arn for this case would be 'arn:aws:ec2:us-west-2:123456789012:vpc/mockVpcID'
  ```python
  stack = Stack()

  imported_vpc = VpcV2.from_vpc_v2_attributes(stack, "ImportedVpc",
      vpc_id="mockVpcID",
      vpc_cidr_block="10.0.0.0/16",
      owner_account_id="123456789012",
      region="us-west-2"
  )
  ```
  Here's an example of how to import a VPC with multiple CIDR blocks, IPv6 support, and different subnet types:
  In this example, we're importing a VPC with:
  * A primary CIDR block (10.1.0.0/16)
  * One secondary IPv4 CIDR block (10.2.0.0/16)
  * Two secondary address using IPAM pool (IPv4 and IPv6)
  * VPC has Amazon-provided IPv6 CIDR enabled
  * An isolated subnet in us-west-2a
  * A public subnet in us-west-2b
  ```python
  stack = Stack()
  imported_vpc = VpcV2.from_vpc_v2_attributes(self, "ImportedVPC",
      vpc_id="vpc-XXX",
      vpc_cidr_block="10.1.0.0/16",
      secondary_cidr_blocks=[VPCCidrBlockattributes(
          cidr_block="10.2.0.0/16",
          cidr_block_name="ImportedBlock1"
      ), VPCCidrBlockattributes(
          ipv6_ipam_pool_id="ipam-pool-XXX",
          ipv6_netmask_length=52,
          cidr_block_name="ImportedIpamIpv6"
      ), VPCCidrBlockattributes(
          ipv4_ipam_pool_id="ipam-pool-XXX",
          ipv4_ipam_provisioned_cidrs=["10.2.0.0/16"],
          cidr_block_name="ImportedIpamIpv4"
      ), VPCCidrBlockattributes(
          amazon_provided_ipv6_cidr_block=True
      )
      ],
      subnets=[SubnetV2Attributes(
          subnet_name="IsolatedSubnet2",
          subnet_id="subnet-03cd773c0fe08ed26",
          subnet_type=SubnetType.PRIVATE_ISOLATED,
          availability_zone="us-west-2a",
          ipv4_cidr_block="10.2.0.0/24",
          route_table_id="rtb-0871c310f98da2cbb"
      ), SubnetV2Attributes(
          subnet_id="subnet-0fa477e01db27d820",
          subnet_type=SubnetType.PUBLIC,
          availability_zone="us-west-2b",
          ipv4_cidr_block="10.3.0.0/24",
          route_table_id="rtb-014f3043098fe4b96"
      )]
  )


  imported_subnet = SubnetV2(self, "NewSubnet",
      availability_zone="us-west-2a",
      ipv4_cidr_block=IpCidr("10.2.2.0/24"),
      vpc=imported_vpc,
      subnet_type=SubnetType.PUBLIC
  )

  imported_vpc.add_internet_gateway()
  imported_vpc.add_nat_gateway(subnet=imported_subnet)
  imported_vpc.add_egress_only_internet_gateway()
  ```
  You can add more subnets as needed by including additional entries in the `isolatedSubnets`, `publicSubnets`, or other subnet type arrays (e.g., `privateSubnets`).

  You can also import individual subnets using the `SubnetV2.fromSubnetV2Attributes()` method. This is useful when you need to work with specific subnets independently of a VPC.
  Here's an example of how to import a subnet:
  ```python
  SubnetV2.from_subnet_v2_attributes(self, "ImportedSubnet",
      subnet_id="subnet-0123456789abcdef0",
      availability_zone="us-west-2a",
      ipv4_cidr_block="10.2.0.0/24",
      route_table_id="rtb-0871c310f98da2cbb",
      subnet_type=SubnetType.PRIVATE_ISOLATED
  )
  ```
  By importing existing VPCs and subnets, you can easily integrate your existing AWS infrastructure with new resources created through CDK. This is particularly useful when you need to work with pre-existing network configurations or when you're migrating existing infrastructure to CDK.


pkgId: e7f45108824cbf91d60f80969a444f1f226ad85dd327488acf3256f02acfc694
name: python-aws-cdk.aws-gamelift-alpha
arch: src
version: 2.163.0a0
epoch: 0
release: 1
summary: The CDK Construct Library for AWS::GameLift
url: https://github.com/aws/aws-cdk
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk.aws-gamelift-alpha-2.163.0a0-1.src.rpm
checksum_type: sha256
description:
  <!--END STABILITY BANNER-->
  [Amazon GameLift](https://docs.aws.amazon.com/gamelift/latest/developerguide/gamelift-intro.html) is a service used
  to deploy, operate, and scale dedicated, low-cost servers in the cloud for session-based multiplayer games. Built
  on AWS global computing infrastructure, GameLift helps deliver high-performance, high-reliability game servers
  while dynamically scaling your resource usage to meet worldwide player demand.
  GameLift is composed of three main components:
  * GameLift FlexMatch which is a customizable matchmaking service for
    multiplayer games. With FlexMatch, you can
    build a custom set of rules that defines what a multiplayer match looks like
    for your game, and determines how to
    evaluate and select compatible players for each match. You can also customize
    key aspects of the matchmaking
    process to fit your game, including fine-tuning the matching algorithm.
  * GameLift hosting for custom or realtime servers which helps you deploy,
    operate, and scale dedicated game servers. It regulates the resources needed to
    host games, finds available game servers to host new game sessions, and puts
    players into games.
  * GameLift FleetIQ to optimize the use of low-cost Amazon Elastic Compute Cloud
    (Amazon EC2) Spot Instances for cloud-based game hosting. With GameLift
    FleetIQ, you can work directly with your hosting resources in Amazon EC2 and
    Amazon EC2 Auto Scaling while taking advantage of GameLift optimizations to
    deliver inexpensive, resilient game hosting for your players
  This module is part of the [AWS Cloud Development Kit](https://github.com/aws/aws-cdk) project. It allows you to define components for your matchmaking
  configuration or game server fleet management system.


  FlexMatch is available both as a GameLift game hosting solution (including
  Realtime Servers) and as a standalone matchmaking service. To set up a
  FlexMatch matchmaker to process matchmaking requests, you have to create a
  matchmaking configuration based on a RuleSet.
  More details about matchmaking ruleSet are covered [below](#matchmaking-ruleset).
  There is two types of Matchmaking configuration:
  Through a game session queue system to let FlexMatch forms matches and uses the specified GameLift queue to start a game session for the match.
  ```python


  gamelift.QueuedMatchmakingConfiguration(self, "QueuedMatchmakingConfiguration",
      matchmaking_configuration_name="test-queued-config-name",
      game_session_queues=[queue],
      rule_set=rule_set
  )
  ```
  Or through a standalone version to let FlexMatch forms matches and returns match information in an event.
  ```python

  gamelift.StandaloneMatchmakingConfiguration(self, "StandaloneMatchmaking",
      matchmaking_configuration_name="test-standalone-config-name",
      rule_set=rule_set
  )
  ```
  More details about Game session queue are covered [below](#game-session-queue).

  Every FlexMatch matchmaker must have a rule set. The rule set determines the
  two key elements of a match: your game's team structure and size, and how to
  group players together for the best possible match.
  For example, a rule set might describe a match like this: Create a match with
  two teams of four to eight players each, one team is the cowboy and the other
  team the aliens. A team can have novice and experienced players, but the
  average skill of the two teams must be within 10 points of each other. If no
  match is made after 30 seconds, gradually relax the skill requirements.
  ```python
  gamelift.MatchmakingRuleSet(self, "RuleSet",
      matchmaking_rule_set_name="my-test-ruleset",
      content=gamelift.RuleSetContent.from_json_file(path.join(__dirname, "my-ruleset", "ruleset.json"))
  )
  ```

  You can monitor GameLift FlexMatch activity for matchmaking configurations and
  matchmaking rules using Amazon CloudWatch. These statistics are used to provide
  a historical perspective on how your Gamelift FlexMatch solution is performing.

  GameLift FlexMatch sends metrics to CloudWatch so that you can collect and
  analyze the activity of your matchmaking solution, including match acceptance
  workflow, ticket consumtion.
  You can then use CloudWatch alarms to alert you, for example, when matches has
  been rejected (potential matches that were rejected by at least one player
  since the last report) exceed a certain thresold which could means that you may
  have an issue in your matchmaking rules.
  CDK provides methods for accessing GameLift FlexMatch metrics with default configuration,
  such as `metricRuleEvaluationsPassed`, or `metricRuleEvaluationsFailed` (see
  [`IMatchmakingRuleSet`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-gamelift.IMatchmakingRuleSet.html)
  for a full list). CDK also provides a generic `metric` method that can be used
  to produce metric configurations for any metric provided by GameLift FlexMatch;
  the configurations are pre-populated with the correct dimensions for the
  matchmaking configuration.
  ```python


  rule_evaluation_ratio = cloudwatch.MathExpression(
      expression="1 - (ruleEvaluationsPassed / ruleEvaluationsFailed)",
      using_metrics={
          "rule_evaluations_passed": matchmaking_rule_set.metric_rule_evaluations_passed(statistic=cloudwatch.Statistic.SUM),
          "rule_evaluations_failed": matchmaking_rule_set.metric("ruleEvaluationsFailed")
      }
  )
  cloudwatch.Alarm(self, "Alarm",
      metric=rule_evaluation_ratio,
      threshold=0.1,
      evaluation_periods=3
  )
  ```
  See: [Monitoring Using CloudWatch Metrics](https://docs.aws.amazon.com/gamelift/latest/developerguide/monitoring-cloudwatch.html)
  in the *Amazon GameLift Developer Guide*.


  Before deploying your GameLift-enabled multiplayer game servers for hosting with the GameLift service, you need to upload
  your game server files. This section provides guidance on preparing and uploading custom game server build
  files or Realtime Servers server script files. When you upload files, you create a GameLift build or script resource, which
  you then deploy on fleets of hosting resources.
  To troubleshoot fleet activation problems related to the server script, see [Debug GameLift fleet issues](https://docs.aws.amazon.com/gamelift/latest/developerguide/fleets-creating-debug.html).

  Before uploading your configured game server to GameLift for hosting, package the game build files into a build directory.
  This directory must include all components required to run your game servers and host game sessions, including the following:
  * Game server binaries – The binary files required to run the game server. A build can include binaries for multiple game
    servers built to run on the same platform. For a list of supported platforms, see [Download Amazon GameLift SDKs](https://docs.aws.amazon.com/gamelift/latest/developerguide/gamelift-supported.html).
  * Dependencies – Any dependent files that your game server executables require to run. Examples include assets, configuration
    files, and dependent libraries.
  * Install script – A script file to handle tasks that are required to fully install your game build on GameLift hosting
    servers. Place this file at the root of the build directory. GameLift runs the install script as part of fleet creation.
  You can set up any application in your build, including your install script, to access your resources securely on other AWS
  services.
  ```python

  build = gamelift.Build(self, "Build",
      content=gamelift.Content.from_bucket(bucket, "sample-asset-key")
  )
  CfnOutput(self, "BuildArn", value=build.build_arn)
  CfnOutput(self, "BuildId", value=build.build_id)
  ```
  To specify a server SDK version you used when integrating your game server build with Amazon GameLift use the `serverSdkVersion` parameter:
  > See [Integrate games with custom game servers](https://docs.aws.amazon.com/gamelift/latest/developerguide/integration-custom-intro.html) for more details.
  ```python

  build = gamelift.Build(self, "Build",
      content=gamelift.Content.from_bucket(bucket, "sample-asset-key"),
      server_sdk_version="5.0.0"
  )
  ```

  Your server script can include one or more files combined into a single .zip file for uploading. The .zip file must contain
  all files that your script needs to run.
  You can store your zipped script files in either a local file directory or in an Amazon Simple Storage Service (Amazon S3)
  bucket or defines a directory asset which is archived as a .zip file and uploaded to S3 during deployment.
  After you create the script resource, GameLift deploys the script with a new Realtime Servers fleet. GameLift installs your
  server script onto each instance in the fleet, placing the script files in `/local/game`.
  ```python

  gamelift.Script(self, "Script",
      content=gamelift.Content.from_bucket(bucket, "sample-asset-key")
  )
  ```


  Your uploaded game servers are hosted on GameLift virtual computing resources,
  called instances. You set up your hosting resources by creating a fleet of
  instances and deploying them to run your game servers. You can design a fleet
  to fit your game's needs.
  ```python
  gamelift.BuildFleet(self, "Game server fleet",
      fleet_name="test-fleet",
      content=gamelift.Build.from_asset(self, "Build", path.join(__dirname, "CustomerGameServer")),
      instance_type=ec2.InstanceType.of(ec2.InstanceClass.C4, ec2.InstanceSize.LARGE),
      runtime_configuration=gamelift.RuntimeConfiguration(
          server_processes=[gamelift.ServerProcess(
              launch_path="test-launch-path"
          )]
      )
  )
  ```

  GameLift uses a fleet's runtime configuration to determine the type and number
  of processes to run on each instance in the fleet. At a minimum, a runtime
  configuration contains one server process configuration that represents one
  game server executable. You can also define additional server process
  configurations to run other types of processes related to your game. Each
  server process configuration contains the following information:
  * The file name and path of an executable in your game build.
  * Optionally Parameters to pass to the process on launch.
  * The number of processes to run concurrently.
  A GameLift instance is limited to 50 processes running concurrently.
  ```python


  fleet = gamelift.BuildFleet(self, "Game server fleet",
      fleet_name="test-fleet",
      content=build,
      instance_type=ec2.InstanceType.of(ec2.InstanceClass.C4, ec2.InstanceSize.LARGE),
      runtime_configuration=gamelift.RuntimeConfiguration(
          server_processes=[gamelift.ServerProcess(
              launch_path="/local/game/GameLiftExampleServer.x86_64",
              parameters="-logFile /local/game/logs/myserver1935.log -port 1935",
              concurrent_executions=100
          )]
      )
  )
  ```
  See [Managing how game servers are launched for hosting](https://docs.aws.amazon.com/gamelift/latest/developerguide/fleets-multiprocess.html)
  in the *Amazon GameLift Developer Guide*.

  GameLift uses Amazon Elastic Compute Cloud (Amazon EC2) resources, called
  instances, to deploy your game servers and host game sessions for your players.
  When setting up a new fleet, you decide what type of instances your game needs
  and how to run game server processes on them (using a runtime configuration). All instances in a fleet use the same type of resources and the same runtime
  configuration. You can edit a fleet's runtime configuration and other fleet
  properties, but the type of resources cannot be changed.
  ```python

  gamelift.BuildFleet(self, "Game server fleet",
      fleet_name="test-fleet",
      content=build,
      instance_type=ec2.InstanceType.of(ec2.InstanceClass.C5, ec2.InstanceSize.LARGE),
      runtime_configuration=gamelift.RuntimeConfiguration(
          server_processes=[gamelift.ServerProcess(
              launch_path="/local/game/GameLiftExampleServer.x86_64"
          )]
      )
  )
  ```

  When setting up your hosting resources, you have the option of using Spot
  Instances, On-Demand Instances, or a combination.
  By default, fleet are using on demand capacity.
  ```python

  gamelift.BuildFleet(self, "Game server fleet",
      fleet_name="test-fleet",
      content=build,
      instance_type=ec2.InstanceType.of(ec2.InstanceClass.C4, ec2.InstanceSize.LARGE),
      runtime_configuration=gamelift.RuntimeConfiguration(
          server_processes=[gamelift.ServerProcess(
              launch_path="/local/game/GameLiftExampleServer.x86_64"
          )]
      ),
      use_spot=True
  )
  ```

  The allowed IP address ranges and port settings that allow inbound traffic to
  access game sessions on this fleet.
  New game sessions are assigned an IP address/port number combination, which
  must fall into the fleet's allowed ranges. Fleets with custom game builds must
  have permissions explicitly set. For Realtime Servers fleets, GameLift
  automatically opens two port ranges, one for TCP messaging and one for UDP.
  ```python

  fleet = gamelift.BuildFleet(self, "Game server fleet",
      fleet_name="test-fleet",
      content=build,
      instance_type=ec2.InstanceType.of(ec2.InstanceClass.C4, ec2.InstanceSize.LARGE),
      runtime_configuration=gamelift.RuntimeConfiguration(
          server_processes=[gamelift.ServerProcess(
              launch_path="/local/game/GameLiftExampleServer.x86_64"
          )]
      ),
      ingress_rules=[gamelift.IngressRule(
          source=gamelift.Peer.any_ipv4(),
          port=gamelift.Port.tcp_range(100, 200)
      )]
  )

  fleet.add_ingress_rule(gamelift.Peer.ipv4("1.2.3.4/32"), gamelift.Port.udp(1111))
  ```

  A single Amazon GameLift fleet has a home Region by default (the Region you
  deploy it to), but it can deploy resources to any number of GameLift supported
  Regions. Select Regions based on where your players are located and your
  latency needs.
  By default, home region is used as default location but we can add new locations if needed and define desired capacity
  ```python


  fleet = gamelift.BuildFleet(self, "Game server fleet",
      fleet_name="test-fleet",
      content=build,
      instance_type=ec2.InstanceType.of(ec2.InstanceClass.C4, ec2.InstanceSize.LARGE),
      runtime_configuration=gamelift.RuntimeConfiguration(
          server_processes=[gamelift.ServerProcess(
              launch_path="/local/game/GameLiftExampleServer.x86_64"
          )]
      ),
      locations=[gamelift.Location(
          region="eu-west-1",
          capacity=gamelift.LocationCapacity(
              desired_capacity=5,
              min_size=2,
              max_size=10
          )
      ), gamelift.Location(
          region="us-east-1",
          capacity=gamelift.LocationCapacity(
              desired_capacity=5,
              min_size=2,
              max_size=10
          )
      )]
  )

  fleet.add_location("ap-southeast-1", 5, 2, 10)
  ```

  Some GameLift features require you to extend limited access to your AWS
  resources. This is done by creating an AWS IAM role. The GameLift Fleet class
  automatically created an IAM role with all the minimum necessary permissions
  for GameLift to access your resources. If you wish, you may
  specify your own IAM role.
  ```python

  role = iam.Role(self, "Role",
      assumed_by=iam.CompositePrincipal(iam.ServicePrincipal("gamelift.amazonaws.com"))
  )
  role.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name("CloudWatchAgentServerPolicy"))
  fleet = gamelift.BuildFleet(self, "Game server fleet",
      fleet_name="test-fleet",
      content=build,
      instance_type=ec2.InstanceType.of(ec2.InstanceClass.C5, ec2.InstanceSize.LARGE),
      runtime_configuration=gamelift.RuntimeConfiguration(
          server_processes=[gamelift.ServerProcess(
              launch_path="/local/game/GameLiftExampleServer.x86_64"
          )]
      ),
      role=role
  )

  fleet.grant(role, "gamelift:ListFleets")
  ```

  A GameLift alias is used to abstract a fleet designation. Fleet designations
  tell Amazon GameLift where to search for available resources when creating new
  game sessions for players. By using aliases instead of specific fleet IDs, you
  can more easily and seamlessly switch player traffic from one fleet to another
  by changing the alias's target location.
  ```python


  live_alias = fleet.add_alias("live")

  gamelift.Alias(self, "TerminalAlias",
      alias_name="terminal-alias",
      terminal_message="A terminal message"
  )
  ```
  See [Add an alias to a GameLift fleet](https://docs.aws.amazon.com/gamelift/latest/developerguide/aliases-creating.html)
  in the *Amazon GameLift Developer Guide*.

  GameLift is integrated with CloudWatch, so you can monitor the performance of
  your game servers via logs and metrics.

  GameLift Fleet sends metrics to CloudWatch so that you can collect and analyze
  the activity of your Fleet, including game  and player sessions and server
  processes.
  You can then use CloudWatch alarms to alert you, for example, when matches has
  been rejected (potential matches that were rejected by at least one player
  since the last report) exceed a certain threshold which could means that you may
  have an issue in your matchmaking rules.
  CDK provides methods for accessing GameLift Fleet metrics with default configuration,
  such as `metricActiveInstances`, or `metricIdleInstances` (see [`IFleet`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-gamelift.IFleet.html)
  for a full list). CDK also provides a generic `metric` method that can be used
  to produce metric configurations for any metric provided by GameLift Fleet,
  Game sessions or server processes; the configurations are pre-populated with
  the correct dimensions for the matchmaking configuration.
  ```python


  instances_used_ratio = cloudwatch.MathExpression(
      expression="1 - (activeInstances / idleInstances)",
      using_metrics={
          "active_instances": fleet.metric("ActiveInstances", statistic=cloudwatch.Statistic.SUM),
          "idle_instances": fleet.metric_idle_instances()
      }
  )
  cloudwatch.Alarm(self, "Alarm",
      metric=instances_used_ratio,
      threshold=0.1,
      evaluation_periods=3
  )
  ```
  See: [Monitoring Using CloudWatch Metrics](https://docs.aws.amazon.com/gamelift/latest/developerguide/monitoring-cloudwatch.html)
  in the *Amazon GameLift Developer Guide*.

  The game session queue is the primary mechanism for processing new game session
  requests and locating available game servers to host them. Although it is
  possible to request a new game session be hosted on specific fleet or location.
  The `GameSessionQueue` resource creates a placement queue that processes requests for
  new game sessions. A queue uses FleetIQ algorithms to determine the best placement
  locations and find an available game server, then prompts the game server to start a
  new game session. Queues can have destinations (GameLift fleets or aliases), which
  determine where the queue can place new game sessions. A queue can have destinations
  with varied fleet type (Spot and On-Demand), instance type, and AWS Region.
  ```python


  queue = gamelift.GameSessionQueue(self, "GameSessionQueue",
      game_session_queue_name="my-queue-name",
      destinations=[fleet]
  )
  queue.add_destination(alias)
  ```
  A more complex configuration can also be definied to override how FleetIQ algorithms prioritize game session placement in order to favour a destination based on `Cost`, `Latency`, `Destination order`or `Location`.
  ```python


  gamelift.GameSessionQueue(self, "MyGameSessionQueue",
      game_session_queue_name="test-gameSessionQueue",
      custom_event_data="test-event-data",
      allowed_locations=["eu-west-1", "eu-west-2"],
      destinations=[fleet],
      notification_target=topic,
      player_latency_policies=[gamelift.PlayerLatencyPolicy(
          maximum_individual_player_latency=Duration.millis(100),
          policy_duration=Duration.seconds(300)
      )],
      priority_configuration=gamelift.PriorityConfiguration(
          location_order=["eu-west-1", "eu-west-2"
          ],
          priority_order=[gamelift.PriorityType.LATENCY, gamelift.PriorityType.COST, gamelift.PriorityType.DESTINATION, gamelift.PriorityType.LOCATION
          ]
      ),
      timeout=Duration.seconds(300)
  )
  ```
  See [Setting up GameLift queues for game session placement](https://docs.aws.amazon.com/gamelift/latest/developerguide/realtime-script-uploading.html)
  in the *Amazon GameLift Developer Guide*.

  The GameLift FleetIQ solution is a game hosting layer that supplements the full
  set of computing resource management tools that you get with Amazon EC2 and
  Auto Scaling. This solution lets you directly manage your Amazon EC2 and Auto
  Scaling resources and integrate as needed with other AWS services.

  When using GameLift FleetIQ, you prepare to launch Amazon EC2 instances as
  usual: make an Amazon Machine Image (AMI) with your game server software,
  create an Amazon EC2 launch template, and define configuration settings for an
  Auto Scaling group. However, instead of creating an Auto Scaling group
  directly, you create a GameLift FleetIQ game server group with your Amazon EC2
  and Auto Scaling resources and configuration. All game server groups must have
  at least two instance types defined for it.
  Once a game server group and Auto Scaling group are up and running with
  instances deployed, when updating a Game Server Group instance, only certain
  properties in the Auto Scaling group may be overwrite. For all other Auto
  Scaling group properties, such as MinSize, MaxSize, and LaunchTemplate, you can
  modify these directly on the Auto Scaling group using the AWS Console or
  dedicated Api.
  ```python


  gamelift.GameServerGroup(self, "Game server group",
      game_server_group_name="sample-gameservergroup-name",
      instance_definitions=[gamelift.InstanceDefinition(
          instance_type=ec2.InstanceType.of(ec2.InstanceClass.C5, ec2.InstanceSize.LARGE)
      ), gamelift.InstanceDefinition(
          instance_type=ec2.InstanceType.of(ec2.InstanceClass.C4, ec2.InstanceSize.LARGE)
      )],
      launch_template=launch_template,
      vpc=vpc
  )
  ```
  See [Manage game server groups](https://docs.aws.amazon.com/gamelift/latest/fleetiqguide/gsg-integrate-gameservergroup.html)
  in the *Amazon GameLift FleetIQ Developer Guide*.

  The scaling policy uses the metric `PercentUtilizedGameServers` to maintain a
  buffer of idle game servers that can immediately accommodate new games and
  players.
  ```python


  gamelift.GameServerGroup(self, "Game server group",
      game_server_group_name="sample-gameservergroup-name",
      instance_definitions=[gamelift.InstanceDefinition(
          instance_type=ec2.InstanceType.of(ec2.InstanceClass.C5, ec2.InstanceSize.LARGE)
      ), gamelift.InstanceDefinition(
          instance_type=ec2.InstanceType.of(ec2.InstanceClass.C4, ec2.InstanceSize.LARGE)
      )],
      launch_template=launch_template,
      vpc=vpc,
      auto_scaling_policy=gamelift.AutoScalingPolicy(
          estimated_instance_warmup=Duration.minutes(5),
          target_tracking_configuration=5
      )
  )
  ```
  See [Manage game server groups](https://docs.aws.amazon.com/gamelift/latest/fleetiqguide/gsg-integrate-gameservergroup.html)
  in the *Amazon GameLift FleetIQ Developer Guide*.

  The GameLift FleetIQ class automatically creates an IAM role with all the minimum necessary
  permissions for GameLift to access your Amazon EC2 Auto Scaling groups. If you wish, you may
  specify your own IAM role. It must have the correct permissions, or FleetIQ creation or resource usage may fail.
  ```python


  role = iam.Role(self, "Role",
      assumed_by=iam.CompositePrincipal(iam.ServicePrincipal("gamelift.amazonaws.com"),
      iam.ServicePrincipal("autoscaling.amazonaws.com"))
  )
  role.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name("GameLiftGameServerGroupPolicy"))
  gamelift.GameServerGroup(self, "Game server group",
      game_server_group_name="sample-gameservergroup-name",
      instance_definitions=[gamelift.InstanceDefinition(
          instance_type=ec2.InstanceType.of(ec2.InstanceClass.C5, ec2.InstanceSize.LARGE)
      ), gamelift.InstanceDefinition(
          instance_type=ec2.InstanceType.of(ec2.InstanceClass.C4, ec2.InstanceSize.LARGE)
      )],
      launch_template=launch_template,
      vpc=vpc,
      role=role
  )
  ```
  See [Controlling Access](https://docs.aws.amazon.com/gamelift/latest/fleetiqguide/gsg-iam-permissions-roles.html)
  in the *Amazon GameLift FleetIQ Developer Guide*.

  GameLift FleetIQ use by default, all supported GameLift FleetIQ Availability
  Zones in your chosen region. You can override this parameter to specify VPCs
  subnets that you've set up.
  This property cannot be updated after the game server group is created, and the
  corresponding Auto Scaling group will always use the property value that is set
  with this request, even if the Auto Scaling group is updated directly.
  ```python


  gamelift.GameServerGroup(self, "GameServerGroup",
      game_server_group_name="sample-gameservergroup-name",
      instance_definitions=[gamelift.InstanceDefinition(
          instance_type=ec2.InstanceType.of(ec2.InstanceClass.C5, ec2.InstanceSize.LARGE)
      ), gamelift.InstanceDefinition(
          instance_type=ec2.InstanceType.of(ec2.InstanceClass.C4, ec2.InstanceSize.LARGE)
      )],
      launch_template=launch_template,
      vpc=vpc,
      vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC)
  )
  ```

  GameLift FleetIQ sends metrics to CloudWatch so that you can collect and
  analyze the activity of your Game server fleet, including the number of
  utilized game servers, and the number of game server interruption due to
  limited Spot availability.
  You can then use CloudWatch alarms to alert you, for example, when the portion
  of game servers that are currently supporting game executions exceed a certain
  threshold which could means that your autoscaling policy need to be adjust to
  add more instances to match with player demand.
  CDK provides a generic `metric` method that can be used
  to produce metric configurations for any metric provided by GameLift FleetIQ;
  the configurations are pre-populated with the correct dimensions for the
  matchmaking configuration.
  ```python


  cloudwatch.Alarm(self, "Alarm",
      metric=game_server_group.metric("UtilizedGameServers"),
      threshold=0.9,
      evaluation_periods=2
  )
  ```
  See: [Monitoring with CloudWatch](https://docs.aws.amazon.com/gamelift/latest/fleetiqguide/gsg-metrics.html)
  in the *Amazon GameLift FleetIQ Developer Guide*.


pkgId: 1557359f01166b78dff3a8706be4f1671bea73d1f8037d3b9eeb2434ccc71984
name: python-aws-cdk.aws-glue-alpha
arch: src
version: 2.159.0a0
epoch: 0
release: 1
summary: The CDK Construct Library for AWS::Glue
url: https://github.com/aws/aws-cdk
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk.aws-glue-alpha-2.159.0a0-1.src.rpm
checksum_type: sha256
description:
  <!--END STABILITY BANNER-->
  This module is part of the [AWS Cloud Development Kit](https://github.com/aws/aws-cdk) project.

  A `Job` encapsulates a script that connects to data sources, processes them, and then writes output to a data target.
  There are 3 types of jobs supported by AWS Glue: Spark ETL, Spark Streaming, and Python Shell jobs.
  The `glue.JobExecutable` allows you to specify the type of job, the language to use and the code assets required by the job.
  `glue.Code` allows you to refer to the different code assets required by the job, either from an existing S3 location or from a local file path.
  `glue.ExecutionClass` allows you to specify `FLEX` or `STANDARD`. `FLEX` is appropriate for non-urgent jobs such as pre-production jobs, testing, and one-time data loads.

  These jobs run in an Apache Spark environment managed by AWS Glue.

  An ETL job processes data in batches using Apache Spark.
  ```python

  glue.Job(self, "ScalaSparkEtlJob",
      executable=glue.JobExecutable.scala_etl(
          glue_version=glue.GlueVersion.V4_0,
          script=glue.Code.from_bucket(bucket, "src/com/example/HelloWorld.scala"),
          class_name="com.example.HelloWorld",
          extra_jars=[glue.Code.from_bucket(bucket, "jars/HelloWorld.jar")]
      ),
      worker_type=glue.WorkerType.G_8X,
      description="an example Scala ETL job"
  )
  ```

  A Streaming job is similar to an ETL job, except that it performs ETL on data streams. It uses the Apache Spark Structured Streaming framework. Some Spark job features are not available to streaming ETL jobs.
  ```python
  glue.Job(self, "PythonSparkStreamingJob",
      executable=glue.JobExecutable.python_streaming(
          glue_version=glue.GlueVersion.V4_0,
          python_version=glue.PythonVersion.THREE,
          script=glue.Code.from_asset(path.join(__dirname, "job-script", "hello_world.py"))
      ),
      description="an example Python Streaming job"
  )
  ```

  A Python shell job runs Python scripts as a shell and supports a Python version that depends on the AWS Glue version you are using.
  This can be used to schedule and run tasks that don't require an Apache Spark environment. Currently, three flavors are supported:
  * PythonVersion.TWO (2.7; EOL)
  * PythonVersion.THREE (3.6)
  * PythonVersion.THREE_NINE (3.9)
  ```python

  glue.Job(self, "PythonShellJob",
      executable=glue.JobExecutable.python_shell(
          glue_version=glue.GlueVersion.V1_0,
          python_version=glue.PythonVersion.THREE,
          script=glue.Code.from_bucket(bucket, "script.py")
      ),
      description="an example Python Shell job"
  )
  ```

  These jobs run in a Ray environment managed by AWS Glue.
  ```python
  glue.Job(self, "RayJob",
      executable=glue.JobExecutable.python_ray(
          glue_version=glue.GlueVersion.V4_0,
          python_version=glue.PythonVersion.THREE_NINE,
          runtime=glue.Runtime.RAY_TWO_FOUR,
          script=glue.Code.from_asset(path.join(__dirname, "job-script", "hello_world.py"))
      ),
      worker_type=glue.WorkerType.Z_2X,
      worker_count=2,
      description="an example Ray job"
  )
  ```

  Enable Spark UI setting the `sparkUI` property.
  ```python
  glue.Job(self, "EnableSparkUI",
      job_name="EtlJobWithSparkUIPrefix",
      spark_uI=glue.SparkUIProps(
          enabled=True
      ),
      executable=glue.JobExecutable.python_etl(
          glue_version=glue.GlueVersion.V3_0,
          python_version=glue.PythonVersion.THREE,
          script=glue.Code.from_asset(path.join(__dirname, "job-script", "hello_world.py"))
      )
  )
  ```
  The `sparkUI` property also allows the specification of an s3 bucket and a bucket prefix.
  See [documentation](https://docs.aws.amazon.com/glue/latest/dg/add-job.html) for more information on adding jobs in Glue.

  A `Connection` allows Glue jobs, crawlers and development endpoints to access certain types of data stores. For example, to create a network connection to connect to a data source within a VPC:
  ```python


  glue.Connection(self, "MyConnection",
      type=glue.ConnectionType.NETWORK,
      
      security_groups=[security_group],
      
      subnet=subnet
  )
  ```
  For RDS `Connection` by JDBC, it is recommended to manage credentials using AWS Secrets Manager. To use Secret, specify `SECRET_ID` in `properties` like the following code. Note that in this case, the subnet must have a route to the AWS Secrets Manager VPC endpoint or to the AWS Secrets Manager endpoint through a NAT gateway.
  ```python



  glue.Connection(self, "RdsConnection",
      type=glue.ConnectionType.JDBC,
      security_groups=[security_group],
      subnet=subnet,
      properties={
          "JDBC_CONNECTION_URL": f"jdbc:mysql://{db.clusterEndpoint.socketAddress}/databasename",
          "JDBC_ENFORCE_SSL": "false",
          "SECRET_ID": db.secret.secret_name
      }
  )
  ```
  If you need to use a connection type that doesn't exist as a static member on `ConnectionType`, you can instantiate a `ConnectionType` object, e.g: `new glue.ConnectionType('NEW_TYPE')`.
  See [Adding a Connection to Your Data Store](https://docs.aws.amazon.com/glue/latest/dg/populate-add-connection.html) and [Connection Structure](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-connections.html#aws-glue-api-catalog-connections-Connection) documentation for more information on the supported data stores and their configurations.

  A `SecurityConfiguration` is a set of security properties that can be used by AWS Glue to encrypt data at rest.
  ```python
  glue.SecurityConfiguration(self, "MySecurityConfiguration",
      cloud_watch_encryption=glue.CloudWatchEncryption(
          mode=glue.CloudWatchEncryptionMode.KMS
      ),
      job_bookmarks_encryption=glue.JobBookmarksEncryption(
          mode=glue.JobBookmarksEncryptionMode.CLIENT_SIDE_KMS
      ),
      s3_encryption=glue.S3Encryption(
          mode=glue.S3EncryptionMode.KMS
      )
  )
  ```
  By default, a shared KMS key is created for use with the encryption configurations that require one. You can also supply your own key for each encryption config, for example, for CloudWatch encryption:
  ```python

  glue.SecurityConfiguration(self, "MySecurityConfiguration",
      cloud_watch_encryption=glue.CloudWatchEncryption(
          mode=glue.CloudWatchEncryptionMode.KMS,
          kms_key=key
      )
  )
  ```
  See [documentation](https://docs.aws.amazon.com/glue/latest/dg/encryption-security-configuration.html) for more info for Glue encrypting data written by Crawlers, Jobs, and Development Endpoints.

  A `Database` is a logical grouping of `Tables` in the Glue Catalog.
  ```python
  glue.Database(self, "MyDatabase",
      database_name="my_database",
      description="my_database_description"
  )
  ```

  A Glue table describes a table of data in S3: its structure (column names and types), location of data (S3 objects with a common prefix in a S3 bucket), and format for the files (Json, Avro, Parquet, etc.):
  ```python

  glue.S3Table(self, "MyTable",
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      ), glue.Column(
          name="col2",
          type=glue.Schema.array(glue.Schema.STRING),
          comment="col2 is an array of strings"
      )],
      data_format=glue.DataFormat.JSON
  )
  ```
  By default, a S3 bucket will be created to store the table's data but you can manually pass the `bucket` and `s3Prefix`:
  ```python


  glue.S3Table(self, "MyTable",
      bucket=my_bucket,
      s3_prefix="my-table/",
      
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      data_format=glue.DataFormat.JSON
  )
  ```
  Glue tables can be configured to contain user-defined properties, to describe the physical storage of table data, through the `storageParameters` property:
  ```python

  glue.S3Table(self, "MyTable",
      storage_parameters=[
          glue.StorageParameter.skip_header_line_count(1),
          glue.StorageParameter.compression_type(glue.CompressionType.GZIP),
          glue.StorageParameter.custom("separatorChar", ",")
      ],
      
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      data_format=glue.DataFormat.JSON
  )
  ```
  Glue tables can also be configured to contain user-defined table properties through the [`parameters`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-tableinput.html#cfn-glue-table-tableinput-parameters) property:
  ```python

  glue.S3Table(self, "MyTable",
      parameters={
          "key1": "val1",
          "key2": "val2"
      },
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      data_format=glue.DataFormat.JSON
  )
  ```

  To improve query performance, a table can specify `partitionKeys` on which data is stored and queried separately. For example, you might partition a table by `year` and `month` to optimize queries based on a time window:
  ```python

  glue.S3Table(self, "MyTable",
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      partition_keys=[glue.Column(
          name="year",
          type=glue.Schema.SMALL_INT
      ), glue.Column(
          name="month",
          type=glue.Schema.SMALL_INT
      )],
      data_format=glue.DataFormat.JSON
  )
  ```

  Another way to improve query performance is to specify partition indexes. If no partition indexes are
  present on the table, AWS Glue loads all partitions of the table and filters the loaded partitions using
  the query expression. The query takes more time to run as the number of partitions increase. With an
  index, the query will try to fetch a subset of the partitions instead of loading all partitions of the
  table.
  The keys of a partition index must be a subset of the partition keys of the table. You can have a
  maximum of 3 partition indexes per table. To specify a partition index, you can use the `partitionIndexes`
  property:
  ```python

  glue.S3Table(self, "MyTable",
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      partition_keys=[glue.Column(
          name="year",
          type=glue.Schema.SMALL_INT
      ), glue.Column(
          name="month",
          type=glue.Schema.SMALL_INT
      )],
      partition_indexes=[glue.PartitionIndex(
          index_name="my-index",  # optional
          key_names=["year"]
      )],  # supply up to 3 indexes
      data_format=glue.DataFormat.JSON
  )
  ```
  Alternatively, you can call the `addPartitionIndex()` function on a table:
  ```python

  my_table.add_partition_index(
      index_name="my-index",
      key_names=["year"]
  )
  ```

  If you have a table with a large number of partitions that grows over time, consider using AWS Glue partition indexing and filtering.
  ```python

  glue.S3Table(self, "MyTable",
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      partition_keys=[glue.Column(
          name="year",
          type=glue.Schema.SMALL_INT
      ), glue.Column(
          name="month",
          type=glue.Schema.SMALL_INT
      )],
      data_format=glue.DataFormat.JSON,
      enable_partition_filtering=True
  )
  ```

  Glue connections allow external data connections to third party databases and data warehouses. However, these connections can also be assigned to Glue Tables, allowing you to query external data sources using the Glue Data Catalog.
  Whereas `S3Table` will point to (and if needed, create) a bucket to store the tables' data, `ExternalTable` will point to an existing table in a data source. For example, to create a table in Glue that points to a table in Redshift:
  ```python


  glue.ExternalTable(self, "MyTable",
      connection=my_connection,
      external_data_location="default_db_public_example",  # A table in Redshift
      
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      data_format=glue.DataFormat.JSON
  )
  ```

  You can enable encryption on a Table's data:
  * [S3Managed](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingServerSideEncryption.html) - (default) Server side encryption (`SSE-S3`) with an Amazon S3-managed key.
  ```python

  glue.S3Table(self, "MyTable",
      encryption=glue.TableEncryption.S3_MANAGED,
      
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      data_format=glue.DataFormat.JSON
  )
  ```
  * [Kms](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html) - Server-side encryption (`SSE-KMS`) with an AWS KMS Key managed by the account owner.
  ```python


  glue.S3Table(self, "MyTable",
      encryption=glue.TableEncryption.KMS,
      
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      data_format=glue.DataFormat.JSON
  )

  glue.S3Table(self, "MyTable",
      encryption=glue.TableEncryption.KMS,
      encryption_key=kms.Key(self, "MyKey"),
      
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      data_format=glue.DataFormat.JSON
  )
  ```
  * [KmsManaged](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html) - Server-side encryption (`SSE-KMS`), like `Kms`, except with an AWS KMS Key managed by the AWS Key Management Service.
  ```python

  glue.S3Table(self, "MyTable",
      encryption=glue.TableEncryption.KMS_MANAGED,
      
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      data_format=glue.DataFormat.JSON
  )
  ```
  * [ClientSideKms](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingClientSideEncryption.html#client-side-encryption-kms-managed-master-key-intro) - Client-side encryption (`CSE-KMS`) with an AWS KMS Key managed by the account owner.
  ```python


  glue.S3Table(self, "MyTable",
      encryption=glue.TableEncryption.CLIENT_SIDE_KMS,
      
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      data_format=glue.DataFormat.JSON
  )

  glue.S3Table(self, "MyTable",
      encryption=glue.TableEncryption.CLIENT_SIDE_KMS,
      encryption_key=kms.Key(self, "MyKey"),
      
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      data_format=glue.DataFormat.JSON
  )
  ```
  *Note: you cannot provide a `Bucket` when creating the `S3Table` if you wish to use server-side encryption (`KMS`, `KMS_MANAGED` or `S3_MANAGED`)*.

  A table's schema is a collection of columns, each of which have a `name` and a `type`. Types are recursive structures, consisting of primitive and complex types:
  ```python

  glue.S3Table(self, "MyTable",
      columns=[glue.Column(
          name="primitive_column",
          type=glue.Schema.STRING
      ), glue.Column(
          name="array_column",
          type=glue.Schema.array(glue.Schema.INTEGER),
          comment="array<integer>"
      ), glue.Column(
          name="map_column",
          type=glue.Schema.map(glue.Schema.STRING, glue.Schema.TIMESTAMP),
          comment="map<string,string>"
      ), glue.Column(
          name="struct_column",
          type=glue.Schema.struct([
              name="nested_column",
              type=glue.Schema.DATE,
              comment="nested comment"
          ]),
          comment="struct<nested_column:date COMMENT 'nested comment'>"
      )],
      
      database=my_database,
      data_format=glue.DataFormat.JSON
  )
  ```


  | Name      	| Type     	| Comments                                                                                                          |
  |-----------	|----------	|------------------------------------------------------------------------------------------------------------------	|
  | FLOAT     	| Constant 	| A 32-bit single-precision floating point number                                                                   |
  | INTEGER   	| Constant 	| A 32-bit signed value in two's complement format, with a minimum value of -2^31 and a maximum value of 2^31-1 	|
  | DOUBLE    	| Constant 	| A 64-bit double-precision floating point number                                                                   |
  | BIG_INT   	| Constant 	| A 64-bit signed INTEGER in two’s complement format, with a minimum value of -2^63 and a maximum value of 2^63 -1  |
  | SMALL_INT 	| Constant 	| A 16-bit signed INTEGER in two’s complement format, with a minimum value of -2^15 and a maximum value of 2^15-1   |
  | TINY_INT  	| Constant 	| A 8-bit signed INTEGER in two’s complement format, with a minimum value of -2^7 and a maximum value of 2^7-1      |

  | Name      	| Type     	| Comments                                                                                                                                                                	|
  |-----------	|----------	|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------	|
  | DATE      	| Constant 	| A date in UNIX format, such as YYYY-MM-DD.                                                                                                                              	|
  | TIMESTAMP 	| Constant 	| Date and time instant in the UNiX format, such as yyyy-mm-dd hh:mm:ss[.f...]. For example, TIMESTAMP '2008-09-15 03:04:05.324'. This format uses the session time zone. 	|

  | Name                                       	| Type     	| Comments                                                                                                                                                                                          	|
  |--------------------------------------------	|----------	|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------	|
  | STRING                                     	| Constant 	| A string literal enclosed in single or double quotes                                                                                                                                              	|
  | decimal(precision: number, scale?: number) 	| Function 	| `precision` is the total number of digits. `scale` (optional) is the number of digits in fractional part with a default of 0. For example, use these type definitions: decimal(11,5), decimal(15) 	|
  | char(length: number)                       	| Function 	| Fixed length character data, with a specified length between 1 and 255, such as char(10)                                                                                                          	|
  | varchar(length: number)                    	| Function 	| Variable length character data, with a specified length between 1 and 65535, such as varchar(10)                                                                                                  	|

  | Name    	| Type     	| Comments                      	|
  |---------	|----------	|-------------------------------	|
  | BOOLEAN 	| Constant 	| Values are `true` and `false` 	|
  | BINARY  	| Constant 	| Value is in binary            	|

  | Name                                	| Type     	| Comments                                                          	|
  |-------------------------------------	|----------	|-------------------------------------------------------------------	|
  | array(itemType: Type)               	| Function 	| An array of some other type                                       	|
  | map(keyType: Type, valueType: Type) 	| Function 	| A map of some primitive key type to any value type                	|
  | struct(collumns: Column[])          	| Function 	| Nested structure containing individually named and typed collumns 	|

  A `DataQualityRuleset` specifies a data quality ruleset with DQDL rules applied to a specified AWS Glue table. For example, to create a data quality ruleset for a given table:
  ```python
  glue.DataQualityRuleset(self, "MyDataQualityRuleset",
      client_token="client_token",
      description="description",
      ruleset_name="ruleset_name",
      ruleset_dqdl="ruleset_dqdl",
      tags={
          "key1": "value1",
          "key2": "value2"
      },
      target_table=glue.DataQualityTargetTable("database_name", "table_name")
  )
  ```
  For more information, see [AWS Glue Data Quality](https://docs.aws.amazon.com/glue/latest/dg/glue-data-quality.html).


pkgId: d1958ba5540b64412ced6bd4b54de7d23203b199a4963b5c608e6a800ef24c8b
name: python-aws-cdk.aws-glue-alpha
arch: src
version: 2.167.0a0
epoch: 0
release: 1
summary: The CDK Construct Library for AWS::Glue
url: https://github.com/aws/aws-cdk
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk.aws-glue-alpha-2.167.0a0-1.src.rpm
checksum_type: sha256
description:
  <!--END STABILITY BANNER-->
  This module is part of the [AWS Cloud Development Kit](https://github.com/aws/aws-cdk) project.

  A `Job` encapsulates a script that connects to data sources, processes them, and then writes output to a data target.
  There are 3 types of jobs supported by AWS Glue: Spark ETL, Spark Streaming, and Python Shell jobs.
  The `glue.JobExecutable` allows you to specify the type of job, the language to use and the code assets required by the job.
  `glue.Code` allows you to refer to the different code assets required by the job, either from an existing S3 location or from a local file path.
  `glue.ExecutionClass` allows you to specify `FLEX` or `STANDARD`. `FLEX` is appropriate for non-urgent jobs such as pre-production jobs, testing, and one-time data loads.

  These jobs run in an Apache Spark environment managed by AWS Glue.

  An ETL job processes data in batches using Apache Spark.
  ```python

  glue.Job(self, "ScalaSparkEtlJob",
      executable=glue.JobExecutable.scala_etl(
          glue_version=glue.GlueVersion.V4_0,
          script=glue.Code.from_bucket(bucket, "src/com/example/HelloWorld.scala"),
          class_name="com.example.HelloWorld",
          extra_jars=[glue.Code.from_bucket(bucket, "jars/HelloWorld.jar")]
      ),
      worker_type=glue.WorkerType.G_8X,
      description="an example Scala ETL job"
  )
  ```

  A Streaming job is similar to an ETL job, except that it performs ETL on data streams. It uses the Apache Spark Structured Streaming framework. Some Spark job features are not available to streaming ETL jobs.
  ```python
  glue.Job(self, "PythonSparkStreamingJob",
      executable=glue.JobExecutable.python_streaming(
          glue_version=glue.GlueVersion.V4_0,
          python_version=glue.PythonVersion.THREE,
          script=glue.Code.from_asset(path.join(__dirname, "job-script", "hello_world.py"))
      ),
      description="an example Python Streaming job"
  )
  ```

  A Python shell job runs Python scripts as a shell and supports a Python version that depends on the AWS Glue version you are using.
  This can be used to schedule and run tasks that don't require an Apache Spark environment. Currently, three flavors are supported:
  * PythonVersion.TWO (2.7; EOL)
  * PythonVersion.THREE (3.6)
  * PythonVersion.THREE_NINE (3.9)
  ```python

  glue.Job(self, "PythonShellJob",
      executable=glue.JobExecutable.python_shell(
          glue_version=glue.GlueVersion.V1_0,
          python_version=glue.PythonVersion.THREE,
          script=glue.Code.from_bucket(bucket, "script.py")
      ),
      description="an example Python Shell job"
  )
  ```

  These jobs run in a Ray environment managed by AWS Glue.
  ```python
  glue.Job(self, "RayJob",
      executable=glue.JobExecutable.python_ray(
          glue_version=glue.GlueVersion.V4_0,
          python_version=glue.PythonVersion.THREE_NINE,
          runtime=glue.Runtime.RAY_TWO_FOUR,
          script=glue.Code.from_asset(path.join(__dirname, "job-script", "hello_world.py"))
      ),
      worker_type=glue.WorkerType.Z_2X,
      worker_count=2,
      description="an example Ray job"
  )
  ```

  Enable Spark UI setting the `sparkUI` property.
  ```python
  glue.Job(self, "EnableSparkUI",
      job_name="EtlJobWithSparkUIPrefix",
      spark_uI=glue.SparkUIProps(
          enabled=True
      ),
      executable=glue.JobExecutable.python_etl(
          glue_version=glue.GlueVersion.V3_0,
          python_version=glue.PythonVersion.THREE,
          script=glue.Code.from_asset(path.join(__dirname, "job-script", "hello_world.py"))
      )
  )
  ```
  The `sparkUI` property also allows the specification of an s3 bucket and a bucket prefix.
  See [documentation](https://docs.aws.amazon.com/glue/latest/dg/add-job.html) for more information on adding jobs in Glue.

  AWS Glue job queuing monitors your account level quotas and limits. If quotas or limits are insufficient to start a Glue job run, AWS Glue will automatically queue the job and wait for limits to free up. Once limits become available, AWS Glue will retry the job run. Glue jobs will queue for limits like max concurrent job runs per account, max concurrent Data Processing Units (DPU), and resource unavailable due to IP address exhaustion in Amazon Virtual Private Cloud (Amazon VPC).
  Enable job run queuing by setting the `jobRunQueuingEnabled` property to `true`.
  ```python
  glue.Job(self, "EnableRunQueuing",
      job_name="EtlJobWithRunQueuing",
      executable=glue.JobExecutable.python_etl(
          glue_version=glue.GlueVersion.V4_0,
          python_version=glue.PythonVersion.THREE,
          script=glue.Code.from_asset(path.join(__dirname, "job-script", "hello_world.py"))
      ),
      job_run_queuing_enabled=True
  )
  ```

  A `Connection` allows Glue jobs, crawlers and development endpoints to access certain types of data stores. For example, to create a network connection to connect to a data source within a VPC:
  ```python


  glue.Connection(self, "MyConnection",
      type=glue.ConnectionType.NETWORK,
      
      security_groups=[security_group],
      
      subnet=subnet
  )
  ```
  For RDS `Connection` by JDBC, it is recommended to manage credentials using AWS Secrets Manager. To use Secret, specify `SECRET_ID` in `properties` like the following code. Note that in this case, the subnet must have a route to the AWS Secrets Manager VPC endpoint or to the AWS Secrets Manager endpoint through a NAT gateway.
  ```python



  glue.Connection(self, "RdsConnection",
      type=glue.ConnectionType.JDBC,
      security_groups=[security_group],
      subnet=subnet,
      properties={
          "JDBC_CONNECTION_URL": f"jdbc:mysql://{db.clusterEndpoint.socketAddress}/databasename",
          "JDBC_ENFORCE_SSL": "false",
          "SECRET_ID": db.secret.secret_name
      }
  )
  ```
  If you need to use a connection type that doesn't exist as a static member on `ConnectionType`, you can instantiate a `ConnectionType` object, e.g: `new glue.ConnectionType('NEW_TYPE')`.
  See [Adding a Connection to Your Data Store](https://docs.aws.amazon.com/glue/latest/dg/populate-add-connection.html) and [Connection Structure](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-connections.html#aws-glue-api-catalog-connections-Connection) documentation for more information on the supported data stores and their configurations.

  A `SecurityConfiguration` is a set of security properties that can be used by AWS Glue to encrypt data at rest.
  ```python
  glue.SecurityConfiguration(self, "MySecurityConfiguration",
      cloud_watch_encryption=glue.CloudWatchEncryption(
          mode=glue.CloudWatchEncryptionMode.KMS
      ),
      job_bookmarks_encryption=glue.JobBookmarksEncryption(
          mode=glue.JobBookmarksEncryptionMode.CLIENT_SIDE_KMS
      ),
      s3_encryption=glue.S3Encryption(
          mode=glue.S3EncryptionMode.KMS
      )
  )
  ```
  By default, a shared KMS key is created for use with the encryption configurations that require one. You can also supply your own key for each encryption config, for example, for CloudWatch encryption:
  ```python

  glue.SecurityConfiguration(self, "MySecurityConfiguration",
      cloud_watch_encryption=glue.CloudWatchEncryption(
          mode=glue.CloudWatchEncryptionMode.KMS,
          kms_key=key
      )
  )
  ```
  See [documentation](https://docs.aws.amazon.com/glue/latest/dg/encryption-security-configuration.html) for more info for Glue encrypting data written by Crawlers, Jobs, and Development Endpoints.

  A `Database` is a logical grouping of `Tables` in the Glue Catalog.
  ```python
  glue.Database(self, "MyDatabase",
      database_name="my_database",
      description="my_database_description"
  )
  ```

  A Glue table describes a table of data in S3: its structure (column names and types), location of data (S3 objects with a common prefix in a S3 bucket), and format for the files (Json, Avro, Parquet, etc.):
  ```python

  glue.S3Table(self, "MyTable",
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      ), glue.Column(
          name="col2",
          type=glue.Schema.array(glue.Schema.STRING),
          comment="col2 is an array of strings"
      )],
      data_format=glue.DataFormat.JSON
  )
  ```
  By default, a S3 bucket will be created to store the table's data but you can manually pass the `bucket` and `s3Prefix`:
  ```python


  glue.S3Table(self, "MyTable",
      bucket=my_bucket,
      s3_prefix="my-table/",
      
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      data_format=glue.DataFormat.JSON
  )
  ```
  Glue tables can be configured to contain user-defined properties, to describe the physical storage of table data, through the `storageParameters` property:
  ```python

  glue.S3Table(self, "MyTable",
      storage_parameters=[
          glue.StorageParameter.skip_header_line_count(1),
          glue.StorageParameter.compression_type(glue.CompressionType.GZIP),
          glue.StorageParameter.custom("separatorChar", ",")
      ],
      
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      data_format=glue.DataFormat.JSON
  )
  ```
  Glue tables can also be configured to contain user-defined table properties through the [`parameters`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-tableinput.html#cfn-glue-table-tableinput-parameters) property:
  ```python

  glue.S3Table(self, "MyTable",
      parameters={
          "key1": "val1",
          "key2": "val2"
      },
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      data_format=glue.DataFormat.JSON
  )
  ```

  To improve query performance, a table can specify `partitionKeys` on which data is stored and queried separately. For example, you might partition a table by `year` and `month` to optimize queries based on a time window:
  ```python

  glue.S3Table(self, "MyTable",
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      partition_keys=[glue.Column(
          name="year",
          type=glue.Schema.SMALL_INT
      ), glue.Column(
          name="month",
          type=glue.Schema.SMALL_INT
      )],
      data_format=glue.DataFormat.JSON
  )
  ```

  Another way to improve query performance is to specify partition indexes. If no partition indexes are
  present on the table, AWS Glue loads all partitions of the table and filters the loaded partitions using
  the query expression. The query takes more time to run as the number of partitions increase. With an
  index, the query will try to fetch a subset of the partitions instead of loading all partitions of the
  table.
  The keys of a partition index must be a subset of the partition keys of the table. You can have a
  maximum of 3 partition indexes per table. To specify a partition index, you can use the `partitionIndexes`
  property:
  ```python

  glue.S3Table(self, "MyTable",
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      partition_keys=[glue.Column(
          name="year",
          type=glue.Schema.SMALL_INT
      ), glue.Column(
          name="month",
          type=glue.Schema.SMALL_INT
      )],
      partition_indexes=[glue.PartitionIndex(
          index_name="my-index",  # optional
          key_names=["year"]
      )],  # supply up to 3 indexes
      data_format=glue.DataFormat.JSON
  )
  ```
  Alternatively, you can call the `addPartitionIndex()` function on a table:
  ```python

  my_table.add_partition_index(
      index_name="my-index",
      key_names=["year"]
  )
  ```

  If you have a table with a large number of partitions that grows over time, consider using AWS Glue partition indexing and filtering.
  ```python

  glue.S3Table(self, "MyTable",
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      partition_keys=[glue.Column(
          name="year",
          type=glue.Schema.SMALL_INT
      ), glue.Column(
          name="month",
          type=glue.Schema.SMALL_INT
      )],
      data_format=glue.DataFormat.JSON,
      enable_partition_filtering=True
  )
  ```

  Glue connections allow external data connections to third party databases and data warehouses. However, these connections can also be assigned to Glue Tables, allowing you to query external data sources using the Glue Data Catalog.
  Whereas `S3Table` will point to (and if needed, create) a bucket to store the tables' data, `ExternalTable` will point to an existing table in a data source. For example, to create a table in Glue that points to a table in Redshift:
  ```python


  glue.ExternalTable(self, "MyTable",
      connection=my_connection,
      external_data_location="default_db_public_example",  # A table in Redshift
      
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      data_format=glue.DataFormat.JSON
  )
  ```

  You can enable encryption on a Table's data:
  * [S3Managed](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingServerSideEncryption.html) - (default) Server side encryption (`SSE-S3`) with an Amazon S3-managed key.
  ```python

  glue.S3Table(self, "MyTable",
      encryption=glue.TableEncryption.S3_MANAGED,
      
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      data_format=glue.DataFormat.JSON
  )
  ```
  * [Kms](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html) - Server-side encryption (`SSE-KMS`) with an AWS KMS Key managed by the account owner.
  ```python


  glue.S3Table(self, "MyTable",
      encryption=glue.TableEncryption.KMS,
      
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      data_format=glue.DataFormat.JSON
  )

  glue.S3Table(self, "MyTable",
      encryption=glue.TableEncryption.KMS,
      encryption_key=kms.Key(self, "MyKey"),
      
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      data_format=glue.DataFormat.JSON
  )
  ```
  * [KmsManaged](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html) - Server-side encryption (`SSE-KMS`), like `Kms`, except with an AWS KMS Key managed by the AWS Key Management Service.
  ```python

  glue.S3Table(self, "MyTable",
      encryption=glue.TableEncryption.KMS_MANAGED,
      
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      data_format=glue.DataFormat.JSON
  )
  ```
  * [ClientSideKms](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingClientSideEncryption.html#client-side-encryption-kms-managed-master-key-intro) - Client-side encryption (`CSE-KMS`) with an AWS KMS Key managed by the account owner.
  ```python


  glue.S3Table(self, "MyTable",
      encryption=glue.TableEncryption.CLIENT_SIDE_KMS,
      
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      data_format=glue.DataFormat.JSON
  )

  glue.S3Table(self, "MyTable",
      encryption=glue.TableEncryption.CLIENT_SIDE_KMS,
      encryption_key=kms.Key(self, "MyKey"),
      
      database=my_database,
      columns=[glue.Column(
          name="col1",
          type=glue.Schema.STRING
      )],
      data_format=glue.DataFormat.JSON
  )
  ```
  *Note: you cannot provide a `Bucket` when creating the `S3Table` if you wish to use server-side encryption (`KMS`, `KMS_MANAGED` or `S3_MANAGED`)*.

  A table's schema is a collection of columns, each of which have a `name` and a `type`. Types are recursive structures, consisting of primitive and complex types:
  ```python

  glue.S3Table(self, "MyTable",
      columns=[glue.Column(
          name="primitive_column",
          type=glue.Schema.STRING
      ), glue.Column(
          name="array_column",
          type=glue.Schema.array(glue.Schema.INTEGER),
          comment="array<integer>"
      ), glue.Column(
          name="map_column",
          type=glue.Schema.map(glue.Schema.STRING, glue.Schema.TIMESTAMP),
          comment="map<string,string>"
      ), glue.Column(
          name="struct_column",
          type=glue.Schema.struct([
              name="nested_column",
              type=glue.Schema.DATE,
              comment="nested comment"
          ]),
          comment="struct<nested_column:date COMMENT 'nested comment'>"
      )],
      
      database=my_database,
      data_format=glue.DataFormat.JSON
  )
  ```


  | Name      	| Type     	| Comments                                                                                                          |
  |-----------	|----------	|------------------------------------------------------------------------------------------------------------------	|
  | FLOAT     	| Constant 	| A 32-bit single-precision floating point number                                                                   |
  | INTEGER   	| Constant 	| A 32-bit signed value in two's complement format, with a minimum value of -2^31 and a maximum value of 2^31-1 	|
  | DOUBLE    	| Constant 	| A 64-bit double-precision floating point number                                                                   |
  | BIG_INT   	| Constant 	| A 64-bit signed INTEGER in two’s complement format, with a minimum value of -2^63 and a maximum value of 2^63 -1  |
  | SMALL_INT 	| Constant 	| A 16-bit signed INTEGER in two’s complement format, with a minimum value of -2^15 and a maximum value of 2^15-1   |
  | TINY_INT  	| Constant 	| A 8-bit signed INTEGER in two’s complement format, with a minimum value of -2^7 and a maximum value of 2^7-1      |

  | Name      	| Type     	| Comments                                                                                                                                                                	|
  |-----------	|----------	|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------	|
  | DATE      	| Constant 	| A date in UNIX format, such as YYYY-MM-DD.                                                                                                                              	|
  | TIMESTAMP 	| Constant 	| Date and time instant in the UNiX format, such as yyyy-mm-dd hh:mm:ss[.f...]. For example, TIMESTAMP '2008-09-15 03:04:05.324'. This format uses the session time zone. 	|

  | Name                                       	| Type     	| Comments                                                                                                                                                                                          	|
  |--------------------------------------------	|----------	|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------	|
  | STRING                                     	| Constant 	| A string literal enclosed in single or double quotes                                                                                                                                              	|
  | decimal(precision: number, scale?: number) 	| Function 	| `precision` is the total number of digits. `scale` (optional) is the number of digits in fractional part with a default of 0. For example, use these type definitions: decimal(11,5), decimal(15) 	|
  | char(length: number)                       	| Function 	| Fixed length character data, with a specified length between 1 and 255, such as char(10)                                                                                                          	|
  | varchar(length: number)                    	| Function 	| Variable length character data, with a specified length between 1 and 65535, such as varchar(10)                                                                                                  	|

  | Name    	| Type     	| Comments                      	|
  |---------	|----------	|-------------------------------	|
  | BOOLEAN 	| Constant 	| Values are `true` and `false` 	|
  | BINARY  	| Constant 	| Value is in binary            	|

  | Name                                	| Type     	| Comments                                                          	|
  |-------------------------------------	|----------	|-------------------------------------------------------------------	|
  | array(itemType: Type)               	| Function 	| An array of some other type                                       	|
  | map(keyType: Type, valueType: Type) 	| Function 	| A map of some primitive key type to any value type                	|
  | struct(collumns: Column[])          	| Function 	| Nested structure containing individually named and typed collumns 	|

  A `DataQualityRuleset` specifies a data quality ruleset with DQDL rules applied to a specified AWS Glue table. For example, to create a data quality ruleset for a given table:
  ```python
  glue.DataQualityRuleset(self, "MyDataQualityRuleset",
      client_token="client_token",
      description="description",
      ruleset_name="ruleset_name",
      ruleset_dqdl="ruleset_dqdl",
      tags={
          "key1": "value1",
          "key2": "value2"
      },
      target_table=glue.DataQualityTargetTable("database_name", "table_name")
  )
  ```
  For more information, see [AWS Glue Data Quality](https://docs.aws.amazon.com/glue/latest/dg/glue-data-quality.html).


pkgId: d459d230d1a120e272b4abb60b8f48716e6e02e617f823374347cdd84870c62c
name: python-aws-cdk.aws-iot-actions-alpha
arch: src
version: 2.162.1a0
epoch: 0
release: 1
summary: Receipt rule actions for AWS IoT
url: https://github.com/aws/aws-cdk
rpm_license: Apache-2.0
rpm_group: Unspecified
rpm_buildhost: localhost
location_href: Packages/python-aws-cdk.aws-iot-actions-alpha-2.162.1a0-1.src.rpm
checksum_type: sha256
description:
  <!--END STABILITY BANNER-->
  This library contains integration classes to send data to any number of
  supported AWS Services. Instances of these classes should be passed to
  `TopicRule` defined in `aws-cdk-lib/aws-iot`.
  Currently supported are:
  * Republish a message to another MQTT topic
  * Invoke a Lambda function
  * Put objects to a S3 bucket
  * Put logs to CloudWatch Logs
  * Capture CloudWatch metrics
  * Change state for a CloudWatch alarm
  * Put records to Kinesis Data stream
  * Put records to Kinesis Data Firehose stream
  * Send messages to SQS queues
  * Publish messages on SNS topics
  * Write messages into columns of DynamoDB
  * Put messages IoT Events input
  * Send messages to HTTPS endpoints

  The code snippet below creates an AWS IoT Rule that republish a message to
  another MQTT topic when it is triggered.
  ```python
  iot.TopicRule(self, "TopicRule",
      sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id, timestamp() as timestamp, temperature FROM 'device/+/data'"),
      actions=[
          actions.IotRepublishMqttAction("${topic()}/republish",
              quality_of_service=actions.MqttQualityOfService.AT_LEAST_ONCE
          )
      ]
  )
  ```

  The code snippet below creates an AWS IoT Rule that invoke a Lambda function
  when it is triggered.
  ```python
  func = lambda_.Function(self, "MyFunction",
      runtime=lambda_.Runtime.NODEJS_LATEST,
      handler="index.handler",
      code=lambda_.Code.from_inline("""
              exports.handler = (event) => {
                console.log("It is test for lambda action of AWS IoT Rule.", event);
              };""")
  )
  iot.TopicRule(self, "TopicRule",
      sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id, timestamp() as timestamp, temperature FROM 'device/+/data'"),
      actions=[actions.LambdaFunctionAction(func)]
  )
  ```

  The code snippet below creates an AWS IoT Rule that puts objects to a S3 bucket
  when it is triggered.
  ```python
  bucket = s3.Bucket(self, "MyBucket")
  iot.TopicRule(self, "TopicRule",
      sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id FROM 'device/+/data'"),
      actions=[actions.S3PutObjectAction(bucket)]
  )
  ```
  The property `key` of `S3PutObjectAction` is given the value `${topic()}/${timestamp()}` by default. This `${topic()}`
  and `${timestamp()}` is called Substitution templates. For more information see
  [this documentation](https://docs.aws.amazon.com/iot/latest/developerguide/iot-substitution-templates.html).
  In above sample, `${topic()}` is replaced by a given MQTT topic as `device/001/data`. And `${timestamp()}` is replaced
  by the number of the current timestamp in milliseconds as `1636289461203`. So if the MQTT broker receives an MQTT topic
  `device/001/data` on `2021-11-07T00:00:00.000Z`, the S3 bucket object will be put to `device/001/data/1636243200000`.
  You can also set specific `key` as following:
  ```python
  bucket = s3.Bucket(self, "MyBucket")
  iot.TopicRule(self, "TopicRule",
      sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'"),
      actions=[
          actions.S3PutObjectAction(bucket,
              key="${year}/${month}/${day}/${topic(2)}"
          )
      ]
  )
  ```
  If you wanna set access control to the S3 bucket object, you can specify `accessControl` as following:
  ```python
  bucket = s3.Bucket(self, "MyBucket")
  iot.TopicRule(self, "TopicRule",
      sql=iot.IotSql.from_string_as_ver20160323("SELECT * FROM 'device/+/data'"),
      actions=[
          actions.S3PutObjectAction(bucket,
              access_control=s3.BucketAccessControl.PUBLIC_READ
          )
      ]
  )
  ```

  The code snippet below creates an AWS IoT Rule that puts logs to CloudWatch Logs
  when it is triggered.
  ```python
  import aws_cdk.aws_logs as logs
  log_group = logs.LogGroup(self, "MyLogGroup")
  iot.TopicRule(self, "TopicRule",
      sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id FROM 'device/+/data'"),
      actions=[actions.CloudWatchLogsAction(log_group)]
  )
  ```

  The code snippet below creates an AWS IoT Rule that capture CloudWatch metrics
  when it is triggered.
  ```python
  topic_rule = iot.TopicRule(self, "TopicRule",
      sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id, namespace, unit, value, timestamp FROM 'device/+/data'"),
      actions=[
          actions.CloudWatchPutMetricAction(
              metric_name="${topic(2)}",
              metric_namespace="${namespace}",
              metric_unit="${unit}",
              metric_value="${value}",
              metric_timestamp="${timestamp}"
          )
      ]
  )
  ```

  The code snippet below creates an AWS IoT Rule that starts a Step Functions State Machine
  when it is triggered.
  ```python
  state_machine = stepfunctions.StateMachine(self, "SM",
      definition_body=stepfunctions.DefinitionBody.from_chainable(stepfunctions.Wait(self, "Hello", time=stepfunctions.WaitTime.duration(Duration.seconds(10))))
  )
  iot.TopicRule(self, "TopicRule",
      sql=iot.IotSql.from_string_as_ver20160323("SELECT * FROM 'device/+/data'"),
      actions=[
          actions.StepFunctionsStateMachineAction(state_machine)
      ]
  )
  ```

  The code snippet below creates an AWS IoT Rule that changes the state of an Amazon CloudWatch alarm when it is triggered:
  ```python
  import aws_cdk.aws_cloudwatch as cloudwatch
  metric = cloudwatch.Metric(
      namespace="MyNamespace",
      metric_name="MyMetric",
      dimensions_map={"MyDimension": "MyDimensionValue"}
  )
  alarm = cloudwatch.Alarm(self, "MyAlarm",
      metric=metric,
      threshold=100,
      evaluation_periods=3,
      datapoints_to_alarm=2
  )
  topic_rule = iot.TopicRule(self, "TopicRule",
      sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id FROM 'device/+/data'"),
      actions=[
          actions.CloudWatchSetAlarmStateAction(alarm,
              reason="AWS Iot Rule action is triggered",
              alarm_state_to_set=cloudwatch.AlarmState.ALARM
          )
      ]
  )
  ```

  The code snippet below creates an AWS IoT Rule that puts records to Kinesis Data
  stream when it is triggered.
  ```python
  import aws_cdk.aws_kinesis as kinesis
  stream = kinesis.Stream(self, "MyStream")
  topic_rule = iot.TopicRule(self, "TopicRule",
      sql=iot.IotSql.from_string_as_ver20160323("SELECT * FROM 'device/+/data'"),
      actions=[
          actions.KinesisPutRecordAction(stream,
              partition_key="${newuuid()}"
          )
      ]
  )
  ```

  The code snippet below creates an AWS IoT Rule that puts records to Put records
  to Kinesis Data Firehose stream when it is triggered.
  ```python
  import aws_cdk.aws_kinesisfirehose_alpha as firehose
  import aws_cdk.aws_kinesisfirehose_destinations_alpha as destinations
  bucket = s3.Bucket(self, "MyBucket")
  stream = firehose.DeliveryStream(self, "MyStream",
      destination=destinations.S3Bucket(bucket)
  )
  topic_rule = iot.TopicRule(self, "TopicRule",
      sql=iot.IotSql.from_string_as_ver20160323("SELECT * FROM 'device/+/data'"),
      actions=[
          actions.FirehosePutRecordAction(stream,
              batch_mode=True,
              record_separator=actions.FirehoseRecordSeparator.NEWLINE
          )
      ]
  )
  ```

  The code snippet below creates an AWS IoT Rule that send messages
  to an SQS queue when it is triggered:
  ```python
  import aws_cdk.aws_sqs as sqs
  queue = sqs.Queue(self, "MyQueue")
  topic_rule = iot.TopicRule(self, "TopicRule",
      sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'"),
      actions=[
          actions.SqsQueueAction(queue,
              use_base64=True
          )
      ]
  )
  ```

  The code snippet below creates and AWS IoT Rule that publishes messages to an SNS topic when it is triggered:
  ```python
  import aws_cdk.aws_sns as sns
  topic = sns.Topic(self, "MyTopic")
  topic_rule = iot.TopicRule(self, "TopicRule",
      sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'"),
      actions=[
          actions.SnsTopicAction(topic,
              message_format=actions.SnsActionMessageFormat.JSON
          )
      ]
  )
  ```

  The code snippet below creates an AWS IoT rule that writes all or part of an
  MQTT message to DynamoDB using the DynamoDBv2 action.
  ```python
  import aws_cdk.aws_dynamodb as dynamodb

  topic_rule = iot.TopicRule(self, "TopicRule",
      sql=iot.IotSql.from_string_as_ver20160323("SELECT * FROM 'device/+/data'"),
      actions=[
          actions.DynamoDBv2PutItemAction(table)
      ]
  )
  ```

  The code snippet below creates an AWS IoT Rule that puts messages
  to an IoT Events input when it is triggered:
  ```python
  import aws_cdk.aws_iotevents_alpha as iotevents
  import aws_cdk.aws_iam as iam

  input = iotevents.Input(self, "MyInput",
      attribute_json_paths=["payload.temperature", "payload.transactionId"]
  )
  topic_rule = iot.TopicRule(self, "TopicRule",
      sql=iot.IotSql.from_string_as_ver20160323("SELECT * FROM 'device/+/data'"),
      actions=[
          actions.IotEventsPutMessageAction(input,
              batch_mode=True,  # optional property, default is 'false'
              message_id="${payload.transactionId}",  # optional property, default is a new UUID
              role=role
          )
      ]
  )
  ```

  The code snippet below creates an AWS IoT Rule that sends messages
  to an HTTPS endpoint when it is triggered:
  ```python
  topic_rule = iot.TopicRule(self, "TopicRule",
      sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'")
  )
  topic_rule.add_action(
      actions.HttpsAction("https://example.com/endpoint",
          confirmation_url="https://example.com",
          headers=[actions.HttpActionHeader(key="key0", value="value0"), actions.HttpActionHeader(key="key1", value="value1")
          ],
          auth=actions.HttpActionSigV4Auth(service_name="serviceName", signing_region="us-east-1")
      ))
  ```

  The code snippet below creates an AWS IoT Rule that writes data
  to an Open Search Service when it is triggered:
  ```python
  import aws_cdk.aws_opensearchservice as opensearch

  topic_rule = iot.TopicRule(self, "TopicRule",
      sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'")
  )
  topic_rule.add_action(actions.OpenSearchAction(domain,
      id="my-id",
      index="my-index",
      type="my-type"
  ))
  ```


