def get_service_control_policies_for_target(policies_target_list,
                                            root_id) -> dict:
    policies_for_each_target = dict()
    policies_name_for_each_target = dict()
    policies_target_IDs = list(policies_target_list.keys())
    print("policies_target_list", policies_target_list)

    for target_id in policies_target_IDs:
        list_service_control_policies = org.list_policies_for_target(
            TargetId=target_id, Filter=SERVICE_CONTROL_POLICY)
        describe_service_control_policies = (
            [  # for every PolicyId get readable description
                org.describe_policy(PolicyId=target.get("Id"))
                for target in list_service_control_policies.get("Policies")
            ])

        policies_for_each_target[policies_target_list[target_id]] = [
            policy.get("Policy")
            for policy in describe_service_control_policies
        ]

        policies_name_for_each_target[
            policies_target_list[target_id]
            if policies_target_list[target_id] != "Root" else root_id] = [
                helper.get_valid_filename(
                    policy.get("Policy").get("PolicySummary").get("Name"))
                for policy in describe_service_control_policies
            ]

    print("policies_name_for_each_target", policies_name_for_each_target)
    return policies_for_each_target, policies_name_for_each_target
def apply_migration_policies(role_arn):
    click.echo("Updating state file")
    with betterboto_client.CrossAccountClientContextManager(
            "organizations",
            role_arn,
            f"organizations",
    ) as organizations:
        list_accounts_response = organizations.list_accounts_single_page()
        list_roots_response = organizations.list_roots_single_page()
        root_id = list_roots_response.get("Roots")[0].get("Id")
        org_path = SEP.join(["environment", root_id])
        all_files_in_environment_list = helper.getListOfFiles(org_path)

    # Step 1 Save Attached policies
    accounts = {
        account.get("Id"): account.get("Name")
        for account in list_accounts_response.get("Accounts")
    }
    ous = get_organizational_units(root_id)  # list all OUs in org

    org_ids_map = accounts | ous
    policy_ids_map = dict()

    # map SCP name to Ids
    for file_path in os.listdir(service_control_policies_path):
        policy = helper.read_json(
            SEP.join([service_control_policies_path,
                      file_path]))["PolicySummary"]
        policy_ids_map[helper.get_valid_filename(
            policy["Name"])] = policy["Id"]

    # TODO make this in accordance with Eamonn's AWS Organized general way of doing things
    # so the user will be able to type in the file name and the migration wil be applied
    reverse_org_ids_map = dict((v, k) for k, v in org_ids_map.items())
    for migration_policy in os.listdir(
            make_individual_migration_policies_path):
        policy = helper.read_json(
            SEP.join(
                [make_individual_migration_policies_path,
                 migration_policy])).get("Migration")

        policy_id = policy.get("Policy_Id")
        policy_name = policy.get("Policy_Name")
        target_name = policy.get("Target")
        target_id = reverse_org_ids_map[target_name]
        policy_type = policy.get("Migration_Type")

        try:
            org.attach_policy(
                PolicyId=policy_id, TargetId=target_id
            ) if policy_type == ATTACH_POLICY else org.detach_policy(
                PolicyId=policy_id, TargetId=target_id)
        except:
            print(
                f"Error when attempting to {policy_type} {policy_name} on target {target_name}."
            )
        else:
            print(
                f"Successfully performed {policy_type} {policy_name} on target {target_name}."
            )
def write_policies_to_target_yaml(target_SCPs, target_name_path) -> dict:
    policies_per_target = dict()

    for target_id, policies_attached_to_target in target_SCPs.items():
        policies_name = [
            helper.get_valid_filename(policy["PolicySummary"]["Name"])
            for policy in policies_attached_to_target
        ]

        target_path = target_name_path[target_id] + "/"
        policies_per_target[
            target_id] = policies_name  # saved initial state policies
        policy_file_name = "_service_control_policies.yaml"

        write_policies_to_individual_target_yaml(policies_name, target_path,
                                                 policy_file_name)
    return policies_per_target
def import_organization_policies(role_arn) -> None:
    click.echo("Updating state file")
    with betterboto_client.CrossAccountClientContextManager(
            "organizations",
            role_arn,
            f"organizations",
    ) as organizations:
        list_accounts_details = organizations.list_accounts_single_page()
        list_roots_response = organizations.list_roots_single_page()
        root_id = list_roots_response.get("Roots")[0].get("Id")
        org_path = SEP.join(["environment", root_id])
        all_files_in_environment_list = helper.getListOfFiles(org_path)

    # Step 0 get all policies in org
    all_service_control_policies_in_org = org.list_policies(
        Filter=SERVICE_CONTROL_POLICY).get("Policies")

    all_service_control_policies_in_org_with_policy_summary = [
        org.describe_policy(PolicyId=policy.get("Id")).get("Policy")
        for policy in all_service_control_policies_in_org
    ]

    [
        helper.write_to_file(
            {
                "PolicySummary": policy.get("PolicySummary"),
                "Content": json.loads(policy.get("Content")),
            },
            service_control_policies_path,
            helper.get_valid_filename(policy.get("PolicySummary").get("Name"))
            + ".json",
        ) for policy in all_service_control_policies_in_org_with_policy_summary
    ]

    # Step 1 Save Attached policies
    accounts = {
        account.get("Id"): account.get("Name")
        for account in list_accounts_details.get("Accounts")
    }
    ous = get_organizational_units(root_id)  # list all OUs in org
    service_control_policies_path_for_target = helper.map_scp_path_for_target_name(
        all_files_in_environment_list, root_id)

    (
        service_control_policies_for_target,
        scp_name_for_each_target,
    ) = get_service_control_policies_for_target(ous | accounts, root_id)
    write_policies_to_target_yaml(service_control_policies_for_target,
                                  service_control_policies_path_for_target)

    # Step 2 Save Inherited policies
    for file_path in all_files_in_environment_list:
        if "_service_control_policies.yaml" in file_path:
            current_scp_path_list = file_path.split("/")
            root_org_scp_path = org_path + "/_service_control_policies.yaml"
            local_policy = [
                policy for policy in helper.read_yaml(root_org_scp_path)
                ["Policies_Attached"]
            ]
            for i in range(len(current_scp_path_list)):
                # go through every OU in org structure
                if "_organizational_units" in current_scp_path_list[i]:
                    current_organizational_unit_index = current_scp_path_list.index(
                        current_scp_path_list[i + 1])
                    current_policy_path = (SEP.join(
                        current_scp_path_list[:
                                              -current_organizational_unit_index]
                    ) + "/_service_control_policies.yaml")

                    # TODO change this to save as policy_name ===> source: Org_source
                    local_policy.extend([
                        attached_policy
                        for attached_policy in helper.read_yaml(
                            current_policy_path)["Policies_Attached"]
                        if attached_policy not in local_policy
                    ])

                if (file_path != root_org_scp_path
                        and "_service_control_policies.yaml"
                        in current_scp_path_list[i]):
                    helper.write_inherited_yaml(local_policy, file_path)
    # save initial set up
    helper.write_to_file(scp_name_for_each_target, policies_migration_path,
                         "initial_state.yaml")
def write_all_policies_to_json(path, policies_dict) -> None:
    for policy in policies_dict.values():
        policy_file_name = helper.get_valid_filename(
            policy.get("PolicySummary").get("Name"))
        helper.write_to_file(policy, path, policy_file_name + ".json")