def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Import Existing Clouformation Template):
        try:
            with open(
                    "stacks_from_cfn/sample_templates/create_s3_bucket_template.json",
                    mode="r") as file:
                cfn_template = json.load(file)
        except OSError:
            print("Unable to read Cfn Template")

        # includes cloudformation template
        resoures_from_cfn_template = core.CfnInclude(self,
                                                     'konstoneInfra',
                                                     template=cfn_template)

        # get arn from resource in template
        encrypted_bkt_arn = core.Fn.get_att("EncryptedS3Bucket", "Arn")

        # Output Arn of encrypted Bucket
        output_1 = core.CfnOutput(
            self,
            "EncryptedBucketArn",
            value=f"{encrypted_bkt_arn.to_string()}",
            description="Arn of Encrypted Bucket from Cfn Template")
Ejemplo n.º 2
0
    def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        #import from cloud-formation template
        try:
            with open("import_from_cfn/s3.json", mode="r") as file:
                cfn_template = json.load(file)
        except OSError:
            print("CFN Read error")

        import_from_cfn = core.CfnInclude(
            self,
            "importfromcfn",
            template=cfn_template
        )

        s3_bucket_arn = core.Fn.get_att("S3Bucket", "Arn")

        #output

        output_s3 = core.CfnOutput(
            self,
            "s3arnoutput",
            value=f"{s3_bucket_arn.to_string()}",
            description="arn for s3 from imported cfn"
        )
Ejemplo n.º 3
0
    def __init__(self,
                 scope: cdk.Construct,
                 id: str,
                 *,
                 source_dir: str,
                 stage_config: Dict,
                 docker_config: DockerConfig = None,
                 **kwargs) -> None:
        """
        :param str source_dir: Path to Chalice application source code
        :param Dict stage_config: Chalice stage configuration.
            The configuration object should have the same structure as Chalice JSON
            stage configuration.
        :param DockerConfig docker_config: If your functions depend on packages
            that have natively compiled dependencies, build your functions inside
            an AWS Lambda-like Docker container (or your own container).
        :raises ChaliceError: Error packaging the application.
        """
        super().__init__(scope, id, **kwargs)

        self.source_dir = source_dir
        self.stage_name = scope.to_string()
        self.stage_config = stage_config
        self.docker_config = docker_config

        self._create_stage_with_config()
        sam_package_dir = self._package_app()
        sam_template = self._update_sam_template(sam_package_dir)

        cdk.CfnInclude(self, 'ChaliceApp', template=sam_template)
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        try:
            with open("./resources/create_s3_bucket_template.json", "r") as f:
                cfn_template = json.load(f)
        except OSError:
            print("unable to read Cfn Template")

        resources_from_cfn = core.CfnInclude(self,
                                             "CustomInfra",
                                             template=cfn_template)

        encrypted_bkt_arn = core.Fn.get_att("EncryptedS3Bucket", "Arn")

        output1 = core.CfnOutput(self,
                                 "EncryptedS3BucketArn",
                                 value=f"{encrypted_bkt_arn.to_string()}")
Ejemplo n.º 5
0
    def __init__(self, scope: cdk.Construct, id: str, *, source_dir: str, stage_config: dict,
                 package_config: PackageConfig = None, **kwargs) -> None:
        """
        :param str source_dir: Path to Chalice application source code.
        :param dict stage_config: Chalice stage configuration.
            The configuration object should have the same structure as Chalice JSON
            stage configuration.
        :param `PackageConfig` package_config: Configuration for packaging the
            Chalice application.
        :raises `ChaliceError`: Error packaging the Chalice application.
        """
        super().__init__(scope, id, **kwargs)

        #: Path to Chalice application source code.
        self.source_dir = os.path.abspath(source_dir)

        #: Chalice stage name.
        #: It is automatically assigned the encompassing CDK ``scope``'s name.
        self.stage_name = scope.to_string()

        #: Chalice stage configuration.
        #: The object has the same structure as Chalice JSON stage configuration.
        self.stage_config = stage_config

        #: :class:`PackageConfig` object.
        #: If not provided, :class:`PackageConfig` instance with default arguments is used.
        self.package_config = PackageConfig() if package_config is None else package_config

        self._create_stage_with_config()

        #: Path to directory with output of `chalice package` command.
        self.sam_package_dir = self._package_app()

        #: AWS SAM template updated with AWS CDK values where applicable.
        self.sam_template = self._update_sam_template()

        cdk.CfnInclude(self, 'ChaliceApp', template=self.sam_template)
Ejemplo n.º 6
0
    def __init__(
        self,
        scope: core.Construct,
        id: str,
        source_directory: Union[Path, str],
        stage_config: Optional[dict] = None,
        lambda_configs: Optional[dict] = None,
        environment: Optional[dict] = None,
        **kwargs,
    ):
        """
        Args:
            scope: cdk stack or construct
            id: identifier
            source_directory: the output directory of `chalice package` or the base path of the
                              chalice codebase
            environment: environment variables to apply across lambdas
            stage_config: stage-level configuration options i.e. `api_gateway_endpoint_type`
                          overwrites `dev`
            lambda_configs: lambda-level configurations, will be passed to `lambda_functions`
                            in `dev`
            **kwargs:
        """

        super().__init__(scope, id, **kwargs)

        stage_config = stage_config if stage_config is not None else {}

        lambda_configs = lambda_configs if lambda_configs is not None else {}

        environment = environment if environment is not None else {}

        source_path = Path(source_directory)

        if Path(source_path, "app.py").exists():

            logging.debug("assuming app has not been packaged")

            config_path = Path(source_path, ".chalice", "config.json")

            original_config_text = config_path.read_text()

            config_data = json.loads(original_config_text)

            config_data["stages"]["dev"].update(stage_config)

            if lambda_configs:

                config_data["stages"]["dev"]["lambda_functions"] = {
                    **config_data["stages"]["dev"].get("lambda_function", {}),
                    **lambda_configs,
                }

            updated_config = json.dumps(config_data, indent=2)

            logging.debug(updated_config)

            config_path.write_text(updated_config)

            output_dir = "chalice.out"

            sp.run(f"chalice package {output_dir}", shell=True, check=True)

            config_path.write_text(original_config_text)

            package_path = Path(output_dir)

        else:

            package_path = Path(source_directory)

        sam_path = Path(package_path, "sam.json")

        text = sam_path.read_text()

        self.template = json.loads(text)

        zip_path = Path(package_path, "deployment.zip")

        s3_asset = aws_s3_assets.Asset(self,
                                       "chalice-app-s3-object",
                                       path=zip_path.__fspath__())

        for resource_name, resource in self.template["Resources"].items():

            if resource["Type"] == "AWS::Serverless::Function":

                properties = resource["Properties"]

                properties["CodeUri"] = {
                    "Bucket": s3_asset.s3_bucket_name,
                    "Key": s3_asset.s3_object_key,
                }

                properties.setdefault("Environment",
                                      {}).setdefault("Variables",
                                                     {}).update(environment)

        core.CfnInclude(self, "chalice-app", template=self.template)