def prepare()

in samcli/hook_packages/terraform/hooks/prepare/hook.py [0:0]


def prepare(params: dict) -> dict:
    """
    Prepares a terraform application for use with the SAM CLI

    Parameters
    ----------
    params: dict
        Parameters of the IaC application

    Returns
    -------
    dict
        information of the generated metadata files
    """
    output_dir_path = params.get("OutputDirPath")

    terraform_application_dir = params.get("IACProjectPath", os.getcwd())
    project_root_dir = params.get("ProjectRootDir", terraform_application_dir)

    if not output_dir_path:
        raise PrepareHookException("OutputDirPath was not supplied")

    _validate_environment_variables()

    LOG.debug("Normalize the terraform application root module directory path %s", terraform_application_dir)
    if not os.path.isabs(terraform_application_dir):
        terraform_application_dir = os.path.normpath(os.path.join(os.getcwd(), terraform_application_dir))
        LOG.debug("The normalized terraform application root module directory path %s", terraform_application_dir)

    LOG.debug("Normalize the project root directory path %s", project_root_dir)
    if not os.path.isabs(project_root_dir):
        project_root_dir = os.path.normpath(os.path.join(os.getcwd(), project_root_dir))
        LOG.debug("The normalized project root directory path %s", project_root_dir)

    LOG.debug("Normalize the OutputDirPath %s", output_dir_path)
    if not os.path.isabs(output_dir_path):
        output_dir_path = os.path.normpath(os.path.join(terraform_application_dir, output_dir_path))
        LOG.debug("The normalized OutputDirPath value is %s", output_dir_path)

    skip_prepare_infra = params.get("SkipPrepareInfra", False)
    metadata_file_path = os.path.join(output_dir_path, TERRAFORM_METADATA_FILE)

    plan_file = params.get("PlanFile")

    if skip_prepare_infra and os.path.exists(metadata_file_path):
        LOG.info("Skipping preparation stage, the metadata file already exists at %s", metadata_file_path)
    else:
        try:
            # initialize terraform application
            if not plan_file:
                tf_json = _generate_plan_file(skip_prepare_infra, terraform_application_dir)
            else:
                LOG.info(f"Using provided plan file: {plan_file}")
                with open(plan_file, "r") as f:
                    tf_json = json.load(f)

            # convert terraform to cloudformation
            LOG.info("Generating metadata file")
            cfn_dict = translate_to_cfn(tf_json, output_dir_path, terraform_application_dir, project_root_dir)

            if cfn_dict.get("Resources"):
                _update_resources_paths(cfn_dict.get("Resources"), terraform_application_dir)  # type: ignore

            # Add hook metadata
            if not cfn_dict.get("Metadata"):
                cfn_dict["Metadata"] = {}
            cfn_dict["Metadata"][HOOK_METADATA_KEY] = TERRAFORM_HOOK_METADATA

            # store in supplied output dir
            if not os.path.exists(output_dir_path):
                os.makedirs(output_dir_path, exist_ok=True)

            LOG.info("Finished generating metadata file. Storing in %s", metadata_file_path)
            with open(metadata_file_path, "w+") as metadata_file:
                json.dump(cfn_dict, metadata_file)

        except OSError as e:
            raise PrepareHookException(f"OSError: {e}") from e

    return {"iac_applications": {"MainApplication": {"metadata_file": metadata_file_path}}}