From d01a9c3c2b8286285b111c4e8a18d1ebe7fb0180 Mon Sep 17 00:00:00 2001 From: Omar Date: Thu, 29 Feb 2024 21:35:00 +0200 Subject: [PATCH 01/47] Initial Commit for Adding Dome9 get onboarding data source --- dome9/common/resourcetype/resource_type.go | 1 + dome9/config.go | 3 + ...ource_dome9_awp_aws_get_onboarding_data.go | 80 +++ dome9/provider.go | 1 + examples/awp_aws_onboarding/main-azure.tf | 266 ++++++++ examples/awp_aws_onboarding/main.tf | 587 ++++++++++++++++++ .../awp_aws_onboarding/awp_aws_onboarding.go | 31 + .../services/awp_aws_onboarding/service.go | 14 + 8 files changed, 983 insertions(+) create mode 100644 dome9/data_source_dome9_awp_aws_get_onboarding_data.go create mode 100644 examples/awp_aws_onboarding/main-azure.tf create mode 100644 examples/awp_aws_onboarding/main.tf create mode 100644 vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go create mode 100644 vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/service.go diff --git a/dome9/common/resourcetype/resource_type.go b/dome9/common/resourcetype/resource_type.go index da5b1887..9beb70bc 100644 --- a/dome9/common/resourcetype/resource_type.go +++ b/dome9/common/resourcetype/resource_type.go @@ -27,4 +27,5 @@ const ( AdmissionControlPolicy = "dome9_admission_control_policy" Assessment = "dome9_assessment" ImageAssurancePolicy = "dome9_image_assurance_policy" + AwpAwsOnboardingData = "dome9_awp_aws_get_onboarding_data" ) diff --git a/dome9/config.go b/dome9/config.go index a41706be..08eac0e3 100644 --- a/dome9/config.go +++ b/dome9/config.go @@ -2,6 +2,7 @@ package dome9 import ( "github.com/dome9/dome9-sdk-go/services/assessment" + "github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding" "log" "github.com/dome9/dome9-sdk-go/dome9" @@ -52,6 +53,7 @@ type Client struct { admissionControlPolicy admission_policy.Service imageAssurancePolicy imageassurance_policy.Service assessment assessment.Service + awpAwsOnboarding awp_aws_onboarding.Service } type Config struct { @@ -87,6 +89,7 @@ func (c *Config) Client() (*Client, error) { admissionControlPolicy: *admission_policy.New(config), imageAssurancePolicy: *imageassurance_policy.New(config), assessment: *assessment.New(config), + awpAwsOnboarding: *awp_aws_onboarding.New(config), } log.Println("[INFO] initialized Dome9 client") diff --git a/dome9/data_source_dome9_awp_aws_get_onboarding_data.go b/dome9/data_source_dome9_awp_aws_get_onboarding_data.go new file mode 100644 index 00000000..48d1ec9d --- /dev/null +++ b/dome9/data_source_dome9_awp_aws_get_onboarding_data.go @@ -0,0 +1,80 @@ +package dome9 + +import ( + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func dataSourceAwpAwsOnboardingData() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAwpAwsOnboardingDataRead, + + Schema: map[string]*schema.Schema{ + "cloudguard_account_id": { + Type: schema.TypeString, + Required: true, + }, + "scan_mode": { + Type: schema.TypeString, + Required: true, + }, + "stage": { + Type: schema.TypeString, + Computed: true, + }, + "region": { + Type: schema.TypeString, + Computed: true, + }, + "cloudGuardBackendAccountId": { + Type: schema.TypeString, + Computed: true, + }, + "agentlessBucketName": { + Type: schema.TypeString, + Computed: true, + }, + "remoteFunctionsPrefixKey": { + Type: schema.TypeString, + Computed: true, + }, + "remoteSnapshotsUtilsFunctionName": { + Type: schema.TypeString, + Computed: true, + }, + "remoteSnapshotsUtilsFunctionRunTime": { + Type: schema.TypeString, + Computed: true, + }, + "remoteSnapshotsUtilsFunctionTimeOut": { + Type: schema.TypeInt, + Computed: true, + }, + "awpClientSideSecurityGroupName": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func dataSourceAwpAwsOnboardingDataRead(d *schema.ResourceData, meta interface{}) error { + d9Client := meta.(*Client) + + resp, _, err := d9Client.awpAwsOnboarding.Get() + if err != nil { + return err + } + + d.SetId(resp.CloudGuardBackendAccountId) + _ = d.Set("stage", resp.Stage) + _ = d.Set("region", resp.Region) + _ = d.Set("cloudGuardBackendAccountId", resp.CloudGuardBackendAccountId) + _ = d.Set("agentlessBucketName", resp.AgentlessBucketName) + _ = d.Set("remoteFunctionsPrefixKey", resp.RemoteFunctionsPrefixKey) + _ = d.Set("remoteSnapshotsUtilsFunctionName", resp.RemoteSnapshotsUtilsFunctionName) + _ = d.Set("remoteSnapshotsUtilsFunctionRunTime", resp.RemoteSnapshotsUtilsFunctionRunTime) + _ = d.Set("remoteSnapshotsUtilsFunctionTimeOut", resp.RemoteSnapshotsUtilsFunctionTimeOut) + _ = d.Set("awpClientSideSecurityGroupName", resp.AwpClientSideSecurityGroupName) + + return nil +} diff --git a/dome9/provider.go b/dome9/provider.go index 47113694..b5540e0e 100644 --- a/dome9/provider.go +++ b/dome9/provider.go @@ -85,6 +85,7 @@ func Provider() terraform.ResourceProvider { resourcetype.AdmissionControlPolicy: dataSourceAdmissionControlPolicy(), resourcetype.Assessment: dataSourceAssessment(), resourcetype.ImageAssurancePolicy: dataSourceImageAssurancePolicy(), + resourcetype.AwpAwsOnboardingData: dataSourceAwpAwsOnboardingData(), }, ConfigureFunc: providerConfigure, } diff --git a/examples/awp_aws_onboarding/main-azure.tf b/examples/awp_aws_onboarding/main-azure.tf new file mode 100644 index 00000000..49345b60 --- /dev/null +++ b/examples/awp_aws_onboarding/main-azure.tf @@ -0,0 +1,266 @@ +# Dome9 Provider Configurations +terraform { + required_providers { + dome9 = { + source = "dome9/dome9" + version = "1.29.6" + } + } +} + +/** +provider "dome9" { + dome9_access_id = "DOME9_CLOUDGUARD_API_ACCESS_ID" + dome9_secret_key = "DOME9_CLOUDGUARD_API_SECRET_KEY" + base_url = "DOME9_API_BASE_URL" +} +**/ + +# Define variables +# Regular Account or Sub Account Subscription ID +variable "subscription_id" {} # Customer should provide it with the onboarding resource +variable "management_group" {} # Customer should provide it with the onboarding resource +variable "tenant_id" {} # should be calculated from azurerm_subscription data source +variable "app_object_id" {} # should be calculated from app_client_id (it should be provided from get onboarding data api) +variable "hub_subscription_id" {} # Customer should provide it with the onboarding resource +variable "scan_mode" {} # Customer should provide it with the onboarding resource +variable "region" {} # should be taken from get onboarding data azure api +variable "awp_version" {} # should be taken from get onboarding data azure api + + +data "dome9_awp_azure_generate_onboarding_data" "dome9_awp_azure_generating_onboarding_data_source" { + subscription_id = "d0dd3387-d9c5-487b-8b18-4fa969fd98cd" + scan_mode = "inAccountHub" # The scan mode (valid options are: $SCAN_MODE_SAAS, $SCAN_MODE_IN_ACCOUNT, $SCAN_MODE_IN_ACCOUNT_HUB, $SCAN_MODE_IN_ACCOUNT_SUB) + hub_subscription_id = "d0dd3387-d9c5-487b-8b18-4fa969fd98cd" # The hub subscription id, this param is relevant in case scan_mode is $SCAN_MODE_IN_ACCOUNT_HUB + # or $SCAN_MODE_IN_ACCOUNT_SUB and represents the subscription where the AWP scans will be executed + skip_function_apps_scan = false # currently this attribute not supported with the azure resources (the default is false as we understood) +} + + +# locals +locals { + SCAN_MODE_SAAS = "saas" + SCAN_MODE_IN_ACCOUNT = "inAccount" + SCAN_MODE_IN_ACCOUNT_SUB = "inAccountSub" + SCAN_MODE_IN_ACCOUNT_HUB = "inAccountHub" + + AWP_VM_SCAN_OPERATOR_ROLE_NAME_PREFIX = "CloudGuard AWP VM Scan Operator" + AWP_VM_SCAN_OPERATOR_ROLE_DESCRIPTION = "Grants all needed permissions for CloudGuard app registration to scan VMs (version: ${var.awp_version})" + AWP_VM_SCAN_OPERATOR_ROLE_ACTIONS = [ + "Microsoft.Compute/disks/read", + "Microsoft.Compute/disks/write", + "Microsoft.Compute/disks/delete", + "Microsoft.Compute/disks/beginGetAccess/action", + "Microsoft.Compute/snapshots/read", + "Microsoft.Compute/snapshots/write", + "Microsoft.Compute/snapshots/delete", + "Microsoft.Compute/snapshots/beginGetAccess/action", + "Microsoft.Compute/snapshots/endGetAccess/action", + "Microsoft.Network/networkInterfaces/join/action", + "Microsoft.Network/networkInterfaces/write", + "Microsoft.Compute/virtualMachines/write", + "Microsoft.Compute/virtualMachines/delete", + "Microsoft.Network/networkSecurityGroups/write", + "Microsoft.Network/networkSecurityGroups/join/action", + "Microsoft.Network/virtualNetworks/write", + "Microsoft.Network/virtualNetworks/subnets/join/action" + ] + + AWP_VM_DATA_SHARE_ROLE_NAME_PREFIX = "CloudGuard AWP VM Data Share" + AWP_VM_DATA_SHARE_ROLE_DESCRIPTION = "Grants needed permissions for CloudGuard app registration to read VMs data (version: ${var.awp_version})" + AWP_VM_DATA_SHARE_ROLE_ACTIONS = [ + "Microsoft.Compute/disks/beginGetAccess/action", + "Microsoft.Compute/virtualMachines/read" + ] + + AWP_FA_MANAGED_IDENTITY_NAME = "CloudGuardAWPScannerManagedIdentity" + + AWP_FA_SCANNER_ROLE_NAME_PREFIX = "CloudGuard AWP Function Apps Scanner" + AWP_FA_SCANNER_ROLE_DESCRIPTION = "Grants needed permissions for CloudGuard AWP function-apps scanner (version: ${var.awp_version})" + AWP_FA_SCANNER_ROLE_ACTIONS = [ + "Microsoft.Web/sites/publish/Action", + "Microsoft.Web/sites/config/list/Action", + "microsoft.web/sites/functions/read" + ] + + AWP_FA_SCAN_OPERATOR_ROLE_NAME_PREFIX = "CloudGuard AWP FunctionApp Scan Operator" + AWP_FA_SCAN_OPERATOR_ROLE_DESCRIPTION = "Grants all needed permissions for CloudGuard app registration to scan function-apps (version: ${var.awp_version})" + AWP_FA_SCAN_OPERATOR_ROLE_ACTIONS = [ + "Microsoft.Compute/virtualMachines/write", + "Microsoft.Compute/virtualMachines/extensions/write", + "Microsoft.Network/networkSecurityGroups/write", + "Microsoft.Network/networkSecurityGroups/join/action", + "Microsoft.Network/virtualNetworks/write", + "Microsoft.Network/virtualNetworks/subnets/join/action", + "Microsoft.ManagedIdentity/userAssignedIdentities/assign/action" + ] + + AWP_RESOURCE_GROUP_NAME_PREFIX = "cloudguard-AWP" + AWP_OWNER_TAG = "Owner=CG.AWP" + AWP_VERSION_TAG = "CloudGuard.AWP.Version=${var.awp_version}" + LOCATION = var.region +} + + +# Provider block for the hub account (used only in In-Account-Sub mode) +provider "azurerm" { + alias = "hub" + features {} + + subscription_id = var.hub_subscription_id + # Add any other necessary authentication details for the hub account +} + +# Provider block for the sub account (used only in In-Account-Sub mode) +provider "azurerm" { + alias = "sub" + features {} + + subscription_id = var.subscription_id + # Add any other necessary authentication details for the sub account +} + +# Data source to retrieve information about the current Azure subscription +data "azurerm_subscription" "hub" { + provider = azurerm.hub +} + +data "azurerm_subscription" "sub" { + provider = azurerm.sub +} + +# Define the resource group where CloudGuard resources will be deployed +resource "azurerm_resource_group" "cloudguard" { + count = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_HUB ? 1 : 0 + name = local.AWP_RESOURCE_GROUP_NAME_PREFIX + location = local.LOCATION + tags = { + Owner = local.AWP_OWNER_TAG + Version = local.AWP_VERSION_TAG + } +} + +resource "azurerm_resource_group" "cloudguard_hub" { + count = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_SUB ? 1 : 0 + provider = azurerm.hub + name = "${local.AWP_RESOURCE_GROUP_NAME_PREFIX}_${var.subscription_id}" + location = local.LOCATION + tags = { + Owner = local.AWP_OWNER_TAG + Version = local.AWP_VERSION_TAG + } +} + +# Define custom roles based on scan mode +resource "azurerm_role_definition" "cloudguard_vm_data_share" { + count = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_HUB || var.scan_mode == local.SCAN_MODE_SAAS ? 1 : 0 + name = "CloudGuard AWP VM Data Share ${var.subscription_id}" # need to change subscription id to hub subscription id when hub mode + description = local.AWP_VM_DATA_SHARE_ROLE_DESCRIPTION + scope = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_SAAS ? "/subscriptions/${var.subscription_id}" : "/providers/Microsoft.Management/managementGroups/${var.management_group}:-${var.tenant_id}" + permissions { + actions = local.AWP_VM_DATA_SHARE_ROLE_ACTIONS + not_actions = [] + } +} + +# Define the managed identity for CloudGuard AWP +resource "azurerm_managed_identity" "cloudguard_identity" { + count = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_HUB ? 1 : 0 + name = local.AWP_FA_MANAGED_IDENTITY_NAME + location = azurerm_resource_group.cloudguard.location + resource_group_name = azurerm_resource_group.cloudguard.name +} + +resource "azurerm_role_definition" "cloudguard_vm_scan_operator" { + count = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_HUB ? 1 : 0 + description = local.AWP_VM_SCAN_OPERATOR_ROLE_DESCRIPTION + name = "${local.AWP_VM_SCAN_OPERATOR_ROLE_NAME_PREFIX} ${var.subscription_id}" + scope = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT ? "/subscriptions/${var.subscription_id}" : "/providers/Microsoft.Management/managementGroups/${var.management_group}:-${var.tenant_id}" + permissions { + actions = local.AWP_VM_SCAN_OPERATOR_ROLE_ACTIONS + not_actions = [] + } +} + +resource "azurerm_role_definition" "cloudguard_function_apps_scanner" { + count = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_HUB ? 1 : 0 + name = "${local.AWP_FA_SCANNER_ROLE_NAME_PREFIX} ${var.subscription_id}" + description = local.AWP_FA_SCANNER_ROLE_DESCRIPTION + scope = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT ? "/subscriptions/${var.subscription_id}" : "/providers/Microsoft.Management/managementGroups/${var.management_group}:-${var.tenant_id}" + permissions { + actions = local.AWP_FA_SCANNER_ROLE_ACTIONS + not_actions = [] + } +} + +resource "azurerm_role_definition" "cloudguard_function_apps_scan_operator" { + count = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_HUB ? 1 : 0 + name = "${local.AWP_FA_SCAN_OPERATOR_ROLE_NAME_PREFIX} ${var.subscription_id}" + description = local.AWP_FA_SCAN_OPERATOR_ROLE_DESCRIPTION + scope = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT ? "/subscriptions/${var.subscription_id}" : "/providers/Microsoft.Management/managementGroups/${var.management_group}:-${var.tenant_id}" + permissions { + actions = local.AWP_FA_SCAN_OPERATOR_ROLE_ACTIONS + not_actions = [] + } +} + +# Assign custom roles based on scan mode +resource "azurerm_role_assignment" "cloudguard_vm_data_share_assignment" { + count = var.scan_mode == local.SCAN_MODE_SAAS || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_SUB ? 1 : 0 + provider = azurerm.sub + name = "${local.AWP_VM_DATA_SHARE_ROLE_NAME_PREFIX} ${var.subscription_id}" + scope = "/subscriptions/${var.subscription_id}" + role_definition_name = azurerm_role_definition.cloudguard_vm_data_share[count.index].name + principal_id = var.app_object_id +} + +resource "azurerm_role_assignment" "cloudguard_vm_scan_operator_assignment" { + count = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_HUB ? 1 : 0 + scope = "/subscriptions/${var.subscription_id}" + role_definition_name = azurerm_role_definition.cloudguard_vm_scan_operator[count.index].name + principal_id = var.app_object_id +} + +resource "azurerm_role_assignment" "cloudguard_function_apps_scanner_assignment" { + count = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_HUB ? 1 : 0 + provider = azurerm.sub + scope = "/subscriptions/${var.subscription_id}" + role_definition_name = azurerm_role_definition.cloudguard_function_apps_scanner[count.index].name + principal_id = azurerm_managed_identity.cloudguard_identity[count.index].id +} + +resource "azurerm_role_assignment" "cloudguard_function_apps_scan_operator_assignment" { + count = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_HUB ? 1 : 0 + scope = "/subscriptions/${var.subscription_id}" + role_definition_name = azurerm_role_definition.cloudguard_function_apps_scan_operator[count.index].name + principal_id = var.app_object_id +} + +resource "azurerm_resource_group" "cloudguard_hub" { + count = var.scan_mode == "inAccountSub" ? 1 : 0 + name = "cloudguard-AWP-${var.subscription_id}" + location = var.region +} + +resource "dome9_awp_azure_onboarding" "awp_azure_onboarding_resource" { + subscription_id = "d0dd3387-d9c5-487b-8b18-4fa969fd98cd" + scan_mode = "inAccountHub" # The scan mode (valid options are: $SCAN_MODE_SAAS, $SCAN_MODE_IN_ACCOUNT, $SCAN_MODE_IN_ACCOUNT_HUB, $SCAN_MODE_IN_ACCOUNT_SUB) + hub_subscription_id = "d0dd3387-d9c5-487b-8b18-4fa969fd98cd" + + # azure role name customizations currently unsupported + onboarding_customizations = { + virtual_machine_data_share_role_name = "string" + virtual_machine_scan_operator_role_name = "string" + function_app_scan_operator_role_name = "string" + function_app_scanner_role_name = "string" + resource_group_name = "string" + scanner_managed_identity_name = "string" + } + agentless_account_settings = { + disabled_regions = ["string"] + scan_machine_interval_in_hours = 0 + max_concurrence_scans_per_region = 0 + skip_function_apps_scan = false # + custom_tags = {} + } +} diff --git a/examples/awp_aws_onboarding/main.tf b/examples/awp_aws_onboarding/main.tf new file mode 100644 index 00000000..1f1cc682 --- /dev/null +++ b/examples/awp_aws_onboarding/main.tf @@ -0,0 +1,587 @@ + +# Dome9 Provider Configurations +terraform { + required_providers { + dome9 = { + source = "dome9/dome9" + version = "1.29.6" + } + } +} + +provider "dome9" { + dome9_access_id = "DOME9_CLOUDGUARD_API_ACCESS_ID" + dome9_secret_key = "DOME9_CLOUDGUARD_API_SECRET_KEY" + base_url = "DOME9_API_BASE_URL" +} + +terraform { + required_providers { + aws = { + source = "hashicorp/aws" + version = "5.37.0" + } + } +} + +provider "aws" { + region = "us-east-1" + profile = "custom" +} + +data "dome9_awp_aws_get_onboarding_data" "dome9_awp_aws_onboarding_data_source" { + cloudguard_account_id = "ae481d4a-603b-4fa6-8f31-6c6d57920e96" + scan_mode = "inAccount" +} + +#onboarding Enable/Disable AWP on AWS Account + +resource "dome9_awp_aws_onboarding" "awp_onboarding_on_aws" { + cloudguard_account_id = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.scan_mode + cross_account_role_name = "CloudGuardAWPCrossAccountRole" # default value can be applicable + # should be similar to "NjM0NzI5NTk3NjIzLWFlNDgxZDRhLTYwM2ItNGZhNi04ZjMxLTZjNmQ1NzkyMGU5Ng==" + cross_account_external_id = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cross_account_external_id + scan_mode = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.scan_mode + should_create_policy = false + force_delete = false + account_settings = { + + } + version = "" + # Add depends_on to ensure this resource is created last + depends_on = [ + aws_iam_role_policy_attachment.CloudGuardAWPCrossAccountRoleAttachment + ] +} + +data "aws_partition" "current" {} + +data "aws_region" "current" {} + +data "aws_caller_identity" "current" {} + +# Cross account role to allow CloudGuard access +resource "aws_iam_role" "CloudGuardAWPCrossAccountRole" { + name = "CloudGuardAWPCrossAccountRole" + description = "CloudGuard AWP Cross Account Role" + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Effect = "Allow" + Principal = { + AWS = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.d9_aws_account_id + } + Action = "sts:AssumeRole" + Condition = { + StringEquals = { + "sts:ExternalId" = "${data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cross_account_external_id}" + } + } + }] + }) + + depends_on = [aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction] +} + +resource "aws_iam_policy" "CloudGuardAWP" { + name = "CloudGuardAWP" + description = "Policy for CloudGuard AWP" + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = [ + "ec2:DescribeInstances", + "ec2:DescribeSnapshots", + "ec2:DescribeRegions", + "ec2:DescribeVolumes" + ] + Resource = "*" + }, + { + Effect = "Allow" + Action = [ + "lambda:InvokeFunction", + "lambda:GetFunction", + "lambda:GetLayerVersion", + "lambda:TagResource", + "lambda:ListTags", + "lambda:UntagResource", + "lambda:UpdateFunctionCode", + "lambda:UpdateFunctionConfiguration", + "lambda:GetFunctionConfiguration" + ] + Resource = aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction.arn + }, + { + Effect = "Allow" + Action = "cloudformation:DescribeStacks" + Resource = "arn:${data.aws_partition.current.partition}:cloudformation:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:stack/stackName/*" + }, + { + Effect = "Allow" + Action = "s3:GetObject" + Resource = "arn:${data.aws_partition.current.partition}:s3:::agentless-prod-us/remote_functions*" + } + ] + }) +} + +resource "aws_iam_role_policy_attachment" "CloudGuardAWPCrossAccountRoleAttachment" { + role = aws_iam_role.CloudGuardAWPCrossAccountRole.name + policy_arn = aws_iam_policy.CloudGuardAWP.arn +} +# end resources for CloudGuardAWPCrossAccountRole + +# Cross account role policy +resource "aws_iam_policy" "CloudGuardAWPCrossAccountRolePolicy" { + count = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.scan_mode == "inAccount" ? 1 : 0 + name = "CloudGuardAWPCrossAccountRolePolicy" + description = "Policy for CloudGuard AWP Cross Account Role" + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = [ + "ec2:CreateSecurityGroup", + "ec2:DescribeManagedPrefixLists", + "ec2:DescribeSecurityGroups", + "ec2:DescribeSecurityGroupRules", + "ec2:RevokeSecurityGroupEgress", + "ec2:AuthorizeSecurityGroupEgress", + "ec2:CreateTags", + ] + Resource = "*" + }, + { + Effect = "Allow" + Action = [ + "ec2:DeleteSecurityGroup", + ] + Resource = "*" + Condition = { + StringEquals = { + "aws:ResourceTag/Owner" = "CG.AWP" + } + } + }, + ] + }) +} + +resource "aws_iam_policy" "CloudGuardAWPCrossAccountRolePolicy_SaaS" { + count = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.scan_mode == "saas" ? 1 : 0 + name = "CloudGuardAWPCrossAccountRolePolicy_SaaS" + description = "Policy for CloudGuard AWP Cross Account Role - SaaS Mode" + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = [ + "kms:DescribeKey", + "kms:ReplicateKey", + ] + Resource = [aws_kms_key.CloudGuardAWPKey.arn] + }, + { + Effect = "Allow" + Action = [ + "kms:PutKeyPolicy", + "kms:ScheduleKeyDeletion", + "kms:CancelKeyDeletion", + "kms:TagResource", + ] + Resource = aws_kms_key.CloudGuardAWPKey.arn + }, + { + Effect = "Allow" + Action = [ + "kms:CreateKey", + ] + Resource = "*" + }, + ] + }) +} + +resource "aws_iam_policy_attachment" "CloudGuardAWPCrossAccountRolePolicyAttachment" { + count = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.scan_mode == "inAccount" ? 1 : 0 + name = "CloudGuardAWPCrossAccountRolePolicyAttachment" + policy_arn = aws_iam_policy.CloudGuardAWPCrossAccountRolePolicy[count.index].arn + roles = [aws_iam_role.CloudGuardAWPCrossAccountRole.name] +} + +resource "aws_iam_policy_attachment" "CloudGuardAWPCrossAccountRolePolicyAttachment_SaaS" { + count = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.scan_mode == "saas" ? 1 : 0 + name = "CloudGuardAWPCrossAccountRolePolicyAttachment_SaaS" + policy_arn = aws_iam_policy.CloudGuardAWPCrossAccountRolePolicy_SaaS[count.index].arn + roles = [aws_iam_role.CloudGuardAWPCrossAccountRole.name] +} +# END Cross account role policy + +# AWP proxy lambda function +resource "aws_lambda_function" "CloudGuardAWPSnapshotsUtilsFunction" { + function_name = "CloudGuardAWPSnapshotsUtils" + handler = "snapshots_utils.lambda_handler" + description = "CloudGuard AWP Proxy for managing remote actions and resources" + role = aws_iam_role.CloudGuardAWPSnapshotsUtilsLambdaExecutionRole.arn + runtime = "python3.9" + memory_size = 256 + timeout = 900 + s3_bucket = "agentless-prod-us" + s3_key = "remote_functions/CloudGuardAWPSnapshotsUtils7.zip" + + environment { + variables = { + CP_AWP_AWS_ACCOUNT = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.d9_aws_account_id + CP_AWP_MR_KMS_KEY_ID = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.scan_mode == "saas" ? aws_kms_key.CloudGuardAWPKey.arn : "" + CP_AWP_SCAN_MODE = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.scan_mode + CP_AWP_SECURITY_GROUP_NAME = "CloudGuardAWPSecurityGroup" + AWS_PARTITION = data.aws_partition.current.partition + } + } + + tags = { + Owner = "CG.AWP" + } + + # Use provisioners to invoke the Lambda function after creation and destruction + # Define Provisioners to do some equivalent to AWS Custom Resource + # Create Provisioner is not relevant + provisioner "local-exec" { + when = "create" + command = < Date: Sun, 3 Mar 2024 13:43:02 +0200 Subject: [PATCH 02/47] add get cloud guard id api from aws account --- ...source_dome9_awp_aws_get_onboarding_data.go | 18 +++++++++++++----- .../main.tf} | 0 .../awp_aws_onboarding/awp_aws_onboarding.go | 16 ++++++++++++++++ 3 files changed, 29 insertions(+), 5 deletions(-) rename examples/{awp_aws_onboarding/main-azure.tf => awp_azure_onboarding/main.tf} (100%) diff --git a/dome9/data_source_dome9_awp_aws_get_onboarding_data.go b/dome9/data_source_dome9_awp_aws_get_onboarding_data.go index 48d1ec9d..84a86783 100644 --- a/dome9/data_source_dome9_awp_aws_get_onboarding_data.go +++ b/dome9/data_source_dome9_awp_aws_get_onboarding_data.go @@ -1,6 +1,7 @@ package dome9 import ( + "encoding/base64" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) @@ -9,11 +10,7 @@ func dataSourceAwpAwsOnboardingData() *schema.Resource { Read: dataSourceAwpAwsOnboardingDataRead, Schema: map[string]*schema.Schema{ - "cloudguard_account_id": { - Type: schema.TypeString, - Required: true, - }, - "scan_mode": { + "externalAwsAccountId": { Type: schema.TypeString, Required: true, }, @@ -53,6 +50,10 @@ func dataSourceAwpAwsOnboardingData() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "crossAccountRoleExternalId": { + Type: schema.TypeString, + Computed: true, + }, }, } } @@ -75,6 +76,13 @@ func dataSourceAwpAwsOnboardingDataRead(d *schema.ResourceData, meta interface{} _ = d.Set("remoteSnapshotsUtilsFunctionRunTime", resp.RemoteSnapshotsUtilsFunctionRunTime) _ = d.Set("remoteSnapshotsUtilsFunctionTimeOut", resp.RemoteSnapshotsUtilsFunctionTimeOut) _ = d.Set("awpClientSideSecurityGroupName", resp.AwpClientSideSecurityGroupName) + cloudAccountID, _, err := d9Client.awpAwsOnboarding.GetCloudAccountId(d.Get("externalAwsAccountId").(string)) + if err != nil { + return err + } + combinedString := resp.CloudGuardBackendAccountId + "-" + cloudAccountID + encodedString := base64.StdEncoding.EncodeToString([]byte(combinedString)) + _ = d.Set("crossAccountRoleExternalId", encodedString) return nil } diff --git a/examples/awp_aws_onboarding/main-azure.tf b/examples/awp_azure_onboarding/main.tf similarity index 100% rename from examples/awp_aws_onboarding/main-azure.tf rename to examples/awp_azure_onboarding/main.tf diff --git a/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go b/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go index d0ff4059..2e8718c6 100644 --- a/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go +++ b/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go @@ -1,11 +1,13 @@ package awp_aws_onboarding import ( + "fmt" "net/http" ) const ( awpAWSGetOnboardingDataPath = "workload/agentless/aws/terraform/onboarding" + cloudAccountsPath = "cloudaccounts/" ) type AgentlessAwsTerraformOnboardingDataResponse struct { @@ -20,6 +22,10 @@ type AgentlessAwsTerraformOnboardingDataResponse struct { AwpClientSideSecurityGroupName string `json:"awpClientSideSecurityGroupName"` } +type CloudAccountResponse struct { + ID string `json:"id"` +} + func (service *Service) Get() (*AgentlessAwsTerraformOnboardingDataResponse, *http.Response, error) { v := new(AgentlessAwsTerraformOnboardingDataResponse) resp, err := service.Client.NewRequestDo("GET", awpAWSGetOnboardingDataPath, nil, nil, v) @@ -29,3 +35,13 @@ func (service *Service) Get() (*AgentlessAwsTerraformOnboardingDataResponse, *ht return v, resp, nil } + +func (service *Service) GetCloudAccountId(externalAccountId string) (string, *http.Response, error) { + path := fmt.Sprintf("%s%s", cloudAccountsPath, externalAccountId) + respData := new(CloudAccountResponse) + resp, err := service.Client.NewRequestDo("GET", path, nil, nil, respData) + if err != nil { + return "", nil, err + } + return respData.ID, resp, nil +} From baf32c791833f3e9cf22f4c89a884f87d1a8a42f Mon Sep 17 00:00:00 2001 From: Omar Date: Sun, 3 Mar 2024 16:37:02 +0200 Subject: [PATCH 03/47] some corrections on dome9_awp_aws_get_onboarding_data resource --- ...ource_dome9_awp_aws_get_onboarding_data.go | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/dome9/data_source_dome9_awp_aws_get_onboarding_data.go b/dome9/data_source_dome9_awp_aws_get_onboarding_data.go index 84a86783..ba71233a 100644 --- a/dome9/data_source_dome9_awp_aws_get_onboarding_data.go +++ b/dome9/data_source_dome9_awp_aws_get_onboarding_data.go @@ -10,7 +10,7 @@ func dataSourceAwpAwsOnboardingData() *schema.Resource { Read: dataSourceAwpAwsOnboardingDataRead, Schema: map[string]*schema.Schema{ - "externalAwsAccountId": { + "external_aws_account_id": { Type: schema.TypeString, Required: true, }, @@ -22,35 +22,35 @@ func dataSourceAwpAwsOnboardingData() *schema.Resource { Type: schema.TypeString, Computed: true, }, - "cloudGuardBackendAccountId": { + "cloud_guard_backend_account_id": { Type: schema.TypeString, Computed: true, }, - "agentlessBucketName": { + "agentless_bucket_name": { Type: schema.TypeString, Computed: true, }, - "remoteFunctionsPrefixKey": { + "remote_functions_prefix_key": { Type: schema.TypeString, Computed: true, }, - "remoteSnapshotsUtilsFunctionName": { + "remote_snapshots_utils_function_name": { Type: schema.TypeString, Computed: true, }, - "remoteSnapshotsUtilsFunctionRunTime": { + "remote_snapshots_utils_function_run_time": { Type: schema.TypeString, Computed: true, }, - "remoteSnapshotsUtilsFunctionTimeOut": { + "remote_snapshots_utils_function_time_out": { Type: schema.TypeInt, Computed: true, }, - "awpClientSideSecurityGroupName": { + "awp_client_side_security_group_name": { Type: schema.TypeString, Computed: true, }, - "crossAccountRoleExternalId": { + "cross_account_role_external_id": { Type: schema.TypeString, Computed: true, }, @@ -69,20 +69,20 @@ func dataSourceAwpAwsOnboardingDataRead(d *schema.ResourceData, meta interface{} d.SetId(resp.CloudGuardBackendAccountId) _ = d.Set("stage", resp.Stage) _ = d.Set("region", resp.Region) - _ = d.Set("cloudGuardBackendAccountId", resp.CloudGuardBackendAccountId) - _ = d.Set("agentlessBucketName", resp.AgentlessBucketName) - _ = d.Set("remoteFunctionsPrefixKey", resp.RemoteFunctionsPrefixKey) - _ = d.Set("remoteSnapshotsUtilsFunctionName", resp.RemoteSnapshotsUtilsFunctionName) - _ = d.Set("remoteSnapshotsUtilsFunctionRunTime", resp.RemoteSnapshotsUtilsFunctionRunTime) - _ = d.Set("remoteSnapshotsUtilsFunctionTimeOut", resp.RemoteSnapshotsUtilsFunctionTimeOut) - _ = d.Set("awpClientSideSecurityGroupName", resp.AwpClientSideSecurityGroupName) - cloudAccountID, _, err := d9Client.awpAwsOnboarding.GetCloudAccountId(d.Get("externalAwsAccountId").(string)) + _ = d.Set("cloud_guard_backend_account_id", resp.CloudGuardBackendAccountId) + _ = d.Set("agentless_bucket_name", resp.AgentlessBucketName) + _ = d.Set("remote_functions_prefix_key", resp.RemoteFunctionsPrefixKey) + _ = d.Set("remote_snapshots_utils_function_name", resp.RemoteSnapshotsUtilsFunctionName) + _ = d.Set("remote_snapshots_utils_function_run_time", resp.RemoteSnapshotsUtilsFunctionRunTime) + _ = d.Set("remote_snapshots_utils_function_time_out", resp.RemoteSnapshotsUtilsFunctionTimeOut) + _ = d.Set("awp_client_side_security_group_name", resp.AwpClientSideSecurityGroupName) + cloudAccountID, _, err := d9Client.awpAwsOnboarding.GetCloudAccountId(d.Get("external_aws_account_id").(string)) if err != nil { return err } combinedString := resp.CloudGuardBackendAccountId + "-" + cloudAccountID encodedString := base64.StdEncoding.EncodeToString([]byte(combinedString)) - _ = d.Set("crossAccountRoleExternalId", encodedString) + _ = d.Set("cross_account_role_external_id", encodedString) return nil } From 1e0c2a984cd73e9e02a49b398635f4ff9478ef57 Mon Sep 17 00:00:00 2001 From: Omar Date: Sun, 3 Mar 2024 20:49:45 +0200 Subject: [PATCH 04/47] add unit test for get onboarding data source --- dome9/common/testing/variable/variable.go | 5 ++ ..._dome9_awp_aws_get_onboarding_data_test.go | 56 +++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go diff --git a/dome9/common/testing/variable/variable.go b/dome9/common/testing/variable/variable.go index 39ce5b3b..1b15c187 100644 --- a/dome9/common/testing/variable/variable.go +++ b/dome9/common/testing/variable/variable.go @@ -211,3 +211,8 @@ const ( HasErrors = "false" HasDataSyncStatusIssues = "false" ) + +// awp aws onboarding data resource/data source +const ( + AwpAwsAccountID = "478980137264" +) diff --git a/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go b/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go new file mode 100644 index 00000000..91b87a2e --- /dev/null +++ b/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go @@ -0,0 +1,56 @@ +package dome9 + +import ( + "fmt" + "github.com/terraform-providers/terraform-provider-dome9/dome9/common/resourcetype" + "github.com/terraform-providers/terraform-provider-dome9/dome9/common/testing/method" + "github.com/terraform-providers/terraform-provider-dome9/dome9/common/testing/variable" + "log" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" +) + +func TestAccDataSourceAwpAwsOnboardingDataBasic(t *testing.T) { + _, awsOnboardingDataSourceTypeAndName, randomDataSourceName := method.GenerateRandomSourcesTypeAndName(resourcetype.AwpAwsOnboardingData) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckAwpAwsOnboardingDataBasic(randomDataSourceName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(awsOnboardingDataSourceTypeAndName, "external_aws_account_id", variable.AwpAwsAccountID), + resource.TestCheckResourceAttrSet(awsOnboardingDataSourceTypeAndName, "stage"), + resource.TestCheckResourceAttrSet(awsOnboardingDataSourceTypeAndName, "region"), + resource.TestCheckResourceAttrSet(awsOnboardingDataSourceTypeAndName, "cloud_guard_backend_account_id"), + resource.TestCheckResourceAttrSet(awsOnboardingDataSourceTypeAndName, "agentless_bucket_name"), + resource.TestCheckResourceAttrSet(awsOnboardingDataSourceTypeAndName, "remote_functions_prefix_key"), + resource.TestCheckResourceAttrSet(awsOnboardingDataSourceTypeAndName, "remote_snapshots_utils_function_name"), + resource.TestCheckResourceAttrSet(awsOnboardingDataSourceTypeAndName, "remote_snapshots_utils_function_run_time"), + resource.TestCheckResourceAttrSet(awsOnboardingDataSourceTypeAndName, "remote_snapshots_utils_function_time_out"), + resource.TestCheckResourceAttrSet(awsOnboardingDataSourceTypeAndName, "awp_client_side_security_group_name"), + resource.TestCheckResourceAttrSet(awsOnboardingDataSourceTypeAndName, "cross_account_role_external_id"), + ), + }, + }, + }) +} + +func testAccCheckAwpAwsOnboardingDataBasic(resourceName string) string { + res := fmt.Sprintf(` + data "%s" "%s" { + external_aws_account_id = "%s" + } + `, + // Add the HCL configuration for the resource here + resourcetype.AwpAwsOnboardingData, + resourceName, + variable.AwpAwsAccountID, + ) + log.Printf("[INFO] testAccCheckAwpAwsOnboardingDataBasic:%+v\n", res) + return res +} From 91d0df3d3bbd4528c8cd1127ba765f8d141ca9f8 Mon Sep 17 00:00:00 2001 From: Omar Date: Wed, 6 Mar 2024 10:36:03 +0200 Subject: [PATCH 05/47] enhance terraform acceptance test for AwpAwsOnboardingData --- dome9/common/providerconst/const.go | 29 ++--- ..._dome9_awp_aws_get_onboarding_data_test.go | 100 ++++++++++++++---- 2 files changed, 97 insertions(+), 32 deletions(-) diff --git a/dome9/common/providerconst/const.go b/dome9/common/providerconst/const.go index a59ba93d..7c2a56dd 100644 --- a/dome9/common/providerconst/const.go +++ b/dome9/common/providerconst/const.go @@ -109,13 +109,13 @@ const ( AF_SOUTH_1 = "26" EU_SOUTH_1 = "27" AP_NORTHEAST_3 = "28" - ME_CENTRAL_1 = "29" - AP_SOUTH_2 = "30" - AP_SOUTHEAST_3 = "31" - AP_SOUTHEAST_4 = "32" - EU_CENTRAL_2 = "33" - EU_SOUTH_2 = "34" - IL_CENTRAL_1 = "35" + ME_CENTRAL_1 = "29" + AP_SOUTH_2 = "30" + AP_SOUTHEAST_3 = "31" + AP_SOUTHEAST_4 = "32" + EU_CENTRAL_2 = "33" + EU_SOUTH_2 = "34" + IL_CENTRAL_1 = "35" ) // Azure consts @@ -185,11 +185,11 @@ var AWSRegionsEnum = map[string]string{ "af_south_1": AF_SOUTH_1, "eu_south_1": EU_SOUTH_1, "ap_northeast_3": AP_NORTHEAST_3, - "me_central_1": ME_CENTRAL_1, - "ap_south_2": AP_SOUTH_2, - "ap_southeast_3": AP_SOUTHEAST_3, - "ap_southeast_4": AP_SOUTHEAST_4, - "eu_central_2": EU_CENTRAL_2, + "me_central_1": ME_CENTRAL_1, + "ap_south_2": AP_SOUTH_2, + "ap_southeast_3": AP_SOUTHEAST_3, + "ap_southeast_4": AP_SOUTHEAST_4, + "eu_central_2": EU_CENTRAL_2, "eu_south_2": EU_SOUTH_2, "il_central_1": IL_CENTRAL_1, } @@ -201,3 +201,8 @@ var PermissionTrafficType = map[string]string{ // All Assessments Cloud Accounts Types var AssessmentCloudAccountType = []string{"Aws", "Azure", "GCP", "Kubernetes", "Terraform", "Generic", "KubernetesRuntimeAssurance", "ShiftLeft", "SourceCodeAssurance", "ImageAssurance", "Alibaba", "Cft", "ContainerRegistry", "Ers"} + +// AWP onboarding +const ( + AwsCloudFormationStack = "aws_cloudformation_stack" +) diff --git a/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go b/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go index 91b87a2e..d17eb8a9 100644 --- a/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go +++ b/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go @@ -2,6 +2,7 @@ package dome9 import ( "fmt" + "github.com/terraform-providers/terraform-provider-dome9/dome9/common/providerconst" "github.com/terraform-providers/terraform-provider-dome9/dome9/common/resourcetype" "github.com/terraform-providers/terraform-provider-dome9/dome9/common/testing/method" "github.com/terraform-providers/terraform-provider-dome9/dome9/common/testing/variable" @@ -12,8 +13,17 @@ import ( ) func TestAccDataSourceAwpAwsOnboardingDataBasic(t *testing.T) { - _, awsOnboardingDataSourceTypeAndName, randomDataSourceName := method.GenerateRandomSourcesTypeAndName(resourcetype.AwpAwsOnboardingData) + // Get dome9_aws_unified_onboarding resource to do aws onboarding + awsUnifiedOnboardingResourceTypeAndName, awsUnifiedOnboardingDataResourceName, awsUnifiedOnboardingResourceName := method.GenerateRandomSourcesTypeAndName(resourcetype.AwsUnifiedOnboarding) + awsUnifiedOnboardingResourceHCL := getAwsUnifiedOnboardingResourceHCL(awsUnifiedOnboardingResourceName, awsUnifiedOnboardingResourceTypeAndName) + + // Get aws_cloudformation_stack resource + _, _, cloudFormationStackGeneratedName := method.GenerateRandomSourcesTypeAndName(providerconst.AwsCloudFormationStack) + awsCloudFormationStackHcl := getAwsCloudFormationStackResourceHCL(cloudFormationStackGeneratedName, awsUnifiedOnboardingResourceTypeAndName) + + // Get dome9_awp_aws_get_onboarding_data resource names + _, awpAwsOnboardingDataSourceTypeAndName, awpAwsOnboardingDataGeneratedName := method.GenerateRandomSourcesTypeAndName(resourcetype.AwpAwsOnboardingData) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) @@ -21,36 +31,86 @@ func TestAccDataSourceAwpAwsOnboardingDataBasic(t *testing.T) { Providers: testAccProviders, Steps: []resource.TestStep{ { - Config: testAccCheckAwpAwsOnboardingDataBasic(randomDataSourceName), + Config: testAccCheckAwpAwsOnboardingDataBasic(awsUnifiedOnboardingResourceHCL, awsCloudFormationStackHcl, awpAwsOnboardingDataGeneratedName, awsUnifiedOnboardingDataResourceName), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(awsOnboardingDataSourceTypeAndName, "external_aws_account_id", variable.AwpAwsAccountID), - resource.TestCheckResourceAttrSet(awsOnboardingDataSourceTypeAndName, "stage"), - resource.TestCheckResourceAttrSet(awsOnboardingDataSourceTypeAndName, "region"), - resource.TestCheckResourceAttrSet(awsOnboardingDataSourceTypeAndName, "cloud_guard_backend_account_id"), - resource.TestCheckResourceAttrSet(awsOnboardingDataSourceTypeAndName, "agentless_bucket_name"), - resource.TestCheckResourceAttrSet(awsOnboardingDataSourceTypeAndName, "remote_functions_prefix_key"), - resource.TestCheckResourceAttrSet(awsOnboardingDataSourceTypeAndName, "remote_snapshots_utils_function_name"), - resource.TestCheckResourceAttrSet(awsOnboardingDataSourceTypeAndName, "remote_snapshots_utils_function_run_time"), - resource.TestCheckResourceAttrSet(awsOnboardingDataSourceTypeAndName, "remote_snapshots_utils_function_time_out"), - resource.TestCheckResourceAttrSet(awsOnboardingDataSourceTypeAndName, "awp_client_side_security_group_name"), - resource.TestCheckResourceAttrSet(awsOnboardingDataSourceTypeAndName, "cross_account_role_external_id"), + resource.TestCheckResourceAttr(awpAwsOnboardingDataSourceTypeAndName, "external_aws_account_id", variable.AwpAwsAccountID), + resource.TestCheckResourceAttrSet(awpAwsOnboardingDataSourceTypeAndName, "stage"), + resource.TestCheckResourceAttrSet(awpAwsOnboardingDataSourceTypeAndName, "region"), + resource.TestCheckResourceAttrSet(awpAwsOnboardingDataSourceTypeAndName, "cloud_guard_backend_account_id"), + resource.TestCheckResourceAttrSet(awpAwsOnboardingDataSourceTypeAndName, "agentless_bucket_name"), + resource.TestCheckResourceAttrSet(awpAwsOnboardingDataSourceTypeAndName, "remote_functions_prefix_key"), + resource.TestCheckResourceAttrSet(awpAwsOnboardingDataSourceTypeAndName, "remote_snapshots_utils_function_name"), + resource.TestCheckResourceAttrSet(awpAwsOnboardingDataSourceTypeAndName, "remote_snapshots_utils_function_run_time"), + resource.TestCheckResourceAttrSet(awpAwsOnboardingDataSourceTypeAndName, "remote_snapshots_utils_function_time_out"), + resource.TestCheckResourceAttrSet(awpAwsOnboardingDataSourceTypeAndName, "awp_client_side_security_group_name"), + resource.TestCheckResourceAttrSet(awpAwsOnboardingDataSourceTypeAndName, "cross_account_role_external_id"), ), }, }, }) } -func testAccCheckAwpAwsOnboardingDataBasic(resourceName string) string { +func testAccCheckAwpAwsOnboardingDataBasic(awsUnifiedOnboardingHcl string, awsCloudFormationStackHcl string, + awpAwsGetOnboardingDataGeneratedName string, awsUnifiedOnboardingDataResourceAndType string) string { res := fmt.Sprintf(` - data "%s" "%s" { - external_aws_account_id = "%s" - } +// AwsUnifiedOnbording resource +%s +// AwsCloudFormationStack resource +%s +data "%s" "%s" { + external_aws_account_id = "%s.environment_external_id" +} `, - // Add the HCL configuration for the resource here + awsUnifiedOnboardingHcl, + awsCloudFormationStackHcl, resourcetype.AwpAwsOnboardingData, - resourceName, - variable.AwpAwsAccountID, + awpAwsGetOnboardingDataGeneratedName, + awsUnifiedOnboardingDataResourceAndType, ) log.Printf("[INFO] testAccCheckAwpAwsOnboardingDataBasic:%+v\n", res) return res } + +func getAwsUnifiedOnboardingResourceHCL(awsUnifiedOnboardingResourceName string, awsUnifiedOnboardingResourceTypeAndName string) string { + return fmt.Sprintf(` +resource "%s" "%s" { + cloud_vendor = "aws" + onboard_type = "Simple" + full_protection = true + enable_stack_modify = true + posture_management_configuration = { + rulesets = "[0]" + } + serverless_configuration = { + enabled = false + } + intelligence_configurations = { + rulesets = "[0]" + enabled = false + } +} +data "%s" "%s" { + id = "%s.id" +} + `, resourcetype.AwsUnifiedOnboarding, + awsUnifiedOnboardingResourceName, + resourcetype.AwsUnifiedOnboarding, + awsUnifiedOnboardingResourceName, + awsUnifiedOnboardingResourceTypeAndName) +} + +func getAwsCloudFormationStackResourceHCL(stackGeneratedName string, awsUnifiedOnboardingResourceTypeAndName string) string { + return fmt.Sprintf(` +resource "%s" "%s"{ + name = %s.stack_name + template_url = %s.template_url + parameters = %s.parameters + capabilities = %s.iam_capabilities +} + `, providerconst.AwsCloudFormationStack, + stackGeneratedName, + awsUnifiedOnboardingResourceTypeAndName, + awsUnifiedOnboardingResourceTypeAndName, + awsUnifiedOnboardingResourceTypeAndName, + awsUnifiedOnboardingResourceTypeAndName) +} From 09de9d814ecc226abc30523c24a1c7f7cf231a1b Mon Sep 17 00:00:00 2001 From: Omar Date: Thu, 7 Mar 2024 21:57:17 +0200 Subject: [PATCH 06/47] add new awp resource - draft --- dome9/resource_dome9_awp_aws_onboarding.go | 133 ++++++++++++++++++ .../awp_aws_onboarding/awp_aws_onboarding.go | 112 ++++++++++++++- 2 files changed, 244 insertions(+), 1 deletion(-) create mode 100644 dome9/resource_dome9_awp_aws_onboarding.go diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go new file mode 100644 index 00000000..66ce8fef --- /dev/null +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -0,0 +1,133 @@ +package dome9 + +import ( + "github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "log" + "strings" +) + +func resourceDome9AWPAWSOnboarding() *schema.Resource { + return &schema.Resource{ + Create: resourceAWPAWSOnboardingCreate, + Read: resourceAWPAWSOnboardingRead, + Delete: resourceAWPAWSOnboardingDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Schema: map[string]*schema.Schema{ + "cloudguard_account_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "cross_account_role_name": { + Type: schema.TypeString, + Required: true, + }, + "cross_account_role_external_id": { + Type: schema.TypeString, + Required: true, + }, + "cloud_guard_awp_stack_name": { + Type: schema.TypeString, + Required: true, + }, + "scan_mode": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + "inAccount", + "saas", + "in-account-hub", + "in-account-sub", + }, false), + }, + "is_terraform": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + "agentless_account_settings": { + Type: schema.TypeList, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "disabled_regions": { + Type: schema.TypeList, + Required: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "scan_machine_interval_in_hours": { + Type: schema.TypeInt, + Required: true, + }, + "max_concurrence_scans_per_region": { + Type: schema.TypeInt, + Required: true, + }, + "skip_function_apps_scan": { + Type: schema.TypeBool, + Required: true, + }, + "custom_tags": { + Type: schema.TypeMap, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + }, + }, + }, + } +} + +func resourceAWPAWSOnboardingCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*Client) + cloudguardAccountId := d.Get("cloudguard_account_id").(string) + req := expandAWPOnboardingRequest(d) + log.Printf("[INFO] Creating AWP AWS Onboarding request %+v\n", req) + _, err := client.awpAwsOnboarding.CreateAWPOnboarding(cloudguardAccountId, req) + if err != nil { + return err + } + d.SetId(cloudguardAccountId) + log.Printf("[INFO] Created AWP AWS Onboarding with CloudGuard Account ID: %v\n", cloudguardAccountId) + d.SetId(cloudguardAccountId) // set the resource ID to the CloudGuard Account ID + + return resourceAWPAWSOnboardingRead(d, meta) +} + +func expandAWPOnboardingRequest(d *schema.ResourceData) awp_aws_onboarding.CreateAWPOnboardingRequest { + return awp_aws_onboarding.CreateAWPOnboardingRequest{ + // populate the request fields from the schema + // replace the field names with the ones used in your schema + Field1: d.Get("field1").(string), + Field2: d.Get("field2").(int), + // continue for all fields + } +} + +func resourceAWPAWSOnboardingRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*Client) + resp, _, err := client.GetAWPOnboarding("aws", d.Id()) + if err != nil { + if strings.Contains(err.Error(), "404") { + d.SetId("") + return nil + } + return err + } + // set the schema fields from the response + return nil +} + +func resourceAWPAWSOnboardingDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*Client) + _, err := client.DeleteAWPOnboarding(d.Id(), true) + if err != nil { + return err + } + return nil +} diff --git a/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go b/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go index 2e8718c6..c3399227 100644 --- a/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go +++ b/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go @@ -2,11 +2,13 @@ package awp_aws_onboarding import ( "fmt" + "log" "net/http" ) const ( awpAWSGetOnboardingDataPath = "workload/agentless/aws/terraform/onboarding" + awsOnboardingResourcePath = "workload/agentless/aws/accounts" cloudAccountsPath = "cloudaccounts/" ) @@ -23,7 +25,114 @@ type AgentlessAwsTerraformOnboardingDataResponse struct { } type CloudAccountResponse struct { - ID string `json:"id"` + ID string `json:"id"` + Vendor string `json:"vendor"` + Name string `json:"name"` + ExternalAccountNumber string `json:"externalAccountNumber"` + Error interface{} `json:"error"` + IsFetchingSuspended bool `json:"isFetchingSuspended"` + CreationDate string `json:"creationDate"` + Credentials Credentials `json:"credentials"` + IamSafe interface{} `json:"iamSafe"` + NetSec NetSec `json:"netSec"` + Magellan bool `json:"magellan"` + FullProtection bool `json:"fullProtection"` + AllowReadOnly bool `json:"allowReadOnly"` + OrganizationId string `json:"organizationId"` + OrganizationalUnitId interface{} `json:"organizationalUnitId"` + OrganizationalUnitPath string `json:"organizationalUnitPath"` + OrganizationalUnitName string `json:"organizationalUnitName"` + LambdaScanner bool `json:"lambdaScanner"` + Serverless Serverless `json:"serverless"` + OnboardingMode string `json:"onboardingMode"` +} + +type Credentials struct { + Apikey interface{} `json:"apikey"` + Arn string `json:"arn"` + Secret interface{} `json:"secret"` + IamUser interface{} `json:"iamUser"` + Type string `json:"type"` + IsReadOnly bool `json:"isReadOnly"` +} + +type NetSec struct { + Regions []Region `json:"regions"` +} + +type Region struct { + Region string `json:"region"` + Name string `json:"name"` + Hidden bool `json:"hidden"` + NewGroupBehavior string `json:"newGroupBehavior"` +} + +type Serverless struct { + CodeAnalyzerEnabled bool `json:"codeAnalyzerEnabled"` + CodeDependencyAnalyzerEnabled bool `json:"codeDependencyAnalyzerEnabled"` +} + +type AgentlessAccountSettings struct { + DisabledRegions []string `json:"disabledRegions"` + ScanMachineIntervalInHours int `json:"scanMachineIntervalInHours"` + MaxConcurrenceScansPerRegion int `json:"maxConcurrenceScansPerRegion"` + SkipFunctionAppsScan bool `json:"skipFunctionAppsScan"` + CustomTags map[string]string `json:"customTags"` +} + +type CreateAWPOnboardingRequest struct { + CrossAccountRoleName string `json:"crossAccountRoleName"` + CrossAccountRoleExternalId string `json:"crossAccountRoleExternalId"` + CloudGuardAWPStackName string `json:"cloudGuardAWPStackName"` + ScanMode string `json:"scanMode"` + IsTerraform bool `json:"isTerraform"` + AgentlessAccountSettings AgentlessAccountSettings `json:"agentlessAccountSettings"` +} + +type AccountIssues struct { + Regions map[string]string `json:"regions"` + Account map[string]string `json:"account"` +} + +type GetAWPOnboardingResponse struct { + AgentlessAccountSettings AgentlessAccountSettings `json:"agentlessAccountSettings"` + MissingAwpPrivateNetworkRegions []string `json:"missingAwpPrivateNetworkRegions"` + AccountIssues AccountIssues `json:"accountIssues"` + CloudAccountId string `json:"cloudAccountId"` + AgentlessProtectionEnabled bool `json:"agentlessProtectionEnabled"` + ScanMode string `json:"scanMode"` + Provider string `json:"provider"` + ShouldUpdate bool `json:"shouldUpdate"` + IsOrgOnboarding bool `json:"isOrgOnboarding"` + CentralizedCloudAccountId string `json:"centralizedCloudAccountId"` +} + +func (service *Service) CreateAWPOnboarding(id string, req CreateAWPOnboardingRequest) (*http.Response, error) { + path := fmt.Sprintf("%s/%s/enable", awsOnboardingResourcePath, id) + resp, err := service.Client.NewRequestDo("POST", path, nil, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (service *Service) GetAWPOnboarding(cloudProvider, id string) (*GetAWPOnboardingResponse, *http.Response, error) { + v := new(GetAWPOnboardingResponse) + path := fmt.Sprintf("workload/agentless/%s/accounts/%s", cloudProvider, id) + resp, err := service.Client.NewRequestDo("GET", path, nil, nil, v) + if err != nil { + return nil, nil, err + } + return v, resp, nil +} + +func (service *Service) DeleteAWPOnboarding(id string, forceDelete bool) (*http.Response, error) { + path := fmt.Sprintf("%s/%s?forceDelete=%t", awsOnboardingResourcePath, id, forceDelete) + resp, err := service.Client.NewRequestDo("DELETE", path, nil, nil, nil) + if err != nil { + return nil, err + } + return resp, nil } func (service *Service) Get() (*AgentlessAwsTerraformOnboardingDataResponse, *http.Response, error) { @@ -39,6 +148,7 @@ func (service *Service) Get() (*AgentlessAwsTerraformOnboardingDataResponse, *ht func (service *Service) GetCloudAccountId(externalAccountId string) (string, *http.Response, error) { path := fmt.Sprintf("%s%s", cloudAccountsPath, externalAccountId) respData := new(CloudAccountResponse) + log.Printf("[DEBUG] GetCloudAccountId Path: %s", path) resp, err := service.Client.NewRequestDo("GET", path, nil, nil, respData) if err != nil { return "", nil, err From 1c7247620cd30aa7ee89bf69af73207dcfdb8fca Mon Sep 17 00:00:00 2001 From: Omar Date: Sun, 10 Mar 2024 20:48:36 +0200 Subject: [PATCH 07/47] update on dome9_awp_aws_onboarding resource --- dome9/common/resourcetype/resource_type.go | 3 +- ..._dome9_awp_aws_get_onboarding_data_test.go | 4 +- dome9/provider.go | 3 +- dome9/resource_dome9_awp_aws_onboarding.go | 191 +++++++++++++++--- .../awp_aws_onboarding/awp_aws_onboarding.go | 21 +- 5 files changed, 182 insertions(+), 40 deletions(-) diff --git a/dome9/common/resourcetype/resource_type.go b/dome9/common/resourcetype/resource_type.go index 9beb70bc..c39d38e1 100644 --- a/dome9/common/resourcetype/resource_type.go +++ b/dome9/common/resourcetype/resource_type.go @@ -27,5 +27,6 @@ const ( AdmissionControlPolicy = "dome9_admission_control_policy" Assessment = "dome9_assessment" ImageAssurancePolicy = "dome9_image_assurance_policy" - AwpAwsOnboardingData = "dome9_awp_aws_get_onboarding_data" + AwpAwsGetOnboardingData = "dome9_awp_aws_get_onboarding_data" + AwpAwsOnboarding = "dome9_awp_aws_onboarding" ) diff --git a/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go b/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go index d17eb8a9..b2a0dbe6 100644 --- a/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go +++ b/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go @@ -23,7 +23,7 @@ func TestAccDataSourceAwpAwsOnboardingDataBasic(t *testing.T) { awsCloudFormationStackHcl := getAwsCloudFormationStackResourceHCL(cloudFormationStackGeneratedName, awsUnifiedOnboardingResourceTypeAndName) // Get dome9_awp_aws_get_onboarding_data resource names - _, awpAwsOnboardingDataSourceTypeAndName, awpAwsOnboardingDataGeneratedName := method.GenerateRandomSourcesTypeAndName(resourcetype.AwpAwsOnboardingData) + _, awpAwsOnboardingDataSourceTypeAndName, awpAwsOnboardingDataGeneratedName := method.GenerateRandomSourcesTypeAndName(resourcetype.AwpAwsGetOnboardingData) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) @@ -63,7 +63,7 @@ data "%s" "%s" { `, awsUnifiedOnboardingHcl, awsCloudFormationStackHcl, - resourcetype.AwpAwsOnboardingData, + resourcetype.AwpAwsGetOnboardingData, awpAwsGetOnboardingDataGeneratedName, awsUnifiedOnboardingDataResourceAndType, ) diff --git a/dome9/provider.go b/dome9/provider.go index b5540e0e..01559ce9 100644 --- a/dome9/provider.go +++ b/dome9/provider.go @@ -60,6 +60,7 @@ func Provider() terraform.ResourceProvider { resourcetype.AdmissionControlPolicy: resourceAdmissionPolicy(), resourcetype.Assessment: resourceAssessment(), resourcetype.ImageAssurancePolicy: resourceImageAssurancePolicy(), + resourcetype.AwpAwsOnboarding: resourceAwpAwsOnboarding(), }, DataSourcesMap: map[string]*schema.Resource{ // terraform date source name: data source schema @@ -85,7 +86,7 @@ func Provider() terraform.ResourceProvider { resourcetype.AdmissionControlPolicy: dataSourceAdmissionControlPolicy(), resourcetype.Assessment: dataSourceAssessment(), resourcetype.ImageAssurancePolicy: dataSourceImageAssurancePolicy(), - resourcetype.AwpAwsOnboardingData: dataSourceAwpAwsOnboardingData(), + resourcetype.AwpAwsGetOnboardingData: dataSourceAwpAwsOnboardingData(), }, ConfigureFunc: providerConfigure, } diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index 66ce8fef..8fc58c09 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -1,17 +1,19 @@ package dome9 import ( + "fmt" + "github.com/dome9/dome9-sdk-go/dome9/client" "github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/helper/validation" "log" - "strings" ) -func resourceDome9AWPAWSOnboarding() *schema.Resource { +func resourceAwpAwsOnboarding() *schema.Resource { return &schema.Resource{ Create: resourceAWPAWSOnboardingCreate, Read: resourceAWPAWSOnboardingRead, + Update: resourceAWPAWSOnboardingUpdate, Delete: resourceAWPAWSOnboardingDelete, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, @@ -22,15 +24,15 @@ func resourceDome9AWPAWSOnboarding() *schema.Resource { Required: true, ForceNew: true, }, - "cross_account_role_name": { + "centralized_cloud_account_id": { Type: schema.TypeString, - Required: true, + Optional: true, }, - "cross_account_role_external_id": { + "cross_account_role_name": { Type: schema.TypeString, Required: true, }, - "cloud_guard_awp_stack_name": { + "cross_account_role_external_id": { Type: schema.TypeString, Required: true, }, @@ -44,14 +46,9 @@ func resourceDome9AWPAWSOnboarding() *schema.Resource { "in-account-sub", }, false), }, - "is_terraform": { - Type: schema.TypeBool, - Optional: true, - Default: true, - }, "agentless_account_settings": { - Type: schema.TypeList, - Required: true, + Type: schema.TypeMap, + Optional: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "disabled_regions": { @@ -79,16 +76,79 @@ func resourceDome9AWPAWSOnboarding() *schema.Resource { }, }, }, + "missing_awp_private_network_regions": { + Type: schema.TypeList, + Optional: true, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "account_issues": { + Type: schema.TypeList, + Optional: true, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "regions": { + Type: schema.TypeMap, + Optional: true, + }, + "account": { + Type: schema.TypeMap, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "issue_type": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, + }, + }, + }, + "cloud_account_id": { + Type: schema.TypeString, + Computed: true, + }, + "agentless_protection_enabled": { + Type: schema.TypeBool, + Computed: true, + }, + "provider": { + Type: schema.TypeString, + Computed: true, + }, + "should_update": { + Type: schema.TypeBool, + Computed: true, + }, + "is_org_onboarding": { + Type: schema.TypeBool, + Computed: true, + }, + }, + CustomizeDiff: func(diff *schema.ResourceDiff, v interface{}) error { + scanMode, scanModeOk := diff.GetOk("scan_mode") + centralizedCloudAccountId, centralizedCloudAccountIdOk := diff.GetOk("centralized_cloud_account_id") + + if scanModeOk && scanMode == "in-account-sub" { + if !centralizedCloudAccountIdOk || centralizedCloudAccountId == "" { + return fmt.Errorf("'centralized_cloud_account_id' must be set and not empty when 'scan_mode' is 'in-account-sub'") + } + } + + return nil }, } } func resourceAWPAWSOnboardingCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Client) + d9client := meta.(*Client) cloudguardAccountId := d.Get("cloudguard_account_id").(string) req := expandAWPOnboardingRequest(d) log.Printf("[INFO] Creating AWP AWS Onboarding request %+v\n", req) - _, err := client.awpAwsOnboarding.CreateAWPOnboarding(cloudguardAccountId, req) + _, err := d9client.awpAwsOnboarding.CreateAWPOnboarding(cloudguardAccountId, req) if err != nil { return err } @@ -100,34 +160,115 @@ func resourceAWPAWSOnboardingCreate(d *schema.ResourceData, meta interface{}) er } func expandAWPOnboardingRequest(d *schema.ResourceData) awp_aws_onboarding.CreateAWPOnboardingRequest { + return awp_aws_onboarding.CreateAWPOnboardingRequest{ - // populate the request fields from the schema - // replace the field names with the ones used in your schema - Field1: d.Get("field1").(string), - Field2: d.Get("field2").(int), - // continue for all fields + CrossAccountRoleName: d.Get("cross_account_role_name").(string), + CrossAccountRoleExternalId: d.Get("cross_account_role_external_id").(string), + ScanMode: d.Get("scan_mode").(string), + IsTerraform: true, + AgentlessAccountSettings: expandAgentlessAccountSettings(d), } } func resourceAWPAWSOnboardingRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Client) - resp, _, err := client.GetAWPOnboarding("aws", d.Id()) + d9client := meta.(*Client) + resp, _, err := d9client.awpAwsOnboarding.GetAWPOnboarding("aws", d.Id()) if err != nil { - if strings.Contains(err.Error(), "404") { + if err.(*client.ErrorResponse).IsObjectNotFound() { + log.Printf("[WARN] Removing AWS cloud account %s from state because it no longer exists in Dome9", d.Id()) d.SetId("") return nil } return err } + + log.Printf("[INFO] Reading AWP AWS Onbaording account data: %+v\n", resp) + // set the schema fields from the response + _ = d.Set("missing_awp_private_network_regions", resp.MissingAwpPrivateNetworkRegions) + _ = d.Set("cloud_account_id", resp.CloudAccountId) + _ = d.Set("agentless_protection_enabled", resp.AgentlessProtectionEnabled) + _ = d.Set("scan_mode", resp.ScanMode) + _ = d.Set("provider", resp.Provider) + _ = d.Set("should_update", resp.ShouldUpdate) + _ = d.Set("is_org_onboarding", resp.IsOrgOnboarding) + _ = d.Set("centralized_cloud_account_id", resp.CentralizedCloudAccountId) + + if resp.AgentlessAccountSettings != nil { + if err := d.Set("agentless_account_settings", flattenAgentlessAccountSettings(*resp.AgentlessAccountSettings)); err != nil { + return err + } + } + + if resp.AccountIssues != nil { + if err := d.Set("account_issues", flattenAccountIssues(*resp.AccountIssues)); err != nil { + return err + } + } + return nil } func resourceAWPAWSOnboardingDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*Client) - _, err := client.DeleteAWPOnboarding(d.Id(), true) + d9client := meta.(*Client) + log.Printf("[INFO] Offboarding AWP Account with cloud guard id : %v\n", d.Id()) + _, err := d9client.awpAwsOnboarding.DeleteAWPOnboarding(d.Id(), true) if err != nil { return err } return nil } + +func expandAgentlessAccountSettings(d *schema.ResourceData) awp_aws_onboarding.AgentlessAccountSettings { + agentlessAccountSettingsMap := d.Get("agentless_account_settings").(map[string]interface{}) + + disabledRegionsInterface := agentlessAccountSettingsMap["disabled_regions"].([]interface{}) + disabledRegions := make([]string, len(disabledRegionsInterface)) + for i, v := range disabledRegionsInterface { + disabledRegions[i] = v.(string) + } + + customTagsInterface := agentlessAccountSettingsMap["custom_tags"].(map[string]interface{}) + customTags := make(map[string]string, len(customTagsInterface)) + for k, v := range customTagsInterface { + customTags[k] = v.(string) + } + + return awp_aws_onboarding.AgentlessAccountSettings{ + DisabledRegions: disabledRegions, + ScanMachineIntervalInHours: agentlessAccountSettingsMap["scan_machine_interval_in_hours"].(int), + MaxConcurrenceScansPerRegion: agentlessAccountSettingsMap["max_concurrence_scans_per_region"].(int), + SkipFunctionAppsScan: agentlessAccountSettingsMap["skip_function_apps_scan"].(bool), + CustomTags: customTags, + } +} + +func flattenAgentlessAccountSettings(settings awp_aws_onboarding.AgentlessAccountSettings) map[string]interface{} { + // Initialize the map + settingsMap := make(map[string]interface{}) + // Flatten DisabledRegions + settingsMap["disabled_regions"] = settings.DisabledRegions + // Flatten ScanMachineIntervalInHours + settingsMap["scan_machine_interval_in_hours"] = settings.ScanMachineIntervalInHours + // Flatten MaxConcurrenceScansPerRegion + settingsMap["max_concurrence_scans_per_region"] = settings.MaxConcurrenceScansPerRegion + // Flatten SkipFunctionAppsScan + settingsMap["skip_function_apps_scan"] = settings.SkipFunctionAppsScan + // Flatten CustomTags + settingsMap["custom_tags"] = settings.CustomTags + + return settingsMap +} + +func flattenAccountIssues(accountIssues awp_aws_onboarding.AccountIssues) []interface{} { + m := map[string]interface{}{ + "regions": accountIssues.Regions, + "account": accountIssues.Account, + } + + return []interface{}{m} +} + +func resourceAWPAWSOnboardingUpdate(d *schema.ResourceData, meta interface{}) error { + return nil +} diff --git a/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go b/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go index c3399227..fe4a3b6e 100644 --- a/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go +++ b/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go @@ -83,7 +83,6 @@ type AgentlessAccountSettings struct { type CreateAWPOnboardingRequest struct { CrossAccountRoleName string `json:"crossAccountRoleName"` CrossAccountRoleExternalId string `json:"crossAccountRoleExternalId"` - CloudGuardAWPStackName string `json:"cloudGuardAWPStackName"` ScanMode string `json:"scanMode"` IsTerraform bool `json:"isTerraform"` AgentlessAccountSettings AgentlessAccountSettings `json:"agentlessAccountSettings"` @@ -95,16 +94,16 @@ type AccountIssues struct { } type GetAWPOnboardingResponse struct { - AgentlessAccountSettings AgentlessAccountSettings `json:"agentlessAccountSettings"` - MissingAwpPrivateNetworkRegions []string `json:"missingAwpPrivateNetworkRegions"` - AccountIssues AccountIssues `json:"accountIssues"` - CloudAccountId string `json:"cloudAccountId"` - AgentlessProtectionEnabled bool `json:"agentlessProtectionEnabled"` - ScanMode string `json:"scanMode"` - Provider string `json:"provider"` - ShouldUpdate bool `json:"shouldUpdate"` - IsOrgOnboarding bool `json:"isOrgOnboarding"` - CentralizedCloudAccountId string `json:"centralizedCloudAccountId"` + AgentlessAccountSettings *AgentlessAccountSettings `json:"agentlessAccountSettings"` + MissingAwpPrivateNetworkRegions []string `json:"missingAwpPrivateNetworkRegions"` + AccountIssues *AccountIssues `json:"accountIssues"` + CloudAccountId string `json:"cloudAccountId"` + AgentlessProtectionEnabled bool `json:"agentlessProtectionEnabled"` + ScanMode string `json:"scanMode"` + Provider string `json:"provider"` + ShouldUpdate bool `json:"shouldUpdate"` + IsOrgOnboarding bool `json:"isOrgOnboarding"` + CentralizedCloudAccountId string `json:"centralizedCloudAccountId"` } func (service *Service) CreateAWPOnboarding(id string, req CreateAWPOnboardingRequest) (*http.Response, error) { From 13bf3499f0f37d640575407e3e048c89de200c31 Mon Sep 17 00:00:00 2001 From: Omar Date: Sun, 10 Mar 2024 21:30:53 +0200 Subject: [PATCH 08/47] add shouldCreatePolicy Query Params --- dome9/resource_dome9_awp_aws_onboarding.go | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index 8fc58c09..6b68aafd 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -127,6 +127,11 @@ func resourceAwpAwsOnboarding() *schema.Resource { Type: schema.TypeBool, Computed: true, }, + "should_create_policy": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, }, CustomizeDiff: func(diff *schema.ResourceDiff, v interface{}) error { scanMode, scanModeOk := diff.GetOk("scan_mode") @@ -148,7 +153,10 @@ func resourceAWPAWSOnboardingCreate(d *schema.ResourceData, meta interface{}) er cloudguardAccountId := d.Get("cloudguard_account_id").(string) req := expandAWPOnboardingRequest(d) log.Printf("[INFO] Creating AWP AWS Onboarding request %+v\n", req) - _, err := d9client.awpAwsOnboarding.CreateAWPOnboarding(cloudguardAccountId, req) + queryParams := map[string]string{ + "shouldCreatePolicy": d.Get("should_create_policy").(string), + } + _, err := d9client.awpAwsOnboarding.CreateAWPOnboarding(cloudguardAccountId, req, queryParams) if err != nil { return err } From 639b3c8aab4a13b433447027c3a0409daa76e7f0 Mon Sep 17 00:00:00 2001 From: Omar Date: Sun, 10 Mar 2024 21:32:20 +0200 Subject: [PATCH 09/47] update vendor --- .../awp_aws_onboarding/awp_aws_onboarding.go | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go b/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go index fe4a3b6e..c0af6071 100644 --- a/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go +++ b/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go @@ -4,6 +4,7 @@ import ( "fmt" "log" "net/http" + "strings" ) const ( @@ -106,9 +107,22 @@ type GetAWPOnboardingResponse struct { CentralizedCloudAccountId string `json:"centralizedCloudAccountId"` } -func (service *Service) CreateAWPOnboarding(id string, req CreateAWPOnboardingRequest) (*http.Response, error) { - path := fmt.Sprintf("%s/%s/enable", awsOnboardingResourcePath, id) - resp, err := service.Client.NewRequestDo("POST", path, nil, req, nil) +func (service *Service) CreateAWPOnboarding(id string, req CreateAWPOnboardingRequest, queryParams map[string]string) (*http.Response, error) { + // Create the base path + basePath := fmt.Sprintf("%s/%s/enable", awsOnboardingResourcePath, id) + + // Add the query parameters to the path + pathWithQueryParams := basePath + if len(queryParams) > 0 { + var params []string + for key, value := range queryParams { + params = append(params, fmt.Sprintf("%s=%s", key, value)) + } + pathWithQueryParams = fmt.Sprintf("%s?%s", basePath, strings.Join(params, "&")) + } + + // Make the request + resp, err := service.Client.NewRequestDo("POST", pathWithQueryParams, nil, req, nil) if err != nil { return nil, err } From b891421588a8a7a91b57c1de4051789ce8585e9e Mon Sep 17 00:00:00 2001 From: Omar Date: Wed, 13 Mar 2024 09:56:50 +0200 Subject: [PATCH 10/47] code enhancements after testing the resource + simple automation test --- dome9/resource_dome9_awp_aws_onboarding.go | 120 +++++++++++++----- .../resource_dome9_awp_aws_onboarding_test.go | 85 +++++++++++++ .../awp_aws_onboarding/awp_aws_onboarding.go | 62 ++++++--- 3 files changed, 211 insertions(+), 56 deletions(-) create mode 100644 dome9/resource_dome9_awp_aws_onboarding_test.go diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index 6b68aafd..181c95fe 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -7,6 +7,8 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/helper/validation" "log" + "strconv" + "strings" ) func resourceAwpAwsOnboarding() *schema.Resource { @@ -49,28 +51,37 @@ func resourceAwpAwsOnboarding() *schema.Resource { "agentless_account_settings": { Type: schema.TypeMap, Optional: true, + Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "disabled_regions": { Type: schema.TypeList, - Required: true, + Optional: true, + Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, + Default: []string{}, }, "scan_machine_interval_in_hours": { Type: schema.TypeInt, - Required: true, + Optional: true, + Computed: true, + Default: 4, }, "max_concurrence_scans_per_region": { Type: schema.TypeInt, - Required: true, + Optional: true, + Computed: true, + Default: 1, }, "skip_function_apps_scan": { Type: schema.TypeBool, - Required: true, + Optional: true, + Computed: true, }, "custom_tags": { Type: schema.TypeMap, Optional: true, + Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, }, @@ -115,7 +126,7 @@ func resourceAwpAwsOnboarding() *schema.Resource { Type: schema.TypeBool, Computed: true, }, - "provider": { + "cloud_provider": { Type: schema.TypeString, Computed: true, }, @@ -132,6 +143,11 @@ func resourceAwpAwsOnboarding() *schema.Resource { Optional: true, Default: false, }, + "force_delete": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, }, CustomizeDiff: func(diff *schema.ResourceDiff, v interface{}) error { scanMode, scanModeOk := diff.GetOk("scan_mode") @@ -153,10 +169,10 @@ func resourceAWPAWSOnboardingCreate(d *schema.ResourceData, meta interface{}) er cloudguardAccountId := d.Get("cloudguard_account_id").(string) req := expandAWPOnboardingRequest(d) log.Printf("[INFO] Creating AWP AWS Onboarding request %+v\n", req) - queryParams := map[string]string{ - "shouldCreatePolicy": d.Get("should_create_policy").(string), + options := awp_aws_onboarding.CreateOptions{ + ShouldCreatePolicy: strconv.FormatBool(d.Get("should_create_policy").(bool)), } - _, err := d9client.awpAwsOnboarding.CreateAWPOnboarding(cloudguardAccountId, req, queryParams) + _, err := d9client.awpAwsOnboarding.CreateAWPOnboarding(cloudguardAccountId, req, options) if err != nil { return err } @@ -197,7 +213,7 @@ func resourceAWPAWSOnboardingRead(d *schema.ResourceData, meta interface{}) erro _ = d.Set("cloud_account_id", resp.CloudAccountId) _ = d.Set("agentless_protection_enabled", resp.AgentlessProtectionEnabled) _ = d.Set("scan_mode", resp.ScanMode) - _ = d.Set("provider", resp.Provider) + _ = d.Set("cloud_provider", resp.Provider) _ = d.Set("should_update", resp.ShouldUpdate) _ = d.Set("is_org_onboarding", resp.IsOrgOnboarding) _ = d.Set("centralized_cloud_account_id", resp.CentralizedCloudAccountId) @@ -220,7 +236,10 @@ func resourceAWPAWSOnboardingRead(d *schema.ResourceData, meta interface{}) erro func resourceAWPAWSOnboardingDelete(d *schema.ResourceData, meta interface{}) error { d9client := meta.(*Client) log.Printf("[INFO] Offboarding AWP Account with cloud guard id : %v\n", d.Id()) - _, err := d9client.awpAwsOnboarding.DeleteAWPOnboarding(d.Id(), true) + options := awp_aws_onboarding.DeleteOptions{ + ForceDelete: strconv.FormatBool(d.Get("force_delete").(bool)), + } + _, err := d9client.awpAwsOnboarding.DeleteAWPOnboarding(d.Id(), options) if err != nil { return err } @@ -228,44 +247,75 @@ func resourceAWPAWSOnboardingDelete(d *schema.ResourceData, meta interface{}) er } func expandAgentlessAccountSettings(d *schema.ResourceData) awp_aws_onboarding.AgentlessAccountSettings { + // Initialize default values + agentlessAccountSettings := awp_aws_onboarding.AgentlessAccountSettings{ + DisabledRegions: make([]string, 0), + CustomTags: make(map[string]string), + ScanMachineIntervalInHours: 4, + MaxConcurrenceScansPerRegion: 1, + SkipFunctionAppsScan: true, + } + if _, ok := d.GetOk("agentless_account_settings"); !ok { + // If "agentless_account_settings" key doesn't exist, return empty AgentlessAccountSettings + return agentlessAccountSettings + } + agentlessAccountSettingsMap := d.Get("agentless_account_settings").(map[string]interface{}) - disabledRegionsInterface := agentlessAccountSettingsMap["disabled_regions"].([]interface{}) - disabledRegions := make([]string, len(disabledRegionsInterface)) - for i, v := range disabledRegionsInterface { - disabledRegions[i] = v.(string) + // Check if the key exists and is not nil + if disabledRegionsInterface, ok := agentlessAccountSettingsMap["disabled_regions"].([]interface{}); ok { + disabledRegions := make([]string, len(disabledRegionsInterface)) + for i, v := range disabledRegionsInterface { + disabledRegions[i] = v.(string) + } + agentlessAccountSettings.DisabledRegions = disabledRegions + } + + if scanMachineInterval, ok := agentlessAccountSettingsMap["scan_machine_interval_in_hours"].(int); ok { + agentlessAccountSettings.ScanMachineIntervalInHours = scanMachineInterval } - customTagsInterface := agentlessAccountSettingsMap["custom_tags"].(map[string]interface{}) - customTags := make(map[string]string, len(customTagsInterface)) - for k, v := range customTagsInterface { - customTags[k] = v.(string) + if maxConcurrenceScans, ok := agentlessAccountSettingsMap["max_concurrence_scans_per_region"].(int); ok { + agentlessAccountSettings.MaxConcurrenceScansPerRegion = maxConcurrenceScans } - return awp_aws_onboarding.AgentlessAccountSettings{ - DisabledRegions: disabledRegions, - ScanMachineIntervalInHours: agentlessAccountSettingsMap["scan_machine_interval_in_hours"].(int), - MaxConcurrenceScansPerRegion: agentlessAccountSettingsMap["max_concurrence_scans_per_region"].(int), - SkipFunctionAppsScan: agentlessAccountSettingsMap["skip_function_apps_scan"].(bool), - CustomTags: customTags, + if skipFunctionAppsScan, ok := agentlessAccountSettingsMap["skip_function_apps_scan"].(bool); ok { + agentlessAccountSettings.SkipFunctionAppsScan = skipFunctionAppsScan } + + if customTagsInterface, ok := agentlessAccountSettingsMap["custom_tags"].(map[string]interface{}); ok { + customTags := make(map[string]string) + for k, v := range customTagsInterface { + customTags[k] = v.(string) + } + agentlessAccountSettings.CustomTags = customTags + } + + return agentlessAccountSettings } func flattenAgentlessAccountSettings(settings awp_aws_onboarding.AgentlessAccountSettings) map[string]interface{} { - // Initialize the map - settingsMap := make(map[string]interface{}) + // Flatten DisabledRegions - settingsMap["disabled_regions"] = settings.DisabledRegions - // Flatten ScanMachineIntervalInHours - settingsMap["scan_machine_interval_in_hours"] = settings.ScanMachineIntervalInHours - // Flatten MaxConcurrenceScansPerRegion - settingsMap["max_concurrence_scans_per_region"] = settings.MaxConcurrenceScansPerRegion - // Flatten SkipFunctionAppsScan - settingsMap["skip_function_apps_scan"] = settings.SkipFunctionAppsScan + disabledRegions := make([]string, len(settings.DisabledRegions)) + for i, region := range settings.DisabledRegions { + disabledRegions[i] = region + } + // Flatten CustomTags - settingsMap["custom_tags"] = settings.CustomTags + customTags := make(map[string]interface{}) + for key, value := range settings.CustomTags { + customTags[key] = value + } - return settingsMap + m := map[string]interface{}{ + "disabled_regions": strings.Join(disabledRegions, ","), + "scan_machine_interval_in_hours": strconv.Itoa(settings.ScanMachineIntervalInHours), + "max_concurrence_scans_per_region": strconv.Itoa(settings.MaxConcurrenceScansPerRegion), + "skip_function_apps_scan": strconv.FormatBool(settings.SkipFunctionAppsScan), + "custom_tags": fmt.Sprintf("%v", customTags), + } + return m } func flattenAccountIssues(accountIssues awp_aws_onboarding.AccountIssues) []interface{} { diff --git a/dome9/resource_dome9_awp_aws_onboarding_test.go b/dome9/resource_dome9_awp_aws_onboarding_test.go new file mode 100644 index 00000000..6401d67e --- /dev/null +++ b/dome9/resource_dome9_awp_aws_onboarding_test.go @@ -0,0 +1,85 @@ +package dome9 + +import ( + "fmt" + "github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/terraform-providers/terraform-provider-dome9/dome9/common/resourcetype" + "github.com/terraform-providers/terraform-provider-dome9/dome9/common/testing/method" +) + +func TestAccResourceAWPAWSOnboardingBasic(t *testing.T) { + var awpCloudAccountInfo awp_aws_onboarding.GetAWPOnboardingResponse + // Generate All Required Random Names for Testing + resourceTypeAndName, _, generatedName := method.GenerateRandomSourcesTypeAndName(resourcetype.AwpAwsOnboarding) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckAWPAWSOnboardingBasic(generatedName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwpAccountExists(resourceTypeAndName, &awpCloudAccountInfo), + resource.TestCheckResourceAttr(resourceTypeAndName, "cloudguard_account_id", "2775e042-928c-4deb-9259-13fe0cfb0ea6"), + // Add more TestCheckResourceAttr functions for each attribute to check + ), + }, + }, + }) +} + +func testAccCheckAWPAWSOnboardingBasic(generatedName string) string { + return fmt.Sprintf(` +resource "%s" "%s" { + cloudguard_account_id = "%s" + cross_account_role_name = "%s" + cross_account_role_external_id = "%s" + scan_mode = "%s" + force_delete = true + agentless_account_settings { + disabled_regions = ["us-east-1", "us-west-1"] # Example disabled regions + scan_machine_interval_in_hours = 6 + max_concurrence_scans_per_region = 2 + skip_function_apps_scan = false + custom_tags = { + tag1 = "value1" + tag2 = "value2" + } + } +} +`, + resourcetype.AwpAwsOnboarding, + generatedName, + "2775e042-928c-4deb-9259-13fe0cfb0ea6", + "CloudGuardAWPCrossAccountRole", + "NDYwNjc4MTkzOTI2LTI3NzVlMDQyLTkyOGMtNGRlYi05MjU5LTEzZmUwY2ZiMGVhNg==", + "inAccount", + ) +} + +func testAccCheckAwpAccountExists(resource string, awpAccount *awp_aws_onboarding.GetAWPOnboardingResponse) resource.TestCheckFunc { + return func(state *terraform.State) error { + rs, ok := state.RootModule().Resources[resource] + if !ok { + return fmt.Errorf("didn't find resource: %s", resource) + } + if rs.Primary.ID == "" { + return fmt.Errorf("no record ID is set") + } + + apiClient := testAccProvider.Meta().(*Client) + receivedCloudAccountResponse, _, err := apiClient.awpAwsOnboarding.GetAWPOnboarding("aws", rs.Primary.ID) + + if err != nil { + return fmt.Errorf("failed fetching resource %s. Recevied error: %s", resource, err) + } + *awpAccount = *receivedCloudAccountResponse + return nil + } +} diff --git a/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go b/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go index c0af6071..a3735a41 100644 --- a/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go +++ b/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go @@ -4,7 +4,7 @@ import ( "fmt" "log" "net/http" - "strings" + "time" ) const ( @@ -90,13 +90,13 @@ type CreateAWPOnboardingRequest struct { } type AccountIssues struct { - Regions map[string]string `json:"regions"` - Account map[string]string `json:"account"` + Regions map[string]interface{} `json:"regions"` + Account *map[string]interface{} `json:"account"` } type GetAWPOnboardingResponse struct { AgentlessAccountSettings *AgentlessAccountSettings `json:"agentlessAccountSettings"` - MissingAwpPrivateNetworkRegions []string `json:"missingAwpPrivateNetworkRegions"` + MissingAwpPrivateNetworkRegions *[]string `json:"missingAwpPrivateNetworkRegions"` AccountIssues *AccountIssues `json:"accountIssues"` CloudAccountId string `json:"cloudAccountId"` AgentlessProtectionEnabled bool `json:"agentlessProtectionEnabled"` @@ -107,26 +107,46 @@ type GetAWPOnboardingResponse struct { CentralizedCloudAccountId string `json:"centralizedCloudAccountId"` } -func (service *Service) CreateAWPOnboarding(id string, req CreateAWPOnboardingRequest, queryParams map[string]string) (*http.Response, error) { +type CreateOptions struct { + ShouldCreatePolicy string `url:"shouldCreatePolicy"` +} + +type DeleteOptions struct { + ForceDelete string `url:"forceDelete"` +} + +func (service *Service) CreateAWPOnboarding(id string, req CreateAWPOnboardingRequest, queryParams CreateOptions) (*http.Response, error) { + // Define the maximum number of retries and the interval between retries + maxRetries := 3 + retryInterval := time.Second * 5 + // Create the base path basePath := fmt.Sprintf("%s/%s/enable", awsOnboardingResourcePath, id) - // Add the query parameters to the path - pathWithQueryParams := basePath - if len(queryParams) > 0 { - var params []string - for key, value := range queryParams { - params = append(params, fmt.Sprintf("%s=%s", key, value)) + // Initialize the response and error variables outside the loop + var resp *http.Response + var err error + + // Attempt the request up to maxRetries times + for i := 0; i < maxRetries; i++ { + // Make the request + resp, err = service.Client.NewRequestDo("POST", basePath, queryParams, req, nil) + if err == nil { + // If the request was successful, return the response + return resp, nil } - pathWithQueryParams = fmt.Sprintf("%s?%s", basePath, strings.Join(params, "&")) - } - // Make the request - resp, err := service.Client.NewRequestDo("POST", pathWithQueryParams, nil, req, nil) - if err != nil { - return nil, err + // If the request failed with a 404 status code, wait for the retry interval before trying again + if resp != nil && resp.StatusCode == 404 { + time.Sleep(retryInterval) + } else { + // If the status code is not 404, return the response and error immediately + return resp, err + } } - return resp, nil + + // If the function hasn't returned after maxRetries, return an error + return nil, fmt.Errorf("failed to create AWP Onboarding after %d attempts: %w", maxRetries, err) } func (service *Service) GetAWPOnboarding(cloudProvider, id string) (*GetAWPOnboardingResponse, *http.Response, error) { @@ -139,9 +159,9 @@ func (service *Service) GetAWPOnboarding(cloudProvider, id string) (*GetAWPOnboa return v, resp, nil } -func (service *Service) DeleteAWPOnboarding(id string, forceDelete bool) (*http.Response, error) { - path := fmt.Sprintf("%s/%s?forceDelete=%t", awsOnboardingResourcePath, id, forceDelete) - resp, err := service.Client.NewRequestDo("DELETE", path, nil, nil, nil) +func (service *Service) DeleteAWPOnboarding(id string, queryParams DeleteOptions) (*http.Response, error) { + path := fmt.Sprintf("%s/%s", awsOnboardingResourcePath, id) + resp, err := service.Client.NewRequestDo("DELETE", path, queryParams, nil, nil) if err != nil { return nil, err } From 66b8dd1e27e58b0b5e72637b1dec0c62f0606596 Mon Sep 17 00:00:00 2001 From: Omar Date: Wed, 13 Mar 2024 13:43:18 +0200 Subject: [PATCH 11/47] update the resource provider and check --- dome9/resource_dome9_awp_aws_onboarding.go | 74 ++++++++----------- .../resource_dome9_awp_aws_onboarding_test.go | 2 +- .../awp_aws_onboarding/awp_aws_onboarding.go | 10 +-- 3 files changed, 35 insertions(+), 51 deletions(-) diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index 181c95fe..dccce802 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -8,7 +8,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/helper/validation" "log" "strconv" - "strings" ) func resourceAwpAwsOnboarding() *schema.Resource { @@ -49,40 +48,37 @@ func resourceAwpAwsOnboarding() *schema.Resource { }, false), }, "agentless_account_settings": { - Type: schema.TypeMap, + Type: schema.TypeSet, Optional: true, - Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "disabled_regions": { Type: schema.TypeList, Optional: true, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Default: []string{}, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, }, "scan_machine_interval_in_hours": { Type: schema.TypeInt, Optional: true, - Computed: true, Default: 4, }, "max_concurrence_scans_per_region": { Type: schema.TypeInt, Optional: true, - Computed: true, Default: 1, }, "skip_function_apps_scan": { Type: schema.TypeBool, Optional: true, - Computed: true, }, "custom_tags": { Type: schema.TypeMap, Optional: true, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{}, + }, }, }, }, @@ -95,7 +91,6 @@ func resourceAwpAwsOnboarding() *schema.Resource { }, "account_issues": { Type: schema.TypeList, - Optional: true, Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -219,13 +214,13 @@ func resourceAWPAWSOnboardingRead(d *schema.ResourceData, meta interface{}) erro _ = d.Set("centralized_cloud_account_id", resp.CentralizedCloudAccountId) if resp.AgentlessAccountSettings != nil { - if err := d.Set("agentless_account_settings", flattenAgentlessAccountSettings(*resp.AgentlessAccountSettings)); err != nil { + if err := d.Set("agentless_account_settings", flattenAgentlessAccountSettings(resp.AgentlessAccountSettings)); err != nil { return err } } if resp.AccountIssues != nil { - if err := d.Set("account_issues", flattenAccountIssues(*resp.AccountIssues)); err != nil { + if err := d.Set("account_issues", flattenAccountIssues(resp.AccountIssues)); err != nil { return err } } @@ -246,27 +241,28 @@ func resourceAWPAWSOnboardingDelete(d *schema.ResourceData, meta interface{}) er return nil } -func expandAgentlessAccountSettings(d *schema.ResourceData) awp_aws_onboarding.AgentlessAccountSettings { - // Initialize default values - agentlessAccountSettings := awp_aws_onboarding.AgentlessAccountSettings{ +func expandAgentlessAccountSettings(d *schema.ResourceData) *awp_aws_onboarding.AgentlessAccountSettings { + if _, ok := d.GetOk("agentless_account_settings"); !ok { + // If "agentless_account_settings" key doesn't exist, return nil (since these settings are optional) + return nil + } + agentlessAccountSettingsItem := d.Get("agentless_account_settings").(*schema.Set).List()[0] + agentlessAccountSettingsMap := agentlessAccountSettingsItem.(map[string]interface{}) + + // Initialize the AgentlessAccountSettings struct with default values + agentlessAccountSettings := &awp_aws_onboarding.AgentlessAccountSettings{ DisabledRegions: make([]string, 0), CustomTags: make(map[string]string), ScanMachineIntervalInHours: 4, MaxConcurrenceScansPerRegion: 1, SkipFunctionAppsScan: true, } - if _, ok := d.GetOk("agentless_account_settings"); !ok { - // If "agentless_account_settings" key doesn't exist, return empty AgentlessAccountSettings - return agentlessAccountSettings - } - - agentlessAccountSettingsMap := d.Get("agentless_account_settings").(map[string]interface{}) // Check if the key exists and is not nil if disabledRegionsInterface, ok := agentlessAccountSettingsMap["disabled_regions"].([]interface{}); ok { disabledRegions := make([]string, len(disabledRegionsInterface)) - for i, v := range disabledRegionsInterface { - disabledRegions[i] = v.(string) + for i, disabledRegion := range disabledRegionsInterface { + disabledRegions[i] = disabledRegion.(string) } agentlessAccountSettings.DisabledRegions = disabledRegions } @@ -294,31 +290,19 @@ func expandAgentlessAccountSettings(d *schema.ResourceData) awp_aws_onboarding.A return agentlessAccountSettings } -func flattenAgentlessAccountSettings(settings awp_aws_onboarding.AgentlessAccountSettings) map[string]interface{} { - - // Flatten DisabledRegions - disabledRegions := make([]string, len(settings.DisabledRegions)) - for i, region := range settings.DisabledRegions { - disabledRegions[i] = region - } - - // Flatten CustomTags - customTags := make(map[string]interface{}) - for key, value := range settings.CustomTags { - customTags[key] = value - } +func flattenAgentlessAccountSettings(settings *awp_aws_onboarding.AgentlessAccountSettings) []interface{} { m := map[string]interface{}{ - "disabled_regions": strings.Join(disabledRegions, ","), - "scan_machine_interval_in_hours": strconv.Itoa(settings.ScanMachineIntervalInHours), - "max_concurrence_scans_per_region": strconv.Itoa(settings.MaxConcurrenceScansPerRegion), - "skip_function_apps_scan": strconv.FormatBool(settings.SkipFunctionAppsScan), - "custom_tags": fmt.Sprintf("%v", customTags), + "disabled_regions": settings.DisabledRegions, + "scan_machine_interval_in_hours": settings.ScanMachineIntervalInHours, + "max_concurrence_scans_per_region": settings.MaxConcurrenceScansPerRegion, + "skip_function_apps_scan": settings.SkipFunctionAppsScan, + "custom_tags": settings.CustomTags, } - return m + return []interface{}{m} } -func flattenAccountIssues(accountIssues awp_aws_onboarding.AccountIssues) []interface{} { +func flattenAccountIssues(accountIssues *awp_aws_onboarding.AccountIssues) []interface{} { m := map[string]interface{}{ "regions": accountIssues.Regions, "account": accountIssues.Account, diff --git a/dome9/resource_dome9_awp_aws_onboarding_test.go b/dome9/resource_dome9_awp_aws_onboarding_test.go index 6401d67e..4220e2fb 100644 --- a/dome9/resource_dome9_awp_aws_onboarding_test.go +++ b/dome9/resource_dome9_awp_aws_onboarding_test.go @@ -46,7 +46,7 @@ resource "%s" "%s" { disabled_regions = ["us-east-1", "us-west-1"] # Example disabled regions scan_machine_interval_in_hours = 6 max_concurrence_scans_per_region = 2 - skip_function_apps_scan = false + skip_function_apps_scan = true custom_tags = { tag1 = "value1" tag2 = "value2" diff --git a/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go b/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go index a3735a41..1a5035a7 100644 --- a/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go +++ b/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go @@ -82,11 +82,11 @@ type AgentlessAccountSettings struct { } type CreateAWPOnboardingRequest struct { - CrossAccountRoleName string `json:"crossAccountRoleName"` - CrossAccountRoleExternalId string `json:"crossAccountRoleExternalId"` - ScanMode string `json:"scanMode"` - IsTerraform bool `json:"isTerraform"` - AgentlessAccountSettings AgentlessAccountSettings `json:"agentlessAccountSettings"` + CrossAccountRoleName string `json:"crossAccountRoleName"` + CrossAccountRoleExternalId string `json:"crossAccountRoleExternalId"` + ScanMode string `json:"scanMode"` + IsTerraform bool `json:"isTerraform"` + AgentlessAccountSettings *AgentlessAccountSettings `json:"agentlessAccountSettings"` } type AccountIssues struct { From 2d2c5c7390b104dae2c12706e2bf2e426107e305 Mon Sep 17 00:00:00 2001 From: Omar Date: Thu, 14 Mar 2024 03:50:07 +0200 Subject: [PATCH 12/47] add update test + validate disabled regions --- dome9/resource_dome9_awp_aws_onboarding.go | 85 ++++++++++++++++--- .../resource_dome9_awp_aws_onboarding_test.go | 44 +++++++++- 2 files changed, 115 insertions(+), 14 deletions(-) diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index dccce802..e8f216e4 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -1,13 +1,16 @@ package dome9 import ( + "errors" "fmt" "github.com/dome9/dome9-sdk-go/dome9/client" "github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/terraform-providers/terraform-provider-dome9/dome9/common/providerconst" "log" "strconv" + "strings" ) func resourceAwpAwsOnboarding() *schema.Resource { @@ -162,31 +165,36 @@ func resourceAwpAwsOnboarding() *schema.Resource { func resourceAWPAWSOnboardingCreate(d *schema.ResourceData, meta interface{}) error { d9client := meta.(*Client) cloudguardAccountId := d.Get("cloudguard_account_id").(string) - req := expandAWPOnboardingRequest(d) + req, err := expandAWPOnboardingRequest(d) + if err != nil { + return err + } log.Printf("[INFO] Creating AWP AWS Onboarding request %+v\n", req) options := awp_aws_onboarding.CreateOptions{ ShouldCreatePolicy: strconv.FormatBool(d.Get("should_create_policy").(bool)), } - _, err := d9client.awpAwsOnboarding.CreateAWPOnboarding(cloudguardAccountId, req, options) + _, err = d9client.awpAwsOnboarding.CreateAWPOnboarding(cloudguardAccountId, req, options) if err != nil { return err } - d.SetId(cloudguardAccountId) - log.Printf("[INFO] Created AWP AWS Onboarding with CloudGuard Account ID: %v\n", cloudguardAccountId) d.SetId(cloudguardAccountId) // set the resource ID to the CloudGuard Account ID + log.Printf("[INFO] Created AWP AWS Onboarding with CloudGuard Account ID: %v\n", cloudguardAccountId) return resourceAWPAWSOnboardingRead(d, meta) } -func expandAWPOnboardingRequest(d *schema.ResourceData) awp_aws_onboarding.CreateAWPOnboardingRequest { - +func expandAWPOnboardingRequest(d *schema.ResourceData) (awp_aws_onboarding.CreateAWPOnboardingRequest, error) { + agentlessAccountSettings, err := expandAgentlessAccountSettings(d) + if err != nil { + return awp_aws_onboarding.CreateAWPOnboardingRequest{}, err + } return awp_aws_onboarding.CreateAWPOnboardingRequest{ CrossAccountRoleName: d.Get("cross_account_role_name").(string), CrossAccountRoleExternalId: d.Get("cross_account_role_external_id").(string), ScanMode: d.Get("scan_mode").(string), IsTerraform: true, - AgentlessAccountSettings: expandAgentlessAccountSettings(d), - } + AgentlessAccountSettings: agentlessAccountSettings, + }, nil } func resourceAWPAWSOnboardingRead(d *schema.ResourceData, meta interface{}) error { @@ -241,10 +249,10 @@ func resourceAWPAWSOnboardingDelete(d *schema.ResourceData, meta interface{}) er return nil } -func expandAgentlessAccountSettings(d *schema.ResourceData) *awp_aws_onboarding.AgentlessAccountSettings { +func expandAgentlessAccountSettings(d *schema.ResourceData) (*awp_aws_onboarding.AgentlessAccountSettings, error) { if _, ok := d.GetOk("agentless_account_settings"); !ok { // If "agentless_account_settings" key doesn't exist, return nil (since these settings are optional) - return nil + return nil, nil } agentlessAccountSettingsItem := d.Get("agentless_account_settings").(*schema.Set).List()[0] agentlessAccountSettingsMap := agentlessAccountSettingsItem.(map[string]interface{}) @@ -264,6 +272,10 @@ func expandAgentlessAccountSettings(d *schema.ResourceData) *awp_aws_onboarding. for i, disabledRegion := range disabledRegionsInterface { disabledRegions[i] = disabledRegion.(string) } + _, err := validateDisabledRegions(disabledRegions) + if err != nil { + return agentlessAccountSettings, err + } agentlessAccountSettings.DisabledRegions = disabledRegions } @@ -287,7 +299,7 @@ func expandAgentlessAccountSettings(d *schema.ResourceData) *awp_aws_onboarding. agentlessAccountSettings.CustomTags = customTags } - return agentlessAccountSettings + return agentlessAccountSettings, nil } func flattenAgentlessAccountSettings(settings *awp_aws_onboarding.AgentlessAccountSettings) []interface{} { @@ -312,5 +324,56 @@ func flattenAccountIssues(accountIssues *awp_aws_onboarding.AccountIssues) []int } func resourceAWPAWSOnboardingUpdate(d *schema.ResourceData, meta interface{}) error { + log.Println("An update occurred") + + if d.HasChange("delete_force") { + log.Println("delete_force has been changed") + if err := d.Set("delete_force", d.Get("delete_force").(bool)); err != nil { + return err + } + } + + if d.HasChange("should_create_policy") { + log.Println("should_create_policy has been changed") + if err := d.Set("should_create_policy", d.Get("should_create_policy").(bool)); err != nil { + return err + } + } + return nil } + +func validateDisabledRegions(regions []string) (bool, error) { + hyphenatedAWSRegions := convertRegionsFormat(providerconst.AWSRegions) + validate, invalidRegions := checkDisabledRegions(regions, hyphenatedAWSRegions) + if !validate { + errorMsg := fmt.Sprintf("Expected disabled-regions to be one of %v, got %v", hyphenatedAWSRegions, invalidRegions) + return false, errors.New(errorMsg) + } + return true, nil +} + +func convertRegionsFormat(regions []string) []string { + hyphenatedRegions := make([]string, len(regions)) + for i, region := range regions { + hyphenatedRegions[i] = strings.ReplaceAll(region, "_", "-") + } + return hyphenatedRegions +} + +func checkDisabledRegions(regions []string, regionsToCompare []string) (bool, []string) { + invalidRegions := make([]string, 0) + for _, val := range regions { + flag := false + for _, region := range regionsToCompare { + if val == region { + flag = true + break + } + } + if !flag { + invalidRegions = append(invalidRegions, val) + } + } + return len(invalidRegions) == 0, invalidRegions +} diff --git a/dome9/resource_dome9_awp_aws_onboarding_test.go b/dome9/resource_dome9_awp_aws_onboarding_test.go index 4220e2fb..c816144c 100644 --- a/dome9/resource_dome9_awp_aws_onboarding_test.go +++ b/dome9/resource_dome9_awp_aws_onboarding_test.go @@ -26,10 +26,17 @@ func TestAccResourceAWPAWSOnboardingBasic(t *testing.T) { Config: testAccCheckAWPAWSOnboardingBasic(generatedName), Check: resource.ComposeTestCheckFunc( testAccCheckAwpAccountExists(resourceTypeAndName, &awpCloudAccountInfo), - resource.TestCheckResourceAttr(resourceTypeAndName, "cloudguard_account_id", "2775e042-928c-4deb-9259-13fe0cfb0ea6"), + resource.TestCheckResourceAttr(resourceTypeAndName, "cloudguard_account_id", "8f9cfb94-4365-4a29-a7b9-cabbb7fe9430"), // Add more TestCheckResourceAttr functions for each attribute to check ), }, + { + Config: testAccCheckAWPAWSOnboardingUpdate(generatedName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(resourceTypeAndName, "force_delete", "false"), + resource.TestCheckResourceAttr(resourceTypeAndName, "should_create_policy", "false"), + ), + }, }, }) } @@ -42,6 +49,37 @@ resource "%s" "%s" { cross_account_role_external_id = "%s" scan_mode = "%s" force_delete = true + should_create_policy = true + agentless_account_settings { + disabled_regions = ["us-east-1", "us-west-1"] # Example disabled regions + scan_machine_interval_in_hours = 6 + max_concurrence_scans_per_region = 2 + skip_function_apps_scan = true + custom_tags = { + tag1 = "value1" + tag2 = "value2" + } + } +} +`, + resourcetype.AwpAwsOnboarding, + generatedName, + "8f9cfb94-4365-4a29-a7b9-cabbb7fe9430", + "CloudGuardAWPCrossAccountRole", + "NDYwNjc4MTkzOTI2LThmOWNmYjk0LTQzNjUtNGEyOS1hN2I5LWNhYmJiN2ZlOTQzMA==", + "inAccount", + ) +} + +func testAccCheckAWPAWSOnboardingUpdate(generatedName string) string { + return fmt.Sprintf(` +resource "%s" "%s" { + cloudguard_account_id = "%s" + cross_account_role_name = "%s" + cross_account_role_external_id = "%s" + scan_mode = "%s" + force_delete = false + should_create_policy = false agentless_account_settings { disabled_regions = ["us-east-1", "us-west-1"] # Example disabled regions scan_machine_interval_in_hours = 6 @@ -56,9 +94,9 @@ resource "%s" "%s" { `, resourcetype.AwpAwsOnboarding, generatedName, - "2775e042-928c-4deb-9259-13fe0cfb0ea6", + "8f9cfb94-4365-4a29-a7b9-cabbb7fe9430", "CloudGuardAWPCrossAccountRole", - "NDYwNjc4MTkzOTI2LTI3NzVlMDQyLTkyOGMtNGRlYi05MjU5LTEzZmUwY2ZiMGVhNg==", + "NDYwNjc4MTkzOTI2LThmOWNmYjk0LTQzNjUtNGEyOS1hN2I5LWNhYmJiN2ZlOTQzMA==", "inAccount", ) } From 3a68325c71436ae51312ac8cb843bf9a929dc4af Mon Sep 17 00:00:00 2001 From: Omar Date: Thu, 14 Mar 2024 10:48:10 +0200 Subject: [PATCH 13/47] add update agentless account settings support --- dome9/resource_dome9_awp_aws_onboarding.go | 19 +++++++++++++++++++ .../resource_dome9_awp_aws_onboarding_test.go | 7 +++---- .../awp_aws_onboarding/awp_aws_onboarding.go | 12 ++++++++++++ 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index e8f216e4..cb38c2c3 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -324,6 +324,7 @@ func flattenAccountIssues(accountIssues *awp_aws_onboarding.AccountIssues) []int } func resourceAWPAWSOnboardingUpdate(d *schema.ResourceData, meta interface{}) error { + d9Client := meta.(*Client) log.Println("An update occurred") if d.HasChange("delete_force") { @@ -339,6 +340,24 @@ func resourceAWPAWSOnboardingUpdate(d *schema.ResourceData, meta interface{}) er return err } } + // Check if there are changes in the AgentlessAccountSettings fields + if d.HasChange("agentless_account_settings") { + log.Println("agentless_account_settings has been changed") + // Build the update request + newAgentlessAccountSettings, err := expandAgentlessAccountSettings(d) + if err != nil { + return err + } + // Send the update request + _, err = d9Client.awpAwsOnboarding.UpdateAWPSettings(d.Get("cloud_provider").(string), d.Id(), *newAgentlessAccountSettings) + if err != nil { + return err + } + log.Printf("[INFO] Updated agentless account settings for cloud account %s\n", d.Id()) + if err != nil { + return err + } + } return nil } diff --git a/dome9/resource_dome9_awp_aws_onboarding_test.go b/dome9/resource_dome9_awp_aws_onboarding_test.go index c816144c..654470d1 100644 --- a/dome9/resource_dome9_awp_aws_onboarding_test.go +++ b/dome9/resource_dome9_awp_aws_onboarding_test.go @@ -81,13 +81,12 @@ resource "%s" "%s" { force_delete = false should_create_policy = false agentless_account_settings { - disabled_regions = ["us-east-1", "us-west-1"] # Example disabled regions - scan_machine_interval_in_hours = 6 - max_concurrence_scans_per_region = 2 + disabled_regions = ["us-east-1"] + scan_machine_interval_in_hours = 8 + max_concurrence_scans_per_region = 4 skip_function_apps_scan = true custom_tags = { tag1 = "value1" - tag2 = "value2" } } } diff --git a/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go b/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go index 1a5035a7..3cc32ac6 100644 --- a/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go +++ b/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go @@ -188,3 +188,15 @@ func (service *Service) GetCloudAccountId(externalAccountId string) (string, *ht } return respData.ID, resp, nil } + +func (service *Service) UpdateAWPSettings(cloudProvider, id string, req AgentlessAccountSettings) (*http.Response, error) { + // Construct the URL path + path := fmt.Sprintf("workload/agentless/%s/accounts/%s/settings", cloudProvider, id) + // Make a PATCH request with the JSON body + resp, err := service.Client.NewRequestDo("PATCH", path, nil, req, nil) + if err != nil { + return nil, err + } + + return resp, nil +} From 6843fdd661863a8698b76d73f2d2b3fe27bf8d57 Mon Sep 17 00:00:00 2001 From: Omar Date: Thu, 14 Mar 2024 15:12:30 +0200 Subject: [PATCH 14/47] fix update issue --- dome9/resource_dome9_awp_aws_onboarding.go | 5 +++-- .../resource_dome9_awp_aws_onboarding_test.go | 22 ++++++++++--------- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index cb38c2c3..86fbaf59 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -144,7 +144,7 @@ func resourceAwpAwsOnboarding() *schema.Resource { "force_delete": { Type: schema.TypeBool, Optional: true, - Default: false, + Default: true, }, }, CustomizeDiff: func(diff *schema.ResourceDiff, v interface{}) error { @@ -254,7 +254,8 @@ func expandAgentlessAccountSettings(d *schema.ResourceData) (*awp_aws_onboarding // If "agentless_account_settings" key doesn't exist, return nil (since these settings are optional) return nil, nil } - agentlessAccountSettingsItem := d.Get("agentless_account_settings").(*schema.Set).List()[0] + agentlessAccountSettingsList := d.Get("agentless_account_settings").(*schema.Set).List() + agentlessAccountSettingsItem := agentlessAccountSettingsList[len(agentlessAccountSettingsList)-1] agentlessAccountSettingsMap := agentlessAccountSettingsItem.(map[string]interface{}) // Initialize the AgentlessAccountSettings struct with default values diff --git a/dome9/resource_dome9_awp_aws_onboarding_test.go b/dome9/resource_dome9_awp_aws_onboarding_test.go index 654470d1..86267b06 100644 --- a/dome9/resource_dome9_awp_aws_onboarding_test.go +++ b/dome9/resource_dome9_awp_aws_onboarding_test.go @@ -26,7 +26,7 @@ func TestAccResourceAWPAWSOnboardingBasic(t *testing.T) { Config: testAccCheckAWPAWSOnboardingBasic(generatedName), Check: resource.ComposeTestCheckFunc( testAccCheckAwpAccountExists(resourceTypeAndName, &awpCloudAccountInfo), - resource.TestCheckResourceAttr(resourceTypeAndName, "cloudguard_account_id", "8f9cfb94-4365-4a29-a7b9-cabbb7fe9430"), + resource.TestCheckResourceAttr(resourceTypeAndName, "cloudguard_account_id", "7a64e5fb-1e22-47ed-a8b0-0f5a4786bb28"), // Add more TestCheckResourceAttr functions for each attribute to check ), }, @@ -54,7 +54,7 @@ resource "%s" "%s" { disabled_regions = ["us-east-1", "us-west-1"] # Example disabled regions scan_machine_interval_in_hours = 6 max_concurrence_scans_per_region = 2 - skip_function_apps_scan = true + skip_function_apps_scan = false custom_tags = { tag1 = "value1" tag2 = "value2" @@ -64,9 +64,9 @@ resource "%s" "%s" { `, resourcetype.AwpAwsOnboarding, generatedName, - "8f9cfb94-4365-4a29-a7b9-cabbb7fe9430", + "7a64e5fb-1e22-47ed-a8b0-0f5a4786bb28", "CloudGuardAWPCrossAccountRole", - "NDYwNjc4MTkzOTI2LThmOWNmYjk0LTQzNjUtNGEyOS1hN2I5LWNhYmJiN2ZlOTQzMA==", + "NDYwNjc4MTkzOTI2LTdhNjRlNWZiLTFlMjItNDdlZC1hOGIwLTBmNWE0Nzg2YmIyOA==", "inAccount", ) } @@ -78,24 +78,26 @@ resource "%s" "%s" { cross_account_role_name = "%s" cross_account_role_external_id = "%s" scan_mode = "%s" - force_delete = false + force_delete = true should_create_policy = false agentless_account_settings { - disabled_regions = ["us-east-1"] - scan_machine_interval_in_hours = 8 - max_concurrence_scans_per_region = 4 + disabled_regions = ["us-east-1", "us-west-1", "ap-northeast-1", "ap-southeast-2"] + scan_machine_interval_in_hours = 10 + max_concurrence_scans_per_region = 6 skip_function_apps_scan = true custom_tags = { tag1 = "value1" + tag2 = "value2" + tag3 = "value3" } } } `, resourcetype.AwpAwsOnboarding, generatedName, - "8f9cfb94-4365-4a29-a7b9-cabbb7fe9430", + "7a64e5fb-1e22-47ed-a8b0-0f5a4786bb28", "CloudGuardAWPCrossAccountRole", - "NDYwNjc4MTkzOTI2LThmOWNmYjk0LTQzNjUtNGEyOS1hN2I5LWNhYmJiN2ZlOTQzMA==", + "NDYwNjc4MTkzOTI2LTdhNjRlNWZiLTFlMjItNDdlZC1hOGIwLTBmNWE0Nzg2YmIyOA==", "inAccount", ) } From 7e01f0f15b268cb90a69227fb0698c2bb2b5d4a4 Mon Sep 17 00:00:00 2001 From: Omar Date: Fri, 15 Mar 2024 02:04:36 +0200 Subject: [PATCH 15/47] update awp aws onboarding test --- .../environment_variable.go | 7 +- dome9/common/testing/variable/variable.go | 13 +- .../resource_dome9_awp_aws_onboarding_test.go | 153 +++++++++++------- 3 files changed, 110 insertions(+), 63 deletions(-) diff --git a/dome9/common/testing/environmentvariable/environment_variable.go b/dome9/common/testing/environmentvariable/environment_variable.go index e1f02f87..ac519f2d 100644 --- a/dome9/common/testing/environmentvariable/environment_variable.go +++ b/dome9/common/testing/environmentvariable/environment_variable.go @@ -20,9 +20,10 @@ const ( // AWS environment variable const ( - CloudAccountAWSEnvVarArn = "ARN" - CloudAccountUpdatedAWSEnvVarArn = "ARN_UPDATE" - CloudAccountAWSEnvVarSecret = "SECRET" + CloudAccountAWSEnvVarArn = "ARN" + CloudAccountUpdatedAWSEnvVarArn = "ARN_UPDATE" + CloudAccountAWSEnvVarSecret = "SECRET" + AwpAwsCrossAccountRoleExternalIdEnvVar = "EXTERNAL_ID" ) // Azure environment variable diff --git a/dome9/common/testing/variable/variable.go b/dome9/common/testing/variable/variable.go index 1b15c187..12f03370 100644 --- a/dome9/common/testing/variable/variable.go +++ b/dome9/common/testing/variable/variable.go @@ -214,5 +214,16 @@ const ( // awp aws onboarding data resource/data source const ( - AwpAwsAccountID = "478980137264" + AwpAwsAccountID = "478980137264" + OnboardedAwsCloudGuardAccountID = "7a64e5fb-1e22-47ed-a8b0-0f5a4786bb28" + AwpAwsCrossAccountRoleName = "CloudGuardAWPCrossAccountRole" + ScanMode = "inAccount" + DisabledRegions = "[\"us-east-1\", \"us-west-1\"]" + DisabledRegionsUpdate = "[\"us-east-1\", \"us-west-1\", \"ap-northeast-1\", \"ap-southeast-2\"]" + ScanMachineIntervalInHours = "6" + ScanMachineIntervalInHoursUpdate = "10" + MaxConcurrenceScansPerRegion = "4" + MaxConcurrenceScansPerRegionUpdate = "8" + CustomTags = "{\"tag1\": \"value1\", \"tag2\": \"value2\"}" + CustomTagsUpdate = "{\"tag1\": \"value1\", \"tag2\": \"value2\", \"tag3\": \"value3\"" ) diff --git a/dome9/resource_dome9_awp_aws_onboarding_test.go b/dome9/resource_dome9_awp_aws_onboarding_test.go index 86267b06..cedfacab 100644 --- a/dome9/resource_dome9_awp_aws_onboarding_test.go +++ b/dome9/resource_dome9_awp_aws_onboarding_test.go @@ -4,6 +4,9 @@ import ( "fmt" "github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding" "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/terraform-providers/terraform-provider-dome9/dome9/common/testing/environmentvariable" + "github.com/terraform-providers/terraform-provider-dome9/dome9/common/testing/variable" + "os" "testing" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" @@ -15,90 +18,86 @@ func TestAccResourceAWPAWSOnboardingBasic(t *testing.T) { var awpCloudAccountInfo awp_aws_onboarding.GetAWPOnboardingResponse // Generate All Required Random Names for Testing resourceTypeAndName, _, generatedName := method.GenerateRandomSourcesTypeAndName(resourcetype.AwpAwsOnboarding) + CrossAccountRoleExternalId := os.Getenv(environmentvariable.AwpAwsCrossAccountRoleExternalIdEnvVar) + // Generate the Awp AWS onboarding HCL Resources + awpAwsOnboardingHcl := getAwpAwsOnboardingResourceHCL(generatedName, CrossAccountRoleExternalId, false) + awpAwsOnboardingUpdateHcl := getAwpAwsOnboardingResourceHCL(generatedName, CrossAccountRoleExternalId, true) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) + testAwpAwsEnvVarsPreCheck(t) }, - Providers: testAccProviders, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWPAWSOnboardingDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckAWPAWSOnboardingBasic(generatedName), + Config: testAccCheckAWPAWSOnboardingBasic(awpAwsOnboardingHcl), Check: resource.ComposeTestCheckFunc( testAccCheckAwpAccountExists(resourceTypeAndName, &awpCloudAccountInfo), - resource.TestCheckResourceAttr(resourceTypeAndName, "cloudguard_account_id", "7a64e5fb-1e22-47ed-a8b0-0f5a4786bb28"), - // Add more TestCheckResourceAttr functions for each attribute to check + resource.TestCheckResourceAttr(resourceTypeAndName, "cloudguard_account_id", variable.OnboardedAwsCloudGuardAccountID), + resource.TestCheckResourceAttr(resourceTypeAndName, "cross_account_role_name", variable.AwpAwsCrossAccountRoleName), + resource.TestCheckResourceAttr(resourceTypeAndName, "cross_account_role_external_id", CrossAccountRoleExternalId), + resource.TestCheckResourceAttr(resourceTypeAndName, "scan_mode", variable.ScanMode), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions", variable.DisabledRegions), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.scan_machine_interval_in_hours", variable.ScanMachineIntervalInHours), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.max_concurrence_scans_per_region", variable.MaxConcurrenceScansPerRegion), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.skip_function_apps_scan", "true"), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.custom_tags", variable.CustomTags), + resource.TestCheckResourceAttrSet(resourceTypeAndName, "id"), + resource.TestCheckResourceAttr(resourceTypeAndName, "cloud_provider", "aws"), + resource.TestCheckResourceAttr(resourceTypeAndName, "force_delete", "true"), + resource.TestCheckResourceAttr(resourceTypeAndName, "should_create_policy", "true"), ), }, { - Config: testAccCheckAWPAWSOnboardingUpdate(generatedName), + Config: testAccCheckAWPAWSOnboardingBasic(awpAwsOnboardingUpdateHcl), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceTypeAndName, "force_delete", "false"), - resource.TestCheckResourceAttr(resourceTypeAndName, "should_create_policy", "false"), + testAccCheckAwpAccountExists(resourceTypeAndName, &awpCloudAccountInfo), + resource.TestCheckResourceAttr(resourceTypeAndName, "cloudguard_account_id", variable.OnboardedAwsCloudGuardAccountID), + resource.TestCheckResourceAttr(resourceTypeAndName, "cross_account_role_name", variable.AwpAwsCrossAccountRoleName), + resource.TestCheckResourceAttr(resourceTypeAndName, "cross_account_role_external_id", CrossAccountRoleExternalId), + resource.TestCheckResourceAttr(resourceTypeAndName, "scan_mode", variable.ScanMode), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions", variable.DisabledRegionsUpdate), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.scan_machine_interval_in_hours", variable.ScanMachineIntervalInHoursUpdate), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.max_concurrence_scans_per_region", variable.MaxConcurrenceScansPerRegionUpdate), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.skip_function_apps_scan", "true"), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.custom_tags", variable.CustomTagsUpdate), + resource.TestCheckResourceAttrSet(resourceTypeAndName, "id"), + resource.TestCheckResourceAttr(resourceTypeAndName, "cloud_provider", "aws"), + resource.TestCheckResourceAttr(resourceTypeAndName, "force_delete", "true"), + resource.TestCheckResourceAttr(resourceTypeAndName, "should_create_policy", "true"), ), }, }, }) } -func testAccCheckAWPAWSOnboardingBasic(generatedName string) string { - return fmt.Sprintf(` -resource "%s" "%s" { - cloudguard_account_id = "%s" - cross_account_role_name = "%s" - cross_account_role_external_id = "%s" - scan_mode = "%s" - force_delete = true - should_create_policy = true - agentless_account_settings { - disabled_regions = ["us-east-1", "us-west-1"] # Example disabled regions - scan_machine_interval_in_hours = 6 - max_concurrence_scans_per_region = 2 - skip_function_apps_scan = false - custom_tags = { - tag1 = "value1" - tag2 = "value2" +func testAccCheckAWPAWSOnboardingDestroy(state *terraform.State) error { + apiClient := testAccProvider.Meta().(*Client) + for _, rs := range state.RootModule().Resources { + if rs.Type != resourcetype.AwpAwsOnboarding { + continue + } + getOnboardingResponse, _, err := apiClient.awpAwsOnboarding.GetAWPOnboarding("aws", rs.Primary.ID) + if err == nil { + return fmt.Errorf("error Awp Aws Onboarding still exists, ID: %s", rs.Primary.ID) } + // verify the getOnboardingResponse also is not exists + if getOnboardingResponse != nil { + return fmt.Errorf("error Awp Aws Onboarding still exists and wasn't destroyed, ID: %s", rs.Primary.ID) + } + } -} -`, - resourcetype.AwpAwsOnboarding, - generatedName, - "7a64e5fb-1e22-47ed-a8b0-0f5a4786bb28", - "CloudGuardAWPCrossAccountRole", - "NDYwNjc4MTkzOTI2LTdhNjRlNWZiLTFlMjItNDdlZC1hOGIwLTBmNWE0Nzg2YmIyOA==", - "inAccount", - ) + return nil } -func testAccCheckAWPAWSOnboardingUpdate(generatedName string) string { +func testAccCheckAWPAWSOnboardingBasic(awpAwsOnboardingHcl string) string { return fmt.Sprintf(` -resource "%s" "%s" { - cloudguard_account_id = "%s" - cross_account_role_name = "%s" - cross_account_role_external_id = "%s" - scan_mode = "%s" - force_delete = true - should_create_policy = false - agentless_account_settings { - disabled_regions = ["us-east-1", "us-west-1", "ap-northeast-1", "ap-southeast-2"] - scan_machine_interval_in_hours = 10 - max_concurrence_scans_per_region = 6 - skip_function_apps_scan = true - custom_tags = { - tag1 = "value1" - tag2 = "value2" - tag3 = "value3" - } - } -} +// awp aws onboarding resource +%s `, - resourcetype.AwpAwsOnboarding, - generatedName, - "7a64e5fb-1e22-47ed-a8b0-0f5a4786bb28", - "CloudGuardAWPCrossAccountRole", - "NDYwNjc4MTkzOTI2LTdhNjRlNWZiLTFlMjItNDdlZC1hOGIwLTBmNWE0Nzg2YmIyOA==", - "inAccount", + awpAwsOnboardingHcl, ) } @@ -122,3 +121,39 @@ func testAccCheckAwpAccountExists(resource string, awpAccount *awp_aws_onboardin return nil } } + +func getAwpAwsOnboardingResourceHCL(generatedResourceName string, externalId string, updateAction bool) string { + return fmt.Sprintf(` +// awp aws onboarding resource +resource "%s" "%s" { + cloudguard_account_id = "%s" + cross_account_role_name = "%s" + cross_account_role_external_id = "%s" + scan_mode = "%s" + agentless_account_settings { + disabled_regions = "%s" + scan_machine_interval_in_hours = "%s" + max_concurrence_scans_per_region = "%s" + skip_function_apps_scan = "true" + custom_tags = "%s" + } +} +`, + resourcetype.AwpAwsOnboarding, + generatedResourceName, + variable.OnboardedAwsCloudGuardAccountID, + variable.AwpAwsCrossAccountRoleName, + externalId, + variable.ScanMode, + IfThenElse(updateAction, variable.DisabledRegionsUpdate, variable.DisabledRegions), + IfThenElse(updateAction, variable.ScanMachineIntervalInHoursUpdate, variable.ScanMachineIntervalInHours), + IfThenElse(updateAction, variable.MaxConcurrenceScansPerRegionUpdate, variable.MaxConcurrenceScansPerRegion), + IfThenElse(updateAction, variable.CustomTagsUpdate, variable.CustomTags), + ) +} + +func testAwpAwsEnvVarsPreCheck(t *testing.T) { + if v := os.Getenv(environmentvariable.AwpAwsCrossAccountRoleExternalIdEnvVar); v == "" { + t.Fatalf("%s must be set for acceptance tests", environmentvariable.AwpAwsCrossAccountRoleExternalIdEnvVar) + } +} From ae795d0f0670b17059218c8a6992d755eaabec1c Mon Sep 17 00:00:00 2001 From: Omar Date: Fri, 15 Mar 2024 02:46:24 +0200 Subject: [PATCH 16/47] adding data source for awp aws onboarding --- dome9/common/resourcetype/resource_type.go | 1 + ...ource_dome9_awp_aws_get_onboarding_data.go | 4 +- dome9/data_source_dome9_awp_aws_onboarding.go | 152 ++++++++++++++++++ dome9/provider.go | 1 + dome9/resource_dome9_awp_aws_onboarding.go | 4 +- 5 files changed, 158 insertions(+), 4 deletions(-) create mode 100644 dome9/data_source_dome9_awp_aws_onboarding.go diff --git a/dome9/common/resourcetype/resource_type.go b/dome9/common/resourcetype/resource_type.go index c39d38e1..a10fe447 100644 --- a/dome9/common/resourcetype/resource_type.go +++ b/dome9/common/resourcetype/resource_type.go @@ -29,4 +29,5 @@ const ( ImageAssurancePolicy = "dome9_image_assurance_policy" AwpAwsGetOnboardingData = "dome9_awp_aws_get_onboarding_data" AwpAwsOnboarding = "dome9_awp_aws_onboarding" + AwpAwsOnboardingData = "dome9_awp_aws_onboarding_data" ) diff --git a/dome9/data_source_dome9_awp_aws_get_onboarding_data.go b/dome9/data_source_dome9_awp_aws_get_onboarding_data.go index ba71233a..eb245a37 100644 --- a/dome9/data_source_dome9_awp_aws_get_onboarding_data.go +++ b/dome9/data_source_dome9_awp_aws_get_onboarding_data.go @@ -10,7 +10,7 @@ func dataSourceAwpAwsOnboardingData() *schema.Resource { Read: dataSourceAwpAwsOnboardingDataRead, Schema: map[string]*schema.Schema{ - "external_aws_account_id": { + "cloudguard_account_id": { Type: schema.TypeString, Required: true, }, @@ -76,7 +76,7 @@ func dataSourceAwpAwsOnboardingDataRead(d *schema.ResourceData, meta interface{} _ = d.Set("remote_snapshots_utils_function_run_time", resp.RemoteSnapshotsUtilsFunctionRunTime) _ = d.Set("remote_snapshots_utils_function_time_out", resp.RemoteSnapshotsUtilsFunctionTimeOut) _ = d.Set("awp_client_side_security_group_name", resp.AwpClientSideSecurityGroupName) - cloudAccountID, _, err := d9Client.awpAwsOnboarding.GetCloudAccountId(d.Get("external_aws_account_id").(string)) + cloudAccountID, _, err := d9Client.awpAwsOnboarding.GetCloudAccountId(d.Get("cloudguard_account_id").(string)) if err != nil { return err } diff --git a/dome9/data_source_dome9_awp_aws_onboarding.go b/dome9/data_source_dome9_awp_aws_onboarding.go new file mode 100644 index 00000000..9f545a9e --- /dev/null +++ b/dome9/data_source_dome9_awp_aws_onboarding.go @@ -0,0 +1,152 @@ +package dome9 + +import ( + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "log" +) + +func dataSourceAwpAwsOnboarding() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAwpAwsOnboardingRead, + + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Required: true, + }, + "centralized_cloud_account_id": { + Type: schema.TypeString, + Computed: true, + }, + "scan_mode": { + Type: schema.TypeString, + Computed: true, + ValidateFunc: validation.StringInSlice([]string{ + "inAccount", + "saas", + "inAccountHub", + "inAccountSub", + }, false), + }, + "agentless_account_settings": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "disabled_regions": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "scan_machine_interval_in_hours": { + Type: schema.TypeInt, + Computed: true, + }, + "max_concurrence_scans_per_region": { + Type: schema.TypeInt, + Computed: true, + }, + "skip_function_apps_scan": { + Type: schema.TypeBool, + Computed: true, + }, + "custom_tags": { + Type: schema.TypeMap, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{}, + }, + }, + }, + }, + }, + "missing_awp_private_network_regions": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "account_issues": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "regions": { + Type: schema.TypeMap, + Optional: true, + }, + "account": { + Type: schema.TypeMap, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "issue_type": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, + }, + }, + }, + "cloud_account_id": { + Type: schema.TypeString, + Computed: true, + }, + "agentless_protection_enabled": { + Type: schema.TypeBool, + Computed: true, + }, + "cloud_provider": { + Type: schema.TypeString, + Computed: true, + }, + "should_update": { + Type: schema.TypeBool, + Computed: true, + }, + "is_org_onboarding": { + Type: schema.TypeBool, + Computed: true, + }, + }, + } +} + +func dataSourceAwpAwsOnboardingRead(d *schema.ResourceData, meta interface{}) error { + d9Client := meta.(*Client) + + cloudguardAccountId := d.Get("id").(string) + log.Printf("Getting data for AWP AWS Onboarding id: %s\n", cloudguardAccountId) + + resp, _, err := d9Client.awpAwsOnboarding.GetAWPOnboarding("aws", cloudguardAccountId) + if err != nil { + return err + } + + d.SetId(resp.CloudAccountId) + // Set other schema fields here + _ = d.Set("centralized_cloud_account_id", resp.CentralizedCloudAccountId) + _ = d.Set("scan_mode", resp.ScanMode) + _ = d.Set("missing_awp_private_network_regions", resp.MissingAwpPrivateNetworkRegions) + _ = d.Set("cloud_account_id", resp.CloudAccountId) + _ = d.Set("agentless_protection_enabled", resp.AgentlessProtectionEnabled) + _ = d.Set("cloud_provider", resp.Provider) + _ = d.Set("should_update", resp.ShouldUpdate) + _ = d.Set("is_org_onboarding", resp.IsOrgOnboarding) + + if resp.AgentlessAccountSettings != nil { + if err := d.Set("agentless_account_settings", flattenAgentlessAccountSettings(resp.AgentlessAccountSettings)); err != nil { + return err + } + } + if resp.AccountIssues != nil { + if err := d.Set("account_issues", flattenAccountIssues(resp.AccountIssues)); err != nil { + return err + } + } + return nil +} diff --git a/dome9/provider.go b/dome9/provider.go index 01559ce9..60d4a2b0 100644 --- a/dome9/provider.go +++ b/dome9/provider.go @@ -87,6 +87,7 @@ func Provider() terraform.ResourceProvider { resourcetype.Assessment: dataSourceAssessment(), resourcetype.ImageAssurancePolicy: dataSourceImageAssurancePolicy(), resourcetype.AwpAwsGetOnboardingData: dataSourceAwpAwsOnboardingData(), + resourcetype.AwpAwsOnboardingData: dataSourceAwpAwsOnboarding(), }, ConfigureFunc: providerConfigure, } diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index 86fbaf59..43404f7f 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -46,8 +46,8 @@ func resourceAwpAwsOnboarding() *schema.Resource { ValidateFunc: validation.StringInSlice([]string{ "inAccount", "saas", - "in-account-hub", - "in-account-sub", + "inAccountHub", + "inAccountSub", }, false), }, "agentless_account_settings": { From 2bcb0ba31f55fa33797e3952312f5e049e6a9b9d Mon Sep 17 00:00:00 2001 From: Omar Date: Sun, 17 Mar 2024 10:57:30 +0200 Subject: [PATCH 17/47] more updates on tests and resources and example --- dome9/common/providerconst/const.go | 5 - dome9/common/testing/variable/variable.go | 16 +- ...ource_dome9_awp_aws_get_onboarding_data.go | 4 +- ..._dome9_awp_aws_get_onboarding_data_test.go | 71 +----- dome9/data_source_dome9_awp_aws_onboarding.go | 7 - dome9/resource_dome9_awp_aws_onboarding.go | 10 +- .../resource_dome9_awp_aws_onboarding_test.go | 50 +++- examples/awp_aws_onboarding/main.tf | 236 +++++++++++------- 8 files changed, 213 insertions(+), 186 deletions(-) diff --git a/dome9/common/providerconst/const.go b/dome9/common/providerconst/const.go index 7c2a56dd..3afe403c 100644 --- a/dome9/common/providerconst/const.go +++ b/dome9/common/providerconst/const.go @@ -201,8 +201,3 @@ var PermissionTrafficType = map[string]string{ // All Assessments Cloud Accounts Types var AssessmentCloudAccountType = []string{"Aws", "Azure", "GCP", "Kubernetes", "Terraform", "Generic", "KubernetesRuntimeAssurance", "ShiftLeft", "SourceCodeAssurance", "ImageAssurance", "Alibaba", "Cft", "ContainerRegistry", "Ers"} - -// AWP onboarding -const ( - AwsCloudFormationStack = "aws_cloudformation_stack" -) diff --git a/dome9/common/testing/variable/variable.go b/dome9/common/testing/variable/variable.go index 12f03370..94ae6e17 100644 --- a/dome9/common/testing/variable/variable.go +++ b/dome9/common/testing/variable/variable.go @@ -214,16 +214,22 @@ const ( // awp aws onboarding data resource/data source const ( - AwpAwsAccountID = "478980137264" OnboardedAwsCloudGuardAccountID = "7a64e5fb-1e22-47ed-a8b0-0f5a4786bb28" AwpAwsCrossAccountRoleName = "CloudGuardAWPCrossAccountRole" ScanMode = "inAccount" - DisabledRegions = "[\"us-east-1\", \"us-west-1\"]" - DisabledRegionsUpdate = "[\"us-east-1\", \"us-west-1\", \"ap-northeast-1\", \"ap-southeast-2\"]" + DisabledRegions = `["us-east-1", "us-west-1"]` + DisabledRegionsUpdate = `["us-east-1", "us-west-1", "ap-northeast-1", "ap-southeast-2"]` ScanMachineIntervalInHours = "6" ScanMachineIntervalInHoursUpdate = "10" MaxConcurrenceScansPerRegion = "4" MaxConcurrenceScansPerRegionUpdate = "8" - CustomTags = "{\"tag1\": \"value1\", \"tag2\": \"value2\"}" - CustomTagsUpdate = "{\"tag1\": \"value1\", \"tag2\": \"value2\", \"tag3\": \"value3\"" + CustomTags = `{ + tag1 = "value1" + tag2 = "value2" + }` + CustomTagsUpdate = `{ + tag1 = "value1" + tag2 = "value2" + tag3 = "value3" + }` ) diff --git a/dome9/data_source_dome9_awp_aws_get_onboarding_data.go b/dome9/data_source_dome9_awp_aws_get_onboarding_data.go index eb245a37..ab3f097d 100644 --- a/dome9/data_source_dome9_awp_aws_get_onboarding_data.go +++ b/dome9/data_source_dome9_awp_aws_get_onboarding_data.go @@ -10,7 +10,7 @@ func dataSourceAwpAwsOnboardingData() *schema.Resource { Read: dataSourceAwpAwsOnboardingDataRead, Schema: map[string]*schema.Schema{ - "cloudguard_account_id": { + "cloud_account_id": { Type: schema.TypeString, Required: true, }, @@ -76,7 +76,7 @@ func dataSourceAwpAwsOnboardingDataRead(d *schema.ResourceData, meta interface{} _ = d.Set("remote_snapshots_utils_function_run_time", resp.RemoteSnapshotsUtilsFunctionRunTime) _ = d.Set("remote_snapshots_utils_function_time_out", resp.RemoteSnapshotsUtilsFunctionTimeOut) _ = d.Set("awp_client_side_security_group_name", resp.AwpClientSideSecurityGroupName) - cloudAccountID, _, err := d9Client.awpAwsOnboarding.GetCloudAccountId(d.Get("cloudguard_account_id").(string)) + cloudAccountID, _, err := d9Client.awpAwsOnboarding.GetCloudAccountId(d.Get("cloud_account_id").(string)) if err != nil { return err } diff --git a/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go b/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go index b2a0dbe6..7d425c2d 100644 --- a/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go +++ b/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go @@ -2,7 +2,6 @@ package dome9 import ( "fmt" - "github.com/terraform-providers/terraform-provider-dome9/dome9/common/providerconst" "github.com/terraform-providers/terraform-provider-dome9/dome9/common/resourcetype" "github.com/terraform-providers/terraform-provider-dome9/dome9/common/testing/method" "github.com/terraform-providers/terraform-provider-dome9/dome9/common/testing/variable" @@ -13,15 +12,6 @@ import ( ) func TestAccDataSourceAwpAwsOnboardingDataBasic(t *testing.T) { - - // Get dome9_aws_unified_onboarding resource to do aws onboarding - awsUnifiedOnboardingResourceTypeAndName, awsUnifiedOnboardingDataResourceName, awsUnifiedOnboardingResourceName := method.GenerateRandomSourcesTypeAndName(resourcetype.AwsUnifiedOnboarding) - awsUnifiedOnboardingResourceHCL := getAwsUnifiedOnboardingResourceHCL(awsUnifiedOnboardingResourceName, awsUnifiedOnboardingResourceTypeAndName) - - // Get aws_cloudformation_stack resource - _, _, cloudFormationStackGeneratedName := method.GenerateRandomSourcesTypeAndName(providerconst.AwsCloudFormationStack) - awsCloudFormationStackHcl := getAwsCloudFormationStackResourceHCL(cloudFormationStackGeneratedName, awsUnifiedOnboardingResourceTypeAndName) - // Get dome9_awp_aws_get_onboarding_data resource names _, awpAwsOnboardingDataSourceTypeAndName, awpAwsOnboardingDataGeneratedName := method.GenerateRandomSourcesTypeAndName(resourcetype.AwpAwsGetOnboardingData) resource.Test(t, resource.TestCase{ @@ -31,9 +21,9 @@ func TestAccDataSourceAwpAwsOnboardingDataBasic(t *testing.T) { Providers: testAccProviders, Steps: []resource.TestStep{ { - Config: testAccCheckAwpAwsOnboardingDataBasic(awsUnifiedOnboardingResourceHCL, awsCloudFormationStackHcl, awpAwsOnboardingDataGeneratedName, awsUnifiedOnboardingDataResourceName), + Config: testAccCheckAwpAwsOnboardingDataBasic(awpAwsOnboardingDataGeneratedName), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(awpAwsOnboardingDataSourceTypeAndName, "external_aws_account_id", variable.AwpAwsAccountID), + resource.TestCheckResourceAttr(awpAwsOnboardingDataSourceTypeAndName, "cloud_account_id", variable.OnboardedAwsCloudGuardAccountID), resource.TestCheckResourceAttrSet(awpAwsOnboardingDataSourceTypeAndName, "stage"), resource.TestCheckResourceAttrSet(awpAwsOnboardingDataSourceTypeAndName, "region"), resource.TestCheckResourceAttrSet(awpAwsOnboardingDataSourceTypeAndName, "cloud_guard_backend_account_id"), @@ -50,67 +40,16 @@ func TestAccDataSourceAwpAwsOnboardingDataBasic(t *testing.T) { }) } -func testAccCheckAwpAwsOnboardingDataBasic(awsUnifiedOnboardingHcl string, awsCloudFormationStackHcl string, - awpAwsGetOnboardingDataGeneratedName string, awsUnifiedOnboardingDataResourceAndType string) string { +func testAccCheckAwpAwsOnboardingDataBasic(awpAwsGetOnboardingDataGeneratedName string) string { res := fmt.Sprintf(` -// AwsUnifiedOnbording resource -%s -// AwsCloudFormationStack resource -%s data "%s" "%s" { - external_aws_account_id = "%s.environment_external_id" + cloud_account_id = "%s" } `, - awsUnifiedOnboardingHcl, - awsCloudFormationStackHcl, resourcetype.AwpAwsGetOnboardingData, awpAwsGetOnboardingDataGeneratedName, - awsUnifiedOnboardingDataResourceAndType, + variable.OnboardedAwsCloudGuardAccountID, ) log.Printf("[INFO] testAccCheckAwpAwsOnboardingDataBasic:%+v\n", res) return res } - -func getAwsUnifiedOnboardingResourceHCL(awsUnifiedOnboardingResourceName string, awsUnifiedOnboardingResourceTypeAndName string) string { - return fmt.Sprintf(` -resource "%s" "%s" { - cloud_vendor = "aws" - onboard_type = "Simple" - full_protection = true - enable_stack_modify = true - posture_management_configuration = { - rulesets = "[0]" - } - serverless_configuration = { - enabled = false - } - intelligence_configurations = { - rulesets = "[0]" - enabled = false - } -} -data "%s" "%s" { - id = "%s.id" -} - `, resourcetype.AwsUnifiedOnboarding, - awsUnifiedOnboardingResourceName, - resourcetype.AwsUnifiedOnboarding, - awsUnifiedOnboardingResourceName, - awsUnifiedOnboardingResourceTypeAndName) -} - -func getAwsCloudFormationStackResourceHCL(stackGeneratedName string, awsUnifiedOnboardingResourceTypeAndName string) string { - return fmt.Sprintf(` -resource "%s" "%s"{ - name = %s.stack_name - template_url = %s.template_url - parameters = %s.parameters - capabilities = %s.iam_capabilities -} - `, providerconst.AwsCloudFormationStack, - stackGeneratedName, - awsUnifiedOnboardingResourceTypeAndName, - awsUnifiedOnboardingResourceTypeAndName, - awsUnifiedOnboardingResourceTypeAndName, - awsUnifiedOnboardingResourceTypeAndName) -} diff --git a/dome9/data_source_dome9_awp_aws_onboarding.go b/dome9/data_source_dome9_awp_aws_onboarding.go index 9f545a9e..246a90a5 100644 --- a/dome9/data_source_dome9_awp_aws_onboarding.go +++ b/dome9/data_source_dome9_awp_aws_onboarding.go @@ -2,7 +2,6 @@ package dome9 import ( "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" "log" ) @@ -22,12 +21,6 @@ func dataSourceAwpAwsOnboarding() *schema.Resource { "scan_mode": { Type: schema.TypeString, Computed: true, - ValidateFunc: validation.StringInSlice([]string{ - "inAccount", - "saas", - "inAccountHub", - "inAccountSub", - }, false), }, "agentless_account_settings": { Type: schema.TypeSet, diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index 43404f7f..3a98c5ce 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -51,7 +51,8 @@ func resourceAwpAwsOnboarding() *schema.Resource { }, false), }, "agentless_account_settings": { - Type: schema.TypeSet, + Type: schema.TypeList, + MaxItems: 1, Optional: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -139,7 +140,7 @@ func resourceAwpAwsOnboarding() *schema.Resource { "should_create_policy": { Type: schema.TypeBool, Optional: true, - Default: false, + Default: true, }, "force_delete": { Type: schema.TypeBool, @@ -254,9 +255,8 @@ func expandAgentlessAccountSettings(d *schema.ResourceData) (*awp_aws_onboarding // If "agentless_account_settings" key doesn't exist, return nil (since these settings are optional) return nil, nil } - agentlessAccountSettingsList := d.Get("agentless_account_settings").(*schema.Set).List() - agentlessAccountSettingsItem := agentlessAccountSettingsList[len(agentlessAccountSettingsList)-1] - agentlessAccountSettingsMap := agentlessAccountSettingsItem.(map[string]interface{}) + agentlessAccountSettingsList := d.Get("agentless_account_settings").([]interface{}) + agentlessAccountSettingsMap := agentlessAccountSettingsList[0].(map[string]interface{}) // Initialize the AgentlessAccountSettings struct with default values agentlessAccountSettings := &awp_aws_onboarding.AgentlessAccountSettings{ diff --git a/dome9/resource_dome9_awp_aws_onboarding_test.go b/dome9/resource_dome9_awp_aws_onboarding_test.go index cedfacab..64d402e4 100644 --- a/dome9/resource_dome9_awp_aws_onboarding_test.go +++ b/dome9/resource_dome9_awp_aws_onboarding_test.go @@ -1,6 +1,7 @@ package dome9 import ( + "encoding/json" "fmt" "github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding" "github.com/hashicorp/terraform-plugin-sdk/terraform" @@ -8,6 +9,7 @@ import ( "github.com/terraform-providers/terraform-provider-dome9/dome9/common/testing/variable" "os" "testing" + "time" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" "github.com/terraform-providers/terraform-provider-dome9/dome9/common/resourcetype" @@ -19,6 +21,10 @@ func TestAccResourceAWPAWSOnboardingBasic(t *testing.T) { // Generate All Required Random Names for Testing resourceTypeAndName, _, generatedName := method.GenerateRandomSourcesTypeAndName(resourcetype.AwpAwsOnboarding) CrossAccountRoleExternalId := os.Getenv(environmentvariable.AwpAwsCrossAccountRoleExternalIdEnvVar) + disabledRegion1, _ := getRegionByIndex(variable.DisabledRegions, 0) + disabledRegion2, _ := getRegionByIndex(variable.DisabledRegions, 1) + disabledRegionUpdate3, _ := getRegionByIndex(variable.DisabledRegionsUpdate, 2) + disabledRegionUpdate4, _ := getRegionByIndex(variable.DisabledRegionsUpdate, 3) // Generate the Awp AWS onboarding HCL Resources awpAwsOnboardingHcl := getAwpAwsOnboardingResourceHCL(generatedName, CrossAccountRoleExternalId, false) @@ -39,11 +45,12 @@ func TestAccResourceAWPAWSOnboardingBasic(t *testing.T) { resource.TestCheckResourceAttr(resourceTypeAndName, "cross_account_role_name", variable.AwpAwsCrossAccountRoleName), resource.TestCheckResourceAttr(resourceTypeAndName, "cross_account_role_external_id", CrossAccountRoleExternalId), resource.TestCheckResourceAttr(resourceTypeAndName, "scan_mode", variable.ScanMode), - resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions", variable.DisabledRegions), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions.0", disabledRegion1), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions.1", disabledRegion2), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.scan_machine_interval_in_hours", variable.ScanMachineIntervalInHours), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.max_concurrence_scans_per_region", variable.MaxConcurrenceScansPerRegion), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.skip_function_apps_scan", "true"), - resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.custom_tags", variable.CustomTags), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.custom_tags.%", "2"), resource.TestCheckResourceAttrSet(resourceTypeAndName, "id"), resource.TestCheckResourceAttr(resourceTypeAndName, "cloud_provider", "aws"), resource.TestCheckResourceAttr(resourceTypeAndName, "force_delete", "true"), @@ -58,11 +65,14 @@ func TestAccResourceAWPAWSOnboardingBasic(t *testing.T) { resource.TestCheckResourceAttr(resourceTypeAndName, "cross_account_role_name", variable.AwpAwsCrossAccountRoleName), resource.TestCheckResourceAttr(resourceTypeAndName, "cross_account_role_external_id", CrossAccountRoleExternalId), resource.TestCheckResourceAttr(resourceTypeAndName, "scan_mode", variable.ScanMode), - resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions", variable.DisabledRegionsUpdate), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions.0", disabledRegion1), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions.1", disabledRegion2), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions.2", disabledRegionUpdate3), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions.3", disabledRegionUpdate4), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.scan_machine_interval_in_hours", variable.ScanMachineIntervalInHoursUpdate), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.max_concurrence_scans_per_region", variable.MaxConcurrenceScansPerRegionUpdate), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.skip_function_apps_scan", "true"), - resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.custom_tags", variable.CustomTagsUpdate), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.custom_tags.%", "3"), resource.TestCheckResourceAttrSet(resourceTypeAndName, "id"), resource.TestCheckResourceAttr(resourceTypeAndName, "cloud_provider", "aws"), resource.TestCheckResourceAttr(resourceTypeAndName, "force_delete", "true"), @@ -79,7 +89,20 @@ func testAccCheckAWPAWSOnboardingDestroy(state *terraform.State) error { if rs.Type != resourcetype.AwpAwsOnboarding { continue } - getOnboardingResponse, _, err := apiClient.awpAwsOnboarding.GetAWPOnboarding("aws", rs.Primary.ID) + maxRetries := 3 + retryInterval := time.Second * 5 + var getOnboardingResponse *awp_aws_onboarding.GetAWPOnboardingResponse + var err error + for i := 0; i < maxRetries; i++ { + getOnboardingResponse, _, err = apiClient.awpAwsOnboarding.GetAWPOnboarding("aws", rs.Primary.ID) + if err == nil || getOnboardingResponse != nil { + // If the request was successful or the resource still exists, wait for the retry interval before trying again + time.Sleep(retryInterval) + } else { + // If the request failed with a 404 status code, break the loop + break + } + } if err == nil { return fmt.Errorf("error Awp Aws Onboarding still exists, ID: %s", rs.Primary.ID) } @@ -87,7 +110,6 @@ func testAccCheckAWPAWSOnboardingDestroy(state *terraform.State) error { if getOnboardingResponse != nil { return fmt.Errorf("error Awp Aws Onboarding still exists and wasn't destroyed, ID: %s", rs.Primary.ID) } - } return nil } @@ -131,11 +153,11 @@ resource "%s" "%s" { cross_account_role_external_id = "%s" scan_mode = "%s" agentless_account_settings { - disabled_regions = "%s" + disabled_regions = %s scan_machine_interval_in_hours = "%s" max_concurrence_scans_per_region = "%s" skip_function_apps_scan = "true" - custom_tags = "%s" + custom_tags = %s } } `, @@ -157,3 +179,15 @@ func testAwpAwsEnvVarsPreCheck(t *testing.T) { t.Fatalf("%s must be set for acceptance tests", environmentvariable.AwpAwsCrossAccountRoleExternalIdEnvVar) } } + +func getRegionByIndex(regionsRaw string, index int) (string, error) { + var regions []string + err := json.Unmarshal([]byte(regionsRaw), ®ions) + if err != nil { + return "", err + } + if index < 0 || index >= len(regions) { + return "", fmt.Errorf("index out of range") + } + return regions[index], nil +} diff --git a/examples/awp_aws_onboarding/main.tf b/examples/awp_aws_onboarding/main.tf index 1f1cc682..d29d16d8 100644 --- a/examples/awp_aws_onboarding/main.tf +++ b/examples/awp_aws_onboarding/main.tf @@ -1,4 +1,3 @@ - # Dome9 Provider Configurations terraform { required_providers { @@ -6,54 +5,100 @@ terraform { source = "dome9/dome9" version = "1.29.6" } - } -} - -provider "dome9" { - dome9_access_id = "DOME9_CLOUDGUARD_API_ACCESS_ID" - dome9_secret_key = "DOME9_CLOUDGUARD_API_SECRET_KEY" - base_url = "DOME9_API_BASE_URL" -} - -terraform { - required_providers { aws = { source = "hashicorp/aws" - version = "5.37.0" + version = "5.39.1" } } } +provider "dome9" { + dome9_access_id = "DOME9_ACCESS_ID" + dome9_secret_key = "DOME9_SECRET_KEY" + base_url = "DOME9_BASE_URL" +} + provider "aws" { - region = "us-east-1" - profile = "custom" + region = "AWS_REGION" + access_key = "AWS_ACCESS_KEY" + secret_key = "AWS_SECRET_KEY" + token = "AWS_SESSION_TOKEN" } -data "dome9_awp_aws_get_onboarding_data" "dome9_awp_aws_onboarding_data_source" { - cloudguard_account_id = "ae481d4a-603b-4fa6-8f31-6c6d57920e96" - scan_mode = "inAccount" +/* +resource "dome9_aws_unified_onboarding" "omark_aws_account_onboarding" { + cloud_vendor = "aws" + onboard_type = "Simple" + full_protection = true + enable_stack_modify = true + posture_management_configuration = { + rulesets = "[0]" + } + serverless_configuration = { + enabled = false + } + intelligence_configurations = { + rulesets = "[0]" + enabled = false + } } -#onboarding Enable/Disable AWP on AWS Account +resource "aws_cloudformation_stack" "stack"{ + name = dome9_aws_unified_onboarding.omark_aws_account_onboarding.stack_name + template_url = dome9_aws_unified_onboarding.omark_aws_account_onboarding.template_url + parameters = dome9_aws_unified_onboarding.omark_aws_account_onboarding.parameters + capabilities = dome9_aws_unified_onboarding.omark_aws_account_onboarding.iam_capabilities +} -resource "dome9_awp_aws_onboarding" "awp_onboarding_on_aws" { - cloudguard_account_id = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.scan_mode - cross_account_role_name = "CloudGuardAWPCrossAccountRole" # default value can be applicable - # should be similar to "NjM0NzI5NTk3NjIzLWFlNDgxZDRhLTYwM2ItNGZhNi04ZjMxLTZjNmQ1NzkyMGU5Ng==" - cross_account_external_id = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cross_account_external_id - scan_mode = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.scan_mode - should_create_policy = false - force_delete = false - account_settings = { +data "dome9_aws_unified_onboarding" "omark_aws_account_onboarding_data" { + id = dome9_aws_unified_onboarding.omark_aws_account_onboarding.id + depends_on = [ + aws_cloudformation_stack.stack + ] +} +output "environment_external_id" { + value = data.dome9_aws_unified_onboarding.omark_aws_account_onboarding_data.environment_external_id + description = "The external ID of the environment" +} +*/ + +resource "dome9_cloudaccount_aws" "omark_aws_account" { + name = "omark_aws_account" + credentials { + arn = "arn:aws:iam::478980137264:role/CloudGuard-Connect" + secret = "IAM_ROLE_SECRET" + type = "RoleBased" } - version = "" - # Add depends_on to ensure this resource is created last + net_sec { + regions { + new_group_behavior = "ReadOnly" + region = "us_west_2" + } + } +} + +data "dome9_awp_aws_get_onboarding_data" "dome9_awp_aws_onboarding_data_source" { + cloud_account_id = dome9_cloudaccount_aws.omark_aws_account.external_account_number depends_on = [ - aws_iam_role_policy_attachment.CloudGuardAWPCrossAccountRoleAttachment + dome9_cloudaccount_aws.omark_aws_account ] } +locals { + scan_mode = "inAccount" + stage = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.stage + region = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.region + cloud_guard_backend_account_id = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cloud_guard_backend_account_id + agentless_bucket_name = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.agentless_bucket_name + remote_functions_prefix_key = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_functions_prefix_key + remote_snapshots_utils_function_name = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_snapshots_utils_function_name + remote_snapshots_utils_function_run_time = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_snapshots_utils_function_run_time + remote_snapshots_utils_function_time_out = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_snapshots_utils_function_time_out + awp_client_side_security_group_name = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.awp_client_side_security_group_name + cross_account_role_external_id = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cross_account_role_external_id +} + data "aws_partition" "current" {} data "aws_region" "current" {} @@ -69,12 +114,12 @@ resource "aws_iam_role" "CloudGuardAWPCrossAccountRole" { Statement = [{ Effect = "Allow" Principal = { - AWS = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.d9_aws_account_id + AWS = local.cloud_guard_backend_account_id } Action = "sts:AssumeRole" Condition = { StringEquals = { - "sts:ExternalId" = "${data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cross_account_external_id}" + "sts:ExternalId" = local.cross_account_role_external_id } } }] @@ -118,12 +163,12 @@ resource "aws_iam_policy" "CloudGuardAWP" { { Effect = "Allow" Action = "cloudformation:DescribeStacks" - Resource = "arn:${data.aws_partition.current.partition}:cloudformation:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:stack/stackName/*" + Resource = "arn:${data.aws_partition.current.partition}:cloudformation:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:stack/*" }, { Effect = "Allow" Action = "s3:GetObject" - Resource = "arn:${data.aws_partition.current.partition}:s3:::agentless-prod-us/remote_functions*" + Resource = "arn:${data.aws_partition.current.partition}:s3:::${local.agentless_bucket_name}/${local.remote_functions_prefix_key}*" } ] }) @@ -137,7 +182,7 @@ resource "aws_iam_role_policy_attachment" "CloudGuardAWPCrossAccountRoleAttachme # Cross account role policy resource "aws_iam_policy" "CloudGuardAWPCrossAccountRolePolicy" { - count = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.scan_mode == "inAccount" ? 1 : 0 + count = local.scan_mode == "inAccount" ? 1 : 0 name = "CloudGuardAWPCrossAccountRolePolicy" description = "Policy for CloudGuard AWP Cross Account Role" @@ -174,7 +219,7 @@ resource "aws_iam_policy" "CloudGuardAWPCrossAccountRolePolicy" { } resource "aws_iam_policy" "CloudGuardAWPCrossAccountRolePolicy_SaaS" { - count = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.scan_mode == "saas" ? 1 : 0 + count = local.scan_mode == "saas" ? 1 : 0 name = "CloudGuardAWPCrossAccountRolePolicy_SaaS" description = "Policy for CloudGuard AWP Cross Account Role - SaaS Mode" @@ -187,7 +232,7 @@ resource "aws_iam_policy" "CloudGuardAWPCrossAccountRolePolicy_SaaS" { "kms:DescribeKey", "kms:ReplicateKey", ] - Resource = [aws_kms_key.CloudGuardAWPKey.arn] + Resource = [aws_kms_key.CloudGuardAWPKey[count.index].arn] }, { Effect = "Allow" @@ -197,7 +242,7 @@ resource "aws_iam_policy" "CloudGuardAWPCrossAccountRolePolicy_SaaS" { "kms:CancelKeyDeletion", "kms:TagResource", ] - Resource = aws_kms_key.CloudGuardAWPKey.arn + Resource = aws_kms_key.CloudGuardAWPKey[count.index].arn }, { Effect = "Allow" @@ -211,14 +256,14 @@ resource "aws_iam_policy" "CloudGuardAWPCrossAccountRolePolicy_SaaS" { } resource "aws_iam_policy_attachment" "CloudGuardAWPCrossAccountRolePolicyAttachment" { - count = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.scan_mode == "inAccount" ? 1 : 0 + count = local.scan_mode == "inAccount" ? 1 : 0 name = "CloudGuardAWPCrossAccountRolePolicyAttachment" policy_arn = aws_iam_policy.CloudGuardAWPCrossAccountRolePolicy[count.index].arn roles = [aws_iam_role.CloudGuardAWPCrossAccountRole.name] } resource "aws_iam_policy_attachment" "CloudGuardAWPCrossAccountRolePolicyAttachment_SaaS" { - count = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.scan_mode == "saas" ? 1 : 0 + count = local.scan_mode == "saas" ? 1 : 0 name = "CloudGuardAWPCrossAccountRolePolicyAttachment_SaaS" policy_arn = aws_iam_policy.CloudGuardAWPCrossAccountRolePolicy_SaaS[count.index].arn roles = [aws_iam_role.CloudGuardAWPCrossAccountRole.name] @@ -227,54 +272,30 @@ resource "aws_iam_policy_attachment" "CloudGuardAWPCrossAccountRolePolicyAttachm # AWP proxy lambda function resource "aws_lambda_function" "CloudGuardAWPSnapshotsUtilsFunction" { - function_name = "CloudGuardAWPSnapshotsUtils" + function_name = local.remote_snapshots_utils_function_name handler = "snapshots_utils.lambda_handler" description = "CloudGuard AWP Proxy for managing remote actions and resources" role = aws_iam_role.CloudGuardAWPSnapshotsUtilsLambdaExecutionRole.arn runtime = "python3.9" memory_size = 256 - timeout = 900 - s3_bucket = "agentless-prod-us" - s3_key = "remote_functions/CloudGuardAWPSnapshotsUtils7.zip" + timeout = local.remote_snapshots_utils_function_time_out + s3_bucket = local.agentless_bucket_name + s3_key = "${local.remote_functions_prefix_key}/${local.remote_snapshots_utils_function_name}7.zip" environment { variables = { - CP_AWP_AWS_ACCOUNT = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.d9_aws_account_id - CP_AWP_MR_KMS_KEY_ID = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.scan_mode == "saas" ? aws_kms_key.CloudGuardAWPKey.arn : "" - CP_AWP_SCAN_MODE = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.scan_mode - CP_AWP_SECURITY_GROUP_NAME = "CloudGuardAWPSecurityGroup" + CP_AWP_AWS_ACCOUNT = local.cloud_guard_backend_account_id + CP_AWP_MR_KMS_KEY_ID = local.scan_mode == "saas" ? aws_kms_key.CloudGuardAWPKey[0].arn : "" + CP_AWP_SCAN_MODE = local.scan_mode + CP_AWP_SECURITY_GROUP_NAME = local.awp_client_side_security_group_name AWS_PARTITION = data.aws_partition.current.partition + CP_AWP_LOG_LEVEL = "DEBUG" } } tags = { Owner = "CG.AWP" } - - # Use provisioners to invoke the Lambda function after creation and destruction - # Define Provisioners to do some equivalent to AWS Custom Resource - # Create Provisioner is not relevant - provisioner "local-exec" { - when = "create" - command = < Date: Sun, 17 Mar 2024 12:48:03 +0200 Subject: [PATCH 18/47] add data_source_dome9_aws_aws_onboarding_test.go --- dome9/common/resourcetype/resource_type.go | 1 - dome9/common/testing/variable/variable.go | 2 +- ...ta_source_dome9_awp_aws_onboarding_test.go | 64 +++++++++++++++++++ dome9/provider.go | 2 +- 4 files changed, 66 insertions(+), 3 deletions(-) create mode 100644 dome9/data_source_dome9_awp_aws_onboarding_test.go diff --git a/dome9/common/resourcetype/resource_type.go b/dome9/common/resourcetype/resource_type.go index a10fe447..c39d38e1 100644 --- a/dome9/common/resourcetype/resource_type.go +++ b/dome9/common/resourcetype/resource_type.go @@ -29,5 +29,4 @@ const ( ImageAssurancePolicy = "dome9_image_assurance_policy" AwpAwsGetOnboardingData = "dome9_awp_aws_get_onboarding_data" AwpAwsOnboarding = "dome9_awp_aws_onboarding" - AwpAwsOnboardingData = "dome9_awp_aws_onboarding_data" ) diff --git a/dome9/common/testing/variable/variable.go b/dome9/common/testing/variable/variable.go index 94ae6e17..a3b35329 100644 --- a/dome9/common/testing/variable/variable.go +++ b/dome9/common/testing/variable/variable.go @@ -214,7 +214,7 @@ const ( // awp aws onboarding data resource/data source const ( - OnboardedAwsCloudGuardAccountID = "7a64e5fb-1e22-47ed-a8b0-0f5a4786bb28" + OnboardedAwsCloudGuardAccountID = "bac8978a-5b86-4d9e-a732-00cbc430b2a6" AwpAwsCrossAccountRoleName = "CloudGuardAWPCrossAccountRole" ScanMode = "inAccount" DisabledRegions = `["us-east-1", "us-west-1"]` diff --git a/dome9/data_source_dome9_awp_aws_onboarding_test.go b/dome9/data_source_dome9_awp_aws_onboarding_test.go new file mode 100644 index 00000000..1aa54d17 --- /dev/null +++ b/dome9/data_source_dome9_awp_aws_onboarding_test.go @@ -0,0 +1,64 @@ +package dome9 + +import ( + "fmt" + "github.com/terraform-providers/terraform-provider-dome9/dome9/common/resourcetype" + "github.com/terraform-providers/terraform-provider-dome9/dome9/common/testing/environmentvariable" + "github.com/terraform-providers/terraform-provider-dome9/dome9/common/testing/method" + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" +) + +func TestAccDataSourceAwpAwsOnboardingBasic(t *testing.T) { + // Get dome9_awp_aws_onboarding resource names and values + awpAwsOnboardingResourceTypeAndName, awpAwsOnboardingDataSourceTypeAndName, resourceGeneratedName := method.GenerateRandomSourcesTypeAndName(resourcetype.AwpAwsOnboarding) + CrossAccountRoleExternalId := os.Getenv(environmentvariable.AwpAwsCrossAccountRoleExternalIdEnvVar) + + // Generate the Awp AWS onboarding HCL Resources + awpAwsOnboardingHcl := getAwpAwsOnboardingResourceHCL(resourceGeneratedName, CrossAccountRoleExternalId, false) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + testAwpAwsEnvVarsPreCheck(t) + }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAwpAwsOnboardingConfig(awpAwsOnboardingHcl, resourceGeneratedName, awpAwsOnboardingResourceTypeAndName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet(awpAwsOnboardingDataSourceTypeAndName, "id"), + resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "scan_mode", awpAwsOnboardingResourceTypeAndName, "scan_mode"), + resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "cloud_account_id", awpAwsOnboardingResourceTypeAndName, "cloudguard_account_id"), + resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "agentless_account_settings.0.disabled_regions.0", awpAwsOnboardingResourceTypeAndName, "agentless_account_settings.0.disabled_regions.0"), + resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "agentless_account_settings.0.disabled_regions.1", awpAwsOnboardingResourceTypeAndName, "agentless_account_settings.0.disabled_regions.1"), + resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "agentless_account_settings.0.scan_machine_interval_in_hours", awpAwsOnboardingResourceTypeAndName, "agentless_account_settings.0.scan_machine_interval_in_hours"), + resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "agentless_account_settings.0.max_concurrence_scans_per_region", awpAwsOnboardingResourceTypeAndName, "agentless_account_settings.0.max_concurrence_scans_per_region"), + resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "agentless_account_settings.0.skip_function_apps_scan", awpAwsOnboardingResourceTypeAndName, "agentless_account_settings.0.skip_function_apps_scan"), + resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "agentless_account_settings.0.custom_tags.%", awpAwsOnboardingResourceTypeAndName, "agentless_account_settings.0.custom_tags.%"), + resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "missing_awp_private_network_regions", awpAwsOnboardingResourceTypeAndName, "missing_awp_private_network_regions"), + resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "agentless_protection_enabled", awpAwsOnboardingResourceTypeAndName, "agentless_protection_enabled"), + ), + }, + }, + }) +} + +func testAccDataSourceAwpAwsOnboardingConfig(awpAwsOnboardingHcl, dataSourceGeneratedName, awpAwsOnboardingResourceTypeAndName string) string { + return fmt.Sprintf(` +// awp aws onboarding resource +%s + +// awp aws onboarding data source +data "%s" "%s" { + id = %s.cloudguard_account_id +} +`, + awpAwsOnboardingHcl, + resourcetype.AwpAwsOnboarding, + dataSourceGeneratedName, + awpAwsOnboardingResourceTypeAndName, + ) +} diff --git a/dome9/provider.go b/dome9/provider.go index 60d4a2b0..8bf99d82 100644 --- a/dome9/provider.go +++ b/dome9/provider.go @@ -87,7 +87,7 @@ func Provider() terraform.ResourceProvider { resourcetype.Assessment: dataSourceAssessment(), resourcetype.ImageAssurancePolicy: dataSourceImageAssurancePolicy(), resourcetype.AwpAwsGetOnboardingData: dataSourceAwpAwsOnboardingData(), - resourcetype.AwpAwsOnboardingData: dataSourceAwpAwsOnboarding(), + resourcetype.AwpAwsOnboarding: dataSourceAwpAwsOnboarding(), }, ConfigureFunc: providerConfigure, } From 3e1efaea43508177430f9fa2ea1ad571e5ce36dd Mon Sep 17 00:00:00 2001 From: Omar Date: Sun, 17 Mar 2024 13:34:54 +0200 Subject: [PATCH 19/47] update main.tf file --- dome9/resource_dome9_awp_aws_onboarding.go | 1 + examples/awp_aws_onboarding/main.tf | 64 ++++++---------------- 2 files changed, 17 insertions(+), 48 deletions(-) diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index 3a98c5ce..f7c05282 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -43,6 +43,7 @@ func resourceAwpAwsOnboarding() *schema.Resource { "scan_mode": { Type: schema.TypeString, Required: true, + Default: "saas", ValidateFunc: validation.StringInSlice([]string{ "inAccount", "saas", diff --git a/examples/awp_aws_onboarding/main.tf b/examples/awp_aws_onboarding/main.tf index d29d16d8..75e46235 100644 --- a/examples/awp_aws_onboarding/main.tf +++ b/examples/awp_aws_onboarding/main.tf @@ -15,59 +15,21 @@ terraform { provider "dome9" { dome9_access_id = "DOME9_ACCESS_ID" dome9_secret_key = "DOME9_SECRET_KEY" - base_url = "DOME9_BASE_URL" + base_url = "https://api.us7.falconetix.com/v2/" } provider "aws" { - region = "AWS_REGION" - access_key = "AWS_ACCESS_KEY" - secret_key = "AWS_SECRET_KEY" - token = "AWS_SESSION_TOKEN" + region = "us-west-2" + access_key = "" + secret_key = "" + token = "" } -/* -resource "dome9_aws_unified_onboarding" "omark_aws_account_onboarding" { - cloud_vendor = "aws" - onboard_type = "Simple" - full_protection = true - enable_stack_modify = true - posture_management_configuration = { - rulesets = "[0]" - } - serverless_configuration = { - enabled = false - } - intelligence_configurations = { - rulesets = "[0]" - enabled = false - } -} - -resource "aws_cloudformation_stack" "stack"{ - name = dome9_aws_unified_onboarding.omark_aws_account_onboarding.stack_name - template_url = dome9_aws_unified_onboarding.omark_aws_account_onboarding.template_url - parameters = dome9_aws_unified_onboarding.omark_aws_account_onboarding.parameters - capabilities = dome9_aws_unified_onboarding.omark_aws_account_onboarding.iam_capabilities -} - -data "dome9_aws_unified_onboarding" "omark_aws_account_onboarding_data" { - id = dome9_aws_unified_onboarding.omark_aws_account_onboarding.id - depends_on = [ - aws_cloudformation_stack.stack - ] -} - -output "environment_external_id" { - value = data.dome9_aws_unified_onboarding.omark_aws_account_onboarding_data.environment_external_id - description = "The external ID of the environment" -} -*/ - resource "dome9_cloudaccount_aws" "omark_aws_account" { name = "omark_aws_account" credentials { - arn = "arn:aws:iam::478980137264:role/CloudGuard-Connect" - secret = "IAM_ROLE_SECRET" + arn = "ARN for IAM Role" + secret = "Secret for IAM Role" type = "RoleBased" } net_sec { @@ -548,7 +510,7 @@ resource "aws_iam_policy_attachment" "CloudGuardAWPLambdaExecutionRolePolicyAtta resource "aws_lambda_invocation" "CloudGuardAWPSnapshotsUtilsCleanupFunctionInvocation" { function_name = aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction.function_name input = jsonencode({ - "target_account_id" : data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.external_aws_account_id + "target_account_id" : data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cloud_account_id }) lifecycle_scope = "CRUD" depends_on = [ @@ -625,7 +587,7 @@ resource "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { cloudguard_account_id = dome9_cloudaccount_aws.omark_aws_account.id cross_account_role_name = aws_iam_role.CloudGuardAWPCrossAccountRole.name cross_account_role_external_id = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cross_account_role_external_id - scan_mode = "inAccount" + scan_mode = local.scan_mode agentless_account_settings { disabled_regions = ["us-east-1", "us-west-1", "ap-northeast-1", "ap-southeast-2"] scan_machine_interval_in_hours = 10 @@ -637,11 +599,17 @@ resource "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { tag3 = "value3" } } - force_delete = true depends_on = [ aws_iam_policy_attachment.CloudGuardAWPLambdaExecutionRolePolicyAttachment, aws_iam_policy_attachment.CloudGuardAWPLambdaExecutionRolePolicyAttachment_SaaS, aws_iam_role.CloudGuardAWPCrossAccountRole, aws_iam_role_policy_attachment.CloudGuardAWPCrossAccountRoleAttachment ] +} + +data "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { + id = dome9_awp_aws_onboarding.awp_aws_onboarding_test.cloudguard_account_id + depends_on = [ + dome9_awp_aws_onboarding.awp_aws_onboarding_test + ] } \ No newline at end of file From afb9faff5ac000ea954ed957ca08e72fc485727d Mon Sep 17 00:00:00 2001 From: Omar Date: Sun, 17 Mar 2024 14:21:49 +0200 Subject: [PATCH 20/47] correct scan_mode schema --- dome9/resource_dome9_awp_aws_onboarding.go | 1 - 1 file changed, 1 deletion(-) diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index f7c05282..3a98c5ce 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -43,7 +43,6 @@ func resourceAwpAwsOnboarding() *schema.Resource { "scan_mode": { Type: schema.TypeString, Required: true, - Default: "saas", ValidateFunc: validation.StringInSlice([]string{ "inAccount", "saas", From aed4a1dc2a98063b0bf27e617c6be9c8ed0e3b47 Mon Sep 17 00:00:00 2001 From: Omar Date: Mon, 18 Mar 2024 13:24:51 +0200 Subject: [PATCH 21/47] change env variable name for awp --- .../common/testing/environmentvariable/environment_variable.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dome9/common/testing/environmentvariable/environment_variable.go b/dome9/common/testing/environmentvariable/environment_variable.go index ac519f2d..fc708e39 100644 --- a/dome9/common/testing/environmentvariable/environment_variable.go +++ b/dome9/common/testing/environmentvariable/environment_variable.go @@ -23,7 +23,7 @@ const ( CloudAccountAWSEnvVarArn = "ARN" CloudAccountUpdatedAWSEnvVarArn = "ARN_UPDATE" CloudAccountAWSEnvVarSecret = "SECRET" - AwpAwsCrossAccountRoleExternalIdEnvVar = "EXTERNAL_ID" + AwpAwsCrossAccountRoleExternalIdEnvVar = "AWP_EXTERNAL_ID" ) // Azure environment variable From 82eba149c524a0093b4e3b9372e2ffdda5decad6 Mon Sep 17 00:00:00 2001 From: Omar Date: Mon, 18 Mar 2024 15:06:37 +0200 Subject: [PATCH 22/47] add kms alias for saas mode --- examples/awp_aws_onboarding/main.tf | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/examples/awp_aws_onboarding/main.tf b/examples/awp_aws_onboarding/main.tf index 75e46235..f0477dec 100644 --- a/examples/awp_aws_onboarding/main.tf +++ b/examples/awp_aws_onboarding/main.tf @@ -25,8 +25,8 @@ provider "aws" { token = "" } -resource "dome9_cloudaccount_aws" "omark_aws_account" { - name = "omark_aws_account" +resource "dome9_cloudaccount_aws" "aws_onboarding_account_test" { + name = "aws_onboarding_account_test" credentials { arn = "ARN for IAM Role" secret = "Secret for IAM Role" @@ -41,14 +41,14 @@ resource "dome9_cloudaccount_aws" "omark_aws_account" { } data "dome9_awp_aws_get_onboarding_data" "dome9_awp_aws_onboarding_data_source" { - cloud_account_id = dome9_cloudaccount_aws.omark_aws_account.external_account_number + cloud_account_id = dome9_cloudaccount_aws.aws_onboarding_account_test.external_account_number depends_on = [ - dome9_cloudaccount_aws.omark_aws_account + dome9_cloudaccount_aws.aws_onboarding_account_test ] } locals { - scan_mode = "inAccount" + scan_mode = "saas" stage = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.stage region = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.region cloud_guard_backend_account_id = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cloud_guard_backend_account_id @@ -583,14 +583,24 @@ resource "aws_kms_key" "CloudGuardAWPKey" { } #END AWP MR key for snapshot re-encryption +resource "aws_kms_alias" "CloudGuardAWPKeyAlias" { + count = local.scan_mode == "saas" ? 1 : 0 + name = "alias/CloudGuardAWPKey" + target_key_id = aws_kms_key.CloudGuardAWPKey[count.index].arn + depends_on = [ + aws_kms_key.CloudGuardAWPKey + ] +} + + resource "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { - cloudguard_account_id = dome9_cloudaccount_aws.omark_aws_account.id + cloudguard_account_id = dome9_cloudaccount_aws.aws_onboarding_account_test.id cross_account_role_name = aws_iam_role.CloudGuardAWPCrossAccountRole.name - cross_account_role_external_id = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cross_account_role_external_id + cross_account_role_external_id = local.cross_account_role_external_id scan_mode = local.scan_mode agentless_account_settings { disabled_regions = ["us-east-1", "us-west-1", "ap-northeast-1", "ap-southeast-2"] - scan_machine_interval_in_hours = 10 + scan_machine_interval_in_hours = 24 max_concurrence_scans_per_region = 6 skip_function_apps_scan = true custom_tags = { From 375ea2327578286624e4f81ffaa33d55b7cf7d84 Mon Sep 17 00:00:00 2001 From: Omar Date: Tue, 19 Mar 2024 23:23:03 +0200 Subject: [PATCH 23/47] make the tf download the s3 function zip from presigned url --- ...ource_dome9_awp_aws_get_onboarding_data.go | 5 ++++ examples/awp_aws_onboarding/main.tf | 29 +++++++++++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/dome9/data_source_dome9_awp_aws_get_onboarding_data.go b/dome9/data_source_dome9_awp_aws_get_onboarding_data.go index ab3f097d..a56bdc46 100644 --- a/dome9/data_source_dome9_awp_aws_get_onboarding_data.go +++ b/dome9/data_source_dome9_awp_aws_get_onboarding_data.go @@ -54,6 +54,10 @@ func dataSourceAwpAwsOnboardingData() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "remote_snapshots_utils_function_s3_pre_signed_url": { + Type: schema.TypeString, + Computed: true, + }, }, } } @@ -83,6 +87,7 @@ func dataSourceAwpAwsOnboardingDataRead(d *schema.ResourceData, meta interface{} combinedString := resp.CloudGuardBackendAccountId + "-" + cloudAccountID encodedString := base64.StdEncoding.EncodeToString([]byte(combinedString)) _ = d.Set("cross_account_role_external_id", encodedString) + _ = d.Set("remote_snapshots_utils_function_s3_pre_signed_url", resp.RemoteSnapshotsUtilsFunctionS3PreSignedUrl) return nil } diff --git a/examples/awp_aws_onboarding/main.tf b/examples/awp_aws_onboarding/main.tf index f0477dec..200d46b0 100644 --- a/examples/awp_aws_onboarding/main.tf +++ b/examples/awp_aws_onboarding/main.tf @@ -9,6 +9,14 @@ terraform { source = "hashicorp/aws" version = "5.39.1" } + http = { + source = "hashicorp/http" + version = "3.4.2" + } + local = { + source = "hashicorp/local" + version = "2.1.0" // specify the version you want to use + } } } @@ -48,7 +56,7 @@ data "dome9_awp_aws_get_onboarding_data" "dome9_awp_aws_onboarding_data_source" } locals { - scan_mode = "saas" + scan_mode = "inAccount" stage = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.stage region = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.region cloud_guard_backend_account_id = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cloud_guard_backend_account_id @@ -59,6 +67,7 @@ locals { remote_snapshots_utils_function_time_out = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_snapshots_utils_function_time_out awp_client_side_security_group_name = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.awp_client_side_security_group_name cross_account_role_external_id = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cross_account_role_external_id + remote_snapshots_utils_function_s3_pre_signed_url = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_snapshots_utils_function_s3_pre_signed_url } data "aws_partition" "current" {} @@ -232,6 +241,21 @@ resource "aws_iam_policy_attachment" "CloudGuardAWPCrossAccountRolePolicyAttachm } # END Cross account role policy +# Download the remote function file from S3 pre-signed URL +data "http" "CloudGuardAWPSnapshotsUtilsFunctionZip" { + url = local.remote_snapshots_utils_function_s3_pre_signed_url + method = "GET" + request_headers = { + Accept = "application/zip" + } +} + +# store the remote function file in a local file to be used in the lambda function +resource "local_file" "CloudGuardAWPSnapshotsUtilsFunctionZip" { + filename = "${local.remote_snapshots_utils_function_name}7.zip" + content_base64 = data.http.CloudGuardAWPSnapshotsUtilsFunctionZip.response_body_base64 +} + # AWP proxy lambda function resource "aws_lambda_function" "CloudGuardAWPSnapshotsUtilsFunction" { function_name = local.remote_snapshots_utils_function_name @@ -241,8 +265,7 @@ resource "aws_lambda_function" "CloudGuardAWPSnapshotsUtilsFunction" { runtime = "python3.9" memory_size = 256 timeout = local.remote_snapshots_utils_function_time_out - s3_bucket = local.agentless_bucket_name - s3_key = "${local.remote_functions_prefix_key}/${local.remote_snapshots_utils_function_name}7.zip" + filename = local_file.CloudGuardAWPSnapshotsUtilsFunctionZip.filename environment { variables = { From f6db7ae3515a7ec8707ddf415ef5760da3871817 Mon Sep 17 00:00:00 2001 From: Omar Date: Tue, 19 Mar 2024 23:35:43 +0200 Subject: [PATCH 24/47] add support for s3 presigned url --- ..._dome9_awp_aws_get_onboarding_data_test.go | 1 + .../awp_aws_onboarding/awp_aws_onboarding.go | 19 ++++++++++--------- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go b/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go index 7d425c2d..fa1fa588 100644 --- a/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go +++ b/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go @@ -34,6 +34,7 @@ func TestAccDataSourceAwpAwsOnboardingDataBasic(t *testing.T) { resource.TestCheckResourceAttrSet(awpAwsOnboardingDataSourceTypeAndName, "remote_snapshots_utils_function_time_out"), resource.TestCheckResourceAttrSet(awpAwsOnboardingDataSourceTypeAndName, "awp_client_side_security_group_name"), resource.TestCheckResourceAttrSet(awpAwsOnboardingDataSourceTypeAndName, "cross_account_role_external_id"), + resource.TestCheckResourceAttrSet(awpAwsOnboardingDataSourceTypeAndName, "remote_snapshots_utils_function_s3_pre_signed_url"), ), }, }, diff --git a/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go b/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go index 3cc32ac6..916d0085 100644 --- a/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go +++ b/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go @@ -14,15 +14,16 @@ const ( ) type AgentlessAwsTerraformOnboardingDataResponse struct { - Stage string `json:"stage"` - Region string `json:"region"` - CloudGuardBackendAccountId string `json:"cloudGuardBackendAccountId"` - AgentlessBucketName string `json:"agentlessBucketName"` - RemoteFunctionsPrefixKey string `json:"remoteFunctionsPrefixKey"` - RemoteSnapshotsUtilsFunctionName string `json:"remoteSnapshotsUtilsFunctionName"` - RemoteSnapshotsUtilsFunctionRunTime string `json:"remoteSnapshotsUtilsFunctionRunTime"` - RemoteSnapshotsUtilsFunctionTimeOut int `json:"remoteSnapshotsUtilsFunctionTimeOut"` - AwpClientSideSecurityGroupName string `json:"awpClientSideSecurityGroupName"` + Stage string `json:"stage"` + Region string `json:"region"` + CloudGuardBackendAccountId string `json:"cloudGuardBackendAccountId"` + AgentlessBucketName string `json:"agentlessBucketName"` + RemoteFunctionsPrefixKey string `json:"remoteFunctionsPrefixKey"` + RemoteSnapshotsUtilsFunctionName string `json:"remoteSnapshotsUtilsFunctionName"` + RemoteSnapshotsUtilsFunctionRunTime string `json:"remoteSnapshotsUtilsFunctionRunTime"` + RemoteSnapshotsUtilsFunctionTimeOut int `json:"remoteSnapshotsUtilsFunctionTimeOut"` + AwpClientSideSecurityGroupName string `json:"awpClientSideSecurityGroupName"` + RemoteSnapshotsUtilsFunctionS3PreSignedUrl string `json:"s3BucketPreSigneUrl"` } type CloudAccountResponse struct { From 1a4f2a4bf3f9e09241fe97a029eb83a18c5d9e0b Mon Sep 17 00:00:00 2001 From: Omar Date: Tue, 19 Mar 2024 23:45:16 +0200 Subject: [PATCH 25/47] correct the presigned field name --- .../services/awp_aws_onboarding/awp_aws_onboarding.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go b/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go index 916d0085..c643039c 100644 --- a/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go +++ b/vendor/github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding/awp_aws_onboarding.go @@ -23,7 +23,7 @@ type AgentlessAwsTerraformOnboardingDataResponse struct { RemoteSnapshotsUtilsFunctionRunTime string `json:"remoteSnapshotsUtilsFunctionRunTime"` RemoteSnapshotsUtilsFunctionTimeOut int `json:"remoteSnapshotsUtilsFunctionTimeOut"` AwpClientSideSecurityGroupName string `json:"awpClientSideSecurityGroupName"` - RemoteSnapshotsUtilsFunctionS3PreSignedUrl string `json:"s3BucketPreSigneUrl"` + RemoteSnapshotsUtilsFunctionS3PreSignedUrl string `json:"remoteSnapshotsUtilsFunctionCodePreSigneUrl"` } type CloudAccountResponse struct { From fc560ca942c1c647247feae37105ed7b1bebe5b2 Mon Sep 17 00:00:00 2001 From: Omar Date: Wed, 20 Mar 2024 11:08:01 +0200 Subject: [PATCH 26/47] add external_id env variable --- .github/workflows/test.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 536cede6..df3d86ca 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -45,4 +45,5 @@ jobs: OCI_TENANCY_ID: ${{ secrets.OCI_TENANCY_ID }} OCI_HOME_REGION: ${{ secrets.OCI_HOME_REGION }} OCI_USER_OCID: ${{ secrets.OCI_USER_OCID }} + AWP_EXTERNAL_ID: ${{ secrets.AWP_EXTERNAL_ID }} run: go test -v -timeout 2400s ./... \ No newline at end of file From c46301aa1536808c108443f10adfbd572e11b374 Mon Sep 17 00:00:00 2001 From: Omar Date: Wed, 20 Mar 2024 11:14:47 +0200 Subject: [PATCH 27/47] update aws onboarded cloudguard account id for aws account : 883712240507 --- dome9/common/testing/variable/variable.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dome9/common/testing/variable/variable.go b/dome9/common/testing/variable/variable.go index a3b35329..e6a8bbc3 100644 --- a/dome9/common/testing/variable/variable.go +++ b/dome9/common/testing/variable/variable.go @@ -214,7 +214,7 @@ const ( // awp aws onboarding data resource/data source const ( - OnboardedAwsCloudGuardAccountID = "bac8978a-5b86-4d9e-a732-00cbc430b2a6" + OnboardedAwsCloudGuardAccountID = "36f79243-5456-4aa7-88c1-6637cad1f426" AwpAwsCrossAccountRoleName = "CloudGuardAWPCrossAccountRole" ScanMode = "inAccount" DisabledRegions = `["us-east-1", "us-west-1"]` From a9cc7e04c56336801312e50b22356cd743c9d156 Mon Sep 17 00:00:00 2001 From: Omar Date: Wed, 20 Mar 2024 11:57:12 +0200 Subject: [PATCH 28/47] add documentation to main.tf example --- examples/awp_aws_onboarding/main.tf | 108 ++++++++++++++++++++++------ 1 file changed, 87 insertions(+), 21 deletions(-) diff --git a/examples/awp_aws_onboarding/main.tf b/examples/awp_aws_onboarding/main.tf index 200d46b0..845333ee 100644 --- a/examples/awp_aws_onboarding/main.tf +++ b/examples/awp_aws_onboarding/main.tf @@ -1,4 +1,4 @@ -# Dome9 Provider Configurations +# Required Providers Configuration Block for Dome9, AWS, HTTP, and Local terraform { required_providers { dome9 = { @@ -15,29 +15,47 @@ terraform { } local = { source = "hashicorp/local" - version = "2.1.0" // specify the version you want to use + version = "2.5.1" } } } - +# The Dome9 provider is used to interact with the resources supported by Dome9. +# The provider needs to be configured with the proper credentials before it can be used. +# Use the dome9_access_id and dome9_secret_key attributes of the provider to provide the Dome9 access key and secret key. +# The base_url attribute is used to specify the base URL of the Dome9 API. +# The Dome9 provider supports several options for providing these credentials. The following example demonstrates the use of static credentials: +#you can read the Dome9 provider documentation to understand the full set of options available for providing credentials. +#https://registry.terraform.io/providers/dome9/dome9/latest/docs#authentication provider "dome9" { dome9_access_id = "DOME9_ACCESS_ID" dome9_secret_key = "DOME9_SECRET_KEY" - base_url = "https://api.us7.falconetix.com/v2/" + base_url = "https://api.dome9.com/v2/" } +# AWS Provider Configurations +# The AWS provider is used to interact with the resources supported by AWS. +# The provider needs to be configured with the proper credentials before it can be used. +# Use the access_key, secret_key, and token attributes of the provider to provide the credentials. +# also you can use the shared_credentials_file attribute to provide the path to the shared credentials file. +# The AWS provider supports several options for providing these credentials. The following example demonstrates the use of static credentials: +#you can read the AWS provider documentation to understand the full set of options available for providing credentials. +#https://registry.terraform.io/providers/hashicorp/aws/latest/docs#authentication-and-configuration provider "aws" { - region = "us-west-2" - access_key = "" - secret_key = "" - token = "" + region = "AWS_REGION" + access_key = "AWS_ACCESS_KEY" + secret_key = "AWS_SECRET_KEY" + token = "AWS_SESSION_TOKEN" } +# The resource block defines a Dome9 AWS Cloud Account onboarding. +# The Dome9 AWS Cloud Account onboarding resource allows you to onboard an AWS account to Dome9. +# this resource is optional and can be ignored and you need to pass CloudGuard account id Dome9 AWP AWS Onboarding resource and "dome9_awp_aws_get_onboarding_data" data source. +/* resource "dome9_cloudaccount_aws" "aws_onboarding_account_test" { name = "aws_onboarding_account_test" credentials { - arn = "ARN for IAM Role" - secret = "Secret for IAM Role" + arn = "arn:aws:iam::478980137264:role/CloudGuard-Connect" + secret = "@R2PUjk0up42HHDtD9CByVF8" type = "RoleBased" } net_sec { @@ -47,16 +65,19 @@ resource "dome9_cloudaccount_aws" "aws_onboarding_account_test" { } } } +*/ +# The dome9_awp_aws_get_onboarding_data data source allows you to get the onboarding data of an AWS account. +# you can pass the CloudGuard account id to get the onboarding data of the AWS account or the external account number for the AWS account. data "dome9_awp_aws_get_onboarding_data" "dome9_awp_aws_onboarding_data_source" { - cloud_account_id = dome9_cloudaccount_aws.aws_onboarding_account_test.external_account_number - depends_on = [ - dome9_cloudaccount_aws.aws_onboarding_account_test - ] + cloud_account_id = "CLOUDGUARD_ACCOUNT_ID or EXTERNAL_AWS_ACCOUNT_NUMBER" } +# The local block defines a local value that can be used to store the data that is used in multiple places in the configuration. +# the scan_mode is used to define the scan mode of the Dome9 AWP AWS Onboarding. +# the valid values are "inAccount" and "saas". you need to select one of them based on the scan mode of the Dome9 AWP AWS Onboarding. locals { - scan_mode = "inAccount" + scan_mode = "inAccount or saas" # the valid values are "inAccount" and "saas" when onboarding the AWS account to Dome9 AWP. stage = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.stage region = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.region cloud_guard_backend_account_id = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cloud_guard_backend_account_id @@ -70,13 +91,28 @@ locals { remote_snapshots_utils_function_s3_pre_signed_url = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_snapshots_utils_function_s3_pre_signed_url } +# +# CloudGuardAWPCrossAccountRole : The IAM role that is used to allow AWP to access the AWS account. +# CloudGuardAWPCrossAccountRolePolicy : The IAM policy that is used to define the permissions for the CloudGuardAWPCrossAccountRole. +# CloudGuardAWPSnapshotsUtilsFunction : The Lambda function that is used to manage remote actions and resources. +# CloudGuardAWPSnapshotsUtilsFunctionZip : The local file that is used to store the remote function file to be used in the lambda function. +# CloudGuardAWPSnapshotsUtilsLogGroup : The CloudWatch log group that is used to store the logs of the CloudGuardAWPSnapshotsUtilsFunction. +# CloudGuardAWPSnapshotsUtilsLambdaExecutionRole : The IAM role that is used to allow the CloudGuardAWPSnapshotsUtilsFunction to execute. +# CloudGuardAWPSnapshotsPolicy : The IAM policy that is used to define the permissions for the CloudGuardAWPSnapshotsUtilsFunction. +# CloudGuardAWPLambdaExecutionRolePolicy : The IAM policy that is used to define the permissions for the CloudGuardAWPSnapshotsUtilsFunction. +# CloudGuardAWPLambdaExecutionRolePolicy_SaaS : The IAM policy that is used to define the permissions for the CloudGuardAWPSnapshotsUtilsFunction in SaaS mode. +# CloudGuardAWPKey : The KMS key that is used to re-encrypt the snapshots in SaaS mode. +# CloudGuardAWPKeyAlias : The KMS key alias that is used to reference the KMS key in SaaS mode. +# CloudGuardAWPSnapshotsUtilsCleanupFunctionInvocation : The Lambda invocation that is used to clean up the resources after the onboarding process. +# The data block defines a data source that can be used to get the current AWS partition. data "aws_partition" "current" {} - +# The data block defines a data source that can be used to get the current AWS region. data "aws_region" "current" {} - +# The data block defines a data source that can be used to get the current AWS caller identity. data "aws_caller_identity" "current" {} # Cross account role to allow CloudGuard access +# The CloudGuardAWPCrossAccountRole resource defines an IAM role that is used to allow AWP to access the AWS account. resource "aws_iam_role" "CloudGuardAWPCrossAccountRole" { name = "CloudGuardAWPCrossAccountRole" description = "CloudGuard AWP Cross Account Role" @@ -99,6 +135,7 @@ resource "aws_iam_role" "CloudGuardAWPCrossAccountRole" { depends_on = [aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction] } +# The CloudGuardAWPCrossAccountRolePolicy resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPCrossAccountRole. resource "aws_iam_policy" "CloudGuardAWP" { name = "CloudGuardAWP" description = "Policy for CloudGuard AWP" @@ -145,6 +182,7 @@ resource "aws_iam_policy" "CloudGuardAWP" { }) } +# The CloudGuardAWPCrossAccountRoleAttachment resource attaches the CloudGuardAWPCrossAccountRolePolicy to the CloudGuardAWPCrossAccountRole. resource "aws_iam_role_policy_attachment" "CloudGuardAWPCrossAccountRoleAttachment" { role = aws_iam_role.CloudGuardAWPCrossAccountRole.name policy_arn = aws_iam_policy.CloudGuardAWP.arn @@ -152,6 +190,7 @@ resource "aws_iam_role_policy_attachment" "CloudGuardAWPCrossAccountRoleAttachme # end resources for CloudGuardAWPCrossAccountRole # Cross account role policy +# The CloudGuardAWPCrossAccountRolePolicy resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPCrossAccountRole. resource "aws_iam_policy" "CloudGuardAWPCrossAccountRolePolicy" { count = local.scan_mode == "inAccount" ? 1 : 0 name = "CloudGuardAWPCrossAccountRolePolicy" @@ -189,6 +228,7 @@ resource "aws_iam_policy" "CloudGuardAWPCrossAccountRolePolicy" { }) } +# The CloudGuardAWPCrossAccountRolePolicy_SaaS resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPCrossAccountRole in SaaS mode. resource "aws_iam_policy" "CloudGuardAWPCrossAccountRolePolicy_SaaS" { count = local.scan_mode == "saas" ? 1 : 0 name = "CloudGuardAWPCrossAccountRolePolicy_SaaS" @@ -226,6 +266,7 @@ resource "aws_iam_policy" "CloudGuardAWPCrossAccountRolePolicy_SaaS" { }) } +# The CloudGuardAWPCrossAccountRolePolicyAttachment resource attaches the CloudGuardAWPCrossAccountRolePolicy to the CloudGuardAWPCrossAccountRole. resource "aws_iam_policy_attachment" "CloudGuardAWPCrossAccountRolePolicyAttachment" { count = local.scan_mode == "inAccount" ? 1 : 0 name = "CloudGuardAWPCrossAccountRolePolicyAttachment" @@ -233,6 +274,7 @@ resource "aws_iam_policy_attachment" "CloudGuardAWPCrossAccountRolePolicyAttachm roles = [aws_iam_role.CloudGuardAWPCrossAccountRole.name] } +# The CloudGuardAWPCrossAccountRolePolicyAttachment_SaaS resource attaches the CloudGuardAWPCrossAccountRolePolicy_SaaS to the CloudGuardAWPCrossAccountRole. resource "aws_iam_policy_attachment" "CloudGuardAWPCrossAccountRolePolicyAttachment_SaaS" { count = local.scan_mode == "saas" ? 1 : 0 name = "CloudGuardAWPCrossAccountRolePolicyAttachment_SaaS" @@ -241,7 +283,7 @@ resource "aws_iam_policy_attachment" "CloudGuardAWPCrossAccountRolePolicyAttachm } # END Cross account role policy -# Download the remote function file from S3 pre-signed URL +# The CloudGuardAWPSnapshotsUtilsFunctionZip resource defines http data source to download the remote function file from S3 pre-signed URL. data "http" "CloudGuardAWPSnapshotsUtilsFunctionZip" { url = local.remote_snapshots_utils_function_s3_pre_signed_url method = "GET" @@ -250,13 +292,14 @@ data "http" "CloudGuardAWPSnapshotsUtilsFunctionZip" { } } -# store the remote function file in a local file to be used in the lambda function +# The CloudGuardAWPSnapshotsUtilsFunctionZip resource defines a local file that is used to store the remote function file to be used in the lambda function. resource "local_file" "CloudGuardAWPSnapshotsUtilsFunctionZip" { filename = "${local.remote_snapshots_utils_function_name}7.zip" content_base64 = data.http.CloudGuardAWPSnapshotsUtilsFunctionZip.response_body_base64 } # AWP proxy lambda function +# The CloudGuardAWPSnapshotsUtilsFunction resource defines a lambda function that is used to manage remote actions and resources. resource "aws_lambda_function" "CloudGuardAWPSnapshotsUtilsFunction" { function_name = local.remote_snapshots_utils_function_name handler = "snapshots_utils.lambda_handler" @@ -292,6 +335,7 @@ resource "aws_lambda_permission" "allow_cloudguard" { } # END AWP proxy lambda function +# CloudGuardAWPSnapshotsUtilsLogGroup : The CloudWatch log group that is used to store the logs of the CloudGuardAWPSnapshotsUtilsFunction. resource "aws_cloudwatch_log_group" "CloudGuardAWPSnapshotsUtilsLogGroup" { name = "/aws/lambda/CloudGuardAWPSnapshotsUtils" retention_in_days = 30 @@ -301,6 +345,7 @@ resource "aws_cloudwatch_log_group" "CloudGuardAWPSnapshotsUtilsLogGroup" { } # AWP proxy lambda function role +# The CloudGuardAWPSnapshotsUtilsLambdaExecutionRole resource defines an IAM role that is used to allow the CloudGuardAWPSnapshotsUtilsFunction to execute. resource "aws_iam_role" "CloudGuardAWPSnapshotsUtilsLambdaExecutionRole" { name = "CloudGuardAWPLambdaExecutionRole" description = "CloudGuard AWP proxy lambda function execution role" @@ -322,6 +367,7 @@ resource "aws_iam_role" "CloudGuardAWPSnapshotsUtilsLambdaExecutionRole" { } } +# The CloudGuardAWPSnapshotsPolicy resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPSnapshotsUtilsFunction. resource "aws_iam_policy" "CloudGuardAWPSnapshotsPolicy" { name = "CloudGuardAWPSnapshotsPolicy" description = "Policy for managing snapshots at client side and delete AWP keys" @@ -365,6 +411,7 @@ resource "aws_iam_policy" "CloudGuardAWPSnapshotsPolicy" { }) } +# The CloudGuardAWPSnapshotsUtilsLambdaExecutionRoleAttachment resource attaches the CloudGuardAWPSnapshotsPolicy to the CloudGuardAWPSnapshotsUtilsLambdaExecutionRole. resource "aws_iam_role_policy_attachment" "CloudGuardAWPSnapshotsUtilsLambdaExecutionRoleAttachment" { role = aws_iam_role.CloudGuardAWPSnapshotsUtilsLambdaExecutionRole.name policy_arn = aws_iam_policy.CloudGuardAWPSnapshotsPolicy.arn @@ -372,6 +419,7 @@ resource "aws_iam_role_policy_attachment" "CloudGuardAWPSnapshotsUtilsLambdaExec # END AWP proxy lambda function role # AWP proxy lambda function role policy +# The CloudGuardAWPLambdaExecutionRolePolicy resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPSnapshotsUtilsFunction. resource "aws_iam_policy" "CloudGuardAWPLambdaExecutionRolePolicy" { count = local.scan_mode == "inAccount" ? 1 : 0 name = "CloudGuardAWPLambdaExecutionRolePolicy" @@ -466,6 +514,7 @@ resource "aws_iam_policy" "CloudGuardAWPLambdaExecutionRolePolicy" { }) } +# The CloudGuardAWPLambdaExecutionRolePolicyAttachment resource attaches the CloudGuardAWPLambdaExecutionRolePolicy to the CloudGuardAWPSnapshotsUtilsLambdaExecutionRole. resource "aws_iam_policy" "CloudGuardAWPLambdaExecutionRolePolicy_SaaS" { count = local.scan_mode == "saas" ? 1 : 0 name = "CloudGuardAWPLambdaExecutionRolePolicy_SaaS" @@ -515,6 +564,7 @@ resource "aws_iam_policy" "CloudGuardAWPLambdaExecutionRolePolicy_SaaS" { }) } +# The CloudGuardAWPLambdaExecutionRolePolicyAttachment resource attaches the CloudGuardAWPLambdaExecutionRolePolicy to the CloudGuardAWPSnapshotsUtilsLambdaExecutionRole. resource "aws_iam_policy_attachment" "CloudGuardAWPLambdaExecutionRolePolicyAttachment" { count = local.scan_mode == "inAccount" ? 1 : 0 name = "CloudGuardAWPLambdaExecutionRolePolicyAttachment" @@ -522,6 +572,7 @@ resource "aws_iam_policy_attachment" "CloudGuardAWPLambdaExecutionRolePolicyAtta roles = [aws_iam_role.CloudGuardAWPSnapshotsUtilsLambdaExecutionRole.name] } +# The CloudGuardAWPLambdaExecutionRolePolicyAttachment_SaaS resource attaches the CloudGuardAWPLambdaExecutionRolePolicy_SaaS to the CloudGuardAWPSnapshotsUtilsLambdaExecutionRole. resource "aws_iam_policy_attachment" "CloudGuardAWPLambdaExecutionRolePolicyAttachment_SaaS" { count = local.scan_mode == "saas" ? 1 : 0 name = "CloudGuardAWPLambdaExecutionRolePolicyAttachment" @@ -530,6 +581,7 @@ resource "aws_iam_policy_attachment" "CloudGuardAWPLambdaExecutionRolePolicyAtta } # END AWP proxy lambda function role policy +# aws_lambda_invocation : The Lambda invocation that is used to clean up the resources after the onboarding process. resource "aws_lambda_invocation" "CloudGuardAWPSnapshotsUtilsCleanupFunctionInvocation" { function_name = aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction.function_name input = jsonencode({ @@ -543,6 +595,7 @@ resource "aws_lambda_invocation" "CloudGuardAWPSnapshotsUtilsCleanupFunctionInvo } # AWP MR key for snapshot re-encryption +# The CloudGuardAWPKey resource defines a KMS key that is used to re-encrypt the snapshots in SaaS mode. resource "aws_kms_key" "CloudGuardAWPKey" { count = local.scan_mode == "saas" ? 1 : 0 description = "CloudGuard AWP Multi-Region primary key for snapshots re-encryption (for Saas mode only)" @@ -606,6 +659,7 @@ resource "aws_kms_key" "CloudGuardAWPKey" { } #END AWP MR key for snapshot re-encryption +# The CloudGuardAWPKeyAlias resource defines a KMS key alias that is used to reference the KMS key in SaaS mode. resource "aws_kms_alias" "CloudGuardAWPKeyAlias" { count = local.scan_mode == "saas" ? 1 : 0 name = "alias/CloudGuardAWPKey" @@ -615,9 +669,20 @@ resource "aws_kms_alias" "CloudGuardAWPKeyAlias" { ] } - +# The dome9_awp_aws_onboarding resource defines a Dome9 AWP AWS Onboarding. +# The Dome9 AWP AWS Onboarding resource allows you to onboard an AWS account to Dome9 AWP. +# The cloudguard_account_id attribute is used to specify the CloudGuard account id of the AWS account. +# The cross_account_role_name attribute is used to specify the name of the cross account role that is used to allow AWP to access the AWS account. +# The cross_account_role_external_id attribute is used to specify the external id of the cross account role that is used to allow AWP to access the AWS account. +# The scan_mode attribute is used to specify the scan mode of the Dome9 AWP AWS Onboarding. The valid values are "inAccount" and "saas". +# The agentless_account_settings attribute is used to specify the agentless account settings of the Dome9 AWP AWS Onboarding. +# The disabled_regions attribute is used to specify the disabled regions of the agentless account settings of the Dome9 AWP AWS Onboarding. +# The scan_machine_interval_in_hours attribute is used to specify the scan machine interval in hours of the agentless account settings of the Dome9 AWP AWS Onboarding. +# The max_concurrence_scans_per_region attribute is used to specify the max concurrence scans per region of the agentless account settings of the Dome9 AWP AWS Onboarding. +# The skip_function_apps_scan attribute is used to specify whether to skip the function apps scan of the agentless account settings of the Dome9 AWP AWS Onboarding. +# The custom_tags attribute is used to specify the custom tags of the agentless account settings of the Dome9 AWP AWS Onboarding. resource "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { - cloudguard_account_id = dome9_cloudaccount_aws.aws_onboarding_account_test.id + cloudguard_account_id = "CLOUDGUARD_ACCOUNT_ID or EXTERNAL_AWS_ACCOUNT_NUMBER" cross_account_role_name = aws_iam_role.CloudGuardAWPCrossAccountRole.name cross_account_role_external_id = local.cross_account_role_external_id scan_mode = local.scan_mode @@ -640,6 +705,7 @@ resource "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { ] } +# The dome9_awp_aws_onboarding data source allows you to get the onboarding data of an AWS account. data "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { id = dome9_awp_aws_onboarding.awp_aws_onboarding_test.cloudguard_account_id depends_on = [ From 7e96f9c96c0753fc26abfed94b7fbe22ba33b73d Mon Sep 17 00:00:00 2001 From: Omar Date: Wed, 20 Mar 2024 17:32:48 +0200 Subject: [PATCH 29/47] add documentation for all awp resources --- examples/awp_aws_onboarding/README.md | 22 ++++++ .../awp_aws_get_onboarding_data.html.markdown | 43 +++++++++++ .../docs/d/awp_aws_onboarding.html.markdown | 42 +++++++++++ .../docs/r/awp_aws_onboarding.html.markdown | 72 +++++++++++++++++++ 4 files changed, 179 insertions(+) create mode 100644 examples/awp_aws_onboarding/README.md create mode 100644 website/docs/d/awp_aws_get_onboarding_data.html.markdown create mode 100644 website/docs/d/awp_aws_onboarding.html.markdown create mode 100644 website/docs/r/awp_aws_onboarding.html.markdown diff --git a/examples/awp_aws_onboarding/README.md b/examples/awp_aws_onboarding/README.md new file mode 100644 index 00000000..132548e9 --- /dev/null +++ b/examples/awp_aws_onboarding/README.md @@ -0,0 +1,22 @@ +# Attach IAM safe Example + +This example will show you how to use Terraform to onboarding AWP AWS cloud account that protected by dome9. +This example codifies [this API](https://docs.cgn.portal.checkpoint.com/reference/agentless). + +To run, configure your Dome9 provider as described in https://www.terraform.io/docs/providers/dome9/index.html + +## Run the example + +From inside of this directory: + +```bash +terraform init +terraform plan -out theplan +terraform apply theplan +``` + +## Destroy 💥 + +```bash +terraform destroy +``` diff --git a/website/docs/d/awp_aws_get_onboarding_data.html.markdown b/website/docs/d/awp_aws_get_onboarding_data.html.markdown new file mode 100644 index 00000000..cbff2f92 --- /dev/null +++ b/website/docs/d/awp_aws_get_onboarding_data.html.markdown @@ -0,0 +1,43 @@ +--- +layout: "dome9" +page_title: "Check Point CloudGuard Dome9: dome9_awp_aws_get_onboarding_data" +sidebar_current: "docs-datasource-dome9-awp-aws-get-onboarding-data" +description: |- + Get information about AWS AWP onboarding data in Dome9. +--- + +# Data Source: dome9_awp_aws_get_onboarding_data + +Use this data source to get information about AWS AWP onboarding data in Dome9. + +## Example Usage + +```hcl +data "dome9_awp_aws_get_onboarding_data" "test" { + cloud_account_id = "d9-aws-cloud-account-id" +} + +``` + +## Argument Reference + +The following arguments supported: + +* `cloud_account_id` - (Required) The Dome9 id for the onboarded AWS account, + * it can be the dome9 cloudguard account id or the external aws account id. + +## Attributes Reference + +In addition to all arguments above, the following attributes exported: + +* `stage` - The stage of the AWP AWS onboarding process(i.e "prod-us"). +* `region` - The region of the AWP AWS onboarding process. +* `cloud_guard_backend_account_id` - The CloudGuard AWS backend account ID. +* `agentless_bucket_name` - The name of the agentless s3 bucket. +* `remote_functions_prefix_key` - The prefix key for remote functions. +* `remote_snapshots_utils_function_name` - The name of the remote snapshots utility function. +* `remote_snapshots_utils_function_run_time` - The runtime of the remote snapshots utility function. +* `remote_snapshots_utils_function_time_out` - The timeout for the remote snapshots utility function. +* `awp_client_side_security_group_name` - The name of the AWP client-side security group. +* `cross_account_role_external_id` - The external ID for the cross-account role. +* `remote_snapshots_utils_function_s3_pre_signed_url` - The pre-signed URL for the remote snapshots utility function. \ No newline at end of file diff --git a/website/docs/d/awp_aws_onboarding.html.markdown b/website/docs/d/awp_aws_onboarding.html.markdown new file mode 100644 index 00000000..99be3679 --- /dev/null +++ b/website/docs/d/awp_aws_onboarding.html.markdown @@ -0,0 +1,42 @@ +--- +layout: "dome9" +page_title: "Check Point CloudGuard Dome9: dome9_awp_aws_onboarding" +sidebar_current: "docs-datasource-dome9-awp-aws-onboarding" +description: |- + Get information about AWS AWP onboarding in Dome9. +--- + +# Data Source: dome9_awp_aws_onboarding + +Use this data source to get information about AWS AWP onboarding in Dome9. +it gives details information about the awp aws account scanner configurations. + +## Example Usage + +```hcl +data "dome9_awp_aws_onboarding" "test" { + id = "d9-aws-cloudguard-account-id or aws-account-id" +} + +``` + +## Argument Reference + +The following arguments supported: + +* `id` - (Required) The Dome9 id for the onboarded AWS account. + +## Attributes Reference + +In addition to all arguments above, the following attributes exported: + +* `centralized_cloud_account_id` - The centralized CloudGuard account ID if configured. +* `scan_mode` - The scan mode of the onboarding process +* `agentless_account_settings` - The settings for the agentless account that the awp scanner will be configured with. +* `missing_awp_private_network_regions` - The regions missing AWP private network. +* `account_issues` - The issues related to the awp account. +* `cloud_account_id` - The CloudGuard account ID. +* `agentless_protection_enabled` - Whether agentless protection is enabled or not. +* `cloud_provider` - The cloud provider for the onboarding process. +* `should_update` - Whether the onboarding process should be updated. +* `is_org_onboarding` - Whether the onboarding process is for an organization. \ No newline at end of file diff --git a/website/docs/r/awp_aws_onboarding.html.markdown b/website/docs/r/awp_aws_onboarding.html.markdown new file mode 100644 index 00000000..e9509686 --- /dev/null +++ b/website/docs/r/awp_aws_onboarding.html.markdown @@ -0,0 +1,72 @@ +--- +layout: "dome9" +page_title: "Check Point CloudGuard Dome9: dome9_awp_aws_onboarding" +sidebar_current: "docs-resource-dome9-awp-aws-onboarding" +description: |- + Creates an AWP AWS Onboarding in Dome9 +--- + +# dome9_awp_aws_onboarding + +This resource is used to create and modify AWP AWS Onboarding in CloudGuard Dome9. + +## Example Usage + +Basic usage: + +```hcl +resource "dome9_awp_aws_onboarding" "test_awp_aws_onboarding" { + cloudguard_account_id = "CloudGuard Account ID or External AWS Account ID" + cross_account_role_name = "Cross Account Role Name" + cross_account_role_external_id = "Cross Account Role External ID" + scan_mode = "inAccount" + agentless_account_settings { + disabled_regions = ["us-east-1", "us-west-1"] + scan_machine_interval_in_hours = 24 + max_concurrence_scans_per_region = 6 + skip_function_apps_scan = true + custom_tags = { + tag1 = "value1" + tag2 = "value2" + } + } +} + +``` + +## Argument Reference + +The following arguments are supported: + +* `cloudguard_account_id` - (Required) The CloudGuard account id. +* `centralized_cloud_account_id` - (Optional) The centralized cloud account id. +* `cross_account_role_name` - (Required) The name of the cross account role. +* `cross_account_role_external_id` - (Required) The external id of the cross account role. +* `scan_mode` - (Required) The scan mode. Valid values are "inAccount", "saas", "inAccountHub", "inAccountSub". +* `agentless_account_settings` - (Optional) The agentless account settings. + * `disabled_regions` - (Optional) The disabled regions. valid values are "us-east-1", "us-west-1", "us-west-2", "eu-west-1", "eu-central-1", "ap-northeast-1", "ap-southeast-1", "ap-southeast-2", "ap-northeast-2", "ap-south-1", "sa-east-1". + * `scan_machine_interval_in_hours` - (Optional) The scan machine interval in hours + * `max_concurrence_scans_per_region` - (Optional) The max concurrence scans per region + * `skip_function_apps_scan` - (Optional) Whether to skip function apps scan. Default is false. + * `custom_tags` - (Optional) The custom tags. +* `should_create_policy` - (Optional) Whether to create a policy. Default is true. + +## Attributes Reference + +* `missing_awp_private_network_regions` - The missing AWP private network regions. +* `account_issues` - The account issues. +* `cloud_account_id` - The cloud guard account id. +* `agentless_protection_enabled` - Whether agentless protection is enabled. +* `cloud_provider` - The cloud provider. +* `should_update` - Whether to update. +* `is_org_onboarding` - Whether is org onboarding. + +## Import + +The AWP AWS Onboarding can be imported; use as the import ID. + +For example: + +```shell +terraform import dome9_awp_aws_onboarding.test_awp_aws_onboarding 00000000-0000-0000-0000-000000000000 +``` From a2ee38a123dc1b4f286a1b2ad70dbfe4df676612 Mon Sep 17 00:00:00 2001 From: Omar Date: Wed, 20 Mar 2024 17:41:55 +0200 Subject: [PATCH 30/47] update valid regions --- website/docs/r/awp_aws_onboarding.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/r/awp_aws_onboarding.html.markdown b/website/docs/r/awp_aws_onboarding.html.markdown index e9509686..48305024 100644 --- a/website/docs/r/awp_aws_onboarding.html.markdown +++ b/website/docs/r/awp_aws_onboarding.html.markdown @@ -44,7 +44,7 @@ The following arguments are supported: * `cross_account_role_external_id` - (Required) The external id of the cross account role. * `scan_mode` - (Required) The scan mode. Valid values are "inAccount", "saas", "inAccountHub", "inAccountSub". * `agentless_account_settings` - (Optional) The agentless account settings. - * `disabled_regions` - (Optional) The disabled regions. valid values are "us-east-1", "us-west-1", "us-west-2", "eu-west-1", "eu-central-1", "ap-northeast-1", "ap-southeast-1", "ap-southeast-2", "ap-northeast-2", "ap-south-1", "sa-east-1". + * `disabled_regions` - (Optional) The disabled regions. valid values are "af-south-1", "ap-south-1", "eu-north-1", "eu-west-3", "eu-south-1", "eu-west-2", "eu-west-1", "ap-northeast-3", "ap-northeast-2", "me-south-1", "ap-northeast-1", "me-central-1", "ca-central-1", "sa-east-1", "ap-east-1", "ap-southeast-1", "ap-southeast-2", "eu-central-1", "ap-southeast-3", "us-east-1", "us-east-2", "us-west-1", "us-west-2" * `scan_machine_interval_in_hours` - (Optional) The scan machine interval in hours * `max_concurrence_scans_per_region` - (Optional) The max concurrence scans per region * `skip_function_apps_scan` - (Optional) Whether to skip function apps scan. Default is false. From da56a4f6c92b239de6d42c210a66a4193b71daf8 Mon Sep 17 00:00:00 2001 From: Omar Date: Thu, 21 Mar 2024 10:19:49 +0200 Subject: [PATCH 31/47] add the aws awp onboarding example to documentation --- dome9/resource_dome9_awp_aws_onboarding.go | 6 +- .../docs/r/awp_aws_onboarding.html.markdown | 709 +++++++++++++++++- 2 files changed, 705 insertions(+), 10 deletions(-) diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index 3a98c5ce..3b817b01 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -151,13 +151,11 @@ func resourceAwpAwsOnboarding() *schema.Resource { CustomizeDiff: func(diff *schema.ResourceDiff, v interface{}) error { scanMode, scanModeOk := diff.GetOk("scan_mode") centralizedCloudAccountId, centralizedCloudAccountIdOk := diff.GetOk("centralized_cloud_account_id") - - if scanModeOk && scanMode == "in-account-sub" { + if scanModeOk && scanMode == "inAccountSub" { if !centralizedCloudAccountIdOk || centralizedCloudAccountId == "" { - return fmt.Errorf("'centralized_cloud_account_id' must be set and not empty when 'scan_mode' is 'in-account-sub'") + return fmt.Errorf("'centralized_cloud_account_id' must be set and not empty when 'scan_mode' is 'inAccountSub'") } } - return nil }, } diff --git a/website/docs/r/awp_aws_onboarding.html.markdown b/website/docs/r/awp_aws_onboarding.html.markdown index 48305024..aadb957b 100644 --- a/website/docs/r/awp_aws_onboarding.html.markdown +++ b/website/docs/r/awp_aws_onboarding.html.markdown @@ -15,23 +15,720 @@ This resource is used to create and modify AWP AWS Onboarding in CloudGuard Dome Basic usage: ```hcl -resource "dome9_awp_aws_onboarding" "test_awp_aws_onboarding" { - cloudguard_account_id = "CloudGuard Account ID or External AWS Account ID" - cross_account_role_name = "Cross Account Role Name" - cross_account_role_external_id = "Cross Account Role External ID" - scan_mode = "inAccount" +# Required Providers Configuration Block for Dome9, AWS, HTTP, and Local +terraform { + required_providers { + dome9 = { + source = "dome9/dome9" + version = "1.29.6" + } + aws = { + source = "hashicorp/aws" + version = "5.39.1" + } + http = { + source = "hashicorp/http" + version = "3.4.2" + } + local = { + source = "hashicorp/local" + version = "2.5.1" + } + } +} +# The Dome9 provider is used to interact with the resources supported by Dome9. +# The provider needs to be configured with the proper credentials before it can be used. +# Use the dome9_access_id and dome9_secret_key attributes of the provider to provide the Dome9 access key and secret key. +# The base_url attribute is used to specify the base URL of the Dome9 API. +# The Dome9 provider supports several options for providing these credentials. The following example demonstrates the use of static credentials: +#you can read the Dome9 provider documentation to understand the full set of options available for providing credentials. +#https://registry.terraform.io/providers/dome9/dome9/latest/docs#authentication +provider "dome9" { + dome9_access_id = "DOME9_ACCESS_ID" + dome9_secret_key = "DOME9_SECRET_KEY" + base_url = "https://api.dome9.com/v2/" +} + +# AWS Provider Configurations +# The AWS provider is used to interact with the resources supported by AWS. +# The provider needs to be configured with the proper credentials before it can be used. +# Use the access_key, secret_key, and token attributes of the provider to provide the credentials. +# also you can use the shared_credentials_file attribute to provide the path to the shared credentials file. +# The AWS provider supports several options for providing these credentials. The following example demonstrates the use of static credentials: +#you can read the AWS provider documentation to understand the full set of options available for providing credentials. +#https://registry.terraform.io/providers/hashicorp/aws/latest/docs#authentication-and-configuration +provider "aws" { + region = "AWS_REGION" + access_key = "AWS_ACCESS_KEY" + secret_key = "AWS_SECRET_KEY" + token = "AWS_SESSION_TOKEN" +} + +# The resource block defines a Dome9 AWS Cloud Account onboarding. +# The Dome9 AWS Cloud Account onboarding resource allows you to onboard an AWS account to Dome9. +# this resource is optional and can be ignored and you need to pass CloudGuard account id Dome9 AWP AWS Onboarding resource and "dome9_awp_aws_get_onboarding_data" data source. +/* +resource "dome9_cloudaccount_aws" "aws_onboarding_account_test" { + name = "aws_onboarding_account_test" + credentials { + arn = "arn:aws:iam::478980137264:role/CloudGuard-Connect" + secret = "@R2PUjk0up42HHDtD9CByVF8" + type = "RoleBased" + } + net_sec { + regions { + new_group_behavior = "ReadOnly" + region = "us_west_2" + } + } +} +*/ + +# The dome9_awp_aws_get_onboarding_data data source allows you to get the onboarding data of an AWS account. +# you can pass the CloudGuard account id to get the onboarding data of the AWS account or the external account number for the AWS account. +data "dome9_awp_aws_get_onboarding_data" "dome9_awp_aws_onboarding_data_source" { + cloud_account_id = "CLOUDGUARD_ACCOUNT_ID or EXTERNAL_AWS_ACCOUNT_NUMBER" +} + +# The local block defines a local value that can be used to store the data that is used in multiple places in the configuration. +# the scan_mode is used to define the scan mode of the Dome9 AWP AWS Onboarding. +# the valid values are "inAccount" and "saas". you need to select one of them based on the scan mode of the Dome9 AWP AWS Onboarding. +locals { + scan_mode = "inAccount or saas" # the valid values are "inAccount" and "saas" when onboarding the AWS account to Dome9 AWP. + stage = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.stage + region = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.region + cloud_guard_backend_account_id = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cloud_guard_backend_account_id + agentless_bucket_name = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.agentless_bucket_name + remote_functions_prefix_key = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_functions_prefix_key + remote_snapshots_utils_function_name = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_snapshots_utils_function_name + remote_snapshots_utils_function_run_time = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_snapshots_utils_function_run_time + remote_snapshots_utils_function_time_out = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_snapshots_utils_function_time_out + awp_client_side_security_group_name = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.awp_client_side_security_group_name + cross_account_role_external_id = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cross_account_role_external_id + remote_snapshots_utils_function_s3_pre_signed_url = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_snapshots_utils_function_s3_pre_signed_url +} + +# +# CloudGuardAWPCrossAccountRole : The IAM role that is used to allow AWP to access the AWS account. +# CloudGuardAWPCrossAccountRolePolicy : The IAM policy that is used to define the permissions for the CloudGuardAWPCrossAccountRole. +# CloudGuardAWPSnapshotsUtilsFunction : The Lambda function that is used to manage remote actions and resources. +# CloudGuardAWPSnapshotsUtilsFunctionZip : The local file that is used to store the remote function file to be used in the lambda function. +# CloudGuardAWPSnapshotsUtilsLogGroup : The CloudWatch log group that is used to store the logs of the CloudGuardAWPSnapshotsUtilsFunction. +# CloudGuardAWPSnapshotsUtilsLambdaExecutionRole : The IAM role that is used to allow the CloudGuardAWPSnapshotsUtilsFunction to execute. +# CloudGuardAWPSnapshotsPolicy : The IAM policy that is used to define the permissions for the CloudGuardAWPSnapshotsUtilsFunction. +# CloudGuardAWPLambdaExecutionRolePolicy : The IAM policy that is used to define the permissions for the CloudGuardAWPSnapshotsUtilsFunction. +# CloudGuardAWPLambdaExecutionRolePolicy_SaaS : The IAM policy that is used to define the permissions for the CloudGuardAWPSnapshotsUtilsFunction in SaaS mode. +# CloudGuardAWPKey : The KMS key that is used to re-encrypt the snapshots in SaaS mode. +# CloudGuardAWPKeyAlias : The KMS key alias that is used to reference the KMS key in SaaS mode. +# CloudGuardAWPSnapshotsUtilsCleanupFunctionInvocation : The Lambda invocation that is used to clean up the resources after the onboarding process. +# The data block defines a data source that can be used to get the current AWS partition. +data "aws_partition" "current" {} +# The data block defines a data source that can be used to get the current AWS region. +data "aws_region" "current" {} +# The data block defines a data source that can be used to get the current AWS caller identity. +data "aws_caller_identity" "current" {} + +# Cross account role to allow CloudGuard access +# The CloudGuardAWPCrossAccountRole resource defines an IAM role that is used to allow AWP to access the AWS account. +resource "aws_iam_role" "CloudGuardAWPCrossAccountRole" { + name = "CloudGuardAWPCrossAccountRole" + description = "CloudGuard AWP Cross Account Role" + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Effect = "Allow" + Principal = { + AWS = local.cloud_guard_backend_account_id + } + Action = "sts:AssumeRole" + Condition = { + StringEquals = { + "sts:ExternalId" = local.cross_account_role_external_id + } + } + }] + }) + + depends_on = [aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction] +} + +# The CloudGuardAWPCrossAccountRolePolicy resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPCrossAccountRole. +resource "aws_iam_policy" "CloudGuardAWP" { + name = "CloudGuardAWP" + description = "Policy for CloudGuard AWP" + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = [ + "ec2:DescribeInstances", + "ec2:DescribeSnapshots", + "ec2:DescribeRegions", + "ec2:DescribeVolumes" + ] + Resource = "*" + }, + { + Effect = "Allow" + Action = [ + "lambda:InvokeFunction", + "lambda:GetFunction", + "lambda:GetLayerVersion", + "lambda:TagResource", + "lambda:ListTags", + "lambda:UntagResource", + "lambda:UpdateFunctionCode", + "lambda:UpdateFunctionConfiguration", + "lambda:GetFunctionConfiguration" + ] + Resource = aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction.arn + }, + { + Effect = "Allow" + Action = "cloudformation:DescribeStacks" + Resource = "arn:${data.aws_partition.current.partition}:cloudformation:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:stack/*" + }, + { + Effect = "Allow" + Action = "s3:GetObject" + Resource = "arn:${data.aws_partition.current.partition}:s3:::${local.agentless_bucket_name}/${local.remote_functions_prefix_key}*" + } + ] + }) +} + +# The CloudGuardAWPCrossAccountRoleAttachment resource attaches the CloudGuardAWPCrossAccountRolePolicy to the CloudGuardAWPCrossAccountRole. +resource "aws_iam_role_policy_attachment" "CloudGuardAWPCrossAccountRoleAttachment" { + role = aws_iam_role.CloudGuardAWPCrossAccountRole.name + policy_arn = aws_iam_policy.CloudGuardAWP.arn +} +# end resources for CloudGuardAWPCrossAccountRole + +# Cross account role policy +# The CloudGuardAWPCrossAccountRolePolicy resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPCrossAccountRole. +resource "aws_iam_policy" "CloudGuardAWPCrossAccountRolePolicy" { + count = local.scan_mode == "inAccount" ? 1 : 0 + name = "CloudGuardAWPCrossAccountRolePolicy" + description = "Policy for CloudGuard AWP Cross Account Role" + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = [ + "ec2:CreateSecurityGroup", + "ec2:DescribeManagedPrefixLists", + "ec2:DescribeSecurityGroups", + "ec2:DescribeSecurityGroupRules", + "ec2:RevokeSecurityGroupEgress", + "ec2:AuthorizeSecurityGroupEgress", + "ec2:CreateTags", + ] + Resource = "*" + }, + { + Effect = "Allow" + Action = [ + "ec2:DeleteSecurityGroup", + ] + Resource = "*" + Condition = { + StringEquals = { + "aws:ResourceTag/Owner" = "CG.AWP" + } + } + }, + ] + }) +} + +# The CloudGuardAWPCrossAccountRolePolicy_SaaS resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPCrossAccountRole in SaaS mode. +resource "aws_iam_policy" "CloudGuardAWPCrossAccountRolePolicy_SaaS" { + count = local.scan_mode == "saas" ? 1 : 0 + name = "CloudGuardAWPCrossAccountRolePolicy_SaaS" + description = "Policy for CloudGuard AWP Cross Account Role - SaaS Mode" + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = [ + "kms:DescribeKey", + "kms:ReplicateKey", + ] + Resource = [aws_kms_key.CloudGuardAWPKey[count.index].arn] + }, + { + Effect = "Allow" + Action = [ + "kms:PutKeyPolicy", + "kms:ScheduleKeyDeletion", + "kms:CancelKeyDeletion", + "kms:TagResource", + ] + Resource = aws_kms_key.CloudGuardAWPKey[count.index].arn + }, + { + Effect = "Allow" + Action = [ + "kms:CreateKey", + ] + Resource = "*" + }, + ] + }) +} + +# The CloudGuardAWPCrossAccountRolePolicyAttachment resource attaches the CloudGuardAWPCrossAccountRolePolicy to the CloudGuardAWPCrossAccountRole. +resource "aws_iam_policy_attachment" "CloudGuardAWPCrossAccountRolePolicyAttachment" { + count = local.scan_mode == "inAccount" ? 1 : 0 + name = "CloudGuardAWPCrossAccountRolePolicyAttachment" + policy_arn = aws_iam_policy.CloudGuardAWPCrossAccountRolePolicy[count.index].arn + roles = [aws_iam_role.CloudGuardAWPCrossAccountRole.name] +} + +# The CloudGuardAWPCrossAccountRolePolicyAttachment_SaaS resource attaches the CloudGuardAWPCrossAccountRolePolicy_SaaS to the CloudGuardAWPCrossAccountRole. +resource "aws_iam_policy_attachment" "CloudGuardAWPCrossAccountRolePolicyAttachment_SaaS" { + count = local.scan_mode == "saas" ? 1 : 0 + name = "CloudGuardAWPCrossAccountRolePolicyAttachment_SaaS" + policy_arn = aws_iam_policy.CloudGuardAWPCrossAccountRolePolicy_SaaS[count.index].arn + roles = [aws_iam_role.CloudGuardAWPCrossAccountRole.name] +} +# END Cross account role policy + +# The CloudGuardAWPSnapshotsUtilsFunctionZip resource defines http data source to download the remote function file from S3 pre-signed URL. +data "http" "CloudGuardAWPSnapshotsUtilsFunctionZip" { + url = local.remote_snapshots_utils_function_s3_pre_signed_url + method = "GET" + request_headers = { + Accept = "application/zip" + } +} + +# The CloudGuardAWPSnapshotsUtilsFunctionZip resource defines a local file that is used to store the remote function file to be used in the lambda function. +resource "local_file" "CloudGuardAWPSnapshotsUtilsFunctionZip" { + filename = "${local.remote_snapshots_utils_function_name}7.zip" + content_base64 = data.http.CloudGuardAWPSnapshotsUtilsFunctionZip.response_body_base64 +} + +# AWP proxy lambda function +# The CloudGuardAWPSnapshotsUtilsFunction resource defines a lambda function that is used to manage remote actions and resources. +resource "aws_lambda_function" "CloudGuardAWPSnapshotsUtilsFunction" { + function_name = local.remote_snapshots_utils_function_name + handler = "snapshots_utils.lambda_handler" + description = "CloudGuard AWP Proxy for managing remote actions and resources" + role = aws_iam_role.CloudGuardAWPSnapshotsUtilsLambdaExecutionRole.arn + runtime = "python3.9" + memory_size = 256 + timeout = local.remote_snapshots_utils_function_time_out + filename = local_file.CloudGuardAWPSnapshotsUtilsFunctionZip.filename + + environment { + variables = { + CP_AWP_AWS_ACCOUNT = local.cloud_guard_backend_account_id + CP_AWP_MR_KMS_KEY_ID = local.scan_mode == "saas" ? aws_kms_key.CloudGuardAWPKey[0].arn : "" + CP_AWP_SCAN_MODE = local.scan_mode + CP_AWP_SECURITY_GROUP_NAME = local.awp_client_side_security_group_name + AWS_PARTITION = data.aws_partition.current.partition + CP_AWP_LOG_LEVEL = "DEBUG" + } + } + + tags = { + Owner = "CG.AWP" + } +} + +resource "aws_lambda_permission" "allow_cloudguard" { + statement_id = "AllowExecutionFromCloudGuard" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction.function_name + principal = "s3.amazonaws.com" + source_arn = "arn:${data.aws_partition.current.partition}:s3:::${local.agentless_bucket_name}/*" +} +# END AWP proxy lambda function + +# CloudGuardAWPSnapshotsUtilsLogGroup : The CloudWatch log group that is used to store the logs of the CloudGuardAWPSnapshotsUtilsFunction. +resource "aws_cloudwatch_log_group" "CloudGuardAWPSnapshotsUtilsLogGroup" { + name = "/aws/lambda/CloudGuardAWPSnapshotsUtils" + retention_in_days = 30 + depends_on = [ + aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction + ] +} + +# AWP proxy lambda function role +# The CloudGuardAWPSnapshotsUtilsLambdaExecutionRole resource defines an IAM role that is used to allow the CloudGuardAWPSnapshotsUtilsFunction to execute. +resource "aws_iam_role" "CloudGuardAWPSnapshotsUtilsLambdaExecutionRole" { + name = "CloudGuardAWPLambdaExecutionRole" + description = "CloudGuard AWP proxy lambda function execution role" + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Principal = { + Service = "lambda.amazonaws.com" + } + Action = "sts:AssumeRole" + } + ] + }) + + tags = { + Owner = "CG.AWP" + } +} + +# The CloudGuardAWPSnapshotsPolicy resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPSnapshotsUtilsFunction. +resource "aws_iam_policy" "CloudGuardAWPSnapshotsPolicy" { + name = "CloudGuardAWPSnapshotsPolicy" + description = "Policy for managing snapshots at client side and delete AWP keys" + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = [ + "ec2:CreateTags", + "ec2:CopySnapshot", + "ec2:CreateSnapshot", + "ec2:CreateSnapshots", + "ec2:DescribeSnapshots", + "ec2:DescribeRegions" + ] + Resource = "*" + }, + { + Effect = "Allow" + Action = [ + "ec2:DeleteSnapshot" + ] + Resource = "*" + Condition = { + StringEquals = { + "aws:ResourceTag/Owner" = "CG.AWP" + } + } + }, + { + Effect = "Allow" + Action = [ + "logs:CreateLogStream", + "logs:PutLogEvents" + ] + Resource = [aws_cloudwatch_log_group.CloudGuardAWPSnapshotsUtilsLogGroup.arn] + } + ] + }) +} + +# The CloudGuardAWPSnapshotsUtilsLambdaExecutionRoleAttachment resource attaches the CloudGuardAWPSnapshotsPolicy to the CloudGuardAWPSnapshotsUtilsLambdaExecutionRole. +resource "aws_iam_role_policy_attachment" "CloudGuardAWPSnapshotsUtilsLambdaExecutionRoleAttachment" { + role = aws_iam_role.CloudGuardAWPSnapshotsUtilsLambdaExecutionRole.name + policy_arn = aws_iam_policy.CloudGuardAWPSnapshotsPolicy.arn +} +# END AWP proxy lambda function role + +# AWP proxy lambda function role policy +# The CloudGuardAWPLambdaExecutionRolePolicy resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPSnapshotsUtilsFunction. +resource "aws_iam_policy" "CloudGuardAWPLambdaExecutionRolePolicy" { + count = local.scan_mode == "inAccount" ? 1 : 0 + name = "CloudGuardAWPLambdaExecutionRolePolicy" + description = "Policy for CloudGuard AWP Lambda Execution Role" + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = [ + "ec2:RunInstances", + ] + Resource = "*" + }, + { + Effect = "Allow" + Action = [ + "ec2:TerminateInstances", + "ec2:DeleteVolume", + ] + Resource = "*" + Condition = local.scan_mode == "inAccount" ? { + StringEquals = { + "aws:ResourceTag/Owner" = "CG.AWP" + } + } : null + }, + { + Effect = "Allow" + Action = [ + "iam:CreateServiceLinkedRole", + ] + Resource = ["arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:role/aws-service-role/spot.amazonaws.com/AWSServiceRoleForEC2Spot"] + }, + { + Effect = "Allow" + Action = [ + "kms:Decrypt", + "kms:DescribeKey", + "kms:GenerateDataKey*", + "kms:CreateGrant", + "kms:Encrypt", + "kms:ReEncrypt*", + ] + Resource = "*" + }, + { + Effect = "Allow" + Action = [ + "ec2:CreateVpc", + "ec2:CreateSecurityGroup", + "ec2:CreateSubnet", + "ec2:DescribeInstances", + "ec2:DescribeVolumes", + "ec2:DescribeVpcs", + "ec2:DescribeSubnets", + "ec2:DescribeRouteTables", + "ec2:DescribeNetworkAcls", + "ec2:DescribeSecurityGroups", + "ec2:DescribeInternetGateways", + "ec2:DescribeSecurityGroupRules", + "ec2:ModifySubnetAttribute", + "ec2:CreateVpcEndpoint", + "ec2:DescribeVpcEndpoints", + ] + Resource = "*" + }, + { + Effect = "Allow" + Action = [ + "ec2:AssociateRouteTable", + "ec2:DeleteVpc", + "ec2:DeleteSubnet", + "ec2:DeleteVolume", + "ec2:DeleteInternetGateway", + "ec2:RevokeSecurityGroupEgress", + "ec2:RevokeSecurityGroupIngress", + "ec2:AuthorizeSecurityGroupEgress", + "ec2:DeleteSecurityGroup", + "ec2:DeleteVpcEndpoints", + "ec2:CreateNetworkAclEntry", + ] + Resource = "*" + Condition = local.scan_mode == "inAccount" ? { + StringEquals = { + "aws:ResourceTag/Owner" = "CG.AWP" + } + } : null + }, + ] + }) +} + +# The CloudGuardAWPLambdaExecutionRolePolicyAttachment resource attaches the CloudGuardAWPLambdaExecutionRolePolicy to the CloudGuardAWPSnapshotsUtilsLambdaExecutionRole. +resource "aws_iam_policy" "CloudGuardAWPLambdaExecutionRolePolicy_SaaS" { + count = local.scan_mode == "saas" ? 1 : 0 + name = "CloudGuardAWPLambdaExecutionRolePolicy_SaaS" + description = "Policy for CloudGuard AWP Lambda Execution Role - SaaS Mode" + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = [ + "ec2:ModifySnapshotAttribute", + ] + Resource = "*" + }, + { + Effect = "Allow" + Action = [ + "kms:ReEncrypt*", + "kms:Encrypt", + ] + Resource = "*" + }, + { + Effect = "Allow" + Action = [ + "kms:Decrypt", + "kms:DescribeKey", + "kms:GenerateDataKey*", + "kms:CreateGrant", + ] + Resource = "*" + }, + { + Effect = "Allow" + Action = [ + "kms:ScheduleKeyDeletion", + ] + Resource = "*" + Condition = { + StringEquals = { + "aws:ResourceTag/Owner" = "CG.AWP" + } + } + }, + ] + }) +} + +# The CloudGuardAWPLambdaExecutionRolePolicyAttachment resource attaches the CloudGuardAWPLambdaExecutionRolePolicy to the CloudGuardAWPSnapshotsUtilsLambdaExecutionRole. +resource "aws_iam_policy_attachment" "CloudGuardAWPLambdaExecutionRolePolicyAttachment" { + count = local.scan_mode == "inAccount" ? 1 : 0 + name = "CloudGuardAWPLambdaExecutionRolePolicyAttachment" + policy_arn = aws_iam_policy.CloudGuardAWPLambdaExecutionRolePolicy[count.index].arn + roles = [aws_iam_role.CloudGuardAWPSnapshotsUtilsLambdaExecutionRole.name] +} + +# The CloudGuardAWPLambdaExecutionRolePolicyAttachment_SaaS resource attaches the CloudGuardAWPLambdaExecutionRolePolicy_SaaS to the CloudGuardAWPSnapshotsUtilsLambdaExecutionRole. +resource "aws_iam_policy_attachment" "CloudGuardAWPLambdaExecutionRolePolicyAttachment_SaaS" { + count = local.scan_mode == "saas" ? 1 : 0 + name = "CloudGuardAWPLambdaExecutionRolePolicyAttachment" + policy_arn = aws_iam_policy.CloudGuardAWPLambdaExecutionRolePolicy_SaaS[count.index].arn + roles = [aws_iam_role.CloudGuardAWPSnapshotsUtilsLambdaExecutionRole.name] +} +# END AWP proxy lambda function role policy + +# aws_lambda_invocation : The Lambda invocation that is used to clean up the resources after the onboarding process. +resource "aws_lambda_invocation" "CloudGuardAWPSnapshotsUtilsCleanupFunctionInvocation" { + function_name = aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction.function_name + input = jsonencode({ + "target_account_id" : data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cloud_account_id + }) + lifecycle_scope = "CRUD" + depends_on = [ + aws_iam_policy_attachment.CloudGuardAWPLambdaExecutionRolePolicyAttachment, + aws_iam_policy_attachment.CloudGuardAWPLambdaExecutionRolePolicyAttachment_SaaS + ] +} + +# AWP MR key for snapshot re-encryption +# The CloudGuardAWPKey resource defines a KMS key that is used to re-encrypt the snapshots in SaaS mode. +resource "aws_kms_key" "CloudGuardAWPKey" { + count = local.scan_mode == "saas" ? 1 : 0 + description = "CloudGuard AWP Multi-Region primary key for snapshots re-encryption (for Saas mode only)" + enable_key_rotation = true + deletion_window_in_days = 7 + + # Conditionally set multi-region based on IsChinaPartition + multi_region = data.aws_partition.current.partition == "aws-cn" ? false : true + + policy = jsonencode({ + Version = "2012-10-17" + Id = "cloud-guard-awp-key" + Statement = [ + { + Sid = "Enable IAM User Permissions" + Effect = "Allow" + Principal = { + AWS = "arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:root" + } + Action = "kms:*" + Resource = "*" + }, + { + Sid = "Allow usage of the key" + Effect = "Allow" + Principal = { + AWS = "arn:${data.aws_partition.current.partition}:iam::${local.cloud_guard_backend_account_id}:root" + } + Action = [ + "kms:DescribeKey", + "kms:Encrypt", + "kms:Decrypt", + "kms:ReEncrypt*", + "kms:GenerateDataKey*", + "kms:PutKeyPolicy", + "kms:ScheduleKeyDeletion", + "kms:CancelKeyDeletion", + ] + Resource = "*" + }, + { + Sid = "Allow attachment of persistent resources" + Effect = "Allow" + Principal = { + AWS = "arn:${data.aws_partition.current.partition}:iam::${local.cloud_guard_backend_account_id}:root" + } + Action = [ + "kms:CreateGrant", + "kms:ListGrants", + "kms:RevokeGrant", + ] + Resource = "*" + Condition = { + Bool = { + "kms:GrantIsForAWSResource" = true + } + } + }, + ] + }) +} +#END AWP MR key for snapshot re-encryption + +# The CloudGuardAWPKeyAlias resource defines a KMS key alias that is used to reference the KMS key in SaaS mode. +resource "aws_kms_alias" "CloudGuardAWPKeyAlias" { + count = local.scan_mode == "saas" ? 1 : 0 + name = "alias/CloudGuardAWPKey" + target_key_id = aws_kms_key.CloudGuardAWPKey[count.index].arn + depends_on = [ + aws_kms_key.CloudGuardAWPKey + ] +} + +# The dome9_awp_aws_onboarding resource defines a Dome9 AWP AWS Onboarding. +# The Dome9 AWP AWS Onboarding resource allows you to onboard an AWS account to Dome9 AWP. +# The cloudguard_account_id attribute is used to specify the CloudGuard account id of the AWS account. +# The cross_account_role_name attribute is used to specify the name of the cross account role that is used to allow AWP to access the AWS account. +# The cross_account_role_external_id attribute is used to specify the external id of the cross account role that is used to allow AWP to access the AWS account. +# The scan_mode attribute is used to specify the scan mode of the Dome9 AWP AWS Onboarding. The valid values are "inAccount" and "saas". +# The agentless_account_settings attribute is used to specify the agentless account settings of the Dome9 AWP AWS Onboarding. +# The disabled_regions attribute is used to specify the disabled regions of the agentless account settings of the Dome9 AWP AWS Onboarding. +# The scan_machine_interval_in_hours attribute is used to specify the scan machine interval in hours of the agentless account settings of the Dome9 AWP AWS Onboarding. +# The max_concurrence_scans_per_region attribute is used to specify the max concurrence scans per region of the agentless account settings of the Dome9 AWP AWS Onboarding. +# The skip_function_apps_scan attribute is used to specify whether to skip the function apps scan of the agentless account settings of the Dome9 AWP AWS Onboarding. +# The custom_tags attribute is used to specify the custom tags of the agentless account settings of the Dome9 AWP AWS Onboarding. +resource "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { + cloudguard_account_id = "CLOUDGUARD_ACCOUNT_ID or EXTERNAL_AWS_ACCOUNT_NUMBER" + cross_account_role_name = aws_iam_role.CloudGuardAWPCrossAccountRole.name + cross_account_role_external_id = local.cross_account_role_external_id + scan_mode = local.scan_mode agentless_account_settings { - disabled_regions = ["us-east-1", "us-west-1"] + disabled_regions = ["us-east-1", "us-west-1", "ap-northeast-1", "ap-southeast-2"] scan_machine_interval_in_hours = 24 max_concurrence_scans_per_region = 6 skip_function_apps_scan = true custom_tags = { tag1 = "value1" tag2 = "value2" + tag3 = "value3" } } + depends_on = [ + aws_iam_policy_attachment.CloudGuardAWPLambdaExecutionRolePolicyAttachment, + aws_iam_policy_attachment.CloudGuardAWPLambdaExecutionRolePolicyAttachment_SaaS, + aws_iam_role.CloudGuardAWPCrossAccountRole, + aws_iam_role_policy_attachment.CloudGuardAWPCrossAccountRoleAttachment + ] } +# The dome9_awp_aws_onboarding data source allows you to get the onboarding data of an AWS account. +data "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { + id = dome9_awp_aws_onboarding.awp_aws_onboarding_test.cloudguard_account_id + depends_on = [ + dome9_awp_aws_onboarding.awp_aws_onboarding_test + ] +} ``` ## Argument Reference From 933657a9c910567fe4292a2bd41af19e4c3fa37b Mon Sep 17 00:00:00 2001 From: Omar Date: Mon, 25 Mar 2024 05:59:29 +0200 Subject: [PATCH 32/47] after CRs --- .../environment_variable.go | 2 +- examples/awp_aws_onboarding/main.tf | 46 +++++++++++-------- .../docs/r/awp_aws_onboarding.html.markdown | 46 +++++++++++-------- 3 files changed, 57 insertions(+), 37 deletions(-) diff --git a/dome9/common/testing/environmentvariable/environment_variable.go b/dome9/common/testing/environmentvariable/environment_variable.go index fc708e39..92b7d25f 100644 --- a/dome9/common/testing/environmentvariable/environment_variable.go +++ b/dome9/common/testing/environmentvariable/environment_variable.go @@ -23,7 +23,7 @@ const ( CloudAccountAWSEnvVarArn = "ARN" CloudAccountUpdatedAWSEnvVarArn = "ARN_UPDATE" CloudAccountAWSEnvVarSecret = "SECRET" - AwpAwsCrossAccountRoleExternalIdEnvVar = "AWP_EXTERNAL_ID" + AwpAwsCrossAccountRoleExternalIdEnvVar = "AWP_EXTERNAL_ID" // it is backed up by this ssm parameter : arn:aws:ssm:us-east-1:969432878134:parameter/dome9/common/consec/automation/CrossAccountRoleExternalId ) // Azure environment variable diff --git a/examples/awp_aws_onboarding/main.tf b/examples/awp_aws_onboarding/main.tf index 845333ee..0941f9a9 100644 --- a/examples/awp_aws_onboarding/main.tf +++ b/examples/awp_aws_onboarding/main.tf @@ -1,3 +1,5 @@ +# This is an example of how to use the Dome9 AWP AWS Onboarding Terraform provider. +## Providers ## # Required Providers Configuration Block for Dome9, AWS, HTTP, and Local terraform { required_providers { @@ -47,6 +49,8 @@ provider "aws" { token = "AWS_SESSION_TOKEN" } +## CloudGuard Account Onboarding (Pre-requisite) ## + # The resource block defines a Dome9 AWS Cloud Account onboarding. # The Dome9 AWS Cloud Account onboarding resource allows you to onboard an AWS account to Dome9. # this resource is optional and can be ignored and you need to pass CloudGuard account id Dome9 AWP AWS Onboarding resource and "dome9_awp_aws_get_onboarding_data" data source. @@ -54,8 +58,8 @@ provider "aws" { resource "dome9_cloudaccount_aws" "aws_onboarding_account_test" { name = "aws_onboarding_account_test" credentials { - arn = "arn:aws:iam::478980137264:role/CloudGuard-Connect" - secret = "@R2PUjk0up42HHDtD9CByVF8" + arn = "arn:aws:iam:::role/CloudGuard-Connect" + secret = "" type = "RoleBased" } net_sec { @@ -67,6 +71,8 @@ resource "dome9_cloudaccount_aws" "aws_onboarding_account_test" { } */ +## CloudGuard AWP Configuration ## + # The dome9_awp_aws_get_onboarding_data data source allows you to get the onboarding data of an AWS account. # you can pass the CloudGuard account id to get the onboarding data of the AWS account or the external account number for the AWS account. data "dome9_awp_aws_get_onboarding_data" "dome9_awp_aws_onboarding_data_source" { @@ -77,8 +83,7 @@ data "dome9_awp_aws_get_onboarding_data" "dome9_awp_aws_onboarding_data_source" # the scan_mode is used to define the scan mode of the Dome9 AWP AWS Onboarding. # the valid values are "inAccount" and "saas". you need to select one of them based on the scan mode of the Dome9 AWP AWS Onboarding. locals { - scan_mode = "inAccount or saas" # the valid values are "inAccount" and "saas" when onboarding the AWS account to Dome9 AWP. - stage = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.stage + scan_mode = "inAccount|saas" # the valid values are "inAccount" and "saas" when onboarding the AWS account to Dome9 AWP. stage = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.stage region = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.region cloud_guard_backend_account_id = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cloud_guard_backend_account_id agentless_bucket_name = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.agentless_bucket_name @@ -135,6 +140,9 @@ resource "aws_iam_role" "CloudGuardAWPCrossAccountRole" { depends_on = [aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction] } +## CloudGuard AWP Resources ## +// Note: count - Used as condition to create resources based on the scan mode. + # The CloudGuardAWPCrossAccountRolePolicy resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPCrossAccountRole. resource "aws_iam_policy" "CloudGuardAWP" { name = "CloudGuardAWP" @@ -317,7 +325,6 @@ resource "aws_lambda_function" "CloudGuardAWPSnapshotsUtilsFunction" { CP_AWP_SCAN_MODE = local.scan_mode CP_AWP_SECURITY_GROUP_NAME = local.awp_client_side_security_group_name AWS_PARTITION = data.aws_partition.current.partition - CP_AWP_LOG_LEVEL = "DEBUG" } } @@ -682,21 +689,24 @@ resource "aws_kms_alias" "CloudGuardAWPKeyAlias" { # The skip_function_apps_scan attribute is used to specify whether to skip the function apps scan of the agentless account settings of the Dome9 AWP AWS Onboarding. # The custom_tags attribute is used to specify the custom tags of the agentless account settings of the Dome9 AWP AWS Onboarding. resource "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { - cloudguard_account_id = "CLOUDGUARD_ACCOUNT_ID or EXTERNAL_AWS_ACCOUNT_NUMBER" + cloudguard_account_id = "dome9_cloudaccount_aws.aws_onboarding_account_test.id | | " cross_account_role_name = aws_iam_role.CloudGuardAWPCrossAccountRole.name cross_account_role_external_id = local.cross_account_role_external_id scan_mode = local.scan_mode - agentless_account_settings { - disabled_regions = ["us-east-1", "us-west-1", "ap-northeast-1", "ap-southeast-2"] - scan_machine_interval_in_hours = 24 - max_concurrence_scans_per_region = 6 - skip_function_apps_scan = true - custom_tags = { - tag1 = "value1" - tag2 = "value2" - tag3 = "value3" - } - } + # Optional Settings + # e.g: + # agentless_account_settings { + # disabled_regions = [] // e.g: ["us-west-1", "us-west-2"] + # scan_machine_interval_in_hours = 24 + # max_concurrence_scans_per_region = 20 + # skip_function_apps_scan = false + # custom_tags = { + # # example of custom tags + # tag1 = "value1" + # tag2 = "value2" + # tag3 = "value3" + # } + # } depends_on = [ aws_iam_policy_attachment.CloudGuardAWPLambdaExecutionRolePolicyAttachment, aws_iam_policy_attachment.CloudGuardAWPLambdaExecutionRolePolicyAttachment_SaaS, @@ -705,7 +715,7 @@ resource "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { ] } -# The dome9_awp_aws_onboarding data source allows you to get the onboarding data of an AWS account. +# The dome9_awp_aws_onboarding data source allows you to get the onboarding data of an AWS account (Optional). data "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { id = dome9_awp_aws_onboarding.awp_aws_onboarding_test.cloudguard_account_id depends_on = [ diff --git a/website/docs/r/awp_aws_onboarding.html.markdown b/website/docs/r/awp_aws_onboarding.html.markdown index aadb957b..4ea195dc 100644 --- a/website/docs/r/awp_aws_onboarding.html.markdown +++ b/website/docs/r/awp_aws_onboarding.html.markdown @@ -15,6 +15,8 @@ This resource is used to create and modify AWP AWS Onboarding in CloudGuard Dome Basic usage: ```hcl +# This is an example of how to use the Dome9 AWP AWS Onboarding Terraform provider. +## Providers ## # Required Providers Configuration Block for Dome9, AWS, HTTP, and Local terraform { required_providers { @@ -64,6 +66,8 @@ provider "aws" { token = "AWS_SESSION_TOKEN" } +## CloudGuard Account Onboarding (Pre-requisite) ## + # The resource block defines a Dome9 AWS Cloud Account onboarding. # The Dome9 AWS Cloud Account onboarding resource allows you to onboard an AWS account to Dome9. # this resource is optional and can be ignored and you need to pass CloudGuard account id Dome9 AWP AWS Onboarding resource and "dome9_awp_aws_get_onboarding_data" data source. @@ -71,8 +75,8 @@ provider "aws" { resource "dome9_cloudaccount_aws" "aws_onboarding_account_test" { name = "aws_onboarding_account_test" credentials { - arn = "arn:aws:iam::478980137264:role/CloudGuard-Connect" - secret = "@R2PUjk0up42HHDtD9CByVF8" + arn = "arn:aws:iam:::role/CloudGuard-Connect" + secret = "" type = "RoleBased" } net_sec { @@ -84,6 +88,8 @@ resource "dome9_cloudaccount_aws" "aws_onboarding_account_test" { } */ +## CloudGuard AWP Configuration ## + # The dome9_awp_aws_get_onboarding_data data source allows you to get the onboarding data of an AWS account. # you can pass the CloudGuard account id to get the onboarding data of the AWS account or the external account number for the AWS account. data "dome9_awp_aws_get_onboarding_data" "dome9_awp_aws_onboarding_data_source" { @@ -94,8 +100,7 @@ data "dome9_awp_aws_get_onboarding_data" "dome9_awp_aws_onboarding_data_source" # the scan_mode is used to define the scan mode of the Dome9 AWP AWS Onboarding. # the valid values are "inAccount" and "saas". you need to select one of them based on the scan mode of the Dome9 AWP AWS Onboarding. locals { - scan_mode = "inAccount or saas" # the valid values are "inAccount" and "saas" when onboarding the AWS account to Dome9 AWP. - stage = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.stage + scan_mode = "inAccount|saas" # the valid values are "inAccount" and "saas" when onboarding the AWS account to Dome9 AWP. stage = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.stage region = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.region cloud_guard_backend_account_id = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cloud_guard_backend_account_id agentless_bucket_name = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.agentless_bucket_name @@ -152,6 +157,9 @@ resource "aws_iam_role" "CloudGuardAWPCrossAccountRole" { depends_on = [aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction] } +## CloudGuard AWP Resources ## +// Note: count - Used as condition to create resources based on the scan mode. + # The CloudGuardAWPCrossAccountRolePolicy resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPCrossAccountRole. resource "aws_iam_policy" "CloudGuardAWP" { name = "CloudGuardAWP" @@ -334,7 +342,6 @@ resource "aws_lambda_function" "CloudGuardAWPSnapshotsUtilsFunction" { CP_AWP_SCAN_MODE = local.scan_mode CP_AWP_SECURITY_GROUP_NAME = local.awp_client_side_security_group_name AWS_PARTITION = data.aws_partition.current.partition - CP_AWP_LOG_LEVEL = "DEBUG" } } @@ -699,21 +706,24 @@ resource "aws_kms_alias" "CloudGuardAWPKeyAlias" { # The skip_function_apps_scan attribute is used to specify whether to skip the function apps scan of the agentless account settings of the Dome9 AWP AWS Onboarding. # The custom_tags attribute is used to specify the custom tags of the agentless account settings of the Dome9 AWP AWS Onboarding. resource "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { - cloudguard_account_id = "CLOUDGUARD_ACCOUNT_ID or EXTERNAL_AWS_ACCOUNT_NUMBER" + cloudguard_account_id = "dome9_cloudaccount_aws.aws_onboarding_account_test.id | | " cross_account_role_name = aws_iam_role.CloudGuardAWPCrossAccountRole.name cross_account_role_external_id = local.cross_account_role_external_id scan_mode = local.scan_mode - agentless_account_settings { - disabled_regions = ["us-east-1", "us-west-1", "ap-northeast-1", "ap-southeast-2"] - scan_machine_interval_in_hours = 24 - max_concurrence_scans_per_region = 6 - skip_function_apps_scan = true - custom_tags = { - tag1 = "value1" - tag2 = "value2" - tag3 = "value3" - } - } + # Optional Settings + # e.g: + # agentless_account_settings { + # disabled_regions = [] // e.g: ["us-west-1", "us-west-2"] + # scan_machine_interval_in_hours = 24 + # max_concurrence_scans_per_region = 20 + # skip_function_apps_scan = false + # custom_tags = { + # # example of custom tags + # tag1 = "value1" + # tag2 = "value2" + # tag3 = "value3" + # } + # } depends_on = [ aws_iam_policy_attachment.CloudGuardAWPLambdaExecutionRolePolicyAttachment, aws_iam_policy_attachment.CloudGuardAWPLambdaExecutionRolePolicyAttachment_SaaS, @@ -722,7 +732,7 @@ resource "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { ] } -# The dome9_awp_aws_onboarding data source allows you to get the onboarding data of an AWS account. +# The dome9_awp_aws_onboarding data source allows you to get the onboarding data of an AWS account (Optional). data "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { id = dome9_awp_aws_onboarding.awp_aws_onboarding_test.cloudguard_account_id depends_on = [ From 4f049bd62c23f53c55c8d1d217087ed8f5bcee39 Mon Sep 17 00:00:00 2001 From: Omar Date: Mon, 25 Mar 2024 13:04:17 +0200 Subject: [PATCH 33/47] update dome9-sdk-go to v1.18.4 to support awp aws onboarding --- go.mod | 2 +- go.sum | 4 ++-- vendor/modules.txt | 3 ++- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index cf80996d..b4a287ee 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,6 @@ module github.com/terraform-providers/terraform-provider-dome9 go 1.13 require ( - github.com/dome9/dome9-sdk-go v1.18.3 + github.com/dome9/dome9-sdk-go v1.18.4 github.com/hashicorp/terraform-plugin-sdk v1.1.0 ) diff --git a/go.sum b/go.sum index 3057c5ca..a130febd 100644 --- a/go.sum +++ b/go.sum @@ -35,8 +35,8 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dome9/dome9-sdk-go v1.18.3 h1:KqGg1OQzAxLmwTCkx64GZU8J/mrCeZKYrWfOyyVFn1A= -github.com/dome9/dome9-sdk-go v1.18.3/go.mod h1:CF7nXCQk74ApsoG2i1+ziC/pnnnsyMeG6Mpho8cRAGM= +github.com/dome9/dome9-sdk-go v1.18.4 h1:Krml7YzbGRLHp4O3hNh1/a12Xk5pPJpya7W0ixIyIVQ= +github.com/dome9/dome9-sdk-go v1.18.4/go.mod h1:CF7nXCQk74ApsoG2i1+ziC/pnnnsyMeG6Mpho8cRAGM= github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= diff --git a/vendor/modules.txt b/vendor/modules.txt index 99c13ca2..59947aa7 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -56,11 +56,12 @@ github.com/bgentry/go-netrc/netrc github.com/bgentry/speakeasy # github.com/davecgh/go-spew v1.1.1 github.com/davecgh/go-spew/spew -# github.com/dome9/dome9-sdk-go v1.18.3 +# github.com/dome9/dome9-sdk-go v1.18.4 github.com/dome9/dome9-sdk-go/dome9 github.com/dome9/dome9-sdk-go/dome9/client github.com/dome9/dome9-sdk-go/services/admissioncontrol/admission_policy github.com/dome9/dome9-sdk-go/services/assessment +github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding github.com/dome9/dome9-sdk-go/services/cloudaccounts github.com/dome9/dome9-sdk-go/services/cloudaccounts/alibaba github.com/dome9/dome9-sdk-go/services/cloudaccounts/aws From 7bbc5c38eede5b5929424efa9cbbeda8f6ddf53c Mon Sep 17 00:00:00 2001 From: Omar Date: Wed, 27 Mar 2024 01:41:10 +0200 Subject: [PATCH 34/47] Fix agentless account settings when running apply another time --- dome9/resource_dome9_awp_aws_onboarding.go | 23 ++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index 3b817b01..4780be57 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -220,10 +220,9 @@ func resourceAWPAWSOnboardingRead(d *schema.ResourceData, meta interface{}) erro _ = d.Set("is_org_onboarding", resp.IsOrgOnboarding) _ = d.Set("centralized_cloud_account_id", resp.CentralizedCloudAccountId) - if resp.AgentlessAccountSettings != nil { - if err := d.Set("agentless_account_settings", flattenAgentlessAccountSettings(resp.AgentlessAccountSettings)); err != nil { - return err - } + err = setAgentlessAccountSettings(resp, d) + if err != nil { + return err } if resp.AccountIssues != nil { @@ -301,6 +300,22 @@ func expandAgentlessAccountSettings(d *schema.ResourceData) (*awp_aws_onboarding return agentlessAccountSettings, nil } +func setAgentlessAccountSettings(resp *awp_aws_onboarding.GetAWPOnboardingResponse, d *schema.ResourceData) error { + if resp.AgentlessAccountSettings != nil { + // Check if all fields of AgentlessAccountSettings are nil + if resp.AgentlessAccountSettings.DisabledRegions != nil || + resp.AgentlessAccountSettings.ScanMachineIntervalInHours != 0 || + resp.AgentlessAccountSettings.MaxConcurrenceScansPerRegion != 0 || + resp.AgentlessAccountSettings.SkipFunctionAppsScan != false || + resp.AgentlessAccountSettings.CustomTags != nil { + if err := d.Set("agentless_account_settings", flattenAgentlessAccountSettings(resp.AgentlessAccountSettings)); err != nil { + return err + } + } + } + return nil +} + func flattenAgentlessAccountSettings(settings *awp_aws_onboarding.AgentlessAccountSettings) []interface{} { m := map[string]interface{}{ From 1375f4f322d6e4885bdc9e4287f4e8b8d5f498ef Mon Sep 17 00:00:00 2001 From: Omar Date: Fri, 29 Mar 2024 04:35:37 +0300 Subject: [PATCH 35/47] add validation for ScanMachineIntervalInHours & MaxConcurrenceScansPerRegion --- dome9/resource_dome9_awp_aws_onboarding.go | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index 4780be57..f77caa50 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -254,13 +254,21 @@ func expandAgentlessAccountSettings(d *schema.ResourceData) (*awp_aws_onboarding } agentlessAccountSettingsList := d.Get("agentless_account_settings").([]interface{}) agentlessAccountSettingsMap := agentlessAccountSettingsList[0].(map[string]interface{}) + scanMode := d.Get("scan_mode").(string) + + var scanMachineIntervalInHours int + if scanMode == "saas" { + scanMachineIntervalInHours = 24 + } else { + scanMachineIntervalInHours = 4 + } // Initialize the AgentlessAccountSettings struct with default values agentlessAccountSettings := &awp_aws_onboarding.AgentlessAccountSettings{ DisabledRegions: make([]string, 0), CustomTags: make(map[string]string), - ScanMachineIntervalInHours: 4, - MaxConcurrenceScansPerRegion: 1, + ScanMachineIntervalInHours: scanMachineIntervalInHours, + MaxConcurrenceScansPerRegion: 20, SkipFunctionAppsScan: true, } @@ -278,10 +286,18 @@ func expandAgentlessAccountSettings(d *schema.ResourceData) (*awp_aws_onboarding } if scanMachineInterval, ok := agentlessAccountSettingsMap["scan_machine_interval_in_hours"].(int); ok { + if scanMode == "saas" && (scanMachineInterval < 24 || scanMachineInterval > 1000) { + return nil, fmt.Errorf("scan_machine_interval_in_hours must be between 24 and 1000 for saas mode") + } else if scanMode == "inAccount" && (scanMachineInterval < 4 || scanMachineInterval > 1000) { + return nil, fmt.Errorf("scan_machine_interval_in_hours must be between 4 and 1000 for inAccount mode") + } agentlessAccountSettings.ScanMachineIntervalInHours = scanMachineInterval } if maxConcurrenceScans, ok := agentlessAccountSettingsMap["max_concurrence_scans_per_region"].(int); ok { + if maxConcurrenceScans < 1 || maxConcurrenceScans > 20 { + return nil, fmt.Errorf("max_concurrence_scans_per_region must be between 1 and 20") + } agentlessAccountSettings.MaxConcurrenceScansPerRegion = maxConcurrenceScans } From f97022802b1295edc3d74922571e114ae5b1a893 Mon Sep 17 00:00:00 2001 From: Omar Date: Mon, 1 Apr 2024 14:23:11 +0300 Subject: [PATCH 36/47] After CR + Adapt use of the new module --- dome9/common/resourcetype/resource_type.go | 2 +- dome9/common/testing/variable/variable.go | 2 +- dome9/data_source_dome9_awp_aws_onboarding.go | 4 - ...ta_source_dome9_awp_aws_onboarding_test.go | 1 - dome9/resource_dome9_awp_aws_onboarding.go | 10 - .../resource_dome9_awp_aws_onboarding_test.go | 7 +- examples/awp_aws_onboarding/README.md | 2 +- examples/awp_aws_onboarding/main.tf | 706 +---------------- examples/awp_azure_onboarding/main.tf | 266 ------- ... => awp_aws_onboarding_data.html.markdown} | 2 +- .../docs/r/awp_aws_onboarding.html.markdown | 724 +----------------- 11 files changed, 77 insertions(+), 1649 deletions(-) delete mode 100644 examples/awp_azure_onboarding/main.tf rename website/docs/d/{awp_aws_get_onboarding_data.html.markdown => awp_aws_onboarding_data.html.markdown} (97%) diff --git a/dome9/common/resourcetype/resource_type.go b/dome9/common/resourcetype/resource_type.go index c39d38e1..5e6f96f4 100644 --- a/dome9/common/resourcetype/resource_type.go +++ b/dome9/common/resourcetype/resource_type.go @@ -27,6 +27,6 @@ const ( AdmissionControlPolicy = "dome9_admission_control_policy" Assessment = "dome9_assessment" ImageAssurancePolicy = "dome9_image_assurance_policy" - AwpAwsGetOnboardingData = "dome9_awp_aws_get_onboarding_data" + AwpAwsGetOnboardingData = "dome9_awp_aws_onboarding_data" AwpAwsOnboarding = "dome9_awp_aws_onboarding" ) diff --git a/dome9/common/testing/variable/variable.go b/dome9/common/testing/variable/variable.go index e6a8bbc3..2bde80bd 100644 --- a/dome9/common/testing/variable/variable.go +++ b/dome9/common/testing/variable/variable.go @@ -221,7 +221,7 @@ const ( DisabledRegionsUpdate = `["us-east-1", "us-west-1", "ap-northeast-1", "ap-southeast-2"]` ScanMachineIntervalInHours = "6" ScanMachineIntervalInHoursUpdate = "10" - MaxConcurrenceScansPerRegion = "4" + MaxConcurrencyScansPerRegion = "4" MaxConcurrenceScansPerRegionUpdate = "8" CustomTags = `{ tag1 = "value1" diff --git a/dome9/data_source_dome9_awp_aws_onboarding.go b/dome9/data_source_dome9_awp_aws_onboarding.go index 246a90a5..3ef6111e 100644 --- a/dome9/data_source_dome9_awp_aws_onboarding.go +++ b/dome9/data_source_dome9_awp_aws_onboarding.go @@ -42,10 +42,6 @@ func dataSourceAwpAwsOnboarding() *schema.Resource { Type: schema.TypeInt, Computed: true, }, - "skip_function_apps_scan": { - Type: schema.TypeBool, - Computed: true, - }, "custom_tags": { Type: schema.TypeMap, Computed: true, diff --git a/dome9/data_source_dome9_awp_aws_onboarding_test.go b/dome9/data_source_dome9_awp_aws_onboarding_test.go index 1aa54d17..c9de1ca5 100644 --- a/dome9/data_source_dome9_awp_aws_onboarding_test.go +++ b/dome9/data_source_dome9_awp_aws_onboarding_test.go @@ -36,7 +36,6 @@ func TestAccDataSourceAwpAwsOnboardingBasic(t *testing.T) { resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "agentless_account_settings.0.disabled_regions.1", awpAwsOnboardingResourceTypeAndName, "agentless_account_settings.0.disabled_regions.1"), resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "agentless_account_settings.0.scan_machine_interval_in_hours", awpAwsOnboardingResourceTypeAndName, "agentless_account_settings.0.scan_machine_interval_in_hours"), resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "agentless_account_settings.0.max_concurrence_scans_per_region", awpAwsOnboardingResourceTypeAndName, "agentless_account_settings.0.max_concurrence_scans_per_region"), - resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "agentless_account_settings.0.skip_function_apps_scan", awpAwsOnboardingResourceTypeAndName, "agentless_account_settings.0.skip_function_apps_scan"), resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "agentless_account_settings.0.custom_tags.%", awpAwsOnboardingResourceTypeAndName, "agentless_account_settings.0.custom_tags.%"), resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "missing_awp_private_network_regions", awpAwsOnboardingResourceTypeAndName, "missing_awp_private_network_regions"), resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "agentless_protection_enabled", awpAwsOnboardingResourceTypeAndName, "agentless_protection_enabled"), diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index f77caa50..985225da 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -73,10 +73,6 @@ func resourceAwpAwsOnboarding() *schema.Resource { Optional: true, Default: 1, }, - "skip_function_apps_scan": { - Type: schema.TypeBool, - Optional: true, - }, "custom_tags": { Type: schema.TypeMap, Optional: true, @@ -269,7 +265,6 @@ func expandAgentlessAccountSettings(d *schema.ResourceData) (*awp_aws_onboarding CustomTags: make(map[string]string), ScanMachineIntervalInHours: scanMachineIntervalInHours, MaxConcurrenceScansPerRegion: 20, - SkipFunctionAppsScan: true, } // Check if the key exists and is not nil @@ -301,10 +296,6 @@ func expandAgentlessAccountSettings(d *schema.ResourceData) (*awp_aws_onboarding agentlessAccountSettings.MaxConcurrenceScansPerRegion = maxConcurrenceScans } - if skipFunctionAppsScan, ok := agentlessAccountSettingsMap["skip_function_apps_scan"].(bool); ok { - agentlessAccountSettings.SkipFunctionAppsScan = skipFunctionAppsScan - } - if customTagsInterface, ok := agentlessAccountSettingsMap["custom_tags"].(map[string]interface{}); ok { customTags := make(map[string]string) for k, v := range customTagsInterface { @@ -338,7 +329,6 @@ func flattenAgentlessAccountSettings(settings *awp_aws_onboarding.AgentlessAccou "disabled_regions": settings.DisabledRegions, "scan_machine_interval_in_hours": settings.ScanMachineIntervalInHours, "max_concurrence_scans_per_region": settings.MaxConcurrenceScansPerRegion, - "skip_function_apps_scan": settings.SkipFunctionAppsScan, "custom_tags": settings.CustomTags, } return []interface{}{m} diff --git a/dome9/resource_dome9_awp_aws_onboarding_test.go b/dome9/resource_dome9_awp_aws_onboarding_test.go index 64d402e4..5626156f 100644 --- a/dome9/resource_dome9_awp_aws_onboarding_test.go +++ b/dome9/resource_dome9_awp_aws_onboarding_test.go @@ -48,8 +48,7 @@ func TestAccResourceAWPAWSOnboardingBasic(t *testing.T) { resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions.0", disabledRegion1), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions.1", disabledRegion2), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.scan_machine_interval_in_hours", variable.ScanMachineIntervalInHours), - resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.max_concurrence_scans_per_region", variable.MaxConcurrenceScansPerRegion), - resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.skip_function_apps_scan", "true"), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.max_concurrence_scans_per_region", variable.MaxConcurrencyScansPerRegion), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.custom_tags.%", "2"), resource.TestCheckResourceAttrSet(resourceTypeAndName, "id"), resource.TestCheckResourceAttr(resourceTypeAndName, "cloud_provider", "aws"), @@ -71,7 +70,6 @@ func TestAccResourceAWPAWSOnboardingBasic(t *testing.T) { resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions.3", disabledRegionUpdate4), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.scan_machine_interval_in_hours", variable.ScanMachineIntervalInHoursUpdate), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.max_concurrence_scans_per_region", variable.MaxConcurrenceScansPerRegionUpdate), - resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.skip_function_apps_scan", "true"), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.custom_tags.%", "3"), resource.TestCheckResourceAttrSet(resourceTypeAndName, "id"), resource.TestCheckResourceAttr(resourceTypeAndName, "cloud_provider", "aws"), @@ -156,7 +154,6 @@ resource "%s" "%s" { disabled_regions = %s scan_machine_interval_in_hours = "%s" max_concurrence_scans_per_region = "%s" - skip_function_apps_scan = "true" custom_tags = %s } } @@ -169,7 +166,7 @@ resource "%s" "%s" { variable.ScanMode, IfThenElse(updateAction, variable.DisabledRegionsUpdate, variable.DisabledRegions), IfThenElse(updateAction, variable.ScanMachineIntervalInHoursUpdate, variable.ScanMachineIntervalInHours), - IfThenElse(updateAction, variable.MaxConcurrenceScansPerRegionUpdate, variable.MaxConcurrenceScansPerRegion), + IfThenElse(updateAction, variable.MaxConcurrenceScansPerRegionUpdate, variable.MaxConcurrencyScansPerRegion), IfThenElse(updateAction, variable.CustomTagsUpdate, variable.CustomTags), ) } diff --git a/examples/awp_aws_onboarding/README.md b/examples/awp_aws_onboarding/README.md index 132548e9..90a74d60 100644 --- a/examples/awp_aws_onboarding/README.md +++ b/examples/awp_aws_onboarding/README.md @@ -1,4 +1,4 @@ -# Attach IAM safe Example +# AWP AWS Onboarding Example This example will show you how to use Terraform to onboarding AWP AWS cloud account that protected by dome9. This example codifies [this API](https://docs.cgn.portal.checkpoint.com/reference/agentless). diff --git a/examples/awp_aws_onboarding/main.tf b/examples/awp_aws_onboarding/main.tf index 0941f9a9..b4257bcc 100644 --- a/examples/awp_aws_onboarding/main.tf +++ b/examples/awp_aws_onboarding/main.tf @@ -1,26 +1,3 @@ -# This is an example of how to use the Dome9 AWP AWS Onboarding Terraform provider. -## Providers ## -# Required Providers Configuration Block for Dome9, AWS, HTTP, and Local -terraform { - required_providers { - dome9 = { - source = "dome9/dome9" - version = "1.29.6" - } - aws = { - source = "hashicorp/aws" - version = "5.39.1" - } - http = { - source = "hashicorp/http" - version = "3.4.2" - } - local = { - source = "hashicorp/local" - version = "2.5.1" - } - } -} # The Dome9 provider is used to interact with the resources supported by Dome9. # The provider needs to be configured with the proper credentials before it can be used. # Use the dome9_access_id and dome9_secret_key attributes of the provider to provide the Dome9 access key and secret key. @@ -49,631 +26,29 @@ provider "aws" { token = "AWS_SESSION_TOKEN" } -## CloudGuard Account Onboarding (Pre-requisite) ## - -# The resource block defines a Dome9 AWS Cloud Account onboarding. -# The Dome9 AWS Cloud Account onboarding resource allows you to onboard an AWS account to Dome9. -# this resource is optional and can be ignored and you need to pass CloudGuard account id Dome9 AWP AWS Onboarding resource and "dome9_awp_aws_get_onboarding_data" data source. -/* -resource "dome9_cloudaccount_aws" "aws_onboarding_account_test" { - name = "aws_onboarding_account_test" - credentials { - arn = "arn:aws:iam:::role/CloudGuard-Connect" - secret = "" - type = "RoleBased" - } - net_sec { - regions { - new_group_behavior = "ReadOnly" - region = "us_west_2" - } - } -} -*/ - -## CloudGuard AWP Configuration ## - -# The dome9_awp_aws_get_onboarding_data data source allows you to get the onboarding data of an AWS account. -# you can pass the CloudGuard account id to get the onboarding data of the AWS account or the external account number for the AWS account. -data "dome9_awp_aws_get_onboarding_data" "dome9_awp_aws_onboarding_data_source" { - cloud_account_id = "CLOUDGUARD_ACCOUNT_ID or EXTERNAL_AWS_ACCOUNT_NUMBER" -} - -# The local block defines a local value that can be used to store the data that is used in multiple places in the configuration. -# the scan_mode is used to define the scan mode of the Dome9 AWP AWS Onboarding. -# the valid values are "inAccount" and "saas". you need to select one of them based on the scan mode of the Dome9 AWP AWS Onboarding. -locals { - scan_mode = "inAccount|saas" # the valid values are "inAccount" and "saas" when onboarding the AWS account to Dome9 AWP. stage = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.stage - region = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.region - cloud_guard_backend_account_id = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cloud_guard_backend_account_id - agentless_bucket_name = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.agentless_bucket_name - remote_functions_prefix_key = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_functions_prefix_key - remote_snapshots_utils_function_name = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_snapshots_utils_function_name - remote_snapshots_utils_function_run_time = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_snapshots_utils_function_run_time - remote_snapshots_utils_function_time_out = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_snapshots_utils_function_time_out - awp_client_side_security_group_name = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.awp_client_side_security_group_name - cross_account_role_external_id = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cross_account_role_external_id - remote_snapshots_utils_function_s3_pre_signed_url = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_snapshots_utils_function_s3_pre_signed_url -} - -# -# CloudGuardAWPCrossAccountRole : The IAM role that is used to allow AWP to access the AWS account. -# CloudGuardAWPCrossAccountRolePolicy : The IAM policy that is used to define the permissions for the CloudGuardAWPCrossAccountRole. -# CloudGuardAWPSnapshotsUtilsFunction : The Lambda function that is used to manage remote actions and resources. -# CloudGuardAWPSnapshotsUtilsFunctionZip : The local file that is used to store the remote function file to be used in the lambda function. -# CloudGuardAWPSnapshotsUtilsLogGroup : The CloudWatch log group that is used to store the logs of the CloudGuardAWPSnapshotsUtilsFunction. -# CloudGuardAWPSnapshotsUtilsLambdaExecutionRole : The IAM role that is used to allow the CloudGuardAWPSnapshotsUtilsFunction to execute. -# CloudGuardAWPSnapshotsPolicy : The IAM policy that is used to define the permissions for the CloudGuardAWPSnapshotsUtilsFunction. -# CloudGuardAWPLambdaExecutionRolePolicy : The IAM policy that is used to define the permissions for the CloudGuardAWPSnapshotsUtilsFunction. -# CloudGuardAWPLambdaExecutionRolePolicy_SaaS : The IAM policy that is used to define the permissions for the CloudGuardAWPSnapshotsUtilsFunction in SaaS mode. -# CloudGuardAWPKey : The KMS key that is used to re-encrypt the snapshots in SaaS mode. -# CloudGuardAWPKeyAlias : The KMS key alias that is used to reference the KMS key in SaaS mode. -# CloudGuardAWPSnapshotsUtilsCleanupFunctionInvocation : The Lambda invocation that is used to clean up the resources after the onboarding process. -# The data block defines a data source that can be used to get the current AWS partition. -data "aws_partition" "current" {} -# The data block defines a data source that can be used to get the current AWS region. -data "aws_region" "current" {} -# The data block defines a data source that can be used to get the current AWS caller identity. -data "aws_caller_identity" "current" {} - -# Cross account role to allow CloudGuard access -# The CloudGuardAWPCrossAccountRole resource defines an IAM role that is used to allow AWP to access the AWS account. -resource "aws_iam_role" "CloudGuardAWPCrossAccountRole" { - name = "CloudGuardAWPCrossAccountRole" - description = "CloudGuard AWP Cross Account Role" - assume_role_policy = jsonencode({ - Version = "2012-10-17" - Statement = [{ - Effect = "Allow" - Principal = { - AWS = local.cloud_guard_backend_account_id - } - Action = "sts:AssumeRole" - Condition = { - StringEquals = { - "sts:ExternalId" = local.cross_account_role_external_id - } - } - }] - }) - - depends_on = [aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction] -} - -## CloudGuard AWP Resources ## -// Note: count - Used as condition to create resources based on the scan mode. - -# The CloudGuardAWPCrossAccountRolePolicy resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPCrossAccountRole. -resource "aws_iam_policy" "CloudGuardAWP" { - name = "CloudGuardAWP" - description = "Policy for CloudGuard AWP" - - policy = jsonencode({ - Version = "2012-10-17" - Statement = [ - { - Effect = "Allow" - Action = [ - "ec2:DescribeInstances", - "ec2:DescribeSnapshots", - "ec2:DescribeRegions", - "ec2:DescribeVolumes" - ] - Resource = "*" - }, - { - Effect = "Allow" - Action = [ - "lambda:InvokeFunction", - "lambda:GetFunction", - "lambda:GetLayerVersion", - "lambda:TagResource", - "lambda:ListTags", - "lambda:UntagResource", - "lambda:UpdateFunctionCode", - "lambda:UpdateFunctionConfiguration", - "lambda:GetFunctionConfiguration" - ] - Resource = aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction.arn - }, - { - Effect = "Allow" - Action = "cloudformation:DescribeStacks" - Resource = "arn:${data.aws_partition.current.partition}:cloudformation:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:stack/*" - }, - { - Effect = "Allow" - Action = "s3:GetObject" - Resource = "arn:${data.aws_partition.current.partition}:s3:::${local.agentless_bucket_name}/${local.remote_functions_prefix_key}*" - } - ] - }) -} - -# The CloudGuardAWPCrossAccountRoleAttachment resource attaches the CloudGuardAWPCrossAccountRolePolicy to the CloudGuardAWPCrossAccountRole. -resource "aws_iam_role_policy_attachment" "CloudGuardAWPCrossAccountRoleAttachment" { - role = aws_iam_role.CloudGuardAWPCrossAccountRole.name - policy_arn = aws_iam_policy.CloudGuardAWP.arn -} -# end resources for CloudGuardAWPCrossAccountRole - -# Cross account role policy -# The CloudGuardAWPCrossAccountRolePolicy resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPCrossAccountRole. -resource "aws_iam_policy" "CloudGuardAWPCrossAccountRolePolicy" { - count = local.scan_mode == "inAccount" ? 1 : 0 - name = "CloudGuardAWPCrossAccountRolePolicy" - description = "Policy for CloudGuard AWP Cross Account Role" - - policy = jsonencode({ - Version = "2012-10-17" - Statement = [ - { - Effect = "Allow" - Action = [ - "ec2:CreateSecurityGroup", - "ec2:DescribeManagedPrefixLists", - "ec2:DescribeSecurityGroups", - "ec2:DescribeSecurityGroupRules", - "ec2:RevokeSecurityGroupEgress", - "ec2:AuthorizeSecurityGroupEgress", - "ec2:CreateTags", - ] - Resource = "*" - }, - { - Effect = "Allow" - Action = [ - "ec2:DeleteSecurityGroup", - ] - Resource = "*" - Condition = { - StringEquals = { - "aws:ResourceTag/Owner" = "CG.AWP" - } - } - }, - ] - }) -} - -# The CloudGuardAWPCrossAccountRolePolicy_SaaS resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPCrossAccountRole in SaaS mode. -resource "aws_iam_policy" "CloudGuardAWPCrossAccountRolePolicy_SaaS" { - count = local.scan_mode == "saas" ? 1 : 0 - name = "CloudGuardAWPCrossAccountRolePolicy_SaaS" - description = "Policy for CloudGuard AWP Cross Account Role - SaaS Mode" - - policy = jsonencode({ - Version = "2012-10-17" - Statement = [ - { - Effect = "Allow" - Action = [ - "kms:DescribeKey", - "kms:ReplicateKey", - ] - Resource = [aws_kms_key.CloudGuardAWPKey[count.index].arn] - }, - { - Effect = "Allow" - Action = [ - "kms:PutKeyPolicy", - "kms:ScheduleKeyDeletion", - "kms:CancelKeyDeletion", - "kms:TagResource", - ] - Resource = aws_kms_key.CloudGuardAWPKey[count.index].arn - }, - { - Effect = "Allow" - Action = [ - "kms:CreateKey", - ] - Resource = "*" - }, - ] - }) -} - -# The CloudGuardAWPCrossAccountRolePolicyAttachment resource attaches the CloudGuardAWPCrossAccountRolePolicy to the CloudGuardAWPCrossAccountRole. -resource "aws_iam_policy_attachment" "CloudGuardAWPCrossAccountRolePolicyAttachment" { - count = local.scan_mode == "inAccount" ? 1 : 0 - name = "CloudGuardAWPCrossAccountRolePolicyAttachment" - policy_arn = aws_iam_policy.CloudGuardAWPCrossAccountRolePolicy[count.index].arn - roles = [aws_iam_role.CloudGuardAWPCrossAccountRole.name] -} - -# The CloudGuardAWPCrossAccountRolePolicyAttachment_SaaS resource attaches the CloudGuardAWPCrossAccountRolePolicy_SaaS to the CloudGuardAWPCrossAccountRole. -resource "aws_iam_policy_attachment" "CloudGuardAWPCrossAccountRolePolicyAttachment_SaaS" { - count = local.scan_mode == "saas" ? 1 : 0 - name = "CloudGuardAWPCrossAccountRolePolicyAttachment_SaaS" - policy_arn = aws_iam_policy.CloudGuardAWPCrossAccountRolePolicy_SaaS[count.index].arn - roles = [aws_iam_role.CloudGuardAWPCrossAccountRole.name] -} -# END Cross account role policy - -# The CloudGuardAWPSnapshotsUtilsFunctionZip resource defines http data source to download the remote function file from S3 pre-signed URL. -data "http" "CloudGuardAWPSnapshotsUtilsFunctionZip" { - url = local.remote_snapshots_utils_function_s3_pre_signed_url - method = "GET" - request_headers = { - Accept = "application/zip" - } -} - -# The CloudGuardAWPSnapshotsUtilsFunctionZip resource defines a local file that is used to store the remote function file to be used in the lambda function. -resource "local_file" "CloudGuardAWPSnapshotsUtilsFunctionZip" { - filename = "${local.remote_snapshots_utils_function_name}7.zip" - content_base64 = data.http.CloudGuardAWPSnapshotsUtilsFunctionZip.response_body_base64 -} - -# AWP proxy lambda function -# The CloudGuardAWPSnapshotsUtilsFunction resource defines a lambda function that is used to manage remote actions and resources. -resource "aws_lambda_function" "CloudGuardAWPSnapshotsUtilsFunction" { - function_name = local.remote_snapshots_utils_function_name - handler = "snapshots_utils.lambda_handler" - description = "CloudGuard AWP Proxy for managing remote actions and resources" - role = aws_iam_role.CloudGuardAWPSnapshotsUtilsLambdaExecutionRole.arn - runtime = "python3.9" - memory_size = 256 - timeout = local.remote_snapshots_utils_function_time_out - filename = local_file.CloudGuardAWPSnapshotsUtilsFunctionZip.filename - - environment { - variables = { - CP_AWP_AWS_ACCOUNT = local.cloud_guard_backend_account_id - CP_AWP_MR_KMS_KEY_ID = local.scan_mode == "saas" ? aws_kms_key.CloudGuardAWPKey[0].arn : "" - CP_AWP_SCAN_MODE = local.scan_mode - CP_AWP_SECURITY_GROUP_NAME = local.awp_client_side_security_group_name - AWS_PARTITION = data.aws_partition.current.partition - } - } - - tags = { - Owner = "CG.AWP" - } -} - -resource "aws_lambda_permission" "allow_cloudguard" { - statement_id = "AllowExecutionFromCloudGuard" - action = "lambda:InvokeFunction" - function_name = aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction.function_name - principal = "s3.amazonaws.com" - source_arn = "arn:${data.aws_partition.current.partition}:s3:::${local.agentless_bucket_name}/*" -} -# END AWP proxy lambda function - -# CloudGuardAWPSnapshotsUtilsLogGroup : The CloudWatch log group that is used to store the logs of the CloudGuardAWPSnapshotsUtilsFunction. -resource "aws_cloudwatch_log_group" "CloudGuardAWPSnapshotsUtilsLogGroup" { - name = "/aws/lambda/CloudGuardAWPSnapshotsUtils" - retention_in_days = 30 - depends_on = [ - aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction - ] -} - -# AWP proxy lambda function role -# The CloudGuardAWPSnapshotsUtilsLambdaExecutionRole resource defines an IAM role that is used to allow the CloudGuardAWPSnapshotsUtilsFunction to execute. -resource "aws_iam_role" "CloudGuardAWPSnapshotsUtilsLambdaExecutionRole" { - name = "CloudGuardAWPLambdaExecutionRole" - description = "CloudGuard AWP proxy lambda function execution role" - assume_role_policy = jsonencode({ - Version = "2012-10-17" - Statement = [ - { - Effect = "Allow" - Principal = { - Service = "lambda.amazonaws.com" - } - Action = "sts:AssumeRole" - } - ] - }) - - tags = { - Owner = "CG.AWP" - } -} - -# The CloudGuardAWPSnapshotsPolicy resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPSnapshotsUtilsFunction. -resource "aws_iam_policy" "CloudGuardAWPSnapshotsPolicy" { - name = "CloudGuardAWPSnapshotsPolicy" - description = "Policy for managing snapshots at client side and delete AWP keys" - - policy = jsonencode({ - Version = "2012-10-17" - Statement = [ - { - Effect = "Allow" - Action = [ - "ec2:CreateTags", - "ec2:CopySnapshot", - "ec2:CreateSnapshot", - "ec2:CreateSnapshots", - "ec2:DescribeSnapshots", - "ec2:DescribeRegions" - ] - Resource = "*" - }, - { - Effect = "Allow" - Action = [ - "ec2:DeleteSnapshot" - ] - Resource = "*" - Condition = { - StringEquals = { - "aws:ResourceTag/Owner" = "CG.AWP" - } - } - }, - { - Effect = "Allow" - Action = [ - "logs:CreateLogStream", - "logs:PutLogEvents" - ] - Resource = [aws_cloudwatch_log_group.CloudGuardAWPSnapshotsUtilsLogGroup.arn] - } - ] - }) -} - -# The CloudGuardAWPSnapshotsUtilsLambdaExecutionRoleAttachment resource attaches the CloudGuardAWPSnapshotsPolicy to the CloudGuardAWPSnapshotsUtilsLambdaExecutionRole. -resource "aws_iam_role_policy_attachment" "CloudGuardAWPSnapshotsUtilsLambdaExecutionRoleAttachment" { - role = aws_iam_role.CloudGuardAWPSnapshotsUtilsLambdaExecutionRole.name - policy_arn = aws_iam_policy.CloudGuardAWPSnapshotsPolicy.arn -} -# END AWP proxy lambda function role - -# AWP proxy lambda function role policy -# The CloudGuardAWPLambdaExecutionRolePolicy resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPSnapshotsUtilsFunction. -resource "aws_iam_policy" "CloudGuardAWPLambdaExecutionRolePolicy" { - count = local.scan_mode == "inAccount" ? 1 : 0 - name = "CloudGuardAWPLambdaExecutionRolePolicy" - description = "Policy for CloudGuard AWP Lambda Execution Role" - - policy = jsonencode({ - Version = "2012-10-17" - Statement = [ - { - Effect = "Allow" - Action = [ - "ec2:RunInstances", - ] - Resource = "*" - }, - { - Effect = "Allow" - Action = [ - "ec2:TerminateInstances", - "ec2:DeleteVolume", - ] - Resource = "*" - Condition = local.scan_mode == "inAccount" ? { - StringEquals = { - "aws:ResourceTag/Owner" = "CG.AWP" - } - } : null - }, - { - Effect = "Allow" - Action = [ - "iam:CreateServiceLinkedRole", - ] - Resource = ["arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:role/aws-service-role/spot.amazonaws.com/AWSServiceRoleForEC2Spot"] - }, - { - Effect = "Allow" - Action = [ - "kms:Decrypt", - "kms:DescribeKey", - "kms:GenerateDataKey*", - "kms:CreateGrant", - "kms:Encrypt", - "kms:ReEncrypt*", - ] - Resource = "*" - }, - { - Effect = "Allow" - Action = [ - "ec2:CreateVpc", - "ec2:CreateSecurityGroup", - "ec2:CreateSubnet", - "ec2:DescribeInstances", - "ec2:DescribeVolumes", - "ec2:DescribeVpcs", - "ec2:DescribeSubnets", - "ec2:DescribeRouteTables", - "ec2:DescribeNetworkAcls", - "ec2:DescribeSecurityGroups", - "ec2:DescribeInternetGateways", - "ec2:DescribeSecurityGroupRules", - "ec2:ModifySubnetAttribute", - "ec2:CreateVpcEndpoint", - "ec2:DescribeVpcEndpoints", - ] - Resource = "*" - }, - { - Effect = "Allow" - Action = [ - "ec2:AssociateRouteTable", - "ec2:DeleteVpc", - "ec2:DeleteSubnet", - "ec2:DeleteVolume", - "ec2:DeleteInternetGateway", - "ec2:RevokeSecurityGroupEgress", - "ec2:RevokeSecurityGroupIngress", - "ec2:AuthorizeSecurityGroupEgress", - "ec2:DeleteSecurityGroup", - "ec2:DeleteVpcEndpoints", - "ec2:CreateNetworkAclEntry", - ] - Resource = "*" - Condition = local.scan_mode == "inAccount" ? { - StringEquals = { - "aws:ResourceTag/Owner" = "CG.AWP" - } - } : null - }, - ] - }) -} - -# The CloudGuardAWPLambdaExecutionRolePolicyAttachment resource attaches the CloudGuardAWPLambdaExecutionRolePolicy to the CloudGuardAWPSnapshotsUtilsLambdaExecutionRole. -resource "aws_iam_policy" "CloudGuardAWPLambdaExecutionRolePolicy_SaaS" { - count = local.scan_mode == "saas" ? 1 : 0 - name = "CloudGuardAWPLambdaExecutionRolePolicy_SaaS" - description = "Policy for CloudGuard AWP Lambda Execution Role - SaaS Mode" - - policy = jsonencode({ - Version = "2012-10-17" - Statement = [ - { - Effect = "Allow" - Action = [ - "ec2:ModifySnapshotAttribute", - ] - Resource = "*" - }, - { - Effect = "Allow" - Action = [ - "kms:ReEncrypt*", - "kms:Encrypt", - ] - Resource = "*" - }, - { - Effect = "Allow" - Action = [ - "kms:Decrypt", - "kms:DescribeKey", - "kms:GenerateDataKey*", - "kms:CreateGrant", - ] - Resource = "*" - }, - { - Effect = "Allow" - Action = [ - "kms:ScheduleKeyDeletion", - ] - Resource = "*" - Condition = { - StringEquals = { - "aws:ResourceTag/Owner" = "CG.AWP" - } - } - }, - ] - }) -} - -# The CloudGuardAWPLambdaExecutionRolePolicyAttachment resource attaches the CloudGuardAWPLambdaExecutionRolePolicy to the CloudGuardAWPSnapshotsUtilsLambdaExecutionRole. -resource "aws_iam_policy_attachment" "CloudGuardAWPLambdaExecutionRolePolicyAttachment" { - count = local.scan_mode == "inAccount" ? 1 : 0 - name = "CloudGuardAWPLambdaExecutionRolePolicyAttachment" - policy_arn = aws_iam_policy.CloudGuardAWPLambdaExecutionRolePolicy[count.index].arn - roles = [aws_iam_role.CloudGuardAWPSnapshotsUtilsLambdaExecutionRole.name] -} - -# The CloudGuardAWPLambdaExecutionRolePolicyAttachment_SaaS resource attaches the CloudGuardAWPLambdaExecutionRolePolicy_SaaS to the CloudGuardAWPSnapshotsUtilsLambdaExecutionRole. -resource "aws_iam_policy_attachment" "CloudGuardAWPLambdaExecutionRolePolicyAttachment_SaaS" { - count = local.scan_mode == "saas" ? 1 : 0 - name = "CloudGuardAWPLambdaExecutionRolePolicyAttachment" - policy_arn = aws_iam_policy.CloudGuardAWPLambdaExecutionRolePolicy_SaaS[count.index].arn - roles = [aws_iam_role.CloudGuardAWPSnapshotsUtilsLambdaExecutionRole.name] -} -# END AWP proxy lambda function role policy - -# aws_lambda_invocation : The Lambda invocation that is used to clean up the resources after the onboarding process. -resource "aws_lambda_invocation" "CloudGuardAWPSnapshotsUtilsCleanupFunctionInvocation" { - function_name = aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction.function_name - input = jsonencode({ - "target_account_id" : data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cloud_account_id - }) - lifecycle_scope = "CRUD" - depends_on = [ - aws_iam_policy_attachment.CloudGuardAWPLambdaExecutionRolePolicyAttachment, - aws_iam_policy_attachment.CloudGuardAWPLambdaExecutionRolePolicyAttachment_SaaS - ] -} - -# AWP MR key for snapshot re-encryption -# The CloudGuardAWPKey resource defines a KMS key that is used to re-encrypt the snapshots in SaaS mode. -resource "aws_kms_key" "CloudGuardAWPKey" { - count = local.scan_mode == "saas" ? 1 : 0 - description = "CloudGuard AWP Multi-Region primary key for snapshots re-encryption (for Saas mode only)" - enable_key_rotation = true - deletion_window_in_days = 7 +# There is a need to use this terraform module [terraform-dome9-awp-aws] to create all the prerequisites for the onboarding process (All the needed AWS Resources) +# Example for the module use: +module "terraform-dome9-awp-aws" { + source = "github.com/dome9/terraform-dome9-awp-aws" + awp_cloud_account_id = "" + awp_scan_mode = "" # Valid Values = "inAccount" or "saas" + # Optional customizations: + # awp_cross_account_role_name = "CheckPoint-AWP-CrossAccount-Role" + # awp_cross_account_role_external_id = "AWP_Fake@ExternalID123" - # Conditionally set multi-region based on IsChinaPartition - multi_region = data.aws_partition.current.partition == "aws-cn" ? false : true - - policy = jsonencode({ - Version = "2012-10-17" - Id = "cloud-guard-awp-key" - Statement = [ - { - Sid = "Enable IAM User Permissions" - Effect = "Allow" - Principal = { - AWS = "arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:root" - } - Action = "kms:*" - Resource = "*" - }, - { - Sid = "Allow usage of the key" - Effect = "Allow" - Principal = { - AWS = "arn:${data.aws_partition.current.partition}:iam::${local.cloud_guard_backend_account_id}:root" - } - Action = [ - "kms:DescribeKey", - "kms:Encrypt", - "kms:Decrypt", - "kms:ReEncrypt*", - "kms:GenerateDataKey*", - "kms:PutKeyPolicy", - "kms:ScheduleKeyDeletion", - "kms:CancelKeyDeletion", - ] - Resource = "*" - }, - { - Sid = "Allow attachment of persistent resources" - Effect = "Allow" - Principal = { - AWS = "arn:${data.aws_partition.current.partition}:iam::${local.cloud_guard_backend_account_id}:root" - } - Action = [ - "kms:CreateGrant", - "kms:ListGrants", - "kms:RevokeGrant", - ] - Resource = "*" - Condition = { - Bool = { - "kms:GrantIsForAWSResource" = true - } - } - }, - ] - }) -} -#END AWP MR key for snapshot re-encryption - -# The CloudGuardAWPKeyAlias resource defines a KMS key alias that is used to reference the KMS key in SaaS mode. -resource "aws_kms_alias" "CloudGuardAWPKeyAlias" { - count = local.scan_mode == "saas" ? 1 : 0 - name = "alias/CloudGuardAWPKey" - target_key_id = aws_kms_key.CloudGuardAWPKey[count.index].arn - depends_on = [ - aws_kms_key.CloudGuardAWPKey - ] + # Optional account Settings + # e.g: + # awp_account_settings_aws = { + # scan_machine_interval_in_hours = 24 + # disabled_regions = ["ap-northeast-1", "ap-northeast-2", ...] + # max_concurrence_scans_per_region = 20 + # custom_tags = { + # tag1 = "value1" + # tag2 = "value2" + # tag3 = "value3" + # ... + # } + # } } # The dome9_awp_aws_onboarding resource defines a Dome9 AWP AWS Onboarding. @@ -686,33 +61,22 @@ resource "aws_kms_alias" "CloudGuardAWPKeyAlias" { # The disabled_regions attribute is used to specify the disabled regions of the agentless account settings of the Dome9 AWP AWS Onboarding. # The scan_machine_interval_in_hours attribute is used to specify the scan machine interval in hours of the agentless account settings of the Dome9 AWP AWS Onboarding. # The max_concurrence_scans_per_region attribute is used to specify the max concurrence scans per region of the agentless account settings of the Dome9 AWP AWS Onboarding. -# The skip_function_apps_scan attribute is used to specify whether to skip the function apps scan of the agentless account settings of the Dome9 AWP AWS Onboarding. # The custom_tags attribute is used to specify the custom tags of the agentless account settings of the Dome9 AWP AWS Onboarding. resource "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { cloudguard_account_id = "dome9_cloudaccount_aws.aws_onboarding_account_test.id | | " - cross_account_role_name = aws_iam_role.CloudGuardAWPCrossAccountRole.name - cross_account_role_external_id = local.cross_account_role_external_id - scan_mode = local.scan_mode - # Optional Settings - # e.g: - # agentless_account_settings { - # disabled_regions = [] // e.g: ["us-west-1", "us-west-2"] - # scan_machine_interval_in_hours = 24 - # max_concurrence_scans_per_region = 20 - # skip_function_apps_scan = false - # custom_tags = { - # # example of custom tags - # tag1 = "value1" - # tag2 = "value2" - # tag3 = "value3" - # } - # } - depends_on = [ - aws_iam_policy_attachment.CloudGuardAWPLambdaExecutionRolePolicyAttachment, - aws_iam_policy_attachment.CloudGuardAWPLambdaExecutionRolePolicyAttachment_SaaS, - aws_iam_role.CloudGuardAWPCrossAccountRole, - aws_iam_role_policy_attachment.CloudGuardAWPCrossAccountRoleAttachment - ] + cross_account_role_name = "" + cross_account_role_external_id = "" + scan_mode = "" # Valid Values = "inAccount" or "saas" + agentless_account_settings { + disabled_regions = ["us-east-1", "us-west-1", "ap-northeast-1", "ap-southeast-2"] + scan_machine_interval_in_hours = 24 + max_concurrence_scans_per_region = 20 + custom_tags = { + tag1 = "value1" + tag2 = "value2" + tag3 = "value3" + } + } } # The dome9_awp_aws_onboarding data source allows you to get the onboarding data of an AWS account (Optional). diff --git a/examples/awp_azure_onboarding/main.tf b/examples/awp_azure_onboarding/main.tf deleted file mode 100644 index 49345b60..00000000 --- a/examples/awp_azure_onboarding/main.tf +++ /dev/null @@ -1,266 +0,0 @@ -# Dome9 Provider Configurations -terraform { - required_providers { - dome9 = { - source = "dome9/dome9" - version = "1.29.6" - } - } -} - -/** -provider "dome9" { - dome9_access_id = "DOME9_CLOUDGUARD_API_ACCESS_ID" - dome9_secret_key = "DOME9_CLOUDGUARD_API_SECRET_KEY" - base_url = "DOME9_API_BASE_URL" -} -**/ - -# Define variables -# Regular Account or Sub Account Subscription ID -variable "subscription_id" {} # Customer should provide it with the onboarding resource -variable "management_group" {} # Customer should provide it with the onboarding resource -variable "tenant_id" {} # should be calculated from azurerm_subscription data source -variable "app_object_id" {} # should be calculated from app_client_id (it should be provided from get onboarding data api) -variable "hub_subscription_id" {} # Customer should provide it with the onboarding resource -variable "scan_mode" {} # Customer should provide it with the onboarding resource -variable "region" {} # should be taken from get onboarding data azure api -variable "awp_version" {} # should be taken from get onboarding data azure api - - -data "dome9_awp_azure_generate_onboarding_data" "dome9_awp_azure_generating_onboarding_data_source" { - subscription_id = "d0dd3387-d9c5-487b-8b18-4fa969fd98cd" - scan_mode = "inAccountHub" # The scan mode (valid options are: $SCAN_MODE_SAAS, $SCAN_MODE_IN_ACCOUNT, $SCAN_MODE_IN_ACCOUNT_HUB, $SCAN_MODE_IN_ACCOUNT_SUB) - hub_subscription_id = "d0dd3387-d9c5-487b-8b18-4fa969fd98cd" # The hub subscription id, this param is relevant in case scan_mode is $SCAN_MODE_IN_ACCOUNT_HUB - # or $SCAN_MODE_IN_ACCOUNT_SUB and represents the subscription where the AWP scans will be executed - skip_function_apps_scan = false # currently this attribute not supported with the azure resources (the default is false as we understood) -} - - -# locals -locals { - SCAN_MODE_SAAS = "saas" - SCAN_MODE_IN_ACCOUNT = "inAccount" - SCAN_MODE_IN_ACCOUNT_SUB = "inAccountSub" - SCAN_MODE_IN_ACCOUNT_HUB = "inAccountHub" - - AWP_VM_SCAN_OPERATOR_ROLE_NAME_PREFIX = "CloudGuard AWP VM Scan Operator" - AWP_VM_SCAN_OPERATOR_ROLE_DESCRIPTION = "Grants all needed permissions for CloudGuard app registration to scan VMs (version: ${var.awp_version})" - AWP_VM_SCAN_OPERATOR_ROLE_ACTIONS = [ - "Microsoft.Compute/disks/read", - "Microsoft.Compute/disks/write", - "Microsoft.Compute/disks/delete", - "Microsoft.Compute/disks/beginGetAccess/action", - "Microsoft.Compute/snapshots/read", - "Microsoft.Compute/snapshots/write", - "Microsoft.Compute/snapshots/delete", - "Microsoft.Compute/snapshots/beginGetAccess/action", - "Microsoft.Compute/snapshots/endGetAccess/action", - "Microsoft.Network/networkInterfaces/join/action", - "Microsoft.Network/networkInterfaces/write", - "Microsoft.Compute/virtualMachines/write", - "Microsoft.Compute/virtualMachines/delete", - "Microsoft.Network/networkSecurityGroups/write", - "Microsoft.Network/networkSecurityGroups/join/action", - "Microsoft.Network/virtualNetworks/write", - "Microsoft.Network/virtualNetworks/subnets/join/action" - ] - - AWP_VM_DATA_SHARE_ROLE_NAME_PREFIX = "CloudGuard AWP VM Data Share" - AWP_VM_DATA_SHARE_ROLE_DESCRIPTION = "Grants needed permissions for CloudGuard app registration to read VMs data (version: ${var.awp_version})" - AWP_VM_DATA_SHARE_ROLE_ACTIONS = [ - "Microsoft.Compute/disks/beginGetAccess/action", - "Microsoft.Compute/virtualMachines/read" - ] - - AWP_FA_MANAGED_IDENTITY_NAME = "CloudGuardAWPScannerManagedIdentity" - - AWP_FA_SCANNER_ROLE_NAME_PREFIX = "CloudGuard AWP Function Apps Scanner" - AWP_FA_SCANNER_ROLE_DESCRIPTION = "Grants needed permissions for CloudGuard AWP function-apps scanner (version: ${var.awp_version})" - AWP_FA_SCANNER_ROLE_ACTIONS = [ - "Microsoft.Web/sites/publish/Action", - "Microsoft.Web/sites/config/list/Action", - "microsoft.web/sites/functions/read" - ] - - AWP_FA_SCAN_OPERATOR_ROLE_NAME_PREFIX = "CloudGuard AWP FunctionApp Scan Operator" - AWP_FA_SCAN_OPERATOR_ROLE_DESCRIPTION = "Grants all needed permissions for CloudGuard app registration to scan function-apps (version: ${var.awp_version})" - AWP_FA_SCAN_OPERATOR_ROLE_ACTIONS = [ - "Microsoft.Compute/virtualMachines/write", - "Microsoft.Compute/virtualMachines/extensions/write", - "Microsoft.Network/networkSecurityGroups/write", - "Microsoft.Network/networkSecurityGroups/join/action", - "Microsoft.Network/virtualNetworks/write", - "Microsoft.Network/virtualNetworks/subnets/join/action", - "Microsoft.ManagedIdentity/userAssignedIdentities/assign/action" - ] - - AWP_RESOURCE_GROUP_NAME_PREFIX = "cloudguard-AWP" - AWP_OWNER_TAG = "Owner=CG.AWP" - AWP_VERSION_TAG = "CloudGuard.AWP.Version=${var.awp_version}" - LOCATION = var.region -} - - -# Provider block for the hub account (used only in In-Account-Sub mode) -provider "azurerm" { - alias = "hub" - features {} - - subscription_id = var.hub_subscription_id - # Add any other necessary authentication details for the hub account -} - -# Provider block for the sub account (used only in In-Account-Sub mode) -provider "azurerm" { - alias = "sub" - features {} - - subscription_id = var.subscription_id - # Add any other necessary authentication details for the sub account -} - -# Data source to retrieve information about the current Azure subscription -data "azurerm_subscription" "hub" { - provider = azurerm.hub -} - -data "azurerm_subscription" "sub" { - provider = azurerm.sub -} - -# Define the resource group where CloudGuard resources will be deployed -resource "azurerm_resource_group" "cloudguard" { - count = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_HUB ? 1 : 0 - name = local.AWP_RESOURCE_GROUP_NAME_PREFIX - location = local.LOCATION - tags = { - Owner = local.AWP_OWNER_TAG - Version = local.AWP_VERSION_TAG - } -} - -resource "azurerm_resource_group" "cloudguard_hub" { - count = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_SUB ? 1 : 0 - provider = azurerm.hub - name = "${local.AWP_RESOURCE_GROUP_NAME_PREFIX}_${var.subscription_id}" - location = local.LOCATION - tags = { - Owner = local.AWP_OWNER_TAG - Version = local.AWP_VERSION_TAG - } -} - -# Define custom roles based on scan mode -resource "azurerm_role_definition" "cloudguard_vm_data_share" { - count = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_HUB || var.scan_mode == local.SCAN_MODE_SAAS ? 1 : 0 - name = "CloudGuard AWP VM Data Share ${var.subscription_id}" # need to change subscription id to hub subscription id when hub mode - description = local.AWP_VM_DATA_SHARE_ROLE_DESCRIPTION - scope = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_SAAS ? "/subscriptions/${var.subscription_id}" : "/providers/Microsoft.Management/managementGroups/${var.management_group}:-${var.tenant_id}" - permissions { - actions = local.AWP_VM_DATA_SHARE_ROLE_ACTIONS - not_actions = [] - } -} - -# Define the managed identity for CloudGuard AWP -resource "azurerm_managed_identity" "cloudguard_identity" { - count = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_HUB ? 1 : 0 - name = local.AWP_FA_MANAGED_IDENTITY_NAME - location = azurerm_resource_group.cloudguard.location - resource_group_name = azurerm_resource_group.cloudguard.name -} - -resource "azurerm_role_definition" "cloudguard_vm_scan_operator" { - count = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_HUB ? 1 : 0 - description = local.AWP_VM_SCAN_OPERATOR_ROLE_DESCRIPTION - name = "${local.AWP_VM_SCAN_OPERATOR_ROLE_NAME_PREFIX} ${var.subscription_id}" - scope = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT ? "/subscriptions/${var.subscription_id}" : "/providers/Microsoft.Management/managementGroups/${var.management_group}:-${var.tenant_id}" - permissions { - actions = local.AWP_VM_SCAN_OPERATOR_ROLE_ACTIONS - not_actions = [] - } -} - -resource "azurerm_role_definition" "cloudguard_function_apps_scanner" { - count = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_HUB ? 1 : 0 - name = "${local.AWP_FA_SCANNER_ROLE_NAME_PREFIX} ${var.subscription_id}" - description = local.AWP_FA_SCANNER_ROLE_DESCRIPTION - scope = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT ? "/subscriptions/${var.subscription_id}" : "/providers/Microsoft.Management/managementGroups/${var.management_group}:-${var.tenant_id}" - permissions { - actions = local.AWP_FA_SCANNER_ROLE_ACTIONS - not_actions = [] - } -} - -resource "azurerm_role_definition" "cloudguard_function_apps_scan_operator" { - count = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_HUB ? 1 : 0 - name = "${local.AWP_FA_SCAN_OPERATOR_ROLE_NAME_PREFIX} ${var.subscription_id}" - description = local.AWP_FA_SCAN_OPERATOR_ROLE_DESCRIPTION - scope = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT ? "/subscriptions/${var.subscription_id}" : "/providers/Microsoft.Management/managementGroups/${var.management_group}:-${var.tenant_id}" - permissions { - actions = local.AWP_FA_SCAN_OPERATOR_ROLE_ACTIONS - not_actions = [] - } -} - -# Assign custom roles based on scan mode -resource "azurerm_role_assignment" "cloudguard_vm_data_share_assignment" { - count = var.scan_mode == local.SCAN_MODE_SAAS || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_SUB ? 1 : 0 - provider = azurerm.sub - name = "${local.AWP_VM_DATA_SHARE_ROLE_NAME_PREFIX} ${var.subscription_id}" - scope = "/subscriptions/${var.subscription_id}" - role_definition_name = azurerm_role_definition.cloudguard_vm_data_share[count.index].name - principal_id = var.app_object_id -} - -resource "azurerm_role_assignment" "cloudguard_vm_scan_operator_assignment" { - count = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_HUB ? 1 : 0 - scope = "/subscriptions/${var.subscription_id}" - role_definition_name = azurerm_role_definition.cloudguard_vm_scan_operator[count.index].name - principal_id = var.app_object_id -} - -resource "azurerm_role_assignment" "cloudguard_function_apps_scanner_assignment" { - count = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_HUB ? 1 : 0 - provider = azurerm.sub - scope = "/subscriptions/${var.subscription_id}" - role_definition_name = azurerm_role_definition.cloudguard_function_apps_scanner[count.index].name - principal_id = azurerm_managed_identity.cloudguard_identity[count.index].id -} - -resource "azurerm_role_assignment" "cloudguard_function_apps_scan_operator_assignment" { - count = var.scan_mode == local.SCAN_MODE_IN_ACCOUNT || var.scan_mode == local.SCAN_MODE_IN_ACCOUNT_HUB ? 1 : 0 - scope = "/subscriptions/${var.subscription_id}" - role_definition_name = azurerm_role_definition.cloudguard_function_apps_scan_operator[count.index].name - principal_id = var.app_object_id -} - -resource "azurerm_resource_group" "cloudguard_hub" { - count = var.scan_mode == "inAccountSub" ? 1 : 0 - name = "cloudguard-AWP-${var.subscription_id}" - location = var.region -} - -resource "dome9_awp_azure_onboarding" "awp_azure_onboarding_resource" { - subscription_id = "d0dd3387-d9c5-487b-8b18-4fa969fd98cd" - scan_mode = "inAccountHub" # The scan mode (valid options are: $SCAN_MODE_SAAS, $SCAN_MODE_IN_ACCOUNT, $SCAN_MODE_IN_ACCOUNT_HUB, $SCAN_MODE_IN_ACCOUNT_SUB) - hub_subscription_id = "d0dd3387-d9c5-487b-8b18-4fa969fd98cd" - - # azure role name customizations currently unsupported - onboarding_customizations = { - virtual_machine_data_share_role_name = "string" - virtual_machine_scan_operator_role_name = "string" - function_app_scan_operator_role_name = "string" - function_app_scanner_role_name = "string" - resource_group_name = "string" - scanner_managed_identity_name = "string" - } - agentless_account_settings = { - disabled_regions = ["string"] - scan_machine_interval_in_hours = 0 - max_concurrence_scans_per_region = 0 - skip_function_apps_scan = false # - custom_tags = {} - } -} diff --git a/website/docs/d/awp_aws_get_onboarding_data.html.markdown b/website/docs/d/awp_aws_onboarding_data.html.markdown similarity index 97% rename from website/docs/d/awp_aws_get_onboarding_data.html.markdown rename to website/docs/d/awp_aws_onboarding_data.html.markdown index cbff2f92..155deae3 100644 --- a/website/docs/d/awp_aws_get_onboarding_data.html.markdown +++ b/website/docs/d/awp_aws_onboarding_data.html.markdown @@ -13,7 +13,7 @@ Use this data source to get information about AWS AWP onboarding data in Dome9. ## Example Usage ```hcl -data "dome9_awp_aws_get_onboarding_data" "test" { +data "dome9_awp_aws_onboarding_data" "test" { cloud_account_id = "d9-aws-cloud-account-id" } diff --git a/website/docs/r/awp_aws_onboarding.html.markdown b/website/docs/r/awp_aws_onboarding.html.markdown index 4ea195dc..25eb5fe6 100644 --- a/website/docs/r/awp_aws_onboarding.html.markdown +++ b/website/docs/r/awp_aws_onboarding.html.markdown @@ -15,50 +15,11 @@ This resource is used to create and modify AWP AWS Onboarding in CloudGuard Dome Basic usage: ```hcl -# This is an example of how to use the Dome9 AWP AWS Onboarding Terraform provider. -## Providers ## -# Required Providers Configuration Block for Dome9, AWS, HTTP, and Local -terraform { - required_providers { - dome9 = { - source = "dome9/dome9" - version = "1.29.6" - } - aws = { - source = "hashicorp/aws" - version = "5.39.1" - } - http = { - source = "hashicorp/http" - version = "3.4.2" - } - local = { - source = "hashicorp/local" - version = "2.5.1" - } - } -} -# The Dome9 provider is used to interact with the resources supported by Dome9. -# The provider needs to be configured with the proper credentials before it can be used. -# Use the dome9_access_id and dome9_secret_key attributes of the provider to provide the Dome9 access key and secret key. -# The base_url attribute is used to specify the base URL of the Dome9 API. -# The Dome9 provider supports several options for providing these credentials. The following example demonstrates the use of static credentials: -#you can read the Dome9 provider documentation to understand the full set of options available for providing credentials. -#https://registry.terraform.io/providers/dome9/dome9/latest/docs#authentication provider "dome9" { dome9_access_id = "DOME9_ACCESS_ID" dome9_secret_key = "DOME9_SECRET_KEY" base_url = "https://api.dome9.com/v2/" } - -# AWS Provider Configurations -# The AWS provider is used to interact with the resources supported by AWS. -# The provider needs to be configured with the proper credentials before it can be used. -# Use the access_key, secret_key, and token attributes of the provider to provide the credentials. -# also you can use the shared_credentials_file attribute to provide the path to the shared credentials file. -# The AWS provider supports several options for providing these credentials. The following example demonstrates the use of static credentials: -#you can read the AWS provider documentation to understand the full set of options available for providing credentials. -#https://registry.terraform.io/providers/hashicorp/aws/latest/docs#authentication-and-configuration provider "aws" { region = "AWS_REGION" access_key = "AWS_ACCESS_KEY" @@ -66,631 +27,30 @@ provider "aws" { token = "AWS_SESSION_TOKEN" } -## CloudGuard Account Onboarding (Pre-requisite) ## - -# The resource block defines a Dome9 AWS Cloud Account onboarding. -# The Dome9 AWS Cloud Account onboarding resource allows you to onboard an AWS account to Dome9. -# this resource is optional and can be ignored and you need to pass CloudGuard account id Dome9 AWP AWS Onboarding resource and "dome9_awp_aws_get_onboarding_data" data source. -/* -resource "dome9_cloudaccount_aws" "aws_onboarding_account_test" { - name = "aws_onboarding_account_test" - credentials { - arn = "arn:aws:iam:::role/CloudGuard-Connect" - secret = "" - type = "RoleBased" - } - net_sec { - regions { - new_group_behavior = "ReadOnly" - region = "us_west_2" - } - } -} -*/ - -## CloudGuard AWP Configuration ## - -# The dome9_awp_aws_get_onboarding_data data source allows you to get the onboarding data of an AWS account. -# you can pass the CloudGuard account id to get the onboarding data of the AWS account or the external account number for the AWS account. -data "dome9_awp_aws_get_onboarding_data" "dome9_awp_aws_onboarding_data_source" { - cloud_account_id = "CLOUDGUARD_ACCOUNT_ID or EXTERNAL_AWS_ACCOUNT_NUMBER" -} - -# The local block defines a local value that can be used to store the data that is used in multiple places in the configuration. -# the scan_mode is used to define the scan mode of the Dome9 AWP AWS Onboarding. -# the valid values are "inAccount" and "saas". you need to select one of them based on the scan mode of the Dome9 AWP AWS Onboarding. -locals { - scan_mode = "inAccount|saas" # the valid values are "inAccount" and "saas" when onboarding the AWS account to Dome9 AWP. stage = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.stage - region = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.region - cloud_guard_backend_account_id = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cloud_guard_backend_account_id - agentless_bucket_name = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.agentless_bucket_name - remote_functions_prefix_key = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_functions_prefix_key - remote_snapshots_utils_function_name = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_snapshots_utils_function_name - remote_snapshots_utils_function_run_time = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_snapshots_utils_function_run_time - remote_snapshots_utils_function_time_out = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_snapshots_utils_function_time_out - awp_client_side_security_group_name = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.awp_client_side_security_group_name - cross_account_role_external_id = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cross_account_role_external_id - remote_snapshots_utils_function_s3_pre_signed_url = data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.remote_snapshots_utils_function_s3_pre_signed_url -} - -# -# CloudGuardAWPCrossAccountRole : The IAM role that is used to allow AWP to access the AWS account. -# CloudGuardAWPCrossAccountRolePolicy : The IAM policy that is used to define the permissions for the CloudGuardAWPCrossAccountRole. -# CloudGuardAWPSnapshotsUtilsFunction : The Lambda function that is used to manage remote actions and resources. -# CloudGuardAWPSnapshotsUtilsFunctionZip : The local file that is used to store the remote function file to be used in the lambda function. -# CloudGuardAWPSnapshotsUtilsLogGroup : The CloudWatch log group that is used to store the logs of the CloudGuardAWPSnapshotsUtilsFunction. -# CloudGuardAWPSnapshotsUtilsLambdaExecutionRole : The IAM role that is used to allow the CloudGuardAWPSnapshotsUtilsFunction to execute. -# CloudGuardAWPSnapshotsPolicy : The IAM policy that is used to define the permissions for the CloudGuardAWPSnapshotsUtilsFunction. -# CloudGuardAWPLambdaExecutionRolePolicy : The IAM policy that is used to define the permissions for the CloudGuardAWPSnapshotsUtilsFunction. -# CloudGuardAWPLambdaExecutionRolePolicy_SaaS : The IAM policy that is used to define the permissions for the CloudGuardAWPSnapshotsUtilsFunction in SaaS mode. -# CloudGuardAWPKey : The KMS key that is used to re-encrypt the snapshots in SaaS mode. -# CloudGuardAWPKeyAlias : The KMS key alias that is used to reference the KMS key in SaaS mode. -# CloudGuardAWPSnapshotsUtilsCleanupFunctionInvocation : The Lambda invocation that is used to clean up the resources after the onboarding process. -# The data block defines a data source that can be used to get the current AWS partition. -data "aws_partition" "current" {} -# The data block defines a data source that can be used to get the current AWS region. -data "aws_region" "current" {} -# The data block defines a data source that can be used to get the current AWS caller identity. -data "aws_caller_identity" "current" {} - -# Cross account role to allow CloudGuard access -# The CloudGuardAWPCrossAccountRole resource defines an IAM role that is used to allow AWP to access the AWS account. -resource "aws_iam_role" "CloudGuardAWPCrossAccountRole" { - name = "CloudGuardAWPCrossAccountRole" - description = "CloudGuard AWP Cross Account Role" - assume_role_policy = jsonencode({ - Version = "2012-10-17" - Statement = [{ - Effect = "Allow" - Principal = { - AWS = local.cloud_guard_backend_account_id - } - Action = "sts:AssumeRole" - Condition = { - StringEquals = { - "sts:ExternalId" = local.cross_account_role_external_id - } - } - }] - }) - - depends_on = [aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction] -} - -## CloudGuard AWP Resources ## -// Note: count - Used as condition to create resources based on the scan mode. - -# The CloudGuardAWPCrossAccountRolePolicy resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPCrossAccountRole. -resource "aws_iam_policy" "CloudGuardAWP" { - name = "CloudGuardAWP" - description = "Policy for CloudGuard AWP" - - policy = jsonencode({ - Version = "2012-10-17" - Statement = [ - { - Effect = "Allow" - Action = [ - "ec2:DescribeInstances", - "ec2:DescribeSnapshots", - "ec2:DescribeRegions", - "ec2:DescribeVolumes" - ] - Resource = "*" - }, - { - Effect = "Allow" - Action = [ - "lambda:InvokeFunction", - "lambda:GetFunction", - "lambda:GetLayerVersion", - "lambda:TagResource", - "lambda:ListTags", - "lambda:UntagResource", - "lambda:UpdateFunctionCode", - "lambda:UpdateFunctionConfiguration", - "lambda:GetFunctionConfiguration" - ] - Resource = aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction.arn - }, - { - Effect = "Allow" - Action = "cloudformation:DescribeStacks" - Resource = "arn:${data.aws_partition.current.partition}:cloudformation:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:stack/*" - }, - { - Effect = "Allow" - Action = "s3:GetObject" - Resource = "arn:${data.aws_partition.current.partition}:s3:::${local.agentless_bucket_name}/${local.remote_functions_prefix_key}*" - } - ] - }) -} - -# The CloudGuardAWPCrossAccountRoleAttachment resource attaches the CloudGuardAWPCrossAccountRolePolicy to the CloudGuardAWPCrossAccountRole. -resource "aws_iam_role_policy_attachment" "CloudGuardAWPCrossAccountRoleAttachment" { - role = aws_iam_role.CloudGuardAWPCrossAccountRole.name - policy_arn = aws_iam_policy.CloudGuardAWP.arn -} -# end resources for CloudGuardAWPCrossAccountRole - -# Cross account role policy -# The CloudGuardAWPCrossAccountRolePolicy resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPCrossAccountRole. -resource "aws_iam_policy" "CloudGuardAWPCrossAccountRolePolicy" { - count = local.scan_mode == "inAccount" ? 1 : 0 - name = "CloudGuardAWPCrossAccountRolePolicy" - description = "Policy for CloudGuard AWP Cross Account Role" - - policy = jsonencode({ - Version = "2012-10-17" - Statement = [ - { - Effect = "Allow" - Action = [ - "ec2:CreateSecurityGroup", - "ec2:DescribeManagedPrefixLists", - "ec2:DescribeSecurityGroups", - "ec2:DescribeSecurityGroupRules", - "ec2:RevokeSecurityGroupEgress", - "ec2:AuthorizeSecurityGroupEgress", - "ec2:CreateTags", - ] - Resource = "*" - }, - { - Effect = "Allow" - Action = [ - "ec2:DeleteSecurityGroup", - ] - Resource = "*" - Condition = { - StringEquals = { - "aws:ResourceTag/Owner" = "CG.AWP" - } - } - }, - ] - }) -} - -# The CloudGuardAWPCrossAccountRolePolicy_SaaS resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPCrossAccountRole in SaaS mode. -resource "aws_iam_policy" "CloudGuardAWPCrossAccountRolePolicy_SaaS" { - count = local.scan_mode == "saas" ? 1 : 0 - name = "CloudGuardAWPCrossAccountRolePolicy_SaaS" - description = "Policy for CloudGuard AWP Cross Account Role - SaaS Mode" - - policy = jsonencode({ - Version = "2012-10-17" - Statement = [ - { - Effect = "Allow" - Action = [ - "kms:DescribeKey", - "kms:ReplicateKey", - ] - Resource = [aws_kms_key.CloudGuardAWPKey[count.index].arn] - }, - { - Effect = "Allow" - Action = [ - "kms:PutKeyPolicy", - "kms:ScheduleKeyDeletion", - "kms:CancelKeyDeletion", - "kms:TagResource", - ] - Resource = aws_kms_key.CloudGuardAWPKey[count.index].arn - }, - { - Effect = "Allow" - Action = [ - "kms:CreateKey", - ] - Resource = "*" - }, - ] - }) -} - -# The CloudGuardAWPCrossAccountRolePolicyAttachment resource attaches the CloudGuardAWPCrossAccountRolePolicy to the CloudGuardAWPCrossAccountRole. -resource "aws_iam_policy_attachment" "CloudGuardAWPCrossAccountRolePolicyAttachment" { - count = local.scan_mode == "inAccount" ? 1 : 0 - name = "CloudGuardAWPCrossAccountRolePolicyAttachment" - policy_arn = aws_iam_policy.CloudGuardAWPCrossAccountRolePolicy[count.index].arn - roles = [aws_iam_role.CloudGuardAWPCrossAccountRole.name] -} - -# The CloudGuardAWPCrossAccountRolePolicyAttachment_SaaS resource attaches the CloudGuardAWPCrossAccountRolePolicy_SaaS to the CloudGuardAWPCrossAccountRole. -resource "aws_iam_policy_attachment" "CloudGuardAWPCrossAccountRolePolicyAttachment_SaaS" { - count = local.scan_mode == "saas" ? 1 : 0 - name = "CloudGuardAWPCrossAccountRolePolicyAttachment_SaaS" - policy_arn = aws_iam_policy.CloudGuardAWPCrossAccountRolePolicy_SaaS[count.index].arn - roles = [aws_iam_role.CloudGuardAWPCrossAccountRole.name] -} -# END Cross account role policy - -# The CloudGuardAWPSnapshotsUtilsFunctionZip resource defines http data source to download the remote function file from S3 pre-signed URL. -data "http" "CloudGuardAWPSnapshotsUtilsFunctionZip" { - url = local.remote_snapshots_utils_function_s3_pre_signed_url - method = "GET" - request_headers = { - Accept = "application/zip" - } -} - -# The CloudGuardAWPSnapshotsUtilsFunctionZip resource defines a local file that is used to store the remote function file to be used in the lambda function. -resource "local_file" "CloudGuardAWPSnapshotsUtilsFunctionZip" { - filename = "${local.remote_snapshots_utils_function_name}7.zip" - content_base64 = data.http.CloudGuardAWPSnapshotsUtilsFunctionZip.response_body_base64 -} - -# AWP proxy lambda function -# The CloudGuardAWPSnapshotsUtilsFunction resource defines a lambda function that is used to manage remote actions and resources. -resource "aws_lambda_function" "CloudGuardAWPSnapshotsUtilsFunction" { - function_name = local.remote_snapshots_utils_function_name - handler = "snapshots_utils.lambda_handler" - description = "CloudGuard AWP Proxy for managing remote actions and resources" - role = aws_iam_role.CloudGuardAWPSnapshotsUtilsLambdaExecutionRole.arn - runtime = "python3.9" - memory_size = 256 - timeout = local.remote_snapshots_utils_function_time_out - filename = local_file.CloudGuardAWPSnapshotsUtilsFunctionZip.filename - - environment { - variables = { - CP_AWP_AWS_ACCOUNT = local.cloud_guard_backend_account_id - CP_AWP_MR_KMS_KEY_ID = local.scan_mode == "saas" ? aws_kms_key.CloudGuardAWPKey[0].arn : "" - CP_AWP_SCAN_MODE = local.scan_mode - CP_AWP_SECURITY_GROUP_NAME = local.awp_client_side_security_group_name - AWS_PARTITION = data.aws_partition.current.partition - } - } - - tags = { - Owner = "CG.AWP" - } -} - -resource "aws_lambda_permission" "allow_cloudguard" { - statement_id = "AllowExecutionFromCloudGuard" - action = "lambda:InvokeFunction" - function_name = aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction.function_name - principal = "s3.amazonaws.com" - source_arn = "arn:${data.aws_partition.current.partition}:s3:::${local.agentless_bucket_name}/*" -} -# END AWP proxy lambda function - -# CloudGuardAWPSnapshotsUtilsLogGroup : The CloudWatch log group that is used to store the logs of the CloudGuardAWPSnapshotsUtilsFunction. -resource "aws_cloudwatch_log_group" "CloudGuardAWPSnapshotsUtilsLogGroup" { - name = "/aws/lambda/CloudGuardAWPSnapshotsUtils" - retention_in_days = 30 - depends_on = [ - aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction - ] -} - -# AWP proxy lambda function role -# The CloudGuardAWPSnapshotsUtilsLambdaExecutionRole resource defines an IAM role that is used to allow the CloudGuardAWPSnapshotsUtilsFunction to execute. -resource "aws_iam_role" "CloudGuardAWPSnapshotsUtilsLambdaExecutionRole" { - name = "CloudGuardAWPLambdaExecutionRole" - description = "CloudGuard AWP proxy lambda function execution role" - assume_role_policy = jsonencode({ - Version = "2012-10-17" - Statement = [ - { - Effect = "Allow" - Principal = { - Service = "lambda.amazonaws.com" - } - Action = "sts:AssumeRole" - } - ] - }) - - tags = { - Owner = "CG.AWP" - } -} - -# The CloudGuardAWPSnapshotsPolicy resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPSnapshotsUtilsFunction. -resource "aws_iam_policy" "CloudGuardAWPSnapshotsPolicy" { - name = "CloudGuardAWPSnapshotsPolicy" - description = "Policy for managing snapshots at client side and delete AWP keys" - - policy = jsonencode({ - Version = "2012-10-17" - Statement = [ - { - Effect = "Allow" - Action = [ - "ec2:CreateTags", - "ec2:CopySnapshot", - "ec2:CreateSnapshot", - "ec2:CreateSnapshots", - "ec2:DescribeSnapshots", - "ec2:DescribeRegions" - ] - Resource = "*" - }, - { - Effect = "Allow" - Action = [ - "ec2:DeleteSnapshot" - ] - Resource = "*" - Condition = { - StringEquals = { - "aws:ResourceTag/Owner" = "CG.AWP" - } - } - }, - { - Effect = "Allow" - Action = [ - "logs:CreateLogStream", - "logs:PutLogEvents" - ] - Resource = [aws_cloudwatch_log_group.CloudGuardAWPSnapshotsUtilsLogGroup.arn] - } - ] - }) -} - -# The CloudGuardAWPSnapshotsUtilsLambdaExecutionRoleAttachment resource attaches the CloudGuardAWPSnapshotsPolicy to the CloudGuardAWPSnapshotsUtilsLambdaExecutionRole. -resource "aws_iam_role_policy_attachment" "CloudGuardAWPSnapshotsUtilsLambdaExecutionRoleAttachment" { - role = aws_iam_role.CloudGuardAWPSnapshotsUtilsLambdaExecutionRole.name - policy_arn = aws_iam_policy.CloudGuardAWPSnapshotsPolicy.arn -} -# END AWP proxy lambda function role - -# AWP proxy lambda function role policy -# The CloudGuardAWPLambdaExecutionRolePolicy resource defines an IAM policy that is used to define the permissions for the CloudGuardAWPSnapshotsUtilsFunction. -resource "aws_iam_policy" "CloudGuardAWPLambdaExecutionRolePolicy" { - count = local.scan_mode == "inAccount" ? 1 : 0 - name = "CloudGuardAWPLambdaExecutionRolePolicy" - description = "Policy for CloudGuard AWP Lambda Execution Role" - - policy = jsonencode({ - Version = "2012-10-17" - Statement = [ - { - Effect = "Allow" - Action = [ - "ec2:RunInstances", - ] - Resource = "*" - }, - { - Effect = "Allow" - Action = [ - "ec2:TerminateInstances", - "ec2:DeleteVolume", - ] - Resource = "*" - Condition = local.scan_mode == "inAccount" ? { - StringEquals = { - "aws:ResourceTag/Owner" = "CG.AWP" - } - } : null - }, - { - Effect = "Allow" - Action = [ - "iam:CreateServiceLinkedRole", - ] - Resource = ["arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:role/aws-service-role/spot.amazonaws.com/AWSServiceRoleForEC2Spot"] - }, - { - Effect = "Allow" - Action = [ - "kms:Decrypt", - "kms:DescribeKey", - "kms:GenerateDataKey*", - "kms:CreateGrant", - "kms:Encrypt", - "kms:ReEncrypt*", - ] - Resource = "*" - }, - { - Effect = "Allow" - Action = [ - "ec2:CreateVpc", - "ec2:CreateSecurityGroup", - "ec2:CreateSubnet", - "ec2:DescribeInstances", - "ec2:DescribeVolumes", - "ec2:DescribeVpcs", - "ec2:DescribeSubnets", - "ec2:DescribeRouteTables", - "ec2:DescribeNetworkAcls", - "ec2:DescribeSecurityGroups", - "ec2:DescribeInternetGateways", - "ec2:DescribeSecurityGroupRules", - "ec2:ModifySubnetAttribute", - "ec2:CreateVpcEndpoint", - "ec2:DescribeVpcEndpoints", - ] - Resource = "*" - }, - { - Effect = "Allow" - Action = [ - "ec2:AssociateRouteTable", - "ec2:DeleteVpc", - "ec2:DeleteSubnet", - "ec2:DeleteVolume", - "ec2:DeleteInternetGateway", - "ec2:RevokeSecurityGroupEgress", - "ec2:RevokeSecurityGroupIngress", - "ec2:AuthorizeSecurityGroupEgress", - "ec2:DeleteSecurityGroup", - "ec2:DeleteVpcEndpoints", - "ec2:CreateNetworkAclEntry", - ] - Resource = "*" - Condition = local.scan_mode == "inAccount" ? { - StringEquals = { - "aws:ResourceTag/Owner" = "CG.AWP" - } - } : null - }, - ] - }) -} - -# The CloudGuardAWPLambdaExecutionRolePolicyAttachment resource attaches the CloudGuardAWPLambdaExecutionRolePolicy to the CloudGuardAWPSnapshotsUtilsLambdaExecutionRole. -resource "aws_iam_policy" "CloudGuardAWPLambdaExecutionRolePolicy_SaaS" { - count = local.scan_mode == "saas" ? 1 : 0 - name = "CloudGuardAWPLambdaExecutionRolePolicy_SaaS" - description = "Policy for CloudGuard AWP Lambda Execution Role - SaaS Mode" - - policy = jsonencode({ - Version = "2012-10-17" - Statement = [ - { - Effect = "Allow" - Action = [ - "ec2:ModifySnapshotAttribute", - ] - Resource = "*" - }, - { - Effect = "Allow" - Action = [ - "kms:ReEncrypt*", - "kms:Encrypt", - ] - Resource = "*" - }, - { - Effect = "Allow" - Action = [ - "kms:Decrypt", - "kms:DescribeKey", - "kms:GenerateDataKey*", - "kms:CreateGrant", - ] - Resource = "*" - }, - { - Effect = "Allow" - Action = [ - "kms:ScheduleKeyDeletion", - ] - Resource = "*" - Condition = { - StringEquals = { - "aws:ResourceTag/Owner" = "CG.AWP" - } - } - }, - ] - }) -} - -# The CloudGuardAWPLambdaExecutionRolePolicyAttachment resource attaches the CloudGuardAWPLambdaExecutionRolePolicy to the CloudGuardAWPSnapshotsUtilsLambdaExecutionRole. -resource "aws_iam_policy_attachment" "CloudGuardAWPLambdaExecutionRolePolicyAttachment" { - count = local.scan_mode == "inAccount" ? 1 : 0 - name = "CloudGuardAWPLambdaExecutionRolePolicyAttachment" - policy_arn = aws_iam_policy.CloudGuardAWPLambdaExecutionRolePolicy[count.index].arn - roles = [aws_iam_role.CloudGuardAWPSnapshotsUtilsLambdaExecutionRole.name] -} - -# The CloudGuardAWPLambdaExecutionRolePolicyAttachment_SaaS resource attaches the CloudGuardAWPLambdaExecutionRolePolicy_SaaS to the CloudGuardAWPSnapshotsUtilsLambdaExecutionRole. -resource "aws_iam_policy_attachment" "CloudGuardAWPLambdaExecutionRolePolicyAttachment_SaaS" { - count = local.scan_mode == "saas" ? 1 : 0 - name = "CloudGuardAWPLambdaExecutionRolePolicyAttachment" - policy_arn = aws_iam_policy.CloudGuardAWPLambdaExecutionRolePolicy_SaaS[count.index].arn - roles = [aws_iam_role.CloudGuardAWPSnapshotsUtilsLambdaExecutionRole.name] -} -# END AWP proxy lambda function role policy - -# aws_lambda_invocation : The Lambda invocation that is used to clean up the resources after the onboarding process. -resource "aws_lambda_invocation" "CloudGuardAWPSnapshotsUtilsCleanupFunctionInvocation" { - function_name = aws_lambda_function.CloudGuardAWPSnapshotsUtilsFunction.function_name - input = jsonencode({ - "target_account_id" : data.dome9_awp_aws_get_onboarding_data.dome9_awp_aws_onboarding_data_source.cloud_account_id - }) - lifecycle_scope = "CRUD" - depends_on = [ - aws_iam_policy_attachment.CloudGuardAWPLambdaExecutionRolePolicyAttachment, - aws_iam_policy_attachment.CloudGuardAWPLambdaExecutionRolePolicyAttachment_SaaS - ] -} +# There is a need to use this terraform module [terraform-dome9-awp-aws] to create all the prerequisites for the onboarding process (All the needed AWS Resources) +# for further information please refer to the module documentation [terraform-dome9-awp-aws](https://registry.terraform.io/modules/dome9/awp-aws/dome9/latest) +# Example for the module use: +module "terraform-dome9-awp-aws" { + source = "github.com/dome9/terraform-dome9-awp-aws" + awp_cloud_account_id = "" + awp_scan_mode = "" # Valid Values = "inAccount" or "saas" + # Optional customizations: + # awp_cross_account_role_name = "CheckPoint-AWP-CrossAccount-Role" + # awp_cross_account_role_external_id = "AWP_Fake@ExternalID123" -# AWP MR key for snapshot re-encryption -# The CloudGuardAWPKey resource defines a KMS key that is used to re-encrypt the snapshots in SaaS mode. -resource "aws_kms_key" "CloudGuardAWPKey" { - count = local.scan_mode == "saas" ? 1 : 0 - description = "CloudGuard AWP Multi-Region primary key for snapshots re-encryption (for Saas mode only)" - enable_key_rotation = true - deletion_window_in_days = 7 - - # Conditionally set multi-region based on IsChinaPartition - multi_region = data.aws_partition.current.partition == "aws-cn" ? false : true - - policy = jsonencode({ - Version = "2012-10-17" - Id = "cloud-guard-awp-key" - Statement = [ - { - Sid = "Enable IAM User Permissions" - Effect = "Allow" - Principal = { - AWS = "arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:root" - } - Action = "kms:*" - Resource = "*" - }, - { - Sid = "Allow usage of the key" - Effect = "Allow" - Principal = { - AWS = "arn:${data.aws_partition.current.partition}:iam::${local.cloud_guard_backend_account_id}:root" - } - Action = [ - "kms:DescribeKey", - "kms:Encrypt", - "kms:Decrypt", - "kms:ReEncrypt*", - "kms:GenerateDataKey*", - "kms:PutKeyPolicy", - "kms:ScheduleKeyDeletion", - "kms:CancelKeyDeletion", - ] - Resource = "*" - }, - { - Sid = "Allow attachment of persistent resources" - Effect = "Allow" - Principal = { - AWS = "arn:${data.aws_partition.current.partition}:iam::${local.cloud_guard_backend_account_id}:root" - } - Action = [ - "kms:CreateGrant", - "kms:ListGrants", - "kms:RevokeGrant", - ] - Resource = "*" - Condition = { - Bool = { - "kms:GrantIsForAWSResource" = true - } - } - }, - ] - }) -} -#END AWP MR key for snapshot re-encryption - -# The CloudGuardAWPKeyAlias resource defines a KMS key alias that is used to reference the KMS key in SaaS mode. -resource "aws_kms_alias" "CloudGuardAWPKeyAlias" { - count = local.scan_mode == "saas" ? 1 : 0 - name = "alias/CloudGuardAWPKey" - target_key_id = aws_kms_key.CloudGuardAWPKey[count.index].arn - depends_on = [ - aws_kms_key.CloudGuardAWPKey - ] + # Optional account Settings + # e.g: + # awp_account_settings_aws = { + # scan_machine_interval_in_hours = 24 + # disabled_regions = ["ap-northeast-1", "ap-northeast-2", ...] + # max_concurrence_scans_per_region = 20 + # custom_tags = { + # tag1 = "value1" + # tag2 = "value2" + # tag3 = "value3" + # ... + # } + # } } # The dome9_awp_aws_onboarding resource defines a Dome9 AWP AWS Onboarding. @@ -703,33 +63,22 @@ resource "aws_kms_alias" "CloudGuardAWPKeyAlias" { # The disabled_regions attribute is used to specify the disabled regions of the agentless account settings of the Dome9 AWP AWS Onboarding. # The scan_machine_interval_in_hours attribute is used to specify the scan machine interval in hours of the agentless account settings of the Dome9 AWP AWS Onboarding. # The max_concurrence_scans_per_region attribute is used to specify the max concurrence scans per region of the agentless account settings of the Dome9 AWP AWS Onboarding. -# The skip_function_apps_scan attribute is used to specify whether to skip the function apps scan of the agentless account settings of the Dome9 AWP AWS Onboarding. # The custom_tags attribute is used to specify the custom tags of the agentless account settings of the Dome9 AWP AWS Onboarding. resource "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { cloudguard_account_id = "dome9_cloudaccount_aws.aws_onboarding_account_test.id | | " - cross_account_role_name = aws_iam_role.CloudGuardAWPCrossAccountRole.name - cross_account_role_external_id = local.cross_account_role_external_id - scan_mode = local.scan_mode - # Optional Settings - # e.g: - # agentless_account_settings { - # disabled_regions = [] // e.g: ["us-west-1", "us-west-2"] - # scan_machine_interval_in_hours = 24 - # max_concurrence_scans_per_region = 20 - # skip_function_apps_scan = false - # custom_tags = { - # # example of custom tags - # tag1 = "value1" - # tag2 = "value2" - # tag3 = "value3" - # } - # } - depends_on = [ - aws_iam_policy_attachment.CloudGuardAWPLambdaExecutionRolePolicyAttachment, - aws_iam_policy_attachment.CloudGuardAWPLambdaExecutionRolePolicyAttachment_SaaS, - aws_iam_role.CloudGuardAWPCrossAccountRole, - aws_iam_role_policy_attachment.CloudGuardAWPCrossAccountRoleAttachment - ] + cross_account_role_name = "" + cross_account_role_external_id = "" + scan_mode = "" # Valid Values = "inAccount" or "saas" + agentless_account_settings { + disabled_regions = ["us-east-1", "us-west-1", "ap-northeast-1", "ap-southeast-2"] + scan_machine_interval_in_hours = 24 + max_concurrence_scans_per_region = 20 + custom_tags = { + tag1 = "value1" + tag2 = "value2" + tag3 = "value3" + } + } } # The dome9_awp_aws_onboarding data source allows you to get the onboarding data of an AWS account (Optional). @@ -754,7 +103,6 @@ The following arguments are supported: * `disabled_regions` - (Optional) The disabled regions. valid values are "af-south-1", "ap-south-1", "eu-north-1", "eu-west-3", "eu-south-1", "eu-west-2", "eu-west-1", "ap-northeast-3", "ap-northeast-2", "me-south-1", "ap-northeast-1", "me-central-1", "ca-central-1", "sa-east-1", "ap-east-1", "ap-southeast-1", "ap-southeast-2", "eu-central-1", "ap-southeast-3", "us-east-1", "us-east-2", "us-west-1", "us-west-2" * `scan_machine_interval_in_hours` - (Optional) The scan machine interval in hours * `max_concurrence_scans_per_region` - (Optional) The max concurrence scans per region - * `skip_function_apps_scan` - (Optional) Whether to skip function apps scan. Default is false. * `custom_tags` - (Optional) The custom tags. * `should_create_policy` - (Optional) Whether to create a policy. Default is true. From b29a8f41ce1dd9e8bf2500e5df169bf322c19e3e Mon Sep 17 00:00:00 2001 From: Omar Date: Mon, 1 Apr 2024 14:26:27 +0300 Subject: [PATCH 37/47] cleanup const.go --- dome9/common/providerconst/const.go | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/dome9/common/providerconst/const.go b/dome9/common/providerconst/const.go index 3afe403c..a59ba93d 100644 --- a/dome9/common/providerconst/const.go +++ b/dome9/common/providerconst/const.go @@ -109,13 +109,13 @@ const ( AF_SOUTH_1 = "26" EU_SOUTH_1 = "27" AP_NORTHEAST_3 = "28" - ME_CENTRAL_1 = "29" - AP_SOUTH_2 = "30" - AP_SOUTHEAST_3 = "31" - AP_SOUTHEAST_4 = "32" - EU_CENTRAL_2 = "33" - EU_SOUTH_2 = "34" - IL_CENTRAL_1 = "35" + ME_CENTRAL_1 = "29" + AP_SOUTH_2 = "30" + AP_SOUTHEAST_3 = "31" + AP_SOUTHEAST_4 = "32" + EU_CENTRAL_2 = "33" + EU_SOUTH_2 = "34" + IL_CENTRAL_1 = "35" ) // Azure consts @@ -185,11 +185,11 @@ var AWSRegionsEnum = map[string]string{ "af_south_1": AF_SOUTH_1, "eu_south_1": EU_SOUTH_1, "ap_northeast_3": AP_NORTHEAST_3, - "me_central_1": ME_CENTRAL_1, - "ap_south_2": AP_SOUTH_2, - "ap_southeast_3": AP_SOUTHEAST_3, - "ap_southeast_4": AP_SOUTHEAST_4, - "eu_central_2": EU_CENTRAL_2, + "me_central_1": ME_CENTRAL_1, + "ap_south_2": AP_SOUTH_2, + "ap_southeast_3": AP_SOUTHEAST_3, + "ap_southeast_4": AP_SOUTHEAST_4, + "eu_central_2": EU_CENTRAL_2, "eu_south_2": EU_SOUTH_2, "il_central_1": IL_CENTRAL_1, } From d59ce303a628b543c8e72b22fce3890329a6de16 Mon Sep 17 00:00:00 2001 From: Omar Date: Mon, 1 Apr 2024 16:27:01 +0300 Subject: [PATCH 38/47] After CRs --- dome9/common/resourcetype/resource_type.go | 2 +- .../environmentvariable/environment_variable.go | 2 +- ...go => data_source_dome9_awp_aws_onboarding_data.go} | 0 ... data_source_dome9_awp_aws_onboarding_data_test.go} | 10 +++++----- dome9/provider.go | 2 +- website/docs/d/awp_aws_onboarding_data.html.markdown | 4 ++-- 6 files changed, 10 insertions(+), 10 deletions(-) rename dome9/{data_source_dome9_awp_aws_get_onboarding_data.go => data_source_dome9_awp_aws_onboarding_data.go} (100%) rename dome9/{data_source_dome9_awp_aws_get_onboarding_data_test.go => data_source_dome9_awp_aws_onboarding_data_test.go} (90%) diff --git a/dome9/common/resourcetype/resource_type.go b/dome9/common/resourcetype/resource_type.go index 5e6f96f4..40817ead 100644 --- a/dome9/common/resourcetype/resource_type.go +++ b/dome9/common/resourcetype/resource_type.go @@ -27,6 +27,6 @@ const ( AdmissionControlPolicy = "dome9_admission_control_policy" Assessment = "dome9_assessment" ImageAssurancePolicy = "dome9_image_assurance_policy" - AwpAwsGetOnboardingData = "dome9_awp_aws_onboarding_data" + AwpAwsOnboardingData = "dome9_awp_aws_onboarding_data" AwpAwsOnboarding = "dome9_awp_aws_onboarding" ) diff --git a/dome9/common/testing/environmentvariable/environment_variable.go b/dome9/common/testing/environmentvariable/environment_variable.go index 92b7d25f..fc708e39 100644 --- a/dome9/common/testing/environmentvariable/environment_variable.go +++ b/dome9/common/testing/environmentvariable/environment_variable.go @@ -23,7 +23,7 @@ const ( CloudAccountAWSEnvVarArn = "ARN" CloudAccountUpdatedAWSEnvVarArn = "ARN_UPDATE" CloudAccountAWSEnvVarSecret = "SECRET" - AwpAwsCrossAccountRoleExternalIdEnvVar = "AWP_EXTERNAL_ID" // it is backed up by this ssm parameter : arn:aws:ssm:us-east-1:969432878134:parameter/dome9/common/consec/automation/CrossAccountRoleExternalId + AwpAwsCrossAccountRoleExternalIdEnvVar = "AWP_EXTERNAL_ID" ) // Azure environment variable diff --git a/dome9/data_source_dome9_awp_aws_get_onboarding_data.go b/dome9/data_source_dome9_awp_aws_onboarding_data.go similarity index 100% rename from dome9/data_source_dome9_awp_aws_get_onboarding_data.go rename to dome9/data_source_dome9_awp_aws_onboarding_data.go diff --git a/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go b/dome9/data_source_dome9_awp_aws_onboarding_data_test.go similarity index 90% rename from dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go rename to dome9/data_source_dome9_awp_aws_onboarding_data_test.go index fa1fa588..12cbd1c1 100644 --- a/dome9/data_source_dome9_awp_aws_get_onboarding_data_test.go +++ b/dome9/data_source_dome9_awp_aws_onboarding_data_test.go @@ -12,8 +12,8 @@ import ( ) func TestAccDataSourceAwpAwsOnboardingDataBasic(t *testing.T) { - // Get dome9_awp_aws_get_onboarding_data resource names - _, awpAwsOnboardingDataSourceTypeAndName, awpAwsOnboardingDataGeneratedName := method.GenerateRandomSourcesTypeAndName(resourcetype.AwpAwsGetOnboardingData) + // Get dome9_awp_aws_onboarding_data resource names + _, awpAwsOnboardingDataSourceTypeAndName, awpAwsOnboardingDataGeneratedName := method.GenerateRandomSourcesTypeAndName(resourcetype.AwpAwsOnboardingData) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) @@ -41,14 +41,14 @@ func TestAccDataSourceAwpAwsOnboardingDataBasic(t *testing.T) { }) } -func testAccCheckAwpAwsOnboardingDataBasic(awpAwsGetOnboardingDataGeneratedName string) string { +func testAccCheckAwpAwsOnboardingDataBasic(awpAwsOnboardingDataGeneratedName string) string { res := fmt.Sprintf(` data "%s" "%s" { cloud_account_id = "%s" } `, - resourcetype.AwpAwsGetOnboardingData, - awpAwsGetOnboardingDataGeneratedName, + resourcetype.AwpAwsOnboardingData, + awpAwsOnboardingDataGeneratedName, variable.OnboardedAwsCloudGuardAccountID, ) log.Printf("[INFO] testAccCheckAwpAwsOnboardingDataBasic:%+v\n", res) diff --git a/dome9/provider.go b/dome9/provider.go index 8bf99d82..121512e1 100644 --- a/dome9/provider.go +++ b/dome9/provider.go @@ -86,7 +86,7 @@ func Provider() terraform.ResourceProvider { resourcetype.AdmissionControlPolicy: dataSourceAdmissionControlPolicy(), resourcetype.Assessment: dataSourceAssessment(), resourcetype.ImageAssurancePolicy: dataSourceImageAssurancePolicy(), - resourcetype.AwpAwsGetOnboardingData: dataSourceAwpAwsOnboardingData(), + resourcetype.AwpAwsOnboardingData: dataSourceAwpAwsOnboardingData(), resourcetype.AwpAwsOnboarding: dataSourceAwpAwsOnboarding(), }, ConfigureFunc: providerConfigure, diff --git a/website/docs/d/awp_aws_onboarding_data.html.markdown b/website/docs/d/awp_aws_onboarding_data.html.markdown index 155deae3..9da1bb5f 100644 --- a/website/docs/d/awp_aws_onboarding_data.html.markdown +++ b/website/docs/d/awp_aws_onboarding_data.html.markdown @@ -1,12 +1,12 @@ --- layout: "dome9" -page_title: "Check Point CloudGuard Dome9: dome9_awp_aws_get_onboarding_data" +page_title: "Check Point CloudGuard Dome9: dome9_awp_aws_onboarding_data" sidebar_current: "docs-datasource-dome9-awp-aws-get-onboarding-data" description: |- Get information about AWS AWP onboarding data in Dome9. --- -# Data Source: dome9_awp_aws_get_onboarding_data +# Data Source: dome9_awp_aws_onboarding_data Use this data source to get information about AWS AWP onboarding data in Dome9. From fae507a059185cd9942e0b1253596c04dd62122d Mon Sep 17 00:00:00 2001 From: Benny Zemmour Date: Tue, 2 Apr 2024 00:59:05 +0300 Subject: [PATCH 39/47] Add ForceNew: true for change mode support align default with BE --- dome9/resource_dome9_awp_aws_onboarding.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index 985225da..dc6be6e4 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -43,6 +43,7 @@ func resourceAwpAwsOnboarding() *schema.Resource { "scan_mode": { Type: schema.TypeString, Required: true, + ForceNew: true, ValidateFunc: validation.StringInSlice([]string{ "inAccount", "saas", @@ -66,12 +67,12 @@ func resourceAwpAwsOnboarding() *schema.Resource { "scan_machine_interval_in_hours": { Type: schema.TypeInt, Optional: true, - Default: 4, + Default: 24, }, "max_concurrence_scans_per_region": { Type: schema.TypeInt, Optional: true, - Default: 1, + Default: 20, }, "custom_tags": { Type: schema.TypeMap, From 03f43dd93eba5aecedc25278d741bad36cdd9212 Mon Sep 17 00:00:00 2001 From: Benny Zemmour Date: Tue, 2 Apr 2024 01:00:26 +0300 Subject: [PATCH 40/47] FMT --- dome9/data_source_dome9_assessment.go | 5 ++--- dome9/data_source_dome9_aws_unified_onboarding.go | 13 ++++++------- ...data_source_dome9_aws_unified_onboarding_test.go | 2 +- ...unified_onbording_update_version_stack_config.go | 1 - ...ed_onbording_update_version_stack_config_test.go | 2 +- dome9/data_source_dome9_cloudaccount_alibaba.go | 2 +- .../data_source_dome9_cloudaccount_alibaba_test.go | 1 - ...urce_dome9_continuous_compliance_notification.go | 8 ++++---- dome9/resource_dome9_assessment.go | 2 +- dome9/resource_dome9_awp_aws_onboarding.go | 7 ++++--- dome9/resource_dome9_cloudaccount_aws.go | 2 +- dome9/resource_dome9_cloudaccount_aws_test.go | 2 +- dome9/resource_dome9_cloudaccount_oci_test.go | 2 +- ...urce_dome9_continuous_compliance_notification.go | 13 ++++++------- dome9/resource_dome9_image_assurance_policy_test.go | 2 +- dome9/resource_dome9_unified_onbording.go | 5 ++--- 16 files changed, 32 insertions(+), 37 deletions(-) diff --git a/dome9/data_source_dome9_assessment.go b/dome9/data_source_dome9_assessment.go index 26e3ff8c..5b915b17 100644 --- a/dome9/data_source_dome9_assessment.go +++ b/dome9/data_source_dome9_assessment.go @@ -8,7 +8,7 @@ import ( func dataSourceAssessment() *schema.Resource { return &schema.Resource{ - Read: dataSourceAssessmentRead, + Read: dataSourceAssessmentRead, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, @@ -31,7 +31,7 @@ func dataSourceAssessment() *schema.Resource { Computed: true, }, "cloud_account_type": { - Type: schema.TypeString, + Type: schema.TypeString, Computed: true, }, "should_minimize_result": { @@ -720,4 +720,3 @@ func dataSourceAssessmentRead(d *schema.ResourceData, meta interface{}) error { return nil } - diff --git a/dome9/data_source_dome9_aws_unified_onboarding.go b/dome9/data_source_dome9_aws_unified_onboarding.go index ed7fe19b..9ba1d130 100644 --- a/dome9/data_source_dome9_aws_unified_onboarding.go +++ b/dome9/data_source_dome9_aws_unified_onboarding.go @@ -6,7 +6,6 @@ import ( "github.com/terraform-providers/terraform-provider-dome9/dome9/common/providerconst" ) - func dataSourceAwsUnifiedOnboarding() *schema.Resource { return &schema.Resource{ Read: dataSourceAwsUnifiedOnboardingReadInfo, @@ -175,12 +174,12 @@ func expendStatuses(statuses aws_unified_onboarding.Statuses) interface{} { for i, statusItem := range statuses { statusesList[i] = map[string]interface{}{ - providerconst.Module : statusItem.Module, - providerconst.Feature: statusItem.Feature, - providerconst.Status: statusItem.Status, - providerconst.StatusMessage: statusItem.StackMessage, - providerconst.StackStatus: statusItem.StackStatus, - providerconst.StackMessage: statusItem.StackMessage, + providerconst.Module: statusItem.Module, + providerconst.Feature: statusItem.Feature, + providerconst.Status: statusItem.Status, + providerconst.StatusMessage: statusItem.StackMessage, + providerconst.StackStatus: statusItem.StackStatus, + providerconst.StackMessage: statusItem.StackMessage, providerconst.RemediationRecommendation: statusItem.RemediationRecommendation, } } diff --git a/dome9/data_source_dome9_aws_unified_onboarding_test.go b/dome9/data_source_dome9_aws_unified_onboarding_test.go index c0754f8e..242f324f 100644 --- a/dome9/data_source_dome9_aws_unified_onboarding_test.go +++ b/dome9/data_source_dome9_aws_unified_onboarding_test.go @@ -34,4 +34,4 @@ func TestAccDataSourceAWSUnifiedOnboardingBasic(t *testing.T) { func testAccCheckAWSUnifiedOnboardingDestroy(state *terraform.State) error { return nil -} \ No newline at end of file +} diff --git a/dome9/data_source_dome9_aws_unified_onbording_update_version_stack_config.go b/dome9/data_source_dome9_aws_unified_onbording_update_version_stack_config.go index 696ed4a1..64ef5741 100644 --- a/dome9/data_source_dome9_aws_unified_onbording_update_version_stack_config.go +++ b/dome9/data_source_dome9_aws_unified_onbording_update_version_stack_config.go @@ -5,7 +5,6 @@ import ( "github.com/terraform-providers/terraform-provider-dome9/dome9/common/providerconst" ) - func dataSourceAwsUnifiedOnboardingUpdateVersionStackConfig() *schema.Resource { return &schema.Resource{ Read: dataSourceAwsUnifiedOnboardingReadConfig, diff --git a/dome9/data_source_dome9_aws_unified_onbording_update_version_stack_config_test.go b/dome9/data_source_dome9_aws_unified_onbording_update_version_stack_config_test.go index 5e20cd72..0d9c960b 100644 --- a/dome9/data_source_dome9_aws_unified_onbording_update_version_stack_config_test.go +++ b/dome9/data_source_dome9_aws_unified_onbording_update_version_stack_config_test.go @@ -13,7 +13,7 @@ import ( func TestAccDataSourceAWSUnifiedOnboardingUpdateVersionStackConfogurationBasic(t *testing.T) { resourceTypeAndName, _, resourceName := method.GenerateRandomSourcesTypeAndName(resourcetype.AwsUnifiedOnboarding) dataTypeAndName := fmt.Sprintf("data.%s.%s", resourcetype.AwsUnifiedOnboardingUpdateVersionStackConfig, resourceName) - log.Println("TestAccDataSourceAWSUnifiedOnboardingUpdateVersionStackConfogurationBasic ",resourceTypeAndName, dataTypeAndName, resourceName) + log.Println("TestAccDataSourceAWSUnifiedOnboardingUpdateVersionStackConfogurationBasic ", resourceTypeAndName, dataTypeAndName, resourceName) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) diff --git a/dome9/data_source_dome9_cloudaccount_alibaba.go b/dome9/data_source_dome9_cloudaccount_alibaba.go index 3dd34d16..5ff920d9 100644 --- a/dome9/data_source_dome9_cloudaccount_alibaba.go +++ b/dome9/data_source_dome9_cloudaccount_alibaba.go @@ -87,7 +87,7 @@ func dataSourceAlibabaRead(d *schema.ResourceData, meta interface{}) error { return nil } -func setCredentials(credentials alibaba.CloudAccountCredentialsResponse) map[string]interface{}{ +func setCredentials(credentials alibaba.CloudAccountCredentialsResponse) map[string]interface{} { return map[string]interface{}{ "access_key": credentials.AccessKey, } diff --git a/dome9/data_source_dome9_cloudaccount_alibaba_test.go b/dome9/data_source_dome9_cloudaccount_alibaba_test.go index 36eed7ee..762e4d55 100644 --- a/dome9/data_source_dome9_cloudaccount_alibaba_test.go +++ b/dome9/data_source_dome9_cloudaccount_alibaba_test.go @@ -32,7 +32,6 @@ func TestAccDataSourceCloudAccountAlibabaBasic(t *testing.T) { resource.TestCheckResourceAttrPair(dataSourceTypeAndName, "organizational_unit_path", resourceTypeAndName, "organizational_unit_path"), resource.TestCheckResourceAttrPair(dataSourceTypeAndName, "organizational_unit_name", resourceTypeAndName, "organizational_unit_name"), resource.TestCheckResourceAttrPair(dataSourceTypeAndName, "vendor", resourceTypeAndName, "vendor"), - ), }, }, diff --git a/dome9/data_source_dome9_continuous_compliance_notification.go b/dome9/data_source_dome9_continuous_compliance_notification.go index ef7e1837..b28da6ca 100644 --- a/dome9/data_source_dome9_continuous_compliance_notification.go +++ b/dome9/data_source_dome9_continuous_compliance_notification.go @@ -91,11 +91,11 @@ func dataSourceContinuousComplianceNotification() *schema.Resource { Computed: true, }, "slack_integration_state": { - Type: schema.TypeString, + Type: schema.TypeString, Computed: true, }, "teams_integration_state": { - Type: schema.TypeString, + Type: schema.TypeString, Computed: true, }, "email_data": { @@ -317,11 +317,11 @@ func dataSourceContinuousComplianceNotificationRead(d *schema.ResourceData, meta } } - flattenChangeDetection, err:= flattenChangeDetection(&resp.ChangeDetection) + flattenChangeDetection, err := flattenChangeDetection(&resp.ChangeDetection) if err != nil { return err } - if err := d.Set("change_detection", flattenChangeDetection); err != nil{ + if err := d.Set("change_detection", flattenChangeDetection); err != nil { return err } diff --git a/dome9/resource_dome9_assessment.go b/dome9/resource_dome9_assessment.go index e290b88d..0f5223aa 100644 --- a/dome9/resource_dome9_assessment.go +++ b/dome9/resource_dome9_assessment.go @@ -44,7 +44,7 @@ func resourceAssessment() *schema.Resource { }, "should_minimize_result": { Type: schema.TypeBool, - Default: true, + Default: true, Optional: true, }, "name": { diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index dc6be6e4..dce2fc74 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -3,14 +3,15 @@ package dome9 import ( "errors" "fmt" + "log" + "strconv" + "strings" + "github.com/dome9/dome9-sdk-go/dome9/client" "github.com/dome9/dome9-sdk-go/services/awp_aws_onboarding" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/helper/validation" "github.com/terraform-providers/terraform-provider-dome9/dome9/common/providerconst" - "log" - "strconv" - "strings" ) func resourceAwpAwsOnboarding() *schema.Resource { diff --git a/dome9/resource_dome9_cloudaccount_aws.go b/dome9/resource_dome9_cloudaccount_aws.go index 813d4091..fdc8750c 100644 --- a/dome9/resource_dome9_cloudaccount_aws.go +++ b/dome9/resource_dome9_cloudaccount_aws.go @@ -375,7 +375,7 @@ func validateAwsGovVendor(credentials aws.CloudAccountCredentials, regions []str } func validateAwsVendor(credentials aws.CloudAccountCredentials, regions []string) (bool, error) { - validate := checkRegions(regions, providerconst.AWSRegions) + validate := checkRegions(regions, providerconst.AWSRegions) if !validate { return validate, fmt.Errorf("aws vendor has an unsutibule regions") } diff --git a/dome9/resource_dome9_cloudaccount_aws_test.go b/dome9/resource_dome9_cloudaccount_aws_test.go index a1d0931a..5f397ee9 100644 --- a/dome9/resource_dome9_cloudaccount_aws_test.go +++ b/dome9/resource_dome9_cloudaccount_aws_test.go @@ -62,7 +62,7 @@ func TestAccResourceCloudAccountAWSBasic(t *testing.T) { resource.TestCheckResourceAttr(resourceTypeAndName, "net_sec.0.regions.2.new_group_behavior", originalGroupBehavior), ), }, - }, + }, }) } diff --git a/dome9/resource_dome9_cloudaccount_oci_test.go b/dome9/resource_dome9_cloudaccount_oci_test.go index 574d9ac5..a25bf198 100644 --- a/dome9/resource_dome9_cloudaccount_oci_test.go +++ b/dome9/resource_dome9_cloudaccount_oci_test.go @@ -56,7 +56,7 @@ func testAccCheckCloudAccountOciDestroy(s *terraform.State) error { return fmt.Errorf("cloudaccounts with id %s exists and wasn't destroyed", rs.Primary.ID) } } - + return nil } diff --git a/dome9/resource_dome9_continuous_compliance_notification.go b/dome9/resource_dome9_continuous_compliance_notification.go index ef0c1a1d..0bcd0bef 100644 --- a/dome9/resource_dome9_continuous_compliance_notification.go +++ b/dome9/resource_dome9_continuous_compliance_notification.go @@ -263,10 +263,10 @@ func resourceContinuousComplianceNotification() *schema.Resource { Required: true, }, "http_method": { - Type: schema.TypeString, - Optional: true, - Default: "Post", - ForceNew: true, + Type: schema.TypeString, + Optional: true, + Default: "Post", + ForceNew: true, ValidateFunc: validation.StringInSlice([]string{"Post", "Put"}, true), }, "auth_method": { @@ -408,7 +408,7 @@ func resourceContinuousComplianceNotificationRead(d *schema.ResourceData, meta i } } - flattenChangeDetection, err:= flattenChangeDetection(&resp.ChangeDetection) + flattenChangeDetection, err := flattenChangeDetection(&resp.ChangeDetection) if err != nil { return err } @@ -613,7 +613,6 @@ func expandWebhookData(webhookData *schema.Set) (*continuous_compliance_notifica webhookDataItem := webhookDataLst[0] webhookData := webhookDataItem.(map[string]interface{}) - PayloadFormatJson := make(map[string]interface{}) err := json.Unmarshal([]byte(webhookData["payload_format"].(string)), &PayloadFormatJson) if err != nil { @@ -871,4 +870,4 @@ func ValidatePayloadFormatJSON(v interface{}, k string) (ws []string, errors []e return } return -} \ No newline at end of file +} diff --git a/dome9/resource_dome9_image_assurance_policy_test.go b/dome9/resource_dome9_image_assurance_policy_test.go index 210fb6a8..ab9da7c6 100644 --- a/dome9/resource_dome9_image_assurance_policy_test.go +++ b/dome9/resource_dome9_image_assurance_policy_test.go @@ -175,4 +175,4 @@ resource "%s" "%s" { IfThenElse(updateAction, variable.ImageAssurancePolicyPreventAction, variable.ImageAssurancePolicyDetectAction), IfThenElse(updateAction, variable.ImageAssurancePolicyPreventAction, variable.ImageAssurancePolicyDetectAction), ) -} \ No newline at end of file +} diff --git a/dome9/resource_dome9_unified_onbording.go b/dome9/resource_dome9_unified_onbording.go index d4bc7dcf..a2d31ccd 100644 --- a/dome9/resource_dome9_unified_onbording.go +++ b/dome9/resource_dome9_unified_onbording.go @@ -157,7 +157,7 @@ func getEnabledFromMap(configurations map[string]interface{}) bool { if len(configurations) > 0 { enabled := configurations[providerconst.Enabled] - if enabled != "" && enabled != nil { + if enabled != "" && enabled != nil { v := enabled.(string) b, _ = strconv.ParseBool(v) } @@ -209,8 +209,7 @@ func addOnboardingIdAsSchemaId(d *schema.ResourceData, resp *aws_unified_onboard } } -func -resourceUnifiedOnboardingDelete(data *schema.ResourceData, i interface{}) error { +func resourceUnifiedOnboardingDelete(data *schema.ResourceData, i interface{}) error { return nil } From 85a7429efd0d14ded825a53c4b0c9f24d4792bda Mon Sep 17 00:00:00 2001 From: Omar Date: Tue, 2 Apr 2024 02:57:22 +0300 Subject: [PATCH 41/47] some docs corrections --- examples/awp_aws_onboarding/main.tf | 73 +++++++++---------- .../docs/r/awp_aws_onboarding.html.markdown | 6 +- 2 files changed, 38 insertions(+), 41 deletions(-) diff --git a/examples/awp_aws_onboarding/main.tf b/examples/awp_aws_onboarding/main.tf index b4257bcc..40f3ee74 100644 --- a/examples/awp_aws_onboarding/main.tf +++ b/examples/awp_aws_onboarding/main.tf @@ -1,3 +1,16 @@ +terraform { + required_providers { + dome9 = { + source = "dome9/dome9" + version = ">=1.29.6" + } + aws = { + source = "hashicorp/aws" + version = ">= 3.0" + } + } +} + # The Dome9 provider is used to interact with the resources supported by Dome9. # The provider needs to be configured with the proper credentials before it can be used. # Use the dome9_access_id and dome9_secret_key attributes of the provider to provide the Dome9 access key and secret key. @@ -26,14 +39,34 @@ provider "aws" { token = "AWS_SESSION_TOKEN" } +# Onboarding AWS Account to CloudGuard Dome9 Account +# This resource is optional and can be ignored and you need to pass CloudGuard account id to the module directly at the parameter awp_cloud_account_id. +# to know how to get the credentials for the onboarding process, please refer to the following link: +## https://sc1.checkpoint.com/documents/CloudGuard_Dome9/Documentation/Assets/AWS/OnboardAWS.htm +resource "dome9_cloudaccount_aws" "aws_onboarding_account_test" { + name = "aws_onboarding_account_test" + credentials { + arn = "CloudGuard Connect Role ARN" + secret = "CloudGuard Connect Role Secret" + type = "RoleBased" + } + net_sec { + regions { + new_group_behavior = "ReadOnly" + region = "us_west_2" + } + } +} + # There is a need to use this terraform module [terraform-dome9-awp-aws] to create all the prerequisites for the onboarding process (All the needed AWS Resources) # Example for the module use: module "terraform-dome9-awp-aws" { - source = "github.com/dome9/terraform-dome9-awp-aws" + source = "github.com/dome9/terraform-dome9-awp-aws?ref=AL-2317-AWP-Terraform-AWS-Module" awp_cloud_account_id = "" awp_scan_mode = "" # Valid Values = "inAccount" or "saas" + # Optional customizations: - # awp_cross_account_role_name = "CheckPoint-AWP-CrossAccount-Role" + # awp_cross_account_role_name = "CheckPoint-AWP-CrossAccount-Role-22" # awp_cross_account_role_external_id = "AWP_Fake@ExternalID123" # Optional account Settings @@ -49,40 +82,4 @@ module "terraform-dome9-awp-aws" { # ... # } # } -} - -# The dome9_awp_aws_onboarding resource defines a Dome9 AWP AWS Onboarding. -# The Dome9 AWP AWS Onboarding resource allows you to onboard an AWS account to Dome9 AWP. -# The cloudguard_account_id attribute is used to specify the CloudGuard account id of the AWS account. -# The cross_account_role_name attribute is used to specify the name of the cross account role that is used to allow AWP to access the AWS account. -# The cross_account_role_external_id attribute is used to specify the external id of the cross account role that is used to allow AWP to access the AWS account. -# The scan_mode attribute is used to specify the scan mode of the Dome9 AWP AWS Onboarding. The valid values are "inAccount" and "saas". -# The agentless_account_settings attribute is used to specify the agentless account settings of the Dome9 AWP AWS Onboarding. -# The disabled_regions attribute is used to specify the disabled regions of the agentless account settings of the Dome9 AWP AWS Onboarding. -# The scan_machine_interval_in_hours attribute is used to specify the scan machine interval in hours of the agentless account settings of the Dome9 AWP AWS Onboarding. -# The max_concurrence_scans_per_region attribute is used to specify the max concurrence scans per region of the agentless account settings of the Dome9 AWP AWS Onboarding. -# The custom_tags attribute is used to specify the custom tags of the agentless account settings of the Dome9 AWP AWS Onboarding. -resource "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { - cloudguard_account_id = "dome9_cloudaccount_aws.aws_onboarding_account_test.id | | " - cross_account_role_name = "" - cross_account_role_external_id = "" - scan_mode = "" # Valid Values = "inAccount" or "saas" - agentless_account_settings { - disabled_regions = ["us-east-1", "us-west-1", "ap-northeast-1", "ap-southeast-2"] - scan_machine_interval_in_hours = 24 - max_concurrence_scans_per_region = 20 - custom_tags = { - tag1 = "value1" - tag2 = "value2" - tag3 = "value3" - } - } -} - -# The dome9_awp_aws_onboarding data source allows you to get the onboarding data of an AWS account (Optional). -data "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { - id = dome9_awp_aws_onboarding.awp_aws_onboarding_test.cloudguard_account_id - depends_on = [ - dome9_awp_aws_onboarding.awp_aws_onboarding_test - ] } \ No newline at end of file diff --git a/website/docs/r/awp_aws_onboarding.html.markdown b/website/docs/r/awp_aws_onboarding.html.markdown index 25eb5fe6..6879c41a 100644 --- a/website/docs/r/awp_aws_onboarding.html.markdown +++ b/website/docs/r/awp_aws_onboarding.html.markdown @@ -27,8 +27,11 @@ provider "aws" { token = "AWS_SESSION_TOKEN" } +# ToDo + # change the repo url to correct links after publishing the module # There is a need to use this terraform module [terraform-dome9-awp-aws] to create all the prerequisites for the onboarding process (All the needed AWS Resources) # for further information please refer to the module documentation [terraform-dome9-awp-aws](https://registry.terraform.io/modules/dome9/awp-aws/dome9/latest) +# for more examples (simple and complete), you can visit this github examples [terraform-dome9-awp-aws](https://github.com/dome9/terraform-dome9-awp-aws/tree/AL-2317-AWP-Terraform-AWS-Module/examples) # Example for the module use: module "terraform-dome9-awp-aws" { source = "github.com/dome9/terraform-dome9-awp-aws" @@ -84,9 +87,6 @@ resource "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { # The dome9_awp_aws_onboarding data source allows you to get the onboarding data of an AWS account (Optional). data "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { id = dome9_awp_aws_onboarding.awp_aws_onboarding_test.cloudguard_account_id - depends_on = [ - dome9_awp_aws_onboarding.awp_aws_onboarding_test - ] } ``` From 0f379e35191a796fe936ab800978f1f8c7900ec1 Mon Sep 17 00:00:00 2001 From: Omar Date: Tue, 2 Apr 2024 11:22:46 +0300 Subject: [PATCH 42/47] update max_concurrent_scans_per_region variable name --- dome9/data_source_dome9_awp_aws_onboarding.go | 2 +- ...ta_source_dome9_awp_aws_onboarding_test.go | 2 +- dome9/resource_dome9_awp_aws_onboarding.go | 19 +++++++++---------- .../resource_dome9_awp_aws_onboarding_test.go | 6 +++--- examples/awp_aws_onboarding/main.tf | 2 +- .../docs/r/awp_aws_onboarding.html.markdown | 8 ++++---- 6 files changed, 19 insertions(+), 20 deletions(-) diff --git a/dome9/data_source_dome9_awp_aws_onboarding.go b/dome9/data_source_dome9_awp_aws_onboarding.go index 3ef6111e..fe00c7b8 100644 --- a/dome9/data_source_dome9_awp_aws_onboarding.go +++ b/dome9/data_source_dome9_awp_aws_onboarding.go @@ -38,7 +38,7 @@ func dataSourceAwpAwsOnboarding() *schema.Resource { Type: schema.TypeInt, Computed: true, }, - "max_concurrence_scans_per_region": { + "max_concurrent_scans_per_region": { Type: schema.TypeInt, Computed: true, }, diff --git a/dome9/data_source_dome9_awp_aws_onboarding_test.go b/dome9/data_source_dome9_awp_aws_onboarding_test.go index c9de1ca5..72eebe1b 100644 --- a/dome9/data_source_dome9_awp_aws_onboarding_test.go +++ b/dome9/data_source_dome9_awp_aws_onboarding_test.go @@ -35,7 +35,7 @@ func TestAccDataSourceAwpAwsOnboardingBasic(t *testing.T) { resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "agentless_account_settings.0.disabled_regions.0", awpAwsOnboardingResourceTypeAndName, "agentless_account_settings.0.disabled_regions.0"), resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "agentless_account_settings.0.disabled_regions.1", awpAwsOnboardingResourceTypeAndName, "agentless_account_settings.0.disabled_regions.1"), resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "agentless_account_settings.0.scan_machine_interval_in_hours", awpAwsOnboardingResourceTypeAndName, "agentless_account_settings.0.scan_machine_interval_in_hours"), - resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "agentless_account_settings.0.max_concurrence_scans_per_region", awpAwsOnboardingResourceTypeAndName, "agentless_account_settings.0.max_concurrence_scans_per_region"), + resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "agentless_account_settings.0.max_concurrent_scans_per_region", awpAwsOnboardingResourceTypeAndName, "agentless_account_settings.0.max_concurrent_scans_per_region"), resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "agentless_account_settings.0.custom_tags.%", awpAwsOnboardingResourceTypeAndName, "agentless_account_settings.0.custom_tags.%"), resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "missing_awp_private_network_regions", awpAwsOnboardingResourceTypeAndName, "missing_awp_private_network_regions"), resource.TestCheckResourceAttrPair(awpAwsOnboardingDataSourceTypeAndName, "agentless_protection_enabled", awpAwsOnboardingResourceTypeAndName, "agentless_protection_enabled"), diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index dce2fc74..c3044fe9 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -68,12 +68,12 @@ func resourceAwpAwsOnboarding() *schema.Resource { "scan_machine_interval_in_hours": { Type: schema.TypeInt, Optional: true, - Default: 24, + Default: 24, }, - "max_concurrence_scans_per_region": { + "max_concurrent_scans_per_region": { Type: schema.TypeInt, Optional: true, - Default: 20, + Default: 20, }, "custom_tags": { Type: schema.TypeMap, @@ -87,7 +87,6 @@ func resourceAwpAwsOnboarding() *schema.Resource { }, "missing_awp_private_network_regions": { Type: schema.TypeList, - Optional: true, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, @@ -291,9 +290,9 @@ func expandAgentlessAccountSettings(d *schema.ResourceData) (*awp_aws_onboarding agentlessAccountSettings.ScanMachineIntervalInHours = scanMachineInterval } - if maxConcurrenceScans, ok := agentlessAccountSettingsMap["max_concurrence_scans_per_region"].(int); ok { + if maxConcurrenceScans, ok := agentlessAccountSettingsMap["max_concurrent_scans_per_region"].(int); ok { if maxConcurrenceScans < 1 || maxConcurrenceScans > 20 { - return nil, fmt.Errorf("max_concurrence_scans_per_region must be between 1 and 20") + return nil, fmt.Errorf("max_concurrent_scans_per_region must be between 1 and 20") } agentlessAccountSettings.MaxConcurrenceScansPerRegion = maxConcurrenceScans } @@ -328,10 +327,10 @@ func setAgentlessAccountSettings(resp *awp_aws_onboarding.GetAWPOnboardingRespon func flattenAgentlessAccountSettings(settings *awp_aws_onboarding.AgentlessAccountSettings) []interface{} { m := map[string]interface{}{ - "disabled_regions": settings.DisabledRegions, - "scan_machine_interval_in_hours": settings.ScanMachineIntervalInHours, - "max_concurrence_scans_per_region": settings.MaxConcurrenceScansPerRegion, - "custom_tags": settings.CustomTags, + "disabled_regions": settings.DisabledRegions, + "scan_machine_interval_in_hours": settings.ScanMachineIntervalInHours, + "max_concurrent_scans_per_region": settings.MaxConcurrenceScansPerRegion, + "custom_tags": settings.CustomTags, } return []interface{}{m} } diff --git a/dome9/resource_dome9_awp_aws_onboarding_test.go b/dome9/resource_dome9_awp_aws_onboarding_test.go index 5626156f..f72e7b91 100644 --- a/dome9/resource_dome9_awp_aws_onboarding_test.go +++ b/dome9/resource_dome9_awp_aws_onboarding_test.go @@ -48,7 +48,7 @@ func TestAccResourceAWPAWSOnboardingBasic(t *testing.T) { resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions.0", disabledRegion1), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions.1", disabledRegion2), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.scan_machine_interval_in_hours", variable.ScanMachineIntervalInHours), - resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.max_concurrence_scans_per_region", variable.MaxConcurrencyScansPerRegion), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.max_concurrent_scans_per_region", variable.MaxConcurrencyScansPerRegion), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.custom_tags.%", "2"), resource.TestCheckResourceAttrSet(resourceTypeAndName, "id"), resource.TestCheckResourceAttr(resourceTypeAndName, "cloud_provider", "aws"), @@ -69,7 +69,7 @@ func TestAccResourceAWPAWSOnboardingBasic(t *testing.T) { resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions.2", disabledRegionUpdate3), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions.3", disabledRegionUpdate4), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.scan_machine_interval_in_hours", variable.ScanMachineIntervalInHoursUpdate), - resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.max_concurrence_scans_per_region", variable.MaxConcurrenceScansPerRegionUpdate), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.max_concurrent_scans_per_region", variable.MaxConcurrenceScansPerRegionUpdate), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.custom_tags.%", "3"), resource.TestCheckResourceAttrSet(resourceTypeAndName, "id"), resource.TestCheckResourceAttr(resourceTypeAndName, "cloud_provider", "aws"), @@ -153,7 +153,7 @@ resource "%s" "%s" { agentless_account_settings { disabled_regions = %s scan_machine_interval_in_hours = "%s" - max_concurrence_scans_per_region = "%s" + max_concurrent_scans_per_region = "%s" custom_tags = %s } } diff --git a/examples/awp_aws_onboarding/main.tf b/examples/awp_aws_onboarding/main.tf index 40f3ee74..b9057b2c 100644 --- a/examples/awp_aws_onboarding/main.tf +++ b/examples/awp_aws_onboarding/main.tf @@ -74,7 +74,7 @@ module "terraform-dome9-awp-aws" { # awp_account_settings_aws = { # scan_machine_interval_in_hours = 24 # disabled_regions = ["ap-northeast-1", "ap-northeast-2", ...] - # max_concurrence_scans_per_region = 20 + # max_concurrent_scans_per_region = 20 # custom_tags = { # tag1 = "value1" # tag2 = "value2" diff --git a/website/docs/r/awp_aws_onboarding.html.markdown b/website/docs/r/awp_aws_onboarding.html.markdown index 6879c41a..b5b96d4e 100644 --- a/website/docs/r/awp_aws_onboarding.html.markdown +++ b/website/docs/r/awp_aws_onboarding.html.markdown @@ -46,7 +46,7 @@ module "terraform-dome9-awp-aws" { # awp_account_settings_aws = { # scan_machine_interval_in_hours = 24 # disabled_regions = ["ap-northeast-1", "ap-northeast-2", ...] - # max_concurrence_scans_per_region = 20 + # max_concurrent_scans_per_region = 20 # custom_tags = { # tag1 = "value1" # tag2 = "value2" @@ -65,7 +65,7 @@ module "terraform-dome9-awp-aws" { # The agentless_account_settings attribute is used to specify the agentless account settings of the Dome9 AWP AWS Onboarding. # The disabled_regions attribute is used to specify the disabled regions of the agentless account settings of the Dome9 AWP AWS Onboarding. # The scan_machine_interval_in_hours attribute is used to specify the scan machine interval in hours of the agentless account settings of the Dome9 AWP AWS Onboarding. -# The max_concurrence_scans_per_region attribute is used to specify the max concurrence scans per region of the agentless account settings of the Dome9 AWP AWS Onboarding. +# The max_concurrent_scans_per_region attribute is used to specify the max concurrence scans per region of the agentless account settings of the Dome9 AWP AWS Onboarding. # The custom_tags attribute is used to specify the custom tags of the agentless account settings of the Dome9 AWP AWS Onboarding. resource "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { cloudguard_account_id = "dome9_cloudaccount_aws.aws_onboarding_account_test.id | | " @@ -75,7 +75,7 @@ resource "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { agentless_account_settings { disabled_regions = ["us-east-1", "us-west-1", "ap-northeast-1", "ap-southeast-2"] scan_machine_interval_in_hours = 24 - max_concurrence_scans_per_region = 20 + max_concurrent_scans_per_region = 20 custom_tags = { tag1 = "value1" tag2 = "value2" @@ -102,7 +102,7 @@ The following arguments are supported: * `agentless_account_settings` - (Optional) The agentless account settings. * `disabled_regions` - (Optional) The disabled regions. valid values are "af-south-1", "ap-south-1", "eu-north-1", "eu-west-3", "eu-south-1", "eu-west-2", "eu-west-1", "ap-northeast-3", "ap-northeast-2", "me-south-1", "ap-northeast-1", "me-central-1", "ca-central-1", "sa-east-1", "ap-east-1", "ap-southeast-1", "ap-southeast-2", "eu-central-1", "ap-southeast-3", "us-east-1", "us-east-2", "us-west-1", "us-west-2" * `scan_machine_interval_in_hours` - (Optional) The scan machine interval in hours - * `max_concurrence_scans_per_region` - (Optional) The max concurrence scans per region + * `max_concurrent_scans_per_region` - (Optional) The max concurrence scans per region * `custom_tags` - (Optional) The custom tags. * `should_create_policy` - (Optional) Whether to create a policy. Default is true. From c5e7b57270e610520001dd5fb562ec5aa1a09436 Mon Sep 17 00:00:00 2001 From: Omar Date: Tue, 2 Apr 2024 12:43:33 +0300 Subject: [PATCH 43/47] prevent update of unsupported fields --- dome9/resource_dome9_awp_aws_onboarding.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index c3044fe9..00a51be0 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -153,6 +153,13 @@ func resourceAwpAwsOnboarding() *schema.Resource { return fmt.Errorf("'centralized_cloud_account_id' must be set and not empty when 'scan_mode' is 'inAccountSub'") } } + // Add checks for unsupported fields + unsupportedFields := []string{"cross_account_role_name", "cross_account_role_external_id"} + for _, field := range unsupportedFields { + if diff.HasChange(field) { + return fmt.Errorf("changing the '%s' field is not supported", field) + } + } return nil }, } From 158dfb025abc97aaf4e0687cd8b9f0e77b646877 Mon Sep 17 00:00:00 2001 From: Omar Date: Tue, 2 Apr 2024 14:41:04 +0300 Subject: [PATCH 44/47] Remove validation for unsupported accounts and use FroceNew : True --- dome9/resource_dome9_awp_aws_onboarding.go | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index 00a51be0..5cb0c7a2 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -35,10 +35,12 @@ func resourceAwpAwsOnboarding() *schema.Resource { }, "cross_account_role_name": { Type: schema.TypeString, + ForceNew: true, Required: true, }, "cross_account_role_external_id": { Type: schema.TypeString, + ForceNew: true, Required: true, }, "scan_mode": { @@ -153,13 +155,6 @@ func resourceAwpAwsOnboarding() *schema.Resource { return fmt.Errorf("'centralized_cloud_account_id' must be set and not empty when 'scan_mode' is 'inAccountSub'") } } - // Add checks for unsupported fields - unsupportedFields := []string{"cross_account_role_name", "cross_account_role_external_id"} - for _, field := range unsupportedFields { - if diff.HasChange(field) { - return fmt.Errorf("changing the '%s' field is not supported", field) - } - } return nil }, } From 377a92833249c59edaa8b2c258c203001eb835ba Mon Sep 17 00:00:00 2001 From: Omar Date: Wed, 3 Apr 2024 01:50:00 +0300 Subject: [PATCH 45/47] remove unnecessary centralized logic + attribute + CRs --- dome9/data_source_dome9_awp_aws_onboarding.go | 5 ----- dome9/resource_dome9_awp_aws_onboarding.go | 19 ------------------- .../docs/d/awp_aws_onboarding.html.markdown | 1 - .../docs/r/awp_aws_onboarding.html.markdown | 1 - 4 files changed, 26 deletions(-) diff --git a/dome9/data_source_dome9_awp_aws_onboarding.go b/dome9/data_source_dome9_awp_aws_onboarding.go index fe00c7b8..e38c2f12 100644 --- a/dome9/data_source_dome9_awp_aws_onboarding.go +++ b/dome9/data_source_dome9_awp_aws_onboarding.go @@ -14,10 +14,6 @@ func dataSourceAwpAwsOnboarding() *schema.Resource { Type: schema.TypeString, Required: true, }, - "centralized_cloud_account_id": { - Type: schema.TypeString, - Computed: true, - }, "scan_mode": { Type: schema.TypeString, Computed: true, @@ -118,7 +114,6 @@ func dataSourceAwpAwsOnboardingRead(d *schema.ResourceData, meta interface{}) er d.SetId(resp.CloudAccountId) // Set other schema fields here - _ = d.Set("centralized_cloud_account_id", resp.CentralizedCloudAccountId) _ = d.Set("scan_mode", resp.ScanMode) _ = d.Set("missing_awp_private_network_regions", resp.MissingAwpPrivateNetworkRegions) _ = d.Set("cloud_account_id", resp.CloudAccountId) diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index 5cb0c7a2..e4a7f73c 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -29,10 +29,6 @@ func resourceAwpAwsOnboarding() *schema.Resource { Required: true, ForceNew: true, }, - "centralized_cloud_account_id": { - Type: schema.TypeString, - Optional: true, - }, "cross_account_role_name": { Type: schema.TypeString, ForceNew: true, @@ -147,16 +143,6 @@ func resourceAwpAwsOnboarding() *schema.Resource { Default: true, }, }, - CustomizeDiff: func(diff *schema.ResourceDiff, v interface{}) error { - scanMode, scanModeOk := diff.GetOk("scan_mode") - centralizedCloudAccountId, centralizedCloudAccountIdOk := diff.GetOk("centralized_cloud_account_id") - if scanModeOk && scanMode == "inAccountSub" { - if !centralizedCloudAccountIdOk || centralizedCloudAccountId == "" { - return fmt.Errorf("'centralized_cloud_account_id' must be set and not empty when 'scan_mode' is 'inAccountSub'") - } - } - return nil - }, } } @@ -217,7 +203,6 @@ func resourceAWPAWSOnboardingRead(d *schema.ResourceData, meta interface{}) erro _ = d.Set("cloud_provider", resp.Provider) _ = d.Set("should_update", resp.ShouldUpdate) _ = d.Set("is_org_onboarding", resp.IsOrgOnboarding) - _ = d.Set("centralized_cloud_account_id", resp.CentralizedCloudAccountId) err = setAgentlessAccountSettings(resp, d) if err != nil { @@ -316,7 +301,6 @@ func setAgentlessAccountSettings(resp *awp_aws_onboarding.GetAWPOnboardingRespon if resp.AgentlessAccountSettings.DisabledRegions != nil || resp.AgentlessAccountSettings.ScanMachineIntervalInHours != 0 || resp.AgentlessAccountSettings.MaxConcurrenceScansPerRegion != 0 || - resp.AgentlessAccountSettings.SkipFunctionAppsScan != false || resp.AgentlessAccountSettings.CustomTags != nil { if err := d.Set("agentless_account_settings", flattenAgentlessAccountSettings(resp.AgentlessAccountSettings)); err != nil { return err @@ -377,9 +361,6 @@ func resourceAWPAWSOnboardingUpdate(d *schema.ResourceData, meta interface{}) er return err } log.Printf("[INFO] Updated agentless account settings for cloud account %s\n", d.Id()) - if err != nil { - return err - } } return nil diff --git a/website/docs/d/awp_aws_onboarding.html.markdown b/website/docs/d/awp_aws_onboarding.html.markdown index 99be3679..eb99329b 100644 --- a/website/docs/d/awp_aws_onboarding.html.markdown +++ b/website/docs/d/awp_aws_onboarding.html.markdown @@ -30,7 +30,6 @@ The following arguments supported: In addition to all arguments above, the following attributes exported: -* `centralized_cloud_account_id` - The centralized CloudGuard account ID if configured. * `scan_mode` - The scan mode of the onboarding process * `agentless_account_settings` - The settings for the agentless account that the awp scanner will be configured with. * `missing_awp_private_network_regions` - The regions missing AWP private network. diff --git a/website/docs/r/awp_aws_onboarding.html.markdown b/website/docs/r/awp_aws_onboarding.html.markdown index b5b96d4e..892abe11 100644 --- a/website/docs/r/awp_aws_onboarding.html.markdown +++ b/website/docs/r/awp_aws_onboarding.html.markdown @@ -95,7 +95,6 @@ data "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { The following arguments are supported: * `cloudguard_account_id` - (Required) The CloudGuard account id. -* `centralized_cloud_account_id` - (Optional) The centralized cloud account id. * `cross_account_role_name` - (Required) The name of the cross account role. * `cross_account_role_external_id` - (Required) The external id of the cross account role. * `scan_mode` - (Required) The scan mode. Valid values are "inAccount", "saas", "inAccountHub", "inAccountSub". From f230019bd10f2a7654bbbba64812c3cbcf8e83b5 Mon Sep 17 00:00:00 2001 From: Benny Zemmour Date: Wed, 3 Apr 2024 18:39:52 +0300 Subject: [PATCH 46/47] doc --- examples/awp_aws_onboarding/main.tf | 13 ++--- .../docs/r/awp_aws_onboarding.html.markdown | 47 ++++++++++--------- 2 files changed, 31 insertions(+), 29 deletions(-) diff --git a/examples/awp_aws_onboarding/main.tf b/examples/awp_aws_onboarding/main.tf index b9057b2c..c18bf8a2 100644 --- a/examples/awp_aws_onboarding/main.tf +++ b/examples/awp_aws_onboarding/main.tf @@ -2,7 +2,7 @@ terraform { required_providers { dome9 = { source = "dome9/dome9" - version = ">=1.29.6" + version = ">=1.29.7" } aws = { source = "hashicorp/aws" @@ -61,19 +61,20 @@ resource "dome9_cloudaccount_aws" "aws_onboarding_account_test" { # There is a need to use this terraform module [terraform-dome9-awp-aws] to create all the prerequisites for the onboarding process (All the needed AWS Resources) # Example for the module use: module "terraform-dome9-awp-aws" { - source = "github.com/dome9/terraform-dome9-awp-aws?ref=AL-2317-AWP-Terraform-AWS-Module" - awp_cloud_account_id = "" + source = "github.com/dome9/terraform-dome9-awp-aws" + awp_cloud_account_id = " or " awp_scan_mode = "" # Valid Values = "inAccount" or "saas" # Optional customizations: - # awp_cross_account_role_name = "CheckPoint-AWP-CrossAccount-Role-22" - # awp_cross_account_role_external_id = "AWP_Fake@ExternalID123" + # e.g: + # awp_cross_account_role_name = "" + # awp_cross_account_role_external_id = "" # Optional account Settings # e.g: # awp_account_settings_aws = { # scan_machine_interval_in_hours = 24 - # disabled_regions = ["ap-northeast-1", "ap-northeast-2", ...] + # disabled_regions = ["ap-northeast-1", "ap-northeast-2", ...] # List of regions to disable # max_concurrent_scans_per_region = 20 # custom_tags = { # tag1 = "value1" diff --git a/website/docs/r/awp_aws_onboarding.html.markdown b/website/docs/r/awp_aws_onboarding.html.markdown index 892abe11..c8e52da6 100644 --- a/website/docs/r/awp_aws_onboarding.html.markdown +++ b/website/docs/r/awp_aws_onboarding.html.markdown @@ -27,33 +27,34 @@ provider "aws" { token = "AWS_SESSION_TOKEN" } -# ToDo - # change the repo url to correct links after publishing the module + # There is a need to use this terraform module [terraform-dome9-awp-aws] to create all the prerequisites for the onboarding process (All the needed AWS Resources) # for further information please refer to the module documentation [terraform-dome9-awp-aws](https://registry.terraform.io/modules/dome9/awp-aws/dome9/latest) -# for more examples (simple and complete), you can visit this github examples [terraform-dome9-awp-aws](https://github.com/dome9/terraform-dome9-awp-aws/tree/AL-2317-AWP-Terraform-AWS-Module/examples) +# for more examples (simple and complete), you can visit this github examples [terraform-dome9-awp-aws](https://github.com/dome9/terraform-dome9-awp-aws/blob/master/examples) # Example for the module use: module "terraform-dome9-awp-aws" { - source = "github.com/dome9/terraform-dome9-awp-aws" - awp_cloud_account_id = "" - awp_scan_mode = "" # Valid Values = "inAccount" or "saas" - # Optional customizations: - # awp_cross_account_role_name = "CheckPoint-AWP-CrossAccount-Role" - # awp_cross_account_role_external_id = "AWP_Fake@ExternalID123" - - # Optional account Settings - # e.g: - # awp_account_settings_aws = { - # scan_machine_interval_in_hours = 24 - # disabled_regions = ["ap-northeast-1", "ap-northeast-2", ...] - # max_concurrent_scans_per_region = 20 - # custom_tags = { - # tag1 = "value1" - # tag2 = "value2" - # tag3 = "value3" - # ... - # } - # } + source = "github.com/dome9/terraform-dome9-awp-aws" + awp_cloud_account_id = " or " + awp_scan_mode = "" # Valid Values = "inAccount" or "saas" + + # Optional customizations: + # e.g: + # awp_cross_account_role_name = "" + # awp_cross_account_role_external_id = "" + + # Optional account Settings + # e.g: + # awp_account_settings_aws = { + # scan_machine_interval_in_hours = 24 + # disabled_regions = ["ap-northeast-1", "ap-northeast-2", ...] # List of regions to disable + # max_concurrent_scans_per_region = 20 + # custom_tags = { + # tag1 = "value1" + # tag2 = "value2" + # tag3 = "value3" + # ... + # } + # } } # The dome9_awp_aws_onboarding resource defines a Dome9 AWP AWS Onboarding. From fee540843fb1c6a8e9520b22464424d57b5f94c8 Mon Sep 17 00:00:00 2001 From: Omar Date: Thu, 4 Apr 2024 16:26:11 +0300 Subject: [PATCH 47/47] changes after CRs + consts --- dome9/common/providerconst/const.go | 33 ++++++++++++------- dome9/common/testing/variable/variable.go | 20 +++++------ dome9/resource_dome9_awp_aws_onboarding.go | 20 +++++------ .../resource_dome9_awp_aws_onboarding_test.go | 6 ++-- .../docs/r/awp_aws_onboarding.html.markdown | 4 +-- 5 files changed, 46 insertions(+), 37 deletions(-) diff --git a/dome9/common/providerconst/const.go b/dome9/common/providerconst/const.go index a59ba93d..8791928b 100644 --- a/dome9/common/providerconst/const.go +++ b/dome9/common/providerconst/const.go @@ -109,13 +109,13 @@ const ( AF_SOUTH_1 = "26" EU_SOUTH_1 = "27" AP_NORTHEAST_3 = "28" - ME_CENTRAL_1 = "29" - AP_SOUTH_2 = "30" - AP_SOUTHEAST_3 = "31" - AP_SOUTHEAST_4 = "32" - EU_CENTRAL_2 = "33" - EU_SOUTH_2 = "34" - IL_CENTRAL_1 = "35" + ME_CENTRAL_1 = "29" + AP_SOUTH_2 = "30" + AP_SOUTHEAST_3 = "31" + AP_SOUTHEAST_4 = "32" + EU_CENTRAL_2 = "33" + EU_SOUTH_2 = "34" + IL_CENTRAL_1 = "35" ) // Azure consts @@ -185,11 +185,11 @@ var AWSRegionsEnum = map[string]string{ "af_south_1": AF_SOUTH_1, "eu_south_1": EU_SOUTH_1, "ap_northeast_3": AP_NORTHEAST_3, - "me_central_1": ME_CENTRAL_1, - "ap_south_2": AP_SOUTH_2, - "ap_southeast_3": AP_SOUTHEAST_3, - "ap_southeast_4": AP_SOUTHEAST_4, - "eu_central_2": EU_CENTRAL_2, + "me_central_1": ME_CENTRAL_1, + "ap_south_2": AP_SOUTH_2, + "ap_southeast_3": AP_SOUTHEAST_3, + "ap_southeast_4": AP_SOUTHEAST_4, + "eu_central_2": EU_CENTRAL_2, "eu_south_2": EU_SOUTH_2, "il_central_1": IL_CENTRAL_1, } @@ -201,3 +201,12 @@ var PermissionTrafficType = map[string]string{ // All Assessments Cloud Accounts Types var AssessmentCloudAccountType = []string{"Aws", "Azure", "GCP", "Kubernetes", "Terraform", "Generic", "KubernetesRuntimeAssurance", "ShiftLeft", "SourceCodeAssurance", "ImageAssurance", "Alibaba", "Cft", "ContainerRegistry", "Ers"} + +// AWP AWS Constants +const ( + DefaultScanMachineIntervalInHoursSaas = 24 + DefaultScanMachineIntervalInHoursInAccount = 4 + DefaultMaxConcurrentScansPerRegion = 20 + MinMaxConcurrentScansPerRegion = 1 + MaxScanMachineIntervalInHours = 1000 +) diff --git a/dome9/common/testing/variable/variable.go b/dome9/common/testing/variable/variable.go index 2bde80bd..fbdedc97 100644 --- a/dome9/common/testing/variable/variable.go +++ b/dome9/common/testing/variable/variable.go @@ -214,16 +214,16 @@ const ( // awp aws onboarding data resource/data source const ( - OnboardedAwsCloudGuardAccountID = "36f79243-5456-4aa7-88c1-6637cad1f426" - AwpAwsCrossAccountRoleName = "CloudGuardAWPCrossAccountRole" - ScanMode = "inAccount" - DisabledRegions = `["us-east-1", "us-west-1"]` - DisabledRegionsUpdate = `["us-east-1", "us-west-1", "ap-northeast-1", "ap-southeast-2"]` - ScanMachineIntervalInHours = "6" - ScanMachineIntervalInHoursUpdate = "10" - MaxConcurrencyScansPerRegion = "4" - MaxConcurrenceScansPerRegionUpdate = "8" - CustomTags = `{ + OnboardedAwsCloudGuardAccountID = "36f79243-5456-4aa7-88c1-6637cad1f426" + AwpAwsCrossAccountRoleName = "CloudGuardAWPCrossAccountRole" + ScanMode = "inAccount" + DisabledRegions = `["us-east-1", "us-west-1"]` + DisabledRegionsUpdate = `["us-east-1", "us-west-1", "ap-northeast-1", "ap-southeast-2"]` + ScanMachineIntervalInHours = "6" + ScanMachineIntervalInHoursUpdate = "10" + MaxConcurrentScansPerRegion = "4" + MaxConcurrentScansPerRegionUpdate = "8" + CustomTags = `{ tag1 = "value1" tag2 = "value2" }` diff --git a/dome9/resource_dome9_awp_aws_onboarding.go b/dome9/resource_dome9_awp_aws_onboarding.go index e4a7f73c..4f00d1ca 100644 --- a/dome9/resource_dome9_awp_aws_onboarding.go +++ b/dome9/resource_dome9_awp_aws_onboarding.go @@ -242,9 +242,9 @@ func expandAgentlessAccountSettings(d *schema.ResourceData) (*awp_aws_onboarding var scanMachineIntervalInHours int if scanMode == "saas" { - scanMachineIntervalInHours = 24 + scanMachineIntervalInHours = providerconst.DefaultScanMachineIntervalInHoursSaas } else { - scanMachineIntervalInHours = 4 + scanMachineIntervalInHours = providerconst.DefaultScanMachineIntervalInHoursInAccount } // Initialize the AgentlessAccountSettings struct with default values @@ -252,7 +252,7 @@ func expandAgentlessAccountSettings(d *schema.ResourceData) (*awp_aws_onboarding DisabledRegions: make([]string, 0), CustomTags: make(map[string]string), ScanMachineIntervalInHours: scanMachineIntervalInHours, - MaxConcurrenceScansPerRegion: 20, + MaxConcurrenceScansPerRegion: providerconst.DefaultMaxConcurrentScansPerRegion, } // Check if the key exists and is not nil @@ -269,19 +269,19 @@ func expandAgentlessAccountSettings(d *schema.ResourceData) (*awp_aws_onboarding } if scanMachineInterval, ok := agentlessAccountSettingsMap["scan_machine_interval_in_hours"].(int); ok { - if scanMode == "saas" && (scanMachineInterval < 24 || scanMachineInterval > 1000) { - return nil, fmt.Errorf("scan_machine_interval_in_hours must be between 24 and 1000 for saas mode") - } else if scanMode == "inAccount" && (scanMachineInterval < 4 || scanMachineInterval > 1000) { - return nil, fmt.Errorf("scan_machine_interval_in_hours must be between 4 and 1000 for inAccount mode") + if scanMode == "saas" && (scanMachineInterval < providerconst.DefaultScanMachineIntervalInHoursSaas || scanMachineInterval > providerconst.MaxScanMachineIntervalInHours) { + return nil, fmt.Errorf("scan_machine_interval_in_hours must be between %d and %d for saas mode", providerconst.DefaultScanMachineIntervalInHoursSaas, providerconst.MaxScanMachineIntervalInHours) + } else if scanMode == "inAccount" && (scanMachineInterval < providerconst.DefaultScanMachineIntervalInHoursInAccount || scanMachineInterval > providerconst.MaxScanMachineIntervalInHours) { + return nil, fmt.Errorf("scan_machine_interval_in_hours must be between %d and %d for inAccount mode", providerconst.DefaultScanMachineIntervalInHoursInAccount, providerconst.MaxScanMachineIntervalInHours) } agentlessAccountSettings.ScanMachineIntervalInHours = scanMachineInterval } - if maxConcurrenceScans, ok := agentlessAccountSettingsMap["max_concurrent_scans_per_region"].(int); ok { - if maxConcurrenceScans < 1 || maxConcurrenceScans > 20 { + if maxConcurrentScans, ok := agentlessAccountSettingsMap["max_concurrent_scans_per_region"].(int); ok { + if maxConcurrentScans < providerconst.MinMaxConcurrentScansPerRegion || maxConcurrentScans > providerconst.DefaultMaxConcurrentScansPerRegion { return nil, fmt.Errorf("max_concurrent_scans_per_region must be between 1 and 20") } - agentlessAccountSettings.MaxConcurrenceScansPerRegion = maxConcurrenceScans + agentlessAccountSettings.MaxConcurrenceScansPerRegion = maxConcurrentScans } if customTagsInterface, ok := agentlessAccountSettingsMap["custom_tags"].(map[string]interface{}); ok { diff --git a/dome9/resource_dome9_awp_aws_onboarding_test.go b/dome9/resource_dome9_awp_aws_onboarding_test.go index f72e7b91..2c700df0 100644 --- a/dome9/resource_dome9_awp_aws_onboarding_test.go +++ b/dome9/resource_dome9_awp_aws_onboarding_test.go @@ -48,7 +48,7 @@ func TestAccResourceAWPAWSOnboardingBasic(t *testing.T) { resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions.0", disabledRegion1), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions.1", disabledRegion2), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.scan_machine_interval_in_hours", variable.ScanMachineIntervalInHours), - resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.max_concurrent_scans_per_region", variable.MaxConcurrencyScansPerRegion), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.max_concurrent_scans_per_region", variable.MaxConcurrentScansPerRegion), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.custom_tags.%", "2"), resource.TestCheckResourceAttrSet(resourceTypeAndName, "id"), resource.TestCheckResourceAttr(resourceTypeAndName, "cloud_provider", "aws"), @@ -69,7 +69,7 @@ func TestAccResourceAWPAWSOnboardingBasic(t *testing.T) { resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions.2", disabledRegionUpdate3), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.disabled_regions.3", disabledRegionUpdate4), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.scan_machine_interval_in_hours", variable.ScanMachineIntervalInHoursUpdate), - resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.max_concurrent_scans_per_region", variable.MaxConcurrenceScansPerRegionUpdate), + resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.max_concurrent_scans_per_region", variable.MaxConcurrentScansPerRegionUpdate), resource.TestCheckResourceAttr(resourceTypeAndName, "agentless_account_settings.0.custom_tags.%", "3"), resource.TestCheckResourceAttrSet(resourceTypeAndName, "id"), resource.TestCheckResourceAttr(resourceTypeAndName, "cloud_provider", "aws"), @@ -166,7 +166,7 @@ resource "%s" "%s" { variable.ScanMode, IfThenElse(updateAction, variable.DisabledRegionsUpdate, variable.DisabledRegions), IfThenElse(updateAction, variable.ScanMachineIntervalInHoursUpdate, variable.ScanMachineIntervalInHours), - IfThenElse(updateAction, variable.MaxConcurrenceScansPerRegionUpdate, variable.MaxConcurrencyScansPerRegion), + IfThenElse(updateAction, variable.MaxConcurrentScansPerRegionUpdate, variable.MaxConcurrentScansPerRegion), IfThenElse(updateAction, variable.CustomTagsUpdate, variable.CustomTags), ) } diff --git a/website/docs/r/awp_aws_onboarding.html.markdown b/website/docs/r/awp_aws_onboarding.html.markdown index c8e52da6..879766be 100644 --- a/website/docs/r/awp_aws_onboarding.html.markdown +++ b/website/docs/r/awp_aws_onboarding.html.markdown @@ -66,7 +66,7 @@ module "terraform-dome9-awp-aws" { # The agentless_account_settings attribute is used to specify the agentless account settings of the Dome9 AWP AWS Onboarding. # The disabled_regions attribute is used to specify the disabled regions of the agentless account settings of the Dome9 AWP AWS Onboarding. # The scan_machine_interval_in_hours attribute is used to specify the scan machine interval in hours of the agentless account settings of the Dome9 AWP AWS Onboarding. -# The max_concurrent_scans_per_region attribute is used to specify the max concurrence scans per region of the agentless account settings of the Dome9 AWP AWS Onboarding. +# The max_concurrent_scans_per_region attribute is used to specify the max concurrent scans per region of the agentless account settings of the Dome9 AWP AWS Onboarding. # The custom_tags attribute is used to specify the custom tags of the agentless account settings of the Dome9 AWP AWS Onboarding. resource "dome9_awp_aws_onboarding" "awp_aws_onboarding_test" { cloudguard_account_id = "dome9_cloudaccount_aws.aws_onboarding_account_test.id | | " @@ -102,7 +102,7 @@ The following arguments are supported: * `agentless_account_settings` - (Optional) The agentless account settings. * `disabled_regions` - (Optional) The disabled regions. valid values are "af-south-1", "ap-south-1", "eu-north-1", "eu-west-3", "eu-south-1", "eu-west-2", "eu-west-1", "ap-northeast-3", "ap-northeast-2", "me-south-1", "ap-northeast-1", "me-central-1", "ca-central-1", "sa-east-1", "ap-east-1", "ap-southeast-1", "ap-southeast-2", "eu-central-1", "ap-southeast-3", "us-east-1", "us-east-2", "us-west-1", "us-west-2" * `scan_machine_interval_in_hours` - (Optional) The scan machine interval in hours - * `max_concurrent_scans_per_region` - (Optional) The max concurrence scans per region + * `max_concurrent_scans_per_region` - (Optional) The max concurrent scans per region * `custom_tags` - (Optional) The custom tags. * `should_create_policy` - (Optional) Whether to create a policy. Default is true.