diff --git a/CHANGELOG.md b/CHANGELOG.md index 41d2de21..b842cc7b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,43 @@ +## 1.6.0 (November 24, 2021) + +FEATURES + +* **New Resource:** `resource_checkpoint_management_aws_data_center_server` +* **New Resource:** `resource_checkpoint_management_azure_data_center_server` +* **New Resource:** `resource_checkpoint_management_gcp_data_center_server` +* **New Resource:** `resource_checkpoint_management_vmware_data_center_server` +* **New Resource:** `resource_checkpoint_management_aci_data_center_server` +* **New Resource:** `resource_checkpoint_management_ise_data_center_server` +* **New Resource:** `resource_checkpoint_management_nuage_data_center_server` +* **New Resource:** `resource_checkpoint_management_openstack_data_center_server` +* **New Resource:** `resource_checkpoint_management_kubernetes_data_center_server` +* **New Resource:** `resource_checkpoint_management_data_center_query` +* **New Data Source:** `data_source_checkpoint_management_aws_data_center_server` +* **New Data Source:** `data_source_checkpoint_management_azure_data_center_server` +* **New Data Source:** `data_source_checkpoint_management_gcp_data_center_server` +* **New Data Source:** `data_source_checkpoint_management_vmware_data_center_server` +* **New Data Source:** `data_source_checkpoint_management_aci_data_center_server` +* **New Data Source:** `data_source_checkpoint_management_ise_data_center_server` +* **New Data Source:** `data_source_checkpoint_management_nuage_data_center_server` +* **New Data Source:** `data_source_checkpoint_management_openstack_data_center_server` +* **New Data Source:** `data_source_checkpoint_management_kubernetes_data_center_server` +* **New Data Source:** `data_source_checkpoint_management_data_center_query` +* **New Data Source:** `data_source_checkpoint_management_data_center_content` +* **New Data Source:** `data_source_checkpoint_management_access_rulebase` +* **New Data Source:** `data_source_checkpoint_management_threat_rulebase` +* **New Data Source:** `data_source_checkpoint_management_https_rulebase` + +ENHANCEMENTS + +* Add support to authenticate management server with api key using `api_key` or via environment variable `CHECKPOINT_API_KEY`. +* Add support to select proxy host using `proxy_host` or via environment variable `CHECKPOINT_PROXY_HOST`. +* Add support to select proxy port using `proxy_port` or via environment variable `CHECKPOINT_PROXY_PORT`. + +BUG FIXES + +* `resource_checkpoint_management_simple_cluster` - Fix bug that the `members` field did not import properly. +* `data_source_checkpoint_management_nat_rulebase` - Save all relevant fields in read function. + ## 1.5.0 (October 28, 2021) FEATURES diff --git a/checkpoint/data_source_checkpoint_management_access_layer.go b/checkpoint/data_source_checkpoint_management_access_layer.go index af460583..a8eafe4e 100644 --- a/checkpoint/data_source_checkpoint_management_access_layer.go +++ b/checkpoint/data_source_checkpoint_management_access_layer.go @@ -93,7 +93,7 @@ func dataSourceManagementAccessLayerRead(d *schema.ResourceData, m interface{}) payload["uid"] = uid } - showAccessLayerRes, err := client.ApiCall("show-access-layer", payload, client.GetSessionID(), true, false) + showAccessLayerRes, err := client.ApiCall("show-access-layer", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_access_point_name.go b/checkpoint/data_source_checkpoint_management_access_point_name.go index 7b41ed01..051e2747 100644 --- a/checkpoint/data_source_checkpoint_management_access_point_name.go +++ b/checkpoint/data_source_checkpoint_management_access_point_name.go @@ -81,7 +81,7 @@ func dataSourceManagementAccessPointNameRead(d *schema.ResourceData, m interface payload["uid"] = uid } - showAccessPointNameRes, err := client.ApiCall("show-access-point-name", payload, client.GetSessionID(), true, false) + showAccessPointNameRes, err := client.ApiCall("show-access-point-name", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_access_role.go b/checkpoint/data_source_checkpoint_management_access_role.go index 6af7f0c8..ef7e89f9 100644 --- a/checkpoint/data_source_checkpoint_management_access_role.go +++ b/checkpoint/data_source_checkpoint_management_access_role.go @@ -130,7 +130,7 @@ func dataSourceManagementAccessRoleRead(d *schema.ResourceData, m interface{}) e payload["uid"] = uid } - showAccessRoleRes, err := client.ApiCall("show-access-role", payload, client.GetSessionID(), true, false) + showAccessRoleRes, err := client.ApiCall("show-access-role", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_access_rule.go b/checkpoint/data_source_checkpoint_management_access_rule.go index 9e1bd160..480d1c89 100644 --- a/checkpoint/data_source_checkpoint_management_access_rule.go +++ b/checkpoint/data_source_checkpoint_management_access_rule.go @@ -275,7 +275,7 @@ func dataSourceManagementAccessRuleRead(d *schema.ResourceData, m interface{}) e payload["uid"] = uid } - showAccessRuleRes, err := client.ApiCall("show-access-rule", payload, client.GetSessionID(), true, false) + showAccessRuleRes, err := client.ApiCall("show-access-rule", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_access_rulebase.go b/checkpoint/data_source_checkpoint_management_access_rulebase.go new file mode 100644 index 00000000..f83a9731 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_access_rulebase.go @@ -0,0 +1,998 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "log" + "math" + "strconv" + "strings" +) + +func dataSourceManagementAccessRuleBase() *schema.Resource { + return &schema.Resource{ + Read: dataSourceManagementAccessRuleBaseRead, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Object name.", + }, + "uid": { + Type: schema.TypeString, + Optional: true, + Description: "Object unique identifier.", + }, + "filter": { + Type: schema.TypeString, + Optional: true, + Description: "Search expression to filter the rulebase. The provided text should be exactly the same as it would be given in Smart Console. The logical operators in the expression ('AND', 'OR') should be provided in capital letters. If an operator is not used, the default OR operator applies.", + }, + "filter_settings": { + Type: schema.TypeMap, + Optional: true, + Description: "Sets filter preferences.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "search_mode": { + Type: schema.TypeString, + Optional: true, + Description: "When set to 'general', both the Full Text Search and Packet Search are enabled. In this mode, Packet Search will not match on 'Any' object, a negated cell or a group-with-exclusion. When the search-mode is set to 'packet', by default, the match on 'Any' object, a negated cell or a group-with-exclusion are enabled. packet-search-settings may be provided to change the default behavior.", + }, + "expand_group_members": { + Type: schema.TypeBool, + Optional: true, + Description: "When true, if the search expression contains a UID or a name of a group object, results will include rules that match on at least one member of the group.", + Default: false, + }, + "expand_group_with_exclusion_members": { + Type: schema.TypeBool, + Optional: true, + Description: "When true, if the search expression contains a UID or a name of a group-with-exclusion object, results will include rules that match at least one member of the \"include\" part and is not a member of the \"except\" part.", + Default: false, + }, + "match_on_any": { + Type: schema.TypeBool, + Optional: true, + Description: "Whether to match on 'Any' object.", + Default: true, + }, + "match_on_group_with_exclusion": { + Type: schema.TypeBool, + Optional: true, + Description: "Whether to match on a group-with-exclusion.", + Default: true, + }, + "match_on_negate": { + Type: schema.TypeBool, + Optional: true, + Description: "Whether to match on a negated cell.", + Default: true, + }, + }, + }, + }, + "limit": { + Type: schema.TypeInt, + Optional: true, + Description: "The maximal number of returned results.", + Default: 50, + }, + "offset": { + Type: schema.TypeInt, + Optional: true, + Description: "Number of the results to initially skip.", + Default: 0, + }, + "order": { + Type: schema.TypeList, + Optional: true, + Description: "Sorts the results by search criteria. Automatically sorts the results by Name, in the ascending order.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "asc": { + Type: schema.TypeString, + Optional: true, + Description: "Sorts results by the given field in ascending order.", + }, + "desc": { + Type: schema.TypeString, + Optional: true, + Description: "Sorts results by the given field in descending order.", + }, + }, + }, + }, + "package": { + Type: schema.TypeString, + Optional: true, + Description: "Name of the package.", + }, + "show_as_ranges": { + Type: schema.TypeBool, + Optional: true, + Description: "When true, the source, destination and services & applications parameters are displayed as ranges of IP addresses and port numbers rather than network objects.\nObjects that are not represented using IP addresses or port numbers are presented as objects.\nIn addition, the response of each rule does not contain the parameters: source, source-negate, destination, destination-negate, service and service-negate, but instead it contains the parameters: source-ranges, destination-ranges and service-ranges.\n\nNote: Requesting to show rules as ranges is limited up to 20 rules per request, otherwise an error is returned. If you wish to request more rules, use the offset and limit parameters to limit your request.", + Default: false, + }, + "show_hits": { + Type: schema.TypeBool, + Optional: true, + Description: "N/A", + }, + "hits_settings": { + Type: schema.TypeMap, + Optional: true, + Description: "N/A", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "from_date": { + Type: schema.TypeString, + Optional: true, + Description: "Format: YYYY-MM-DD, YYYY-mm-ddThh:mm:ss.", + }, + "target": { + Type: schema.TypeString, + Optional: true, + Description: "Target gateway name or UID.", + }, + "to_date": { + Type: schema.TypeString, + Optional: true, + Description: "Format: YYYY-MM-DD, YYYY-mm-ddThh:mm:ss.", + }, + }, + }, + }, + "dereference_group_members": { + Type: schema.TypeBool, + Optional: true, + Description: "When true, the source, destination and services & applications parameters are displayed as ranges of IP addresses and port numbers rather than network objects.\nObjects that are not represented using IP addresses or port numbers are presented as objects.\nIn addition, the response of each rule does not contain the parameters: source, source-negate, destination, destination-negate, service and service-negate, but instead it contains the parameters: source-ranges, destination-ranges and service-ranges.\n\nNote: Requesting to show rules as ranges is limited up to 20 rules per request, otherwise an error is returned. If you wish to request more rules, use the offset and limit parameters to limit your request.", + Default: false, + }, + "show_membership": { + Type: schema.TypeBool, + Optional: true, + Description: "N/A", + Default: false, + }, + "rulebase": { + Type: schema.TypeList, + Computed: true, + Description: "The show rulebase api reply", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "from": { + Type: schema.TypeInt, + Computed: true, + Description: "From which element number the query was done.", + }, + "to": { + Type: schema.TypeInt, + Computed: true, + Description: "To which element number the query was done.", + }, + "total": { + Type: schema.TypeInt, + Computed: true, + Description: "Total number of elements returned by the query.", + }, + "objects_dictionary": { + Type: schema.TypeList, + Computed: true, + Description: "Level of details in the output corresponds to the number of details for search. This table shows the level of details in the Standard level.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Computed: true, + Description: "Object name. Must be unique in the domain", + }, + "uid": { + Type: schema.TypeString, + Computed: true, + Description: "Object unique identifier.", + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "Object type.", + }, + }, + }, + }, + "rulebase": { + Type: schema.TypeList, + MaxItems: 1, + Computed: true, + Description: "N/A", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "uid": { + Type: schema.TypeString, + Computed: true, + Description: "Rules uid.", + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: "Rules name.", + }, + "destination": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "destination_negate": { + Type: schema.TypeBool, + Computed: true, + Description: "True if negate is set for destination.", + }, + "install_on": { + Type: schema.TypeList, + Computed: true, + Description: "Which Gateways identified by the name or UID to install the policy on.", + Elem: schema.TypeString, + }, + "enabled": { + Type: schema.TypeBool, + Computed: true, + Description: "Enable/Disable the rule.", + }, + "service": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "service_negate": { + Type: schema.TypeBool, + Computed: true, + Description: "True if negate is set for service.", + }, + "service_resource": { + Type: schema.TypeString, + Computed: true, + Description: "service resource.", + }, + "source": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "source_negate": { + Type: schema.TypeBool, + Computed: true, + Description: "True if negate is set for source.", + }, + "vpn": { + Type: schema.TypeList, + Computed: true, + Description: "Communities or Directional.", + Elem: schema.TypeString, + }, + "comments": { + Type: schema.TypeString, + Computed: true, + Description: "Comments string.", + }, + "action": { + Type: schema.TypeString, + Computed: true, + Description: "\"Accept\", \"Drop\", \"Ask\", \"Inform\", \"Reject\", \"User Auth\", \"Client Auth\", \"Apply Layer\".", + }, + "action_settings": { + Type: schema.TypeMap, + Computed: true, + Description: "Action settings.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enable_identity_captive_portal": { + Type: schema.TypeBool, + Computed: true, + Description: "N/A", + }, + "limit": { + Type: schema.TypeString, + Computed: true, + Description: "N/A", + }, + }, + }, + }, + "content": { + Type: schema.TypeSet, + Computed: true, + Description: "List of processed file types that this rule applies on.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "content_direction": { + Type: schema.TypeString, + Computed: true, + Description: "On which direction the file types processing is applied.", + }, + "content_negate": { + Type: schema.TypeBool, + Computed: true, + Description: "True if negate is set for data.", + }, + "custom_fields": { + Type: schema.TypeMap, + Computed: true, + Description: "Custom fields.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "field_1": { + Type: schema.TypeString, + Computed: true, + Description: "First custom field.", + }, + "field_2": { + Type: schema.TypeString, + Computed: true, + Description: "Second custom field.", + }, + "field_3": { + Type: schema.TypeString, + Computed: true, + Description: "Third custom field.", + }, + }, + }, + }, + "rule_number": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of the rule.", + }, + "inline_layer": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Inline Layer identified by the name or UID. Relevant only if \"Action\" was set to \"Apply Layer\".", + }, + "from": { + Type: schema.TypeInt, + Computed: true, + Description: "From which element number the query was done.", + }, + "to": { + Type: schema.TypeInt, + Computed: true, + Description: "To which element number the query was done.", + }, + "time": { + Type: schema.TypeSet, + Computed: true, + Description: "List of time objects. For example: \"Weekend\", \"Off-Work\", \"Every-Day\".", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "track": { + Type: schema.TypeMap, + Computed: true, + Description: "Track Settings.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "accounting": { + Type: schema.TypeBool, + Computed: true, + Description: "Turns accounting for track on and off.", + }, + "alert": { + Type: schema.TypeString, + Computed: true, + Description: "Type of alert for the track.", + }, + "enable_firewall_session": { + Type: schema.TypeBool, + Computed: true, + Description: "Determine whether to generate session log to firewall only connections.", + }, + "per_connection": { + Type: schema.TypeBool, + Computed: true, + Description: "Determines whether to perform the log per connection.", + }, + "per_session": { + Type: schema.TypeBool, + Computed: true, + Description: "Determines whether to perform the log per session.", + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "\"Log\", \"Extended Log\", \"Detailed Log\", \"None\".", + }, + }, + }, + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "Rules type.", + }, + "rulebase": { + Type: schema.TypeList, + Computed: true, + Description: "N/A", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "uid": { + Type: schema.TypeString, + Computed: true, + Description: "Rules uid.", + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: "Rules name.", + }, + "destination": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "destination_negate": { + Type: schema.TypeBool, + Computed: true, + Description: "True if negate is set for destination.", + }, + "install_on": { + Type: schema.TypeList, + Computed: true, + Description: "Which Gateways identified by the name or UID to install the policy on.", + Elem: schema.TypeString, + }, + "enabled": { + Type: schema.TypeBool, + Computed: true, + Description: "Enable/Disable the rule.", + }, + "service": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "service_negate": { + Type: schema.TypeBool, + Computed: true, + Description: "True if negate is set for service.", + }, + "service_resource": { + Type: schema.TypeString, + Computed: true, + Description: "service resource.", + }, + "source": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "source_negate": { + Type: schema.TypeBool, + Computed: true, + Description: "True if negate is set for source.", + }, + "vpn": { + Type: schema.TypeList, + Computed: true, + Description: "Communities or Directional.", + Elem: schema.TypeString, + }, + "comments": { + Type: schema.TypeString, + Computed: true, + Description: "Comments string.", + }, + "action": { + Type: schema.TypeString, + Computed: true, + Description: "\"Accept\", \"Drop\", \"Ask\", \"Inform\", \"Reject\", \"User Auth\", \"Client Auth\", \"Apply Layer\".", + }, + "action_settings": { + Type: schema.TypeMap, + Computed: true, + Description: "Action settings.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enable_identity_captive_portal": { + Type: schema.TypeBool, + Computed: true, + Description: "N/A", + }, + "limit": { + Type: schema.TypeString, + Computed: true, + Description: "N/A", + }, + }, + }, + }, + "content": { + Type: schema.TypeSet, + Computed: true, + Description: "List of processed file types that this rule applies on.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "content_direction": { + Type: schema.TypeString, + Computed: true, + Description: "On which direction the file types processing is applied.", + }, + "content_negate": { + Type: schema.TypeBool, + Computed: true, + Description: "True if negate is set for data.", + }, + "custom_fields": { + Type: schema.TypeMap, + Computed: true, + Description: "Custom fields.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "field_1": { + Type: schema.TypeString, + Computed: true, + Description: "First custom field.", + }, + "field_2": { + Type: schema.TypeString, + Computed: true, + Description: "Second custom field.", + }, + "field_3": { + Type: schema.TypeString, + Computed: true, + Description: "Third custom field.", + }, + }, + }, + }, + "rule_number": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of the rule.", + }, + "inline_layer": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + Description: "Inline Layer identified by the name or UID. Relevant only if \"Action\" was set to \"Apply Layer\".", + }, + "time": { + Type: schema.TypeSet, + Computed: true, + Description: "List of time objects. For example: \"Weekend\", \"Off-Work\", \"Every-Day\".", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "track": { + Type: schema.TypeMap, + Computed: true, + Description: "Track Settings.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "accounting": { + Type: schema.TypeBool, + Computed: true, + Description: "Turns accounting for track on and off.", + }, + "alert": { + Type: schema.TypeString, + Computed: true, + Description: "Type of alert for the track.", + }, + "enable_firewall_session": { + Type: schema.TypeBool, + Computed: true, + Description: "Determine whether to generate session log to firewall only connections.", + }, + "per_connection": { + Type: schema.TypeBool, + Computed: true, + Description: "Determines whether to perform the log per connection.", + }, + "per_session": { + Type: schema.TypeBool, + Computed: true, + Description: "Determines whether to perform the log per session.", + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "\"Log\", \"Extended Log\", \"Detailed Log\", \"None\".", + }, + }, + }, + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "Rules type.", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func dataSourceManagementAccessRuleBaseRead(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + + name := d.Get("name").(string) + uid := d.Get("uid").(string) + + payload := map[string]interface{}{} + if name != "" { + payload["name"] = name + } else if uid != "" { + payload["uid"] = uid + } + if v, ok := d.GetOk("filter"); ok { + payload["filter"] = v.(string) + } + if v, ok := d.GetOk("filter_settings"); ok { + filters, ok := v.(map[string]interface{}) + if ok { + + filtersMapToReturn := make(map[string]interface{}) + packetSearchMap := make(map[string]interface{}) + + if val, ok := filters["search_mode"]; ok { + filtersMapToReturn["search-mode"] = val + } else { + filtersMapToReturn["search-mode"] = "general" + } + + if val, ok := filters["expand_group_members"]; ok { + packetSearchMap["expand-group-members"] = val + } else { + packetSearchMap["expand-group-members"] = false + } + + if val, ok := filters["expand_group_with_exclusion_members"]; ok { + packetSearchMap["expand-group-with-exclusion-members"] = val + } else { + packetSearchMap["expand-group-with-exclusion-members"] = false + } + + if val, ok := filters["match_on_any"]; ok { + packetSearchMap["match-on-any"] = val + } else { + packetSearchMap["match-on-any"] = true + } + + if val, ok := filters["match_on_group_with_exclusion"]; ok { + packetSearchMap["match-on-group-with-exclusion"] = val + } else { + packetSearchMap["match-on-group-with-exclusion"] = true + } + + if val, ok := filters["match_on_negate"]; ok { + packetSearchMap["match-on-negate"] = val + } else { + packetSearchMap["match-on-negate"] = true + } + + filtersMapToReturn["packet-search-settings"] = packetSearchMap + payload["filter-settings"] = filtersMapToReturn + } + } + if v, ok := d.GetOk("limit"); ok { + payload["limit"] = v.(int) + } + if v, ok := d.GetOk("offset"); ok { + payload["offset"] = v.(int) + } + if v, ok := d.GetOk("order"); ok { + + ordersList, ok := v.([]interface{}) + var ordersDictToReturn []map[string]interface{} + + if ok { + for i := range ordersList { + + objectsMap := ordersList[i].(map[string]interface{}) + + tempOrder := make(map[string]interface{}) + + if v, _ := objectsMap["asc"]; v != nil && v != "" { + tempOrder["ASC"] = v + } + + if v, _ := objectsMap["desc"]; v != nil && v != "" { + tempOrder["DESC"] = v + } + + ordersDictToReturn = append(ordersDictToReturn, tempOrder) + } + payload["order"] = ordersDictToReturn + } + } + if v, ok := d.GetOk("package"); ok { + payload["package"] = v.(string) + } + if v, ok := d.GetOk("show_as_ranges"); ok { + payload["show-as-ranges"] = v.(bool) + } + if v, ok := d.GetOkExists("show_hits"); ok { + payload["show-hits"] = v.(bool) + } + + if v, ok := d.GetOk("hits_settings"); ok { + newPayload := make(map[string]interface{}) + tempPayload := v.(map[string]interface{}) + + if val, ok := tempPayload["from_date"]; ok { + newPayload["from-date"] = val + } + if val, ok := tempPayload["target"]; ok { + newPayload["target"] = val + } + if val, ok := tempPayload["to_date"]; ok { + newPayload["to-date"] = val + } + payload["hits-settings"] = newPayload + } + + if v, ok := d.GetOk("dereference_group_members"); ok { + payload["dereference-group-members"] = v.(bool) + } + + if v, ok := d.GetOk("show_membership"); ok { + payload["show-membership"] = v.(bool) + } + showRuleBaseRes, err := client.ApiCall("show-access-rulebase", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showRuleBaseRes.Success { + return fmt.Errorf(showRuleBaseRes.ErrorMsg) + } + ruleBaseJson := showRuleBaseRes.GetData() + + log.Println("Read ruleBaseJson - Show JSON = ", ruleBaseJson) + var outputRuleBase []interface{} + ruleBaseToReturn := make(map[string]interface{}) + if v := ruleBaseJson["uid"]; v != nil { + _ = d.Set("uid", v) + d.SetId(v.(string)) + } + + if v := ruleBaseJson["name"]; v != nil { + _ = d.Set("name", v) + } + + if v := ruleBaseJson["from"]; v != nil { + ruleBaseToReturn["from"] = int(math.Round(v.(float64))) + } else { + ruleBaseToReturn["from"] = 0 + } + if ruleBaseJson["objects-dictionary"] != nil { + + objectsList, ok := ruleBaseJson["objects-dictionary"].([]interface{}) + var objectDictToReturn []map[string]interface{} + + if ok { + for i := range objectsList { + + objectsMap := objectsList[i].(map[string]interface{}) + + tempObject := make(map[string]interface{}) + + if v, _ := objectsMap["name"]; v != nil { + tempObject["name"] = v + } + + if v, _ := objectsMap["uid"]; v != nil { + tempObject["uid"] = v + } + + if v, _ := objectsMap["type"]; v != nil { + tempObject["type"] = v + } + + objectDictToReturn = append(objectDictToReturn, tempObject) + } + ruleBaseToReturn["objects_dictionary"] = objectDictToReturn + } + } else { + ruleBaseToReturn["objects_dictionary"] = []map[string]interface{}{} + } + + if ruleBaseJson["rulebase"] != nil { + ruleBaseDictToReturn := readAccessRuleBaseField(ruleBaseJson) + ruleBaseToReturn["rulebase"] = ruleBaseDictToReturn + } else { + ruleBaseToReturn["rulebase"] = []map[string]interface{}{} + } + + if v := ruleBaseJson["to"]; v != nil { + ruleBaseToReturn["to"] = int(math.Round(v.(float64))) + } else { + ruleBaseToReturn["to"] = 0 + } + if v := ruleBaseJson["total"]; v != nil { + ruleBaseToReturn["total"] = int(math.Round(v.(float64))) + } else { + ruleBaseToReturn["total"] = 0 + } + outputRuleBase = append(outputRuleBase, ruleBaseToReturn) + _ = d.Set("rulebase", outputRuleBase) + return nil +} + +func readAccessRuleBaseField(RuleBase map[string]interface{}) []map[string]interface{} { + ruleBaseList, ok := RuleBase["rulebase"].([]interface{}) + var ruleBaseDictToReturn []map[string]interface{} + + if ok { + for i := range ruleBaseList { + + ruleBaseMap := ruleBaseList[i].(map[string]interface{}) + + tempRulebase := make(map[string]interface{}) + if v, _ := ruleBaseMap["uid"]; v != nil { + tempRulebase["uid"] = v + } + + if v, _ := ruleBaseMap["name"]; v != nil { + tempRulebase["name"] = v + } + + if v, _ := ruleBaseMap["destination"]; v != nil { + tempRulebase["destination"] = v + } + + if v, _ := ruleBaseMap["destination-negate"]; v != nil { + tempRulebase["destination_negate"] = v.(bool) + } + + if v, _ := ruleBaseMap["install-on"]; v != nil { + tempRulebase["install_on"] = v + } + + if v, _ := ruleBaseMap["enabled"]; v != nil { + tempRulebase["enabled"] = v.(bool) + } + + if v, _ := ruleBaseMap["source"]; v != nil { + tempRulebase["source"] = v + } + + if v, _ := ruleBaseMap["source-negate"]; v != nil { + tempRulebase["source_negate"] = v.(bool) + } + + if v, _ := ruleBaseMap["service"]; v != nil { + tempRulebase["service"] = v + } + + if v, _ := ruleBaseMap["service-negate"]; v != nil { + tempRulebase["service_negate"] = v.(bool) + } + + if v, _ := ruleBaseMap["type"]; v != nil { + tempRulebase["type"] = v + } + if v, _ := ruleBaseMap["comments"]; v != nil && v != "" { + tempRulebase["comments"] = v + } + + if v, _ := ruleBaseMap["service-resource"]; v != nil { + tempRulebase["service_resource"] = v + } + + if v, _ := ruleBaseMap["vpn"]; v != nil { + tempRulebase["vpn"] = v + } + + if v, _ := ruleBaseMap["action"]; v != nil { + tempRulebase["action"] = v + } + + if v, _ := ruleBaseMap["action-settings"]; v != nil { + propsJson, ok := ruleBaseMap["action-settings"].(map[string]interface{}) + if ok { + actionSettingsMapToReturn := make(map[string]interface{}) + for field, value := range propsJson { + propName := strings.ReplaceAll(field, "-", "_") + if propName == "enable_identity_captive_portal" { + value = strconv.FormatBool(value.(bool)) + } + actionSettingsMapToReturn[propName] = value + } + tempRulebase["action_settings"] = actionSettingsMapToReturn + } + } + if v, _ := ruleBaseMap["content"]; v != nil { + tempRulebase["content"] = v + } + + if v, _ := ruleBaseMap["content-negate"]; v != nil { + tempRulebase["content_negate"] = v.(bool) + } + + if v, _ := ruleBaseMap["content-direction"]; v != nil { + tempRulebase["content_direction"] = v + } + + if v, _ := ruleBaseMap["time"]; v != nil { + tempRulebase["time"] = v + } + + if v := ruleBaseMap["from"]; v != nil && v != 0 { + tempRulebase["from"] = int(math.Round(v.(float64))) + } + + if v, _ := ruleBaseMap["to"]; v != nil { + tempRulebase["to"] = int(math.Round(v.(float64))) + } + + if v, _ := ruleBaseMap["track"]; v != nil { + propsJson, ok := ruleBaseMap["track"].(map[string]interface{}) + if ok { + trackMapToReturn := make(map[string]interface{}) + for field, value := range propsJson { + propName := strings.ReplaceAll(field, "-", "_") + if propName != "type" && propName != "alert" { + value = strconv.FormatBool(value.(bool)) + } + trackMapToReturn[propName] = value + } + tempRulebase["track"] = trackMapToReturn + } + } + + if v, _ := ruleBaseMap["custom-fields"]; v != nil { + propsJson, ok := ruleBaseMap["custom-fields"].(map[string]interface{}) + if ok { + customFieldMapToReturn := make(map[string]interface{}) + for field, value := range propsJson { + propName := strings.ReplaceAll(field, "-", "_") + customFieldMapToReturn[propName] = value + } + tempRulebase["custom_fields"] = customFieldMapToReturn + } + } + + if v := ruleBaseMap["rule-number"]; v != nil { + tempRulebase["rule_number"] = v + } + + if v := ruleBaseMap["inline-layer"]; v != nil { + tempRulebase["inline_layer"] = v + } + + if v, _ := ruleBaseMap["type"]; v != nil { + tempRulebase["type"] = v + } + + if v, _ := ruleBaseMap["rulebase"]; v != nil { + tempRulebase["rulebase"] = readAccessRuleBaseField(ruleBaseMap) + } + + ruleBaseDictToReturn = append(ruleBaseDictToReturn, tempRulebase) + } + } + return ruleBaseDictToReturn +} diff --git a/checkpoint/data_source_checkpoint_management_access_rulebase_test.go b/checkpoint/data_source_checkpoint_management_access_rulebase_test.go new file mode 100644 index 00000000..a27bb4a4 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_access_rulebase_test.go @@ -0,0 +1,87 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + _ "github.com/hashicorp/terraform-plugin-sdk/terraform" + "os" + _ "strings" + "testing" +) + +func TestAccDataSourceCheckpointManagementAccessRulebase_basic(t *testing.T) { + var showObjectsQuery map[string]interface{} + dataSourceShowObjects := "data.checkpoint_management_access_rulebase.test" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceManagementAccessRulebaseConfig("Network", 1), + Check: resource.ComposeTestCheckFunc( + testAccCheckCheckpointAccessRulebase(dataSourceShowObjects, &showObjectsQuery), + testAccCheckCheckpointAccessRulebaseAttributes(&showObjectsQuery), + ), + }, + }, + }) +} + +func testAccCheckCheckpointAccessRulebase(resourceTfName string, res *map[string]interface{}) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[resourceTfName] + if !ok { + return fmt.Errorf("show-access-rulebase data source not found: %s", resourceTfName) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("show-access-rulebase data source ID is not set") + } + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + response, _ := client.ApiCall("show-access-rulebase", map[string]interface{}{"name": "Network", "limit": 1}, client.GetSessionID(), true, client.IsProxyUsed()) + if !response.Success { + return fmt.Errorf(response.ErrorMsg) + } + + *res = response.GetData() + + return nil + } +} + +func testAccCheckCheckpointAccessRulebaseAttributes(showAccessRulebaseMap *map[string]interface{}) resource.TestCheckFunc { + return func(s *terraform.State) error { + + showAccessRulebaseMap := *showAccessRulebaseMap + if showAccessRulebaseMap == nil { + return fmt.Errorf("showAccessRulebaseMap is nil") + } + + rulebase := showAccessRulebaseMap["rulebase"].([]interface{}) + + if len(rulebase) != 1 { + return fmt.Errorf("show-access-rulebase returned wrong number of rulebase objects. exptected for 1, found %d", len(rulebase)) + } + + return nil + } +} + +func testAccDataSourceManagementAccessRulebaseConfig(name string, limit int) string { + return fmt.Sprintf(` +data "checkpoint_management_access_rulebase" "test" { + name = "%s" + limit = %d +} +`, name, limit) +} diff --git a/checkpoint/data_source_checkpoint_management_access_section.go b/checkpoint/data_source_checkpoint_management_access_section.go index 70c3d9ff..866653ba 100644 --- a/checkpoint/data_source_checkpoint_management_access_section.go +++ b/checkpoint/data_source_checkpoint_management_access_section.go @@ -47,7 +47,7 @@ func dataSourceManagementAccessSectionRead(d *schema.ResourceData, m interface{} payload["uid"] = uid } - showAccessSectionRes, err := client.ApiCall("show-access-section", payload, client.GetSessionID(), true, false) + showAccessSectionRes, err := client.ApiCall("show-access-section", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_aci_data_center_server.go b/checkpoint/data_source_checkpoint_management_aci_data_center_server.go new file mode 100644 index 00000000..2d515d54 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_aci_data_center_server.go @@ -0,0 +1,157 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "strconv" + "strings" +) + +func dataSourceManagementAciDataCenterServer() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAciDataCenterServerRead, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Object name. Must be unique in the domain.", + }, + "uid": { + Type: schema.TypeString, + Optional: true, + Description: "Object unique identifier.", + }, + "urls": { + Type: schema.TypeList, + Computed: true, + Description: "Address of APIC cluster members.\nExample: http(s)://.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "username": { + Type: schema.TypeString, + Computed: true, + Description: "User ID of the Cisco APIC server.\nWhen using commonLoginLogic Domains use the following syntax:\napic:\\.", + }, + "certificate_fingerprint": { + Type: schema.TypeString, + Computed: true, + Description: "Specify the SHA-1 or SHA-256 fingerprint of the Data Center Server's certificate.", + }, + "unsafe_auto_accept": { + Type: schema.TypeBool, + Computed: true, + Description: "When set to false, the current Data Center Server's certificate should be trusted, either by providing the certificate-fingerprint argument or by relying on a previously trusted certificate of this hostname.\n\nWhen set to true, trust the current Data Center Server's certificate as-is.", + }, + "tags": { + Type: schema.TypeSet, + Computed: true, + Description: "Collection of tag identifiers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "color": { + Type: schema.TypeString, + Computed: true, + Description: "Color of the object. Should be one of existing colors.", + }, + "comments": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func dataSourceAciDataCenterServerRead(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + var name string + var uid string + + if v, ok := d.GetOk("name"); ok { + name = v.(string) + } + if v, ok := d.GetOk("uid"); ok { + uid = v.(string) + } + payload := make(map[string]interface{}) + + if name != "" { + payload["name"] = name + } else if uid != "" { + payload["uid"] = uid + } + showAciDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showAciDataCenterServerRes.Success { + return fmt.Errorf(showAciDataCenterServerRes.ErrorMsg) + } + aciDataCenterServer := showAciDataCenterServerRes.GetData() + + if v := aciDataCenterServer["uid"]; v != nil { + _ = d.Set("uid", v) + d.SetId(v.(string)) + } + + if v := aciDataCenterServer["name"]; v != nil { + _ = d.Set("name", v) + } + + if aciDataCenterServer["properties"] != nil { + propsJson, ok := aciDataCenterServer["properties"].([]interface{}) + if ok { + for _, prop := range propsJson { + propMap := prop.(map[string]interface{}) + propName := strings.ReplaceAll(propMap["name"].(string), "-", "_") + propValue := propMap["value"] + if propName == "unsafe_auto_accept" { + propValue, _ = strconv.ParseBool(propValue.(string)) + } + if propName == "urls" { + propValue = strings.Split(propValue.(string), ";") + } + _ = d.Set(propName, propValue) + } + } + } + + if aciDataCenterServer["tags"] != nil { + tagsJson, ok := aciDataCenterServer["tags"].([]interface{}) + if ok { + tagsIds := make([]string, 0) + if len(tagsJson) > 0 { + for _, tags := range tagsJson { + tags := tags.(map[string]interface{}) + tagsIds = append(tagsIds, tags["name"].(string)) + } + } + _ = d.Set("tags", tagsIds) + } + } else { + _ = d.Set("tags", nil) + } + + if v := aciDataCenterServer["color"]; v != nil { + _ = d.Set("color", v) + } + + if v := aciDataCenterServer["comments"]; v != nil { + _ = d.Set("comments", v) + } + + if v := aciDataCenterServer["ignore-warnings"]; v != nil { + _ = d.Set("ignore_warnings", v) + } + + if v := aciDataCenterServer["ignore-errors"]; v != nil { + _ = d.Set("ignore_errors", v) + } + + return nil + +} diff --git a/checkpoint/data_source_checkpoint_management_aci_data_center_server_test.go b/checkpoint/data_source_checkpoint_management_aci_data_center_server_test.go new file mode 100644 index 00000000..043ff37d --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_aci_data_center_server_test.go @@ -0,0 +1,54 @@ +package checkpoint + +import ( + "fmt" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "os" + "testing" +) + +func TestAccDataSourceCheckpointManagementAciDataCenterServer_basic(t *testing.T) { + + objName := "tfTestManagementDataAciDataCenterServer_" + acctest.RandString(6) + resourceName := "checkpoint_management_aci_data_center_server.aci_data_center_server" + dataSourceName := "data.checkpoint_management_aci_data_center_server.aci_data_center_server" + username := "USERNAME" + password := "PASSWORD" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceManagementAciDataCenterServerConfig(objName, username, password), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), + ), + }, + }, + }) + +} + +func testAccDataSourceManagementAciDataCenterServerConfig(name string, username string, password string) string { + return fmt.Sprintf(` +resource "checkpoint_management_aci_data_center_server" "aci_data_center_server" { + name = "%s" + username = "%s" + password = "%s" + urls = ["url1", "url2"] + unsafe_auto_accept = true + ignore_warnings = true +} + +data "checkpoint_management_aci_data_center_server" "aci_data_center_server" { + name = "${checkpoint_management_aci_data_center_server.aci_data_center_server.name}" +} +`, name, username, password) +} diff --git a/checkpoint/data_source_checkpoint_management_address_range.go b/checkpoint/data_source_checkpoint_management_address_range.go index 14e5a1fd..78656bd0 100644 --- a/checkpoint/data_source_checkpoint_management_address_range.go +++ b/checkpoint/data_source_checkpoint_management_address_range.go @@ -127,7 +127,7 @@ func dataSourceManagementAddressRangeRead(d *schema.ResourceData, m interface{}) payload["uid"] = uid } - showAddressRangeRes, err := client.ApiCall("show-address-range", payload, client.GetSessionID(), true, false) + showAddressRangeRes, err := client.ApiCall("show-address-range", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_application_site.go b/checkpoint/data_source_checkpoint_management_application_site.go index 705c4e07..c5782f96 100644 --- a/checkpoint/data_source_checkpoint_management_application_site.go +++ b/checkpoint/data_source_checkpoint_management_application_site.go @@ -103,7 +103,7 @@ func dataSourceManagementApplicationSiteRead(d *schema.ResourceData, m interface payload["uid"] = uid } - showApplicationSiteRes, err := client.ApiCall("show-application-site", payload, client.GetSessionID(), true, false) + showApplicationSiteRes, err := client.ApiCall("show-application-site", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_application_site_category.go b/checkpoint/data_source_checkpoint_management_application_site_category.go index 154bef46..35d1ad84 100644 --- a/checkpoint/data_source_checkpoint_management_application_site_category.go +++ b/checkpoint/data_source_checkpoint_management_application_site_category.go @@ -71,7 +71,7 @@ func dataSourceManagementApplicationSiteCategoryRead(d *schema.ResourceData, m i payload["uid"] = uid } - showApplicationSiteCategoryRes, err := client.ApiCall("show-application-site-category", payload, client.GetSessionID(), true, false) + showApplicationSiteCategoryRes, err := client.ApiCall("show-application-site-category", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_application_site_group.go b/checkpoint/data_source_checkpoint_management_application_site_group.go index ef5167bd..ab4f582e 100644 --- a/checkpoint/data_source_checkpoint_management_application_site_group.go +++ b/checkpoint/data_source_checkpoint_management_application_site_group.go @@ -74,7 +74,7 @@ func dataSourceManagementApplicationSiteGroupRead(d *schema.ResourceData, m inte payload["uid"] = uid } - showApplicationSiteGroupRes, err := client.ApiCall("show-application-site-group", payload, client.GetSessionID(), true, false) + showApplicationSiteGroupRes, err := client.ApiCall("show-application-site-group", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_aws_data_center_server.go b/checkpoint/data_source_checkpoint_management_aws_data_center_server.go new file mode 100644 index 00000000..b2f055e3 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_aws_data_center_server.go @@ -0,0 +1,161 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "strconv" + "strings" +) + +func dataSourceManagementAwsDataCenterServer() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAwsDataCenterServerRead, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Object name. Must be unique in the domain.", + }, + "uid": { + Type: schema.TypeString, + Optional: true, + Description: "Object unique identifier.", + }, + "authentication_method": { + Type: schema.TypeString, + Computed: true, + Description: "user-authentication\nUses the Access keys to authenticate.\nrole-authentication\nUses the AWS IAM role to authenticate.\nThis option requires the Security Management Server be deployed in AWS and has an IAM Role.", + }, + "access_key_id": { + Type: schema.TypeString, + Computed: true, + Description: "Access key ID for the AWS account.\nRequired for authentication-method: user-authentication.", + }, + "region": { + Type: schema.TypeString, + Computed: true, + Description: "Select the AWS region.", + }, + "enable_sts_assume_role": { + Type: schema.TypeBool, + Computed: true, + Description: "Enables the STS Assume Role option. After it is enabled, the sts-role field is mandatory, whereas the sts-external-id is optional.", + }, + "sts_role": { + Type: schema.TypeString, + Computed: true, + Description: "The STS RoleARN of the role to be assumed.\nRequired for enable-sts-assume-role: true.", + }, + "sts_external_id": { + Type: schema.TypeString, + Computed: true, + Description: "An optional STS External-Id to use when assuming the role.", + }, + "tags": { + Type: schema.TypeSet, + Computed: true, + Description: "Collection of tag identifiers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "color": { + Type: schema.TypeString, + Computed: true, + Description: "Color of the object. Should be one of existing colors.", + }, + "comments": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func dataSourceAwsDataCenterServerRead(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + var name string + var uid string + + if v, ok := d.GetOk("name"); ok { + name = v.(string) + } + if v, ok := d.GetOk("uid"); ok { + uid = v.(string) + } + payload := make(map[string]interface{}) + + if name != "" { + payload["name"] = name + } else if uid != "" { + payload["uid"] = uid + } + showAwsDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showAwsDataCenterServerRes.Success { + return fmt.Errorf(showAwsDataCenterServerRes.ErrorMsg) + } + awsDataCenterServer := showAwsDataCenterServerRes.GetData() + + if v := awsDataCenterServer["uid"]; v != nil { + _ = d.Set("uid", v) + d.SetId(v.(string)) + } + + if v := awsDataCenterServer["name"]; v != nil { + _ = d.Set("name", v) + } + + if awsDataCenterServer["properties"] != nil { + propsJson, ok := awsDataCenterServer["properties"].([]interface{}) + if ok { + for _, prop := range propsJson { + propMap := prop.(map[string]interface{}) + propName := strings.ReplaceAll(propMap["name"].(string), "-", "_") + propValue := propMap["value"] + if propName == "enable_sts_assume_role" { + propValue, _ = strconv.ParseBool(propValue.(string)) + } + _ = d.Set(propName, propValue) + } + } + } + + if awsDataCenterServer["tags"] != nil { + tagsJson, ok := awsDataCenterServer["tags"].([]interface{}) + if ok { + tagsIds := make([]string, 0) + if len(tagsJson) > 0 { + for _, tags := range tagsJson { + tags := tags.(map[string]interface{}) + tagsIds = append(tagsIds, tags["name"].(string)) + } + } + _ = d.Set("tags", tagsIds) + } + } else { + _ = d.Set("tags", nil) + } + + if v := awsDataCenterServer["color"]; v != nil { + _ = d.Set("color", v) + } + + if v := awsDataCenterServer["comments"]; v != nil { + _ = d.Set("comments", v) + } + + if v := awsDataCenterServer["ignore-warnings"]; v != nil { + _ = d.Set("ignore_warnings", v) + } + + if v := awsDataCenterServer["ignore-errors"]; v != nil { + _ = d.Set("ignore_errors", v) + } + + return nil + +} diff --git a/checkpoint/data_source_checkpoint_management_aws_data_center_server_test.go b/checkpoint/data_source_checkpoint_management_aws_data_center_server_test.go new file mode 100644 index 00000000..e8ddb924 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_aws_data_center_server_test.go @@ -0,0 +1,56 @@ +package checkpoint + +import ( + "fmt" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "os" + "testing" +) + +func TestAccDataSourceCheckpointManagementAwsDataCenterServer_basic(t *testing.T) { + + objName := "tfTestManagementDataAwsDataCenterServer_" + acctest.RandString(6) + resourceName := "checkpoint_management_aws_data_center_server.aws_data_center_server" + dataSourceName := "data.checkpoint_management_aws_data_center_server.aws_data_center_server" + authenticationMethod := "user-authentication" + accessKeyId := "MY-KEY-ID" + secretAccessKey := "MY-SECRET-KEY" + region := "us-east-1" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceManagementAwsDataCenterServerConfig(objName, authenticationMethod, accessKeyId, secretAccessKey, region), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), + ), + }, + }, + }) + +} + +func testAccDataSourceManagementAwsDataCenterServerConfig(name string, authenticationMethod string, accessKeyId string, secretAccessKey string, region string) string { + return fmt.Sprintf(` +resource "checkpoint_management_aws_data_center_server" "aws_data_center_server" { + name = "%s" + authentication_method = "%s" + access_key_id = "%s" + secret_access_key = "%s" + region = "%s" + ignore_warnings = true +} + +data "checkpoint_management_aws_data_center_server" "aws_data_center_server" { + name = "${checkpoint_management_aws_data_center_server.aws_data_center_server.name}" +} +`, name, authenticationMethod, accessKeyId, secretAccessKey, region) +} diff --git a/checkpoint/data_source_checkpoint_management_azure_data_center_server.go b/checkpoint/data_source_checkpoint_management_azure_data_center_server.go new file mode 100644 index 00000000..900cbe21 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_azure_data_center_server.go @@ -0,0 +1,156 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "strconv" + "strings" +) + +func dataSourceManagementAzureDataCenterServer() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAzureDataCenterServerRead, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Object name. Must be unique in the domain.", + }, + "uid": { + Type: schema.TypeString, + Optional: true, + Description: "Object unique identifier.", + }, + "authentication_method": { + Type: schema.TypeString, + Computed: true, + Description: "user-authentication\nUses the Azure AD User to authenticate.\nservice-principal-authentication\nUses the Service Principal to authenticate.", + }, + "username": { + Type: schema.TypeString, + Computed: true, + Description: "An Azure Active Directory user Format @.\nRequired for authentication-method: user-authentication.", + }, + "application_id": { + Type: schema.TypeString, + Computed: true, + Description: "The Application ID of the Service Principal, in UUID format.\nRequired for authentication-method: service-principal-authentication.", + }, + "directory_id": { + Type: schema.TypeString, + Computed: true, + Description: "The Directory ID of the Azure AD, in UUID format.\nRequired for authentication-method: service-principal-authentication.", + }, + "environment": { + Type: schema.TypeString, + Computed: true, + Description: "Select the Azure Cloud Environment.", + }, + "tags": { + Type: schema.TypeSet, + Computed: true, + Description: "Collection of tag identifiers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "color": { + Type: schema.TypeString, + Computed: true, + Description: "Color of the object. Should be one of existing colors.", + }, + "comments": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func dataSourceAzureDataCenterServerRead(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + var name string + var uid string + + if v, ok := d.GetOk("name"); ok { + name = v.(string) + } + if v, ok := d.GetOk("uid"); ok { + uid = v.(string) + } + payload := make(map[string]interface{}) + + if name != "" { + payload["name"] = name + } else if uid != "" { + payload["uid"] = uid + } + showAzureDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showAzureDataCenterServerRes.Success { + return fmt.Errorf(showAzureDataCenterServerRes.ErrorMsg) + } + azureDataCenterServer := showAzureDataCenterServerRes.GetData() + + if v := azureDataCenterServer["uid"]; v != nil { + _ = d.Set("uid", v) + d.SetId(v.(string)) + } + + if v := azureDataCenterServer["name"]; v != nil { + _ = d.Set("name", v) + } + + if azureDataCenterServer["properties"] != nil { + propsJson, ok := azureDataCenterServer["properties"].([]interface{}) + if ok { + for _, prop := range propsJson { + propMap := prop.(map[string]interface{}) + propName := strings.ReplaceAll(propMap["name"].(string), "-", "_") + propValue := propMap["value"] + if propName == "enable_sts_assume_role" { + propValue, _ = strconv.ParseBool(propValue.(string)) + } + _ = d.Set(propName, propValue) + } + } + } + + if azureDataCenterServer["tags"] != nil { + tagsJson, ok := azureDataCenterServer["tags"].([]interface{}) + if ok { + tagsIds := make([]string, 0) + if len(tagsJson) > 0 { + for _, tags := range tagsJson { + tags := tags.(map[string]interface{}) + tagsIds = append(tagsIds, tags["name"].(string)) + } + } + _ = d.Set("tags", tagsIds) + } + } else { + _ = d.Set("tags", nil) + } + + if v := azureDataCenterServer["color"]; v != nil { + _ = d.Set("color", v) + } + + if v := azureDataCenterServer["comments"]; v != nil { + _ = d.Set("comments", v) + } + + if v := azureDataCenterServer["ignore-warnings"]; v != nil { + _ = d.Set("ignore_warnings", v) + } + + if v := azureDataCenterServer["ignore-errors"]; v != nil { + _ = d.Set("ignore_errors", v) + } + + return nil + +} diff --git a/checkpoint/data_source_checkpoint_management_azure_data_center_server_test.go b/checkpoint/data_source_checkpoint_management_azure_data_center_server_test.go new file mode 100644 index 00000000..72652b54 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_azure_data_center_server_test.go @@ -0,0 +1,54 @@ +package checkpoint + +import ( + "fmt" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "os" + "testing" +) + +func TestAccDataSourceCheckpointManagementAzureDataCenterServer_basic(t *testing.T) { + + objName := "tfTestManagementDataAzureDataCenterServer_" + acctest.RandString(6) + resourceName := "checkpoint_management_azure_data_center_server.azure_data_center_server" + dataSourceName := "data.checkpoint_management_azure_data_center_server.azure_data_center_server" + authenticationMethod := "user-authentication" + username := "MY-KEY-ID" + password := "MY-SECRET-KEY" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceManagementAzureDataCenterServerConfig(objName, username, password, authenticationMethod), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), + ), + }, + }, + }) + +} + +func testAccDataSourceManagementAzureDataCenterServerConfig(name string, username string, password string, authenticationMethod string) string { + return fmt.Sprintf(` +resource "checkpoint_management_azure_data_center_server" "azure_data_center_server" { + name = "%s" + username = "%s" + password = "%s" + authentication_method = "%s" + ignore_warnings = true +} + +data "checkpoint_management_azure_data_center_server" "azure_data_center_server" { + name = "${checkpoint_management_azure_data_center_server.azure_data_center_server.name}" +} +`, name, username, password, authenticationMethod) +} diff --git a/checkpoint/data_source_checkpoint_management_checkpoint_host.go b/checkpoint/data_source_checkpoint_management_checkpoint_host.go index 02574c8b..afe45d27 100644 --- a/checkpoint/data_source_checkpoint_management_checkpoint_host.go +++ b/checkpoint/data_source_checkpoint_management_checkpoint_host.go @@ -410,7 +410,7 @@ func dataSourceManagementCheckpointHostRead(d *schema.ResourceData, m interface{ payload["uid"] = uid } - showCheckpointHostRes, err := client.ApiCall("show-checkpoint-host", payload, client.GetSessionID(), true, false) + showCheckpointHostRes, err := client.ApiCall("show-checkpoint-host", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_data_center_content.go b/checkpoint/data_source_checkpoint_management_data_center_content.go new file mode 100644 index 00000000..97df86a1 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_data_center_content.go @@ -0,0 +1,317 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "log" + "math" + "strconv" + "strings" +) + +func dataSourceManagementDataCenterContent() *schema.Resource { + return &schema.Resource{ + Read: dataSourceManagementDataCenterContentRead, + + Schema: map[string]*schema.Schema{ + "data_center_name": { + Type: schema.TypeString, + Optional: true, + Description: "Name of the Data Center Server where to search for objects.", + }, + "data_center_uid": { + Type: schema.TypeString, + Optional: true, + Description: "Unique identifier of the Data Center Server where to search for objects.", + }, + "limit": { + Type: schema.TypeInt, + Optional: true, + Description: "The maximal number of returned results.", + Default: 50, + }, + "offset": { + Type: schema.TypeInt, + Optional: true, + Description: "Number of the results to initially skip.", + Default: 0, + }, + "order": { + Type: schema.TypeList, + Optional: true, + Description: "Sorts the results by search criteria. Automatically sorts the results by Name, in the ascending order.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "asc": { + Type: schema.TypeString, + Optional: true, + Description: "Sorts results by the given field in ascending order.", + }, + "desc": { + Type: schema.TypeString, + Optional: true, + Description: "Sorts results by the given field in descending order.", + }, + }, + }, + }, + "uid_in_data_center": { + Type: schema.TypeString, + Optional: true, + Description: "Return result matching the unique identifier of the object on the Data Center Server.", + }, + "filter": { + Type: schema.TypeMap, + Optional: true, + Description: "Return results matching the specified filter.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "text": { + Type: schema.TypeString, + Computed: true, + Description: "Return results containing the specified text value.", + }, + "uri": { + Type: schema.TypeString, + Computed: true, + Description: "Return results under the specified Data Center Object (identified by URI).", + }, + "parent_uid_in_data_center": { + Type: schema.TypeString, + Computed: true, + Description: "Return results under the specified Data Center Object (identified by UID).", + }, + }, + }, + }, + "from": { + Type: schema.TypeInt, + Computed: true, + Description: "From which element number the query was done.", + }, + "objects": { + Type: schema.TypeList, + Computed: true, + Description: "Remote objects views.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name_in_data_center": { + Type: schema.TypeString, + Computed: true, + Description: "Object name in the Data Center.", + }, + "uid_in_data_center": { + Type: schema.TypeString, + Computed: true, + Description: "Unique identifier of the object in the Data Center.", + }, + "data_center_object": { + Type: schema.TypeMap, + Computed: true, + Description: "The imported management object (if exists). Level of details in the output corresponds to the number of details for search. This table shows the level of details in the Standard level.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Computed: true, + Description: "Object name. Must be unique in the domain.", + }, + "uid": { + Type: schema.TypeString, + Computed: true, + Description: "Object unique identifier.", + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "Object type.", + }, + }, + }, + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: "Object management name.", + }, + "type_in_data_center": { + Type: schema.TypeString, + Computed: true, + Description: "Object type in Data Center.", + }, + "additional_properties": { + Type: schema.TypeMap, + Computed: true, + Description: "Additional properties on the object.\nRemote objects views.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Computed: true, + Description: "N/A", + }, + "value": { + Type: schema.TypeString, + Computed: true, + Description: "N/A", + }, + }, + }, + }, + }, + }, + }, + "to": { + Type: schema.TypeInt, + Computed: true, + Description: "To which element number the query was done.", + }, + "total": { + Type: schema.TypeInt, + Computed: true, + Description: "Total number of elements returned by the query.", + }, + }, + } +} + +func dataSourceManagementDataCenterContentRead(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + + name := d.Get("data_center_name").(string) + uid := d.Get("data_center_uid").(string) + + payload := map[string]interface{}{} + + if name != "" { + payload["data-center-name"] = name + } else if uid != "" { + payload["data-center-uid"] = uid + } + + if v, ok := d.GetOk("limit"); ok { + payload["limit"] = v.(int) + } + if v, ok := d.GetOk("offset"); ok { + payload["offset"] = v.(int) + } + if v, ok := d.GetOk("order"); ok { + + ordersList, ok := v.([]interface{}) + var ordersDictToReturn []map[string]interface{} + + if ok { + for i := range ordersList { + + objectsMap := ordersList[i].(map[string]interface{}) + + tempOrder := make(map[string]interface{}) + + if v, _ := objectsMap["asc"]; v != nil && v != "" { + tempOrder["ASC"] = v + } + + if v, _ := objectsMap["desc"]; v != nil && v != "" { + tempOrder["DESC"] = v + } + + ordersDictToReturn = append(ordersDictToReturn, tempOrder) + } + payload["order"] = ordersDictToReturn + } + } + if v, ok := d.GetOk("uid_in_data_center"); ok { + payload["uid-in-data-center"] = v.(string) + } + if v, ok := d.GetOk("filter"); ok { + dataCenterContentFilter := v.(map[string]interface{}) + dataCenterContentFilterMap := make(map[string]interface{}) + if v, ok := dataCenterContentFilter["text"]; ok { + dataCenterContentFilterMap["text"] = v.(string) + } + if v, ok := dataCenterContentFilter["uri"]; ok { + dataCenterContentFilterMap["uri"] = v.(string) + } + if v, ok := dataCenterContentFilter["parent_uid_in_data_center"]; ok { + dataCenterContentFilterMap["parent-uid-in-data-center"] = v.(string) + } + payload["filter"] = dataCenterContentFilterMap + } + showDataCenterContentRes, err := client.ApiCall("show-data-center-content", payload, client.GetSessionID(), true, client.IsProxyUsed()) + + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showDataCenterContentRes.Success { + return fmt.Errorf(showDataCenterContentRes.ErrorMsg) + } + DataCenterContent := showDataCenterContentRes.GetData() + + log.Println("Read DataCenterContent - Show JSON = ", DataCenterContent) + + d.SetId("show-data-center-content-" + acctest.RandString(10)) + + if v := DataCenterContent["data-center-name"]; v != nil { + _ = d.Set("data_center_name", v) + } + + if v := DataCenterContent["from"]; v != nil { + _ = d.Set("from", int(math.Round(v.(float64)))) + } + + if DataCenterContent["objects"] != nil { + dataCenterContentObjects := DataCenterContent["objects"].([]interface{}) + var dataCenterContentObjectToReturn []map[string]interface{} + for i, _ := range dataCenterContentObjects { + dataCenterContentObject := dataCenterContentObjects[i].(map[string]interface{}) + dataCenterContentObjectsMap := make(map[string]interface{}) + if v, ok := dataCenterContentObject["name-in-data-center"]; ok { + dataCenterContentObjectsMap["name_in_data_center"] = v.(string) + } + if v, ok := dataCenterContentObject["uid-in-data-center"]; ok { + dataCenterContentObjectsMap["uid_in_data_center"] = v.(string) + } + if v, ok := dataCenterContentObject["data-center-object"]; ok { + dataCenterContentObjectsMap["data_center_object"] = v + } + if v, ok := dataCenterContentObject["name"]; ok { + dataCenterContentObjectsMap["name"] = v.(string) + } + if v, ok := dataCenterContentObject["type-in-data-center"]; ok { + dataCenterContentObjectsMap["type_in_data_center"] = v.(string) + } + if v, ok := dataCenterContentObject["additional-properties"]; ok { + propsJson, ok := v.([]interface{}) + propsMapToReturn := make(map[string]interface{}) + if ok { + for _, prop := range propsJson { + propMap := prop.(map[string]interface{}) + propName := strings.ReplaceAll(propMap["name"].(string), "-", "_") + propValue := propMap["value"] + if propName == "unsafe_auto_accept" || propName == "enable_sts_assume_role" { + propValue, _ = strconv.ParseBool(propValue.(string)) + } + if propName == "urls" || propName == "hostnames" { + propValue = strings.Split(propValue.(string), ";") + } + propsMapToReturn[propName] = propValue + } + } + dataCenterContentObjectsMap["additional_properties"] = propsMapToReturn + } + dataCenterContentObjectToReturn = append(dataCenterContentObjectToReturn, dataCenterContentObjectsMap) + } + _ = d.Set("objects", dataCenterContentObjectToReturn) + } + + if v := DataCenterContent["to"]; v != nil { + _ = d.Set("to", int(math.Round(v.(float64)))) + } + if v := DataCenterContent["total"]; v != nil { + _ = d.Set("total", int(math.Round(v.(float64)))) + } + return nil +} diff --git a/checkpoint/data_source_checkpoint_management_data_center_content_test.go b/checkpoint/data_source_checkpoint_management_data_center_content_test.go new file mode 100644 index 00000000..b1a8c3dd --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_data_center_content_test.go @@ -0,0 +1,37 @@ +package checkpoint + +import ( + "fmt" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "os" + "testing" +) + +func TestAccDataSourceCheckpointManagementDataCenterContent_basic(t *testing.T) { + + objName := "myApic" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceManagementDataCenterContentConfig(objName), + }, + }, + }) + +} + +func testAccDataSourceManagementDataCenterContentConfig(name string) string { + return fmt.Sprintf(` +data "checkpoint_management_data_center_content" "data_center_content" { + data_center_name = "%s" +} +`, name) +} diff --git a/checkpoint/data_source_checkpoint_management_data_center_query.go b/checkpoint/data_source_checkpoint_management_data_center_query.go new file mode 100644 index 00000000..728afe77 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_data_center_query.go @@ -0,0 +1,214 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "log" +) + +func dataSourceManagementDataCenterQuery() *schema.Resource { + return &schema.Resource{ + Read: dataSourceDataCenterQueryRead, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Object name. Must be unique in the domain.", + }, + "uid": { + Type: schema.TypeString, + Optional: true, + Description: "Object unique identifier.", + }, + "data_centers": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Data Center servers identified by the name or UID. Use \"All\" to select all data centers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "query_rules": { + Type: schema.TypeList, + Computed: true, + Description: "Data Center Query Rules.
There is an 'AND' operation between multiple Query Rules.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key_type": { + Type: schema.TypeString, + Optional: true, + Description: "The type of the \"key\" parameter.
Use \"predefined\" for these keys: type-in-data-center, name-in-data-center, and ip-address.
Use \"tag\" to query the Data Center tag�s property.", + }, + "key": { + Type: schema.TypeString, + Optional: true, + Description: "Defines in which Data Center property to query.
For key-type \"predefined\", use these keys: type-in-data-center, name-in-data-center, and ip-address.
For key-type \"tag\", use the Data Center tag key to query.
Keys are case-insensitive.", + }, + "values": { + Type: schema.TypeList, + Optional: true, + Description: "The value(s) of the Data Center property to match the Query Rule.
Values are case-insensitive.
There is an 'OR' operation between multiple values.
For key-type \"predefined\" and key 'ip-address', the values must be an IPv4 or IPv6 address.
For key-type \"tag\", the values must be the Data Center tag values.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + }, + }, + "tags": { + Type: schema.TypeSet, + Computed: true, + Description: "Collection of tag identifiers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "color": { + Type: schema.TypeString, + Computed: true, + Description: "Color of the object. Should be one of existing colors.", + }, + "comments": { + Type: schema.TypeString, + Computed: true, + Description: "Comments string.", + }, + }, + } +} + +func dataSourceDataCenterQueryRead(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + var name string + var uid string + + if v, ok := d.GetOk("name"); ok { + name = v.(string) + } + if v, ok := d.GetOk("uid"); ok { + uid = v.(string) + } + payload := make(map[string]interface{}) + + if name != "" { + payload["name"] = name + } else if uid != "" { + payload["uid"] = uid + } + showDataCenterQueryRes, err := client.ApiCall("show-data-center-query", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showDataCenterQueryRes.Success { + return fmt.Errorf(showDataCenterQueryRes.ErrorMsg) + } + + dataCenterQuery := showDataCenterQueryRes.GetData() + + KeysToFixedKeys := getKeysToFixedKeys() + + log.Println("Read DataCenterQuery - Show JSON = ", dataCenterQuery) + + if v := dataCenterQuery["uid"]; v != nil { + _ = d.Set("uid", v) + d.SetId(v.(string)) + } + + if v := dataCenterQuery["name"]; v != nil { + _ = d.Set("name", v) + } + + if dataCenterQuery["data-centers"] != nil { + dataCentersJson, ok := dataCenterQuery["data-centers"].([]interface{}) + if ok { + dataCentersIds := make([]string, 0) + if len(dataCentersJson) > 0 { + for _, data_centers := range dataCentersJson { + data_centers := data_centers.(map[string]interface{}) + dataCentersIds = append(dataCentersIds, data_centers["name"].(string)) + } + _ = d.Set("data_centers", dataCentersIds) + } else { + _ = d.Set("data_centers", []string{"All"}) + } + } + } + + if dataCenterQuery["query-rules"] != nil { + + queryRulesList, ok := dataCenterQuery["query-rules"].([]interface{}) + + if ok { + + if len(queryRulesList) > 0 { + + var queryRulesListToReturn []map[string]interface{} + + for i := range queryRulesList { + + queryRulesMap := queryRulesList[i].(map[string]interface{}) + + queryRulesMapToAdd := make(map[string]interface{}) + + if v, _ := queryRulesMap["key-type"]; v != nil { + keyType := v.(string) + if newType, ok := KeysToFixedKeys[keyType]; ok { + queryRulesMapToAdd["key_type"] = newType + } else { + queryRulesMapToAdd["key_type"] = v + } + } + if v, _ := queryRulesMap["key"]; v != nil { + key := v.(string) + if newType, ok := KeysToFixedKeys[key]; ok { + queryRulesMapToAdd["key"] = newType + } else { + queryRulesMapToAdd["key"] = v + } + } + if v, _ := queryRulesMap["values"]; v != nil { + queryRulesMapToAdd["values"] = v + } + queryRulesListToReturn = append(queryRulesListToReturn, queryRulesMapToAdd) + } + _ = d.Set("query_rules", queryRulesListToReturn) + } + } + } + + if dataCenterQuery["tags"] != nil { + tagsJson, ok := dataCenterQuery["tags"].([]interface{}) + if ok { + tagsIds := make([]string, 0) + if len(tagsJson) > 0 { + for _, tags := range tagsJson { + tags := tags.(map[string]interface{}) + tagsIds = append(tagsIds, tags["name"].(string)) + } + } + _ = d.Set("tags", tagsIds) + } + } else { + _ = d.Set("tags", nil) + } + + if v := dataCenterQuery["color"]; v != nil { + _ = d.Set("color", v) + } + + if v := dataCenterQuery["comments"]; v != nil { + _ = d.Set("comments", v) + } + + if v := dataCenterQuery["ignore-warnings"]; v != nil { + _ = d.Set("ignore_warnings", v) + } + + if v := dataCenterQuery["ignore-errors"]; v != nil { + _ = d.Set("ignore_errors", v) + } + + return nil + +} diff --git a/checkpoint/data_source_checkpoint_management_data_center_query_test.go b/checkpoint/data_source_checkpoint_management_data_center_query_test.go new file mode 100644 index 00000000..5ed54c45 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_data_center_query_test.go @@ -0,0 +1,54 @@ +package checkpoint + +import ( + "fmt" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "os" + "testing" +) + +func TestAccDataSourceCheckpointManagementDataCenterQuery_basic(t *testing.T) { + + objName := "tfTestManagementDataDataCenterQuery_" + acctest.RandString(6) + resourceName := "checkpoint_management_data_center_query.data_center_query" + dataSourceName := "data.checkpoint_management_data_center_query.data_center_query" + firstVal := "value1" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceManagementDataCenterQueryConfig(objName, firstVal), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), + ), + }, + }, + }) + +} + +func testAccDataSourceManagementDataCenterQueryConfig(name string, firstVal string) string { + return fmt.Sprintf(` +resource "checkpoint_management_data_center_query" "data_center_query" { + name = "%s" + data_centers = ["All"] + query_rules { + key_type = "predefined" + key = "name-in-data-center" + values = ["%s"] + } +} + +data "checkpoint_management_data_center_query" "data_center_query" { + name = "${checkpoint_management_data_center_query.data_center_query.name}" +} +`, name, firstVal) +} diff --git a/checkpoint/data_source_checkpoint_management_dns_domain.go b/checkpoint/data_source_checkpoint_management_dns_domain.go index 541d58e5..8ba5f998 100644 --- a/checkpoint/data_source_checkpoint_management_dns_domain.go +++ b/checkpoint/data_source_checkpoint_management_dns_domain.go @@ -62,7 +62,7 @@ func dataSourceManagementDnsDomainRead(d *schema.ResourceData, m interface{}) er payload["uid"] = uid } - showDnsDomainRes, err := client.ApiCall("show-dns-domain", payload, client.GetSessionID(), true, false) + showDnsDomainRes, err := client.ApiCall("show-dns-domain", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_dynamic_object.go b/checkpoint/data_source_checkpoint_management_dynamic_object.go index c9bad6b0..fd8f1d97 100644 --- a/checkpoint/data_source_checkpoint_management_dynamic_object.go +++ b/checkpoint/data_source_checkpoint_management_dynamic_object.go @@ -58,7 +58,7 @@ func dataSourceManagementDynamicObjectRead(d *schema.ResourceData, m interface{} payload["uid"] = uid } - showDynamicObjectRes, err := client.ApiCall("show-dynamic-object", payload, client.GetSessionID(), true, false) + showDynamicObjectRes, err := client.ApiCall("show-dynamic-object", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_exception_group.go b/checkpoint/data_source_checkpoint_management_exception_group.go index 3bc6be46..4e4e7d3b 100644 --- a/checkpoint/data_source_checkpoint_management_exception_group.go +++ b/checkpoint/data_source_checkpoint_management_exception_group.go @@ -68,7 +68,7 @@ func dataSourceManagementExceptionGroupRead(d *schema.ResourceData, m interface{ payload["uid"] = uid } - showExceptionGroupRes, err := client.ApiCall("show-exception-group", payload, client.GetSessionID(), true, false) + showExceptionGroupRes, err := client.ApiCall("show-exception-group", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_gcp_data_center_server.go b/checkpoint/data_source_checkpoint_management_gcp_data_center_server.go new file mode 100644 index 00000000..55d115bf --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_gcp_data_center_server.go @@ -0,0 +1,136 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "strconv" + "strings" +) + +func dataSourceManagementGcpDataCenterServer() *schema.Resource { + return &schema.Resource{ + Read: dataSourceGcpDataCenterServerRead, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Object name. Must be unique in the domain.", + }, + "uid": { + Type: schema.TypeString, + Optional: true, + Description: "Object unique identifier.", + }, + "authentication_method": { + Type: schema.TypeString, + Computed: true, + Description: "key-authentication\nUses the Service Account private key file to authenticate.\nvm-instance-authentication\nUses the Service Account VM Instance to authenticate.\nThis option requires the Security Management Server deployed in a GCP, and runs as a Service Account with the required permissions.", + }, + "tags": { + Type: schema.TypeSet, + Computed: true, + Description: "Collection of tag identifiers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "color": { + Type: schema.TypeString, + Computed: true, + Description: "Color of the object. Should be one of existing colors.", + }, + "comments": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func dataSourceGcpDataCenterServerRead(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + var name string + var uid string + + if v, ok := d.GetOk("name"); ok { + name = v.(string) + } + if v, ok := d.GetOk("uid"); ok { + uid = v.(string) + } + payload := make(map[string]interface{}) + + if name != "" { + payload["name"] = name + } else if uid != "" { + payload["uid"] = uid + } + showGcpDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showGcpDataCenterServerRes.Success { + return fmt.Errorf(showGcpDataCenterServerRes.ErrorMsg) + } + gcpDataCenterServer := showGcpDataCenterServerRes.GetData() + + if v := gcpDataCenterServer["uid"]; v != nil { + _ = d.Set("uid", v) + d.SetId(v.(string)) + } + + if v := gcpDataCenterServer["name"]; v != nil { + _ = d.Set("name", v) + } + + if gcpDataCenterServer["properties"] != nil { + propsJson, ok := gcpDataCenterServer["properties"].([]interface{}) + if ok { + for _, prop := range propsJson { + propMap := prop.(map[string]interface{}) + propName := strings.ReplaceAll(propMap["name"].(string), "-", "_") + propValue := propMap["value"] + if propName == "enable_sts_assume_role" { + propValue, _ = strconv.ParseBool(propValue.(string)) + } + _ = d.Set(propName, propValue) + } + } + } + + if gcpDataCenterServer["tags"] != nil { + tagsJson, ok := gcpDataCenterServer["tags"].([]interface{}) + if ok { + tagsIds := make([]string, 0) + if len(tagsJson) > 0 { + for _, tags := range tagsJson { + tags := tags.(map[string]interface{}) + tagsIds = append(tagsIds, tags["name"].(string)) + } + } + _ = d.Set("tags", tagsIds) + } + } else { + _ = d.Set("tags", nil) + } + + if v := gcpDataCenterServer["color"]; v != nil { + _ = d.Set("color", v) + } + + if v := gcpDataCenterServer["comments"]; v != nil { + _ = d.Set("comments", v) + } + + if v := gcpDataCenterServer["ignore-warnings"]; v != nil { + _ = d.Set("ignore_warnings", v) + } + + if v := gcpDataCenterServer["ignore-errors"]; v != nil { + _ = d.Set("ignore_errors", v) + } + + return nil + +} diff --git a/checkpoint/data_source_checkpoint_management_gcp_data_center_server_test.go b/checkpoint/data_source_checkpoint_management_gcp_data_center_server_test.go new file mode 100644 index 00000000..f39144e4 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_gcp_data_center_server_test.go @@ -0,0 +1,52 @@ +package checkpoint + +import ( + "fmt" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "os" + "testing" +) + +func TestAccDataSourceCheckpointManagementGcpDataCenterServer_basic(t *testing.T) { + + objName := "tfTestManagementDataGcpDataCenterServer_" + acctest.RandString(6) + resourceName := "checkpoint_management_gcp_data_center_server.gcp_data_center_server" + dataSourceName := "data.checkpoint_management_gcp_data_center_server.gcp_data_center_server" + authenticationMethod := "key-authentication" + privateKey := "MYKEY.json" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceManagementGcpDataCenterServerConfig(objName, authenticationMethod, privateKey), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), + ), + }, + }, + }) + +} + +func testAccDataSourceManagementGcpDataCenterServerConfig(name string, authenticationMethod string, privateKey string) string { + return fmt.Sprintf(` +resource "checkpoint_management_gcp_data_center_server" "gcp_data_center_server" { + name = "%s" + authentication_method = "%s" + private_key = "%s" + ignore_warnings = true +} + +data "checkpoint_management_gcp_data_center_server" "gcp_data_center_server" { + name = "${checkpoint_management_gcp_data_center_server.gcp_data_center_server.name}" +} +`, name, authenticationMethod, privateKey) +} diff --git a/checkpoint/data_source_checkpoint_management_generic_data_center_server.go b/checkpoint/data_source_checkpoint_management_generic_data_center_server.go index b72655c5..c26891cf 100644 --- a/checkpoint/data_source_checkpoint_management_generic_data_center_server.go +++ b/checkpoint/data_source_checkpoint_management_generic_data_center_server.go @@ -85,7 +85,7 @@ func dataSourceGenericDataCenterServerRead(d *schema.ResourceData, m interface{} } else if uid != "" { payload["uid"] = uid } - showGenericDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, false) + showGenericDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_generic_data_center_server_test.go b/checkpoint/data_source_checkpoint_management_generic_data_center_server_test.go index fd0280c9..f3661714 100644 --- a/checkpoint/data_source_checkpoint_management_generic_data_center_server_test.go +++ b/checkpoint/data_source_checkpoint_management_generic_data_center_server_test.go @@ -13,7 +13,7 @@ func TestAccDataSourceCheckpointManagementGenericDataCenterServer_basic(t *testi objName := "tfTestManagementDataGenericDataCenterServer_" + acctest.RandString(6) resourceName := "checkpoint_management_generic_data_center_server.generic_data_center_server" dataSourceName := "data.checkpoint_management_generic_data_center_server.generic_data_center_server" - url := "/home/admin/test.json" + url := "MY_URL" interval := "60" context := os.Getenv("CHECKPOINT_CONTEXT") @@ -42,6 +42,7 @@ resource "checkpoint_management_generic_data_center_server" "generic_data_center name = "%s" url = "%s" interval = "%s" + ignore_warnings = true } data "checkpoint_management_generic_data_center_server" "generic_data_center_server" { diff --git a/checkpoint/data_source_checkpoint_management_group.go b/checkpoint/data_source_checkpoint_management_group.go index a89801cd..70ccb104 100644 --- a/checkpoint/data_source_checkpoint_management_group.go +++ b/checkpoint/data_source_checkpoint_management_group.go @@ -73,7 +73,7 @@ func dataSourceManagementGroupRead(d *schema.ResourceData, m interface{}) error payload["uid"] = uid } - showGroupRes, err := client.ApiCall("show-group", payload, client.GetSessionID(), true, false) + showGroupRes, err := client.ApiCall("show-group", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_group_with_exclusion.go b/checkpoint/data_source_checkpoint_management_group_with_exclusion.go index a7fc740d..38e942f9 100644 --- a/checkpoint/data_source_checkpoint_management_group_with_exclusion.go +++ b/checkpoint/data_source_checkpoint_management_group_with_exclusion.go @@ -76,7 +76,7 @@ func dataSourceManagementGroupWithExclusionRead(d *schema.ResourceData, m interf payload["uid"] = uid } - showGroupWithExclusionRes, err := client.ApiCall("show-group-with-exclusion", payload, client.GetSessionID(), true, false) + showGroupWithExclusionRes, err := client.ApiCall("show-group-with-exclusion", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_gsn_handover_group.go b/checkpoint/data_source_checkpoint_management_gsn_handover_group.go index af35d145..3c77aee1 100644 --- a/checkpoint/data_source_checkpoint_management_gsn_handover_group.go +++ b/checkpoint/data_source_checkpoint_management_gsn_handover_group.go @@ -76,7 +76,7 @@ func dataSourceManagementGsnHandoverGroupRead(d *schema.ResourceData, m interfac payload["uid"] = uid } - showGsnHandoverGroupRes, err := client.ApiCall("show-gsn-handover-group", payload, client.GetSessionID(), true, false) + showGsnHandoverGroupRes, err := client.ApiCall("show-gsn-handover-group", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_host.go b/checkpoint/data_source_checkpoint_management_host.go index 123537bc..52d9cd26 100644 --- a/checkpoint/data_source_checkpoint_management_host.go +++ b/checkpoint/data_source_checkpoint_management_host.go @@ -223,7 +223,7 @@ func dataSourceManagementHostRead(d *schema.ResourceData, m interface{}) error { payload["uid"] = uid } - showHostRes, err := client.ApiCall("show-host", payload, client.GetSessionID(), true, false) + showHostRes, err := client.ApiCall("show-host", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -386,7 +386,7 @@ func dataSourceManagementHostRead(d *schema.ResourceData, m interface{}) error { payload := map[string]interface{}{ "uid": v, } - showProtectedByRes, err := client.ApiCall("show-object", payload, client.GetSessionID(), true, false) + showProtectedByRes, err := client.ApiCall("show-object", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !showProtectedByRes.Success { if showProtectedByRes.ErrorMsg != "" { return fmt.Errorf(showProtectedByRes.ErrorMsg) diff --git a/checkpoint/data_source_checkpoint_management_https_layer.go b/checkpoint/data_source_checkpoint_management_https_layer.go index 23f81c60..5b608d79 100644 --- a/checkpoint/data_source_checkpoint_management_https_layer.go +++ b/checkpoint/data_source_checkpoint_management_https_layer.go @@ -64,7 +64,7 @@ func dataSourceManagementHttpsLayerRead(d *schema.ResourceData, m interface{}) e payload["uid"] = uid } - showHttpsLayerRes, err := client.ApiCall("show-https-layer", payload, client.GetSessionID(), true, false) + showHttpsLayerRes, err := client.ApiCall("show-https-layer", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_https_rule.go b/checkpoint/data_source_checkpoint_management_https_rule.go index 31af4701..425b1c4c 100644 --- a/checkpoint/data_source_checkpoint_management_https_rule.go +++ b/checkpoint/data_source_checkpoint_management_https_rule.go @@ -145,7 +145,7 @@ func dataSourceManagementHttpsRuleRead(d *schema.ResourceData, m interface{}) er payload["uid"] = uid } - showHttpsRuleRes, err := client.ApiCall("show-https-rule", payload, client.GetSessionID(), true, false) + showHttpsRuleRes, err := client.ApiCall("show-https-rule", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_https_rulebase.go b/checkpoint/data_source_checkpoint_management_https_rulebase.go new file mode 100644 index 00000000..e09eec98 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_https_rulebase.go @@ -0,0 +1,730 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "log" + "math" +) + +func dataSourceManagementHttpsRuleBase() *schema.Resource { + return &schema.Resource{ + Read: dataSourceManagementHttpsRuleBaseRead, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + Description: "Object name.", + }, + "uid": { + Type: schema.TypeString, + Optional: true, + Description: "Object unique identifier.", + }, + "filter": { + Type: schema.TypeString, + Optional: true, + Description: "Search expression to filter the rulebase. The provided text should be exactly the same as it would be given in Smart Console. The logical operators in the expression ('AND', 'OR') should be provided in capital letters. If an operator is not used, the default OR operator applies.", + }, + "filter_settings": { + Type: schema.TypeMap, + Optional: true, + Description: "Sets filter preferences.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "search_mode": { + Type: schema.TypeString, + Optional: true, + Description: "When set to 'general', both the Full Text Search and Packet Search are enabled. In this mode, Packet Search will not match on 'Any' object, a negated cell or a group-with-exclusion. When the search-mode is set to 'packet', by default, the match on 'Any' object, a negated cell or a group-with-exclusion are enabled. packet-search-settings may be provided to change the default behavior.", + }, + "expand_group_members": { + Type: schema.TypeBool, + Optional: true, + Description: "When true, if the search expression contains a UID or a name of a group object, results will include rules that match on at least one member of the group.", + Default: false, + }, + "expand_group_with_exclusion_members": { + Type: schema.TypeBool, + Optional: true, + Description: "When true, if the search expression contains a UID or a name of a group-with-exclusion object, results will include rules that match at least one member of the \"include\" part and is not a member of the \"except\" part.", + Default: false, + }, + "match_on_any": { + Type: schema.TypeBool, + Optional: true, + Description: "Whether to match on 'Any' object.", + Default: true, + }, + "match_on_group_with_exclusion": { + Type: schema.TypeBool, + Optional: true, + Description: "Whether to match on a group-with-exclusion.", + Default: true, + }, + "match_on_negate": { + Type: schema.TypeBool, + Optional: true, + Description: "Whether to match on a negated cell.", + Default: true, + }, + }, + }, + }, + "limit": { + Type: schema.TypeInt, + Optional: true, + Description: "The maximal number of returned results.", + Default: 50, + }, + "offset": { + Type: schema.TypeInt, + Optional: true, + Description: "Number of the results to initially skip.", + Default: 0, + }, + "order": { + Type: schema.TypeList, + Optional: true, + Description: "Sorts the results by search criteria. Automatically sorts the results by Name, in the ascending order.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "asc": { + Type: schema.TypeString, + Optional: true, + Description: "Sorts results by the given field in ascending order.", + }, + "desc": { + Type: schema.TypeString, + Optional: true, + Description: "Sorts results by the given field in descending order.", + }, + }, + }, + }, + "package": { + Type: schema.TypeString, + Optional: true, + Description: "Name of the package.", + }, + "dereference_group_members": { + Type: schema.TypeBool, + Optional: true, + Description: "When true, the source, destination and services & applications parameters are displayed as ranges of IP addresses and port numbers rather than network objects.\nObjects that are not represented using IP addresses or port numbers are presented as objects.\nIn addition, the response of each rule does not contain the parameters: source, source-negate, destination, destination-negate, service and service-negate, but instead it contains the parameters: source-ranges, destination-ranges and service-ranges.\n\nNote: Requesting to show rules as ranges is limited up to 20 rules per request, otherwise an error is returned. If you wish to request more rules, use the offset and limit parameters to limit your request.", + Default: false, + }, + "show_membership": { + Type: schema.TypeBool, + Optional: true, + Description: "N/A", + Default: false, + }, + "rulebase": { + Type: schema.TypeList, + Computed: true, + Description: "The show rulebase api reply", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "from": { + Type: schema.TypeInt, + Computed: true, + Description: "From which element number the query was done.", + }, + "to": { + Type: schema.TypeInt, + Computed: true, + Description: "To which element number the query was done.", + }, + "total": { + Type: schema.TypeInt, + Computed: true, + Description: "Total number of elements returned by the query.", + }, + "objects_dictionary": { + Type: schema.TypeList, + Computed: true, + Description: "Level of details in the output corresponds to the number of details for search. This table shows the level of details in the Standard level.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Computed: true, + Description: "Object name. Must be unique in the domain", + }, + "uid": { + Type: schema.TypeString, + Computed: true, + Description: "Object unique identifier.", + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "Object type.", + }, + }, + }, + }, + "rulebase": { + Type: schema.TypeList, + MaxItems: 1, + Computed: true, + Description: "N/A", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "uid": { + Type: schema.TypeString, + Computed: true, + Description: "Rules uid.", + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: "Rules name.", + }, + "from": { + Type: schema.TypeInt, + Computed: true, + Description: "From which element number the query was done.", + }, + "to": { + Type: schema.TypeInt, + Computed: true, + Description: "To which element number the query was done.", + }, + "destination": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "destination_negate": { + Type: schema.TypeBool, + Computed: true, + Description: "True if negate is set for destination.", + }, + "install_on": { + Type: schema.TypeList, + Computed: true, + Description: "Which Gateways identified by the name or UID to install the policy on.", + Elem: schema.TypeString, + }, + "enabled": { + Type: schema.TypeBool, + Computed: true, + Description: "Enable/Disable the rule.", + }, + "service": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "service_negate": { + Type: schema.TypeBool, + Computed: true, + Description: "True if negate is set for service.", + }, + "source": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "source_negate": { + Type: schema.TypeBool, + Computed: true, + Description: "True if negate is set for source.", + }, + "site_category": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "site_category_negate": { + Type: schema.TypeBool, + Computed: true, + Description: "True if negate is set for source.", + }, + "layer": { + Type: schema.TypeString, + Computed: true, + Description: "Comments string.", + }, + "certificate": { + Type: schema.TypeString, + Computed: true, + Description: "\"Accept\", \"Drop\", \"Ask\", \"Inform\", \"Reject\", \"User Auth\", \"Client Auth\", \"Apply Layer\".", + }, + "track": { + Type: schema.TypeString, + Computed: true, + Description: "\"Accept\", \"Drop\", \"Ask\", \"Inform\", \"Reject\", \"User Auth\", \"Client Auth\", \"Apply Layer\".", + }, + "blade": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "comments": { + Type: schema.TypeString, + Computed: true, + Description: "Comments string.", + }, + "action": { + Type: schema.TypeString, + Computed: true, + Description: "\"Accept\", \"Drop\", \"Ask\", \"Inform\", \"Reject\", \"User Auth\", \"Client Auth\", \"Apply Layer\".", + }, + "rule_number": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of the rule.", + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "Rules type.", + }, + "rulebase": { + Type: schema.TypeList, + Computed: true, + Description: "N/A", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "uid": { + Type: schema.TypeString, + Computed: true, + Description: "Rules uid.", + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: "Rules name.", + }, + "destination": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "destination_negate": { + Type: schema.TypeBool, + Computed: true, + Description: "True if negate is set for destination.", + }, + "install_on": { + Type: schema.TypeList, + Computed: true, + Description: "Which Gateways identified by the name or UID to install the policy on.", + Elem: schema.TypeString, + }, + "enabled": { + Type: schema.TypeBool, + Computed: true, + Description: "Enable/Disable the rule.", + }, + "service": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "service_negate": { + Type: schema.TypeBool, + Computed: true, + Description: "True if negate is set for service.", + }, + "source": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "source_negate": { + Type: schema.TypeBool, + Computed: true, + Description: "True if negate is set for source.", + }, + "site_category": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "site_category_negate": { + Type: schema.TypeBool, + Computed: true, + Description: "True if negate is set for source.", + }, + "layer": { + Type: schema.TypeString, + Computed: true, + Description: "Comments string.", + }, + "certificate": { + Type: schema.TypeString, + Computed: true, + Description: "\"Accept\", \"Drop\", \"Ask\", \"Inform\", \"Reject\", \"User Auth\", \"Client Auth\", \"Apply Layer\".", + }, + "track": { + Type: schema.TypeString, + Computed: true, + Description: "\"Accept\", \"Drop\", \"Ask\", \"Inform\", \"Reject\", \"User Auth\", \"Client Auth\", \"Apply Layer\".", + }, + "blade": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "comments": { + Type: schema.TypeString, + Computed: true, + Description: "Comments string.", + }, + "action": { + Type: schema.TypeString, + Computed: true, + Description: "\"Accept\", \"Drop\", \"Ask\", \"Inform\", \"Reject\", \"User Auth\", \"Client Auth\", \"Apply Layer\".", + }, + "rule_number": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of the rule.", + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "Rules type.", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func dataSourceManagementHttpsRuleBaseRead(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + + payload := map[string]interface{}{} + payload["name"] = d.Get("name").(string) + + if v, ok := d.GetOk("uid"); ok { + payload["uid"] = v.(string) + } + + if v, ok := d.GetOk("filter"); ok { + payload["filter"] = v.(string) + } + if v, ok := d.GetOk("filter_settings"); ok { + filters, ok := v.(map[string]interface{}) + if ok { + + filtersMapToReturn := make(map[string]interface{}) + packetSearchMap := make(map[string]interface{}) + + if val, ok := filters["search_mode"]; ok { + filtersMapToReturn["search-mode"] = val + } else { + filtersMapToReturn["search-mode"] = "general" + } + + if val, ok := filters["expand_group_members"]; ok { + packetSearchMap["expand-group-members"] = val + } else { + packetSearchMap["expand-group-members"] = false + } + + if val, ok := filters["expand_group_with_exclusion_members"]; ok { + packetSearchMap["expand-group-with-exclusion-members"] = val + } else { + packetSearchMap["expand-group-with-exclusion-members"] = false + } + + if val, ok := filters["match_on_any"]; ok { + packetSearchMap["match-on-any"] = val + } else { + packetSearchMap["match-on-any"] = true + } + + if val, ok := filters["match_on_group_with_exclusion"]; ok { + packetSearchMap["match-on-group-with-exclusion"] = val + } else { + packetSearchMap["match-on-group-with-exclusion"] = true + } + + if val, ok := filters["match_on_negate"]; ok { + packetSearchMap["match-on-negate"] = val + } else { + packetSearchMap["match-on-negate"] = true + } + + filtersMapToReturn["packet-search-settings"] = packetSearchMap + payload["filter-settings"] = filtersMapToReturn + } + } + if v, ok := d.GetOk("limit"); ok { + payload["limit"] = v.(int) + } + if v, ok := d.GetOk("offset"); ok { + payload["offset"] = v.(int) + } + if v, ok := d.GetOk("order"); ok { + + ordersList, ok := v.([]interface{}) + var ordersDictToReturn []map[string]interface{} + + if ok { + for i := range ordersList { + + objectsMap := ordersList[i].(map[string]interface{}) + + tempOrder := make(map[string]interface{}) + + if v, _ := objectsMap["asc"]; v != nil && v != "" { + tempOrder["ASC"] = v + } + + if v, _ := objectsMap["desc"]; v != nil && v != "" { + tempOrder["DESC"] = v + } + + ordersDictToReturn = append(ordersDictToReturn, tempOrder) + } + payload["order"] = ordersDictToReturn + } + } + if v, ok := d.GetOk("package"); ok { + payload["package"] = v.(string) + } + if v, ok := d.GetOk("show_as_ranges"); ok { + payload["show-as-ranges"] = v.(bool) + } + if v, ok := d.GetOkExists("show_hits"); ok { + payload["show-hits"] = v.(bool) + } + + if v, ok := d.GetOk("hits_settings"); ok { + newPayload := make(map[string]interface{}) + tempPayload := v.(map[string]interface{}) + + if val, ok := tempPayload["from_date"]; ok { + newPayload["from-date"] = val + } + if val, ok := tempPayload["target"]; ok { + newPayload["target"] = val + } + if val, ok := tempPayload["to_date"]; ok { + newPayload["to-date"] = val + } + payload["hits-settings"] = newPayload + } + + if v, ok := d.GetOk("dereference_group_members"); ok { + payload["dereference-group-members"] = v.(bool) + } + + if v, ok := d.GetOk("show_membership"); ok { + payload["show-membership"] = v.(bool) + } + showRuleBaseRes, err := client.ApiCall("show-https-rulebase", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showRuleBaseRes.Success { + return fmt.Errorf(showRuleBaseRes.ErrorMsg) + } + ruleBaseJson := showRuleBaseRes.GetData() + + log.Println("Read ruleBaseJson - Show JSON = ", ruleBaseJson) + var outputRuleBase []interface{} + ruleBaseToReturn := make(map[string]interface{}) + if v := ruleBaseJson["uid"]; v != nil { + _ = d.Set("uid", v) + d.SetId(v.(string)) + } + + if v := ruleBaseJson["name"]; v != nil { + _ = d.Set("name", v) + } + + if v := ruleBaseJson["from"]; v != nil { + ruleBaseToReturn["from"] = int(math.Round(v.(float64))) + } else { + ruleBaseToReturn["from"] = 0 + } + if ruleBaseJson["objects-dictionary"] != nil { + + objectsList, ok := ruleBaseJson["objects-dictionary"].([]interface{}) + var objectDictToReturn []map[string]interface{} + + if ok { + for i := range objectsList { + + objectsMap := objectsList[i].(map[string]interface{}) + + tempObject := make(map[string]interface{}) + + if v, _ := objectsMap["name"]; v != nil { + tempObject["name"] = v + } + + if v, _ := objectsMap["uid"]; v != nil { + tempObject["uid"] = v + } + + if v, _ := objectsMap["type"]; v != nil { + tempObject["type"] = v + } + + objectDictToReturn = append(objectDictToReturn, tempObject) + } + ruleBaseToReturn["objects_dictionary"] = objectDictToReturn + } + } else { + ruleBaseToReturn["objects_dictionary"] = []map[string]interface{}{} + } + + if ruleBaseJson["rulebase"] != nil { + ruleBaseDictToReturn := readHttpsRuleBaseField(ruleBaseJson) + ruleBaseToReturn["rulebase"] = ruleBaseDictToReturn + } else { + ruleBaseToReturn["rulebase"] = []map[string]interface{}{} + } + + if v := ruleBaseJson["to"]; v != nil { + ruleBaseToReturn["to"] = int(math.Round(v.(float64))) + } else { + ruleBaseToReturn["to"] = 0 + } + if v := ruleBaseJson["total"]; v != nil { + ruleBaseToReturn["total"] = int(math.Round(v.(float64))) + } else { + ruleBaseToReturn["total"] = 0 + } + outputRuleBase = append(outputRuleBase, ruleBaseToReturn) + _ = d.Set("rulebase", outputRuleBase) + return nil +} + +func readHttpsRuleBaseField(RuleBase map[string]interface{}) []map[string]interface{} { + ruleBaseList, ok := RuleBase["rulebase"].([]interface{}) + var ruleBaseDictToReturn []map[string]interface{} + + if ok { + for i := range ruleBaseList { + + ruleBaseMap := ruleBaseList[i].(map[string]interface{}) + + tempRulebase := make(map[string]interface{}) + if v, _ := ruleBaseMap["uid"]; v != nil { + tempRulebase["uid"] = v + } + + if v, _ := ruleBaseMap["name"]; v != nil { + tempRulebase["name"] = v + } + + if v, _ := ruleBaseMap["destination"]; v != nil { + tempRulebase["destination"] = v + } + + if v, _ := ruleBaseMap["destination-negate"]; v != nil { + tempRulebase["destination_negate"] = v.(bool) + } + + if v, _ := ruleBaseMap["install-on"]; v != nil { + tempRulebase["install_on"] = v + } + + if v, _ := ruleBaseMap["enabled"]; v != nil { + tempRulebase["enabled"] = v.(bool) + } + + if v, _ := ruleBaseMap["source"]; v != nil { + tempRulebase["source"] = v + } + + if v, _ := ruleBaseMap["source-negate"]; v != nil { + tempRulebase["source_negate"] = v.(bool) + } + + if v, _ := ruleBaseMap["service"]; v != nil { + tempRulebase["service"] = v + } + + if v, _ := ruleBaseMap["service-negate"]; v != nil { + tempRulebase["service_negate"] = v.(bool) + } + + if v, _ := ruleBaseMap["type"]; v != nil { + tempRulebase["type"] = v + } + if v, _ := ruleBaseMap["comments"]; v != nil && v != "" { + tempRulebase["comments"] = v + } + + if v, _ := ruleBaseMap["action"]; v != nil { + tempRulebase["action"] = v + } + + if v, _ := ruleBaseMap["site-category"]; v != nil { + tempRulebase["site_category"] = v + } + + if v, _ := ruleBaseMap["site-category-negate"]; v != nil { + tempRulebase["site_category_negate"] = v.(bool) + } + + if v := ruleBaseMap["from"]; v != nil && v != 0 { + tempRulebase["from"] = int(math.Round(v.(float64))) + } + + if v, _ := ruleBaseMap["to"]; v != nil { + tempRulebase["to"] = int(math.Round(v.(float64))) + } + + if v, _ := ruleBaseMap["track"]; v != nil { + tempRulebase["track"] = v + } + + if v := ruleBaseMap["rule-number"]; v != nil { + tempRulebase["rule_number"] = v + } + + if v, _ := ruleBaseMap["type"]; v != nil { + tempRulebase["type"] = v + } + + if v, _ := ruleBaseMap["blade"]; v != nil { + tempRulebase["blade"] = v + } + + if v, _ := ruleBaseMap["certificate"]; v != nil { + tempRulebase["certificate"] = v + } + + if v, _ := ruleBaseMap["layer"]; v != nil { + tempRulebase["layer"] = v + } + + if v, _ := ruleBaseMap["rulebase"]; v != nil { + tempRulebase["rulebase"] = readHttpsRuleBaseField(ruleBaseMap) + } + + ruleBaseDictToReturn = append(ruleBaseDictToReturn, tempRulebase) + } + } + return ruleBaseDictToReturn +} diff --git a/checkpoint/data_source_checkpoint_management_https_rulebase_test.go b/checkpoint/data_source_checkpoint_management_https_rulebase_test.go new file mode 100644 index 00000000..c1451638 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_https_rulebase_test.go @@ -0,0 +1,87 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + _ "github.com/hashicorp/terraform-plugin-sdk/terraform" + "os" + _ "strings" + "testing" +) + +func TestAccDataSourceCheckpointManagementHttpsRulebase_basic(t *testing.T) { + var showObjectsQuery map[string]interface{} + dataSourceShowObjects := "data.checkpoint_management_https_rulebase.test" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceManagementHttpsRulebaseConfig("Default Layer", 1), + Check: resource.ComposeTestCheckFunc( + testAccCheckCheckpointHttpsRulebase(dataSourceShowObjects, &showObjectsQuery), + testAccCheckCheckpointHttpsRulebaseAttributes(&showObjectsQuery), + ), + }, + }, + }) +} + +func testAccCheckCheckpointHttpsRulebase(resourceTfName string, res *map[string]interface{}) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[resourceTfName] + if !ok { + return fmt.Errorf("show-https-rulebase data source not found: %s", resourceTfName) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("show-https-rulebase data source ID is not set") + } + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + response, _ := client.ApiCall("show-https-rulebase", map[string]interface{}{"name": "Default Layer", "limit": 1}, client.GetSessionID(), true, client.IsProxyUsed()) + if !response.Success { + return fmt.Errorf(response.ErrorMsg) + } + + *res = response.GetData() + + return nil + } +} + +func testAccCheckCheckpointHttpsRulebaseAttributes(showHttpsRulebaseMap *map[string]interface{}) resource.TestCheckFunc { + return func(s *terraform.State) error { + + showHttpsRulebaseMap := *showHttpsRulebaseMap + if showHttpsRulebaseMap == nil { + return fmt.Errorf("showHttpsRulebaseMap is nil") + } + + rulebase := showHttpsRulebaseMap["rulebase"].([]interface{}) + + if len(rulebase) != 1 { + return fmt.Errorf("show-https-rulebase returned wrong number of rulebase objects. exptected for 1, found %d", len(rulebase)) + } + + return nil + } +} + +func testAccDataSourceManagementHttpsRulebaseConfig(name string, limit int) string { + return fmt.Sprintf(` +data "checkpoint_management_https_rulebase" "test" { + name = "%s" + limit = %d +} +`, name, limit) +} diff --git a/checkpoint/data_source_checkpoint_management_https_section.go b/checkpoint/data_source_checkpoint_management_https_section.go index 60ad5f84..9bd60aaf 100644 --- a/checkpoint/data_source_checkpoint_management_https_section.go +++ b/checkpoint/data_source_checkpoint_management_https_section.go @@ -47,7 +47,7 @@ func dataSourceManagementHttpsSectionRead(d *schema.ResourceData, m interface{}) payload["uid"] = uid } - showHttpsSectionRes, err := client.ApiCall("show-https-section", payload, client.GetSessionID(), true, false) + showHttpsSectionRes, err := client.ApiCall("show-https-section", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_identity_tag.go b/checkpoint/data_source_checkpoint_management_identity_tag.go index 33b2c7f3..ae83eb37 100644 --- a/checkpoint/data_source_checkpoint_management_identity_tag.go +++ b/checkpoint/data_source_checkpoint_management_identity_tag.go @@ -62,7 +62,7 @@ func dataSourceManagementIdentityTagRead(d *schema.ResourceData, m interface{}) payload["uid"] = uid } - showIdentityTagRes, err := client.ApiCall("show-identity-tag", payload, client.GetSessionID(), true, false) + showIdentityTagRes, err := client.ApiCall("show-identity-tag", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_ise_data_center_server.go b/checkpoint/data_source_checkpoint_management_ise_data_center_server.go new file mode 100644 index 00000000..d129c7a4 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_ise_data_center_server.go @@ -0,0 +1,157 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "strconv" + "strings" +) + +func dataSourceManagementIseDataCenterServer() *schema.Resource { + return &schema.Resource{ + Read: dataSourceIseDataCenterServerRead, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Object name. Must be unique in the domain.", + }, + "uid": { + Type: schema.TypeString, + Optional: true, + Description: "Object unique identifier.", + }, + "hostnames": { + Type: schema.TypeList, + Computed: true, + Description: "Address of APIC cluster members.\nExample: http(s)://.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "username": { + Type: schema.TypeString, + Computed: true, + Description: "User ID of the Cisco ISE administrator.\nWhen using commonLoginLogic Domains use the following syntax:\napic:\\.", + }, + "certificate_fingerprint": { + Type: schema.TypeString, + Computed: true, + Description: "Specify the SHA-1 or SHA-256 fingerprint of the Data Center Server's certificate.", + }, + "unsafe_auto_accept": { + Type: schema.TypeBool, + Computed: true, + Description: "When set to false, the current Data Center Server's certificate should be trusted, either by providing the certificate-fingerprint argument or by relying on a previously trusted certificate of this hostname.\n\nWhen set to true, trust the current Data Center Server's certificate as-is.", + }, + "tags": { + Type: schema.TypeSet, + Computed: true, + Description: "Collection of tag identifiers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "color": { + Type: schema.TypeString, + Computed: true, + Description: "Color of the object. Should be one of existing colors.", + }, + "comments": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func dataSourceIseDataCenterServerRead(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + var name string + var uid string + + if v, ok := d.GetOk("name"); ok { + name = v.(string) + } + if v, ok := d.GetOk("uid"); ok { + uid = v.(string) + } + payload := make(map[string]interface{}) + + if name != "" { + payload["name"] = name + } else if uid != "" { + payload["uid"] = uid + } + showIseDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showIseDataCenterServerRes.Success { + return fmt.Errorf(showIseDataCenterServerRes.ErrorMsg) + } + iseDataCenterServer := showIseDataCenterServerRes.GetData() + + if v := iseDataCenterServer["uid"]; v != nil { + _ = d.Set("uid", v) + d.SetId(v.(string)) + } + + if v := iseDataCenterServer["name"]; v != nil { + _ = d.Set("name", v) + } + + if iseDataCenterServer["properties"] != nil { + propsJson, ok := iseDataCenterServer["properties"].([]interface{}) + if ok { + for _, prop := range propsJson { + propMap := prop.(map[string]interface{}) + propName := strings.ReplaceAll(propMap["name"].(string), "-", "_") + propValue := propMap["value"] + if propName == "unsafe_auto_accept" { + propValue, _ = strconv.ParseBool(propValue.(string)) + } + if propName == "hostnames" { + propValue = strings.Split(propValue.(string), ";") + } + _ = d.Set(propName, propValue) + } + } + } + + if iseDataCenterServer["tags"] != nil { + tagsJson, ok := iseDataCenterServer["tags"].([]interface{}) + if ok { + tagsIds := make([]string, 0) + if len(tagsJson) > 0 { + for _, tags := range tagsJson { + tags := tags.(map[string]interface{}) + tagsIds = append(tagsIds, tags["name"].(string)) + } + } + _ = d.Set("tags", tagsIds) + } + } else { + _ = d.Set("tags", nil) + } + + if v := iseDataCenterServer["color"]; v != nil { + _ = d.Set("color", v) + } + + if v := iseDataCenterServer["comments"]; v != nil { + _ = d.Set("comments", v) + } + + if v := iseDataCenterServer["ignore-warnings"]; v != nil { + _ = d.Set("ignore_warnings", v) + } + + if v := iseDataCenterServer["ignore-errors"]; v != nil { + _ = d.Set("ignore_errors", v) + } + + return nil + +} diff --git a/checkpoint/data_source_checkpoint_management_ise_data_center_server_test.go b/checkpoint/data_source_checkpoint_management_ise_data_center_server_test.go new file mode 100644 index 00000000..8c4924c3 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_ise_data_center_server_test.go @@ -0,0 +1,54 @@ +package checkpoint + +import ( + "fmt" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "os" + "testing" +) + +func TestAccDataSourceCheckpointManagementIseDataCenterServer_basic(t *testing.T) { + + objName := "tfTestManagementDataIseDataCenterServer_" + acctest.RandString(6) + resourceName := "checkpoint_management_ise_data_center_server.ise_data_center_server" + dataSourceName := "data.checkpoint_management_ise_data_center_server.ise_data_center_server" + username := "USERNAME" + password := "PASSWORD" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceManagementIseDataCenterServerConfig(objName, username, password), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), + ), + }, + }, + }) + +} + +func testAccDataSourceManagementIseDataCenterServerConfig(name string, username string, password string) string { + return fmt.Sprintf(` +resource "checkpoint_management_ise_data_center_server" "ise_data_center_server" { + name = "%s" + username = "%s" + password = "%s" + hostnames = ["host1", "host2"] + unsafe_auto_accept = true + ignore_warnings = true +} + +data "checkpoint_management_ise_data_center_server" "ise_data_center_server" { + name = "${checkpoint_management_ise_data_center_server.ise_data_center_server.name}" +} +`, name, username, password) +} diff --git a/checkpoint/data_source_checkpoint_management_kubernetes_data_center_server.go b/checkpoint/data_source_checkpoint_management_kubernetes_data_center_server.go new file mode 100644 index 00000000..38432b51 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_kubernetes_data_center_server.go @@ -0,0 +1,153 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "strconv" + "strings" +) + +func dataSourceManagementKubernetesDataCenterServer() *schema.Resource { + return &schema.Resource{ + Read: dataSourceKubernetesDataCenterServerRead, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Object name. Must be unique in the domain.", + }, + "uid": { + Type: schema.TypeString, + Optional: true, + Description: "Object unique identifier.", + }, + "hostname": { + Type: schema.TypeString, + Computed: true, + Description: "IP address or hostname of the Kubernetes server.", + }, + "token_file": { + Type: schema.TypeString, + Computed: true, + Description: "Kubernetes access token encoded in base64.", + }, + "ca_certificate": { + Type: schema.TypeString, + Computed: true, + Description: "The Kubernetes public certificate key encoded in base64.", + }, + "unsafe_auto_accept": { + Type: schema.TypeBool, + Computed: true, + Description: "When set to false, the current Data Center Server's certificate should be trusted, either by providing the certificate-fingerprint argument or by relying on a previously trusted certificate of this hostname.\n\nWhen set to true, trust the current Data Center Server's certificate as-is.", + }, + "tags": { + Type: schema.TypeSet, + Computed: true, + Description: "Collection of tag identifiers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "color": { + Type: schema.TypeString, + Computed: true, + Description: "Color of the object. Should be one of existing colors.", + }, + "comments": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func dataSourceKubernetesDataCenterServerRead(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + var name string + var uid string + + if v, ok := d.GetOk("name"); ok { + name = v.(string) + } + if v, ok := d.GetOk("uid"); ok { + uid = v.(string) + } + payload := make(map[string]interface{}) + + if name != "" { + payload["name"] = name + } else if uid != "" { + payload["uid"] = uid + } + showKubernetesDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showKubernetesDataCenterServerRes.Success { + return fmt.Errorf(showKubernetesDataCenterServerRes.ErrorMsg) + } + kubernetesDataCenterServer := showKubernetesDataCenterServerRes.GetData() + + if v := kubernetesDataCenterServer["uid"]; v != nil { + _ = d.Set("uid", v) + d.SetId(v.(string)) + } + + if v := kubernetesDataCenterServer["name"]; v != nil { + _ = d.Set("name", v) + } + + if kubernetesDataCenterServer["properties"] != nil { + propsJson, ok := kubernetesDataCenterServer["properties"].([]interface{}) + if ok { + for _, prop := range propsJson { + propMap := prop.(map[string]interface{}) + if propMap["name"] != nil { + propName := strings.ReplaceAll(propMap["name"].(string), "-", "_") + propValue := propMap["value"] + if propName == "unsafe_auto_accept" { + propValue, _ = strconv.ParseBool(propValue.(string)) + } + _ = d.Set(propName, propValue) + } + } + } + } + + if kubernetesDataCenterServer["tags"] != nil { + tagsJson, ok := kubernetesDataCenterServer["tags"].([]interface{}) + if ok { + tagsIds := make([]string, 0) + if len(tagsJson) > 0 { + for _, tags := range tagsJson { + tags := tags.(map[string]interface{}) + tagsIds = append(tagsIds, tags["name"].(string)) + } + } + _ = d.Set("tags", tagsIds) + } + } else { + _ = d.Set("tags", nil) + } + + if v := kubernetesDataCenterServer["color"]; v != nil { + _ = d.Set("color", v) + } + + if v := kubernetesDataCenterServer["comments"]; v != nil { + _ = d.Set("comments", v) + } + + if v := kubernetesDataCenterServer["ignore-warnings"]; v != nil { + _ = d.Set("ignore_warnings", v) + } + + if v := kubernetesDataCenterServer["ignore-errors"]; v != nil { + _ = d.Set("ignore_errors", v) + } + + return nil + +} diff --git a/checkpoint/data_source_checkpoint_management_kubernetes_data_center_server_test.go b/checkpoint/data_source_checkpoint_management_kubernetes_data_center_server_test.go new file mode 100644 index 00000000..8cecdfa8 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_kubernetes_data_center_server_test.go @@ -0,0 +1,53 @@ +package checkpoint + +import ( + "fmt" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "os" + "testing" +) + +func TestAccDataSourceCheckpointManagementKubernetesDataCenterServer_basic(t *testing.T) { + + objName := "tfTestManagementDataKubernetesDataCenterServer_" + acctest.RandString(6) + resourceName := "checkpoint_management_kubernetes_data_center_server.kubernetes_data_center_server" + dataSourceName := "data.checkpoint_management_kubernetes_data_center_server.kubernetes_data_center_server" + hostname := "MY_HOSTNAME" + token_file := "MY_TOKEN" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceManagementKubernetesDataCenterServerConfig(objName, hostname, token_file), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), + ), + }, + }, + }) + +} + +func testAccDataSourceManagementKubernetesDataCenterServerConfig(name string, hostname string, token_file string) string { + return fmt.Sprintf(` +resource "checkpoint_management_kubernetes_data_center_server" "kubernetes_data_center_server" { + name = "%s" + hostname = "%s" + token_file = "%s" + unsafe_auto_accept = true + ignore_warnings = true +} + +data "checkpoint_management_kubernetes_data_center_server" "kubernetes_data_center_server" { + name = "${checkpoint_management_kubernetes_data_center_server.kubernetes_data_center_server.name}" +} +`, name, hostname, token_file) +} diff --git a/checkpoint/data_source_checkpoint_management_mds.go b/checkpoint/data_source_checkpoint_management_mds.go index 16b4e4f5..c0304770 100644 --- a/checkpoint/data_source_checkpoint_management_mds.go +++ b/checkpoint/data_source_checkpoint_management_mds.go @@ -123,7 +123,7 @@ func dataSourceManagementMdsRead(d *schema.ResourceData, m interface{}) error { payload["uid"] = uid } - showMdsRes, err := client.ApiCall("show-mds", payload, client.GetSessionID(), true, false) + showMdsRes, err := client.ApiCall("show-mds", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_multicast_address_range.go b/checkpoint/data_source_checkpoint_management_multicast_address_range.go index e2d38b43..6e1d0a86 100644 --- a/checkpoint/data_source_checkpoint_management_multicast_address_range.go +++ b/checkpoint/data_source_checkpoint_management_multicast_address_range.go @@ -96,7 +96,7 @@ func dataSourceManagementMulticastAddressRangeRead(d *schema.ResourceData, m int payload["uid"] = uid } - showMulticastAddressRangeRes, err := client.ApiCall("show-multicast-address-range", payload, client.GetSessionID(), true, false) + showMulticastAddressRangeRes, err := client.ApiCall("show-multicast-address-range", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_nat_rule.go b/checkpoint/data_source_checkpoint_management_nat_rule.go index 804bb38d..fd97876d 100644 --- a/checkpoint/data_source_checkpoint_management_nat_rule.go +++ b/checkpoint/data_source_checkpoint_management_nat_rule.go @@ -105,7 +105,7 @@ func dataSourceManagementNatRuleRead(d *schema.ResourceData, m interface{}) erro payload["uid"] = uid } - showNatRuleRes, err := client.ApiCall("show-nat-rule", payload, client.GetSessionID(), true, false) + showNatRuleRes, err := client.ApiCall("show-nat-rule", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_nat_rulebase.go b/checkpoint/data_source_checkpoint_management_nat_rulebase.go index 4fc67078..a8b2d0db 100644 --- a/checkpoint/data_source_checkpoint_management_nat_rulebase.go +++ b/checkpoint/data_source_checkpoint_management_nat_rulebase.go @@ -3,40 +3,30 @@ package checkpoint import ( "fmt" checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "log" - "strconv" + "math" ) -func dataSourceManagementNatRulebase() *schema.Resource { +func dataSourceManagementNatRuleBase() *schema.Resource { return &schema.Resource{ - Read: dataSourceManagementNatRulebaseRead, + Read: dataSourceManagementNatRuleBaseRead, + Schema: map[string]*schema.Schema{ "package": { Type: schema.TypeString, Required: true, Description: "Name of the package.", }, - "filter": { + "uid": { Type: schema.TypeString, Optional: true, - Description: "Search expression to filter objects by. The provided text should be exactly the same as it would be given in Smart Console. The logical operators in the expression ('AND', 'OR') should be provided in capital letters. By default, the search involves both a textual search and a IP search. To use IP search only, set the \"ip-only\" parameter to true.", - }, - "limit": { - Type: schema.TypeInt, - Optional: true, - Description: "The maximal number of returned results.", - }, - "offset": { - Type: schema.TypeInt, - Optional: true, - Description: "Number of the results to initially skip.", + Description: "Object unique identifier.", }, - "use_object_dictionary": { - Type: schema.TypeBool, + "filter": { + Type: schema.TypeString, Optional: true, - Description: "Use object dictionary.", + Description: "Search expression to filter the rulebase. The provided text should be exactly the same as it would be given in Smart Console. The logical operators in the expression ('AND', 'OR') should be provided in capital letters. If an operator is not used, the default OR operator applies.", }, "filter_settings": { Type: schema.TypeMap, @@ -49,43 +39,51 @@ func dataSourceManagementNatRulebase() *schema.Resource { Optional: true, Description: "When set to 'general', both the Full Text Search and Packet Search are enabled. In this mode, Packet Search will not match on 'Any' object, a negated cell or a group-with-exclusion. When the search-mode is set to 'packet', by default, the match on 'Any' object, a negated cell or a group-with-exclusion are enabled. packet-search-settings may be provided to change the default behavior.", }, - "packet_search_settings": { - Type: schema.TypeMap, + "expand_group_members": { + Type: schema.TypeBool, Optional: true, - Description: "When 'search_mode' is set to 'packet', this object allows to set the packet search preferences.", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "expand_group_members": { - Type: schema.TypeBool, - Optional: true, - Description: "When true, if the search expression contains a UID or a name of a group object, results will include rules that match on at least one member of the group.", - }, - "expand_group_with_exclusion_members": { - Type: schema.TypeBool, - Optional: true, - Description: "Whether to match on 'Any' object.", - }, - "match_on_any": { - Type: schema.TypeBool, - Optional: true, - Description: "When true, if the search expression contains a UID or a name of a group object, results will include rules that match on at least one member of the group.", - }, - "match_on_group_with_exclusion": { - Type: schema.TypeBool, - Optional: true, - Description: "Whether to match on a group-with-exclusion.", - }, - "match_on_negate": { - Type: schema.TypeBool, - Optional: true, - Description: "Whether to match on a negated cell.", - }, - }, - }, + Description: "When true, if the search expression contains a UID or a name of a group object, results will include rules that match on at least one member of the group.", + Default: false, + }, + "expand_group_with_exclusion_members": { + Type: schema.TypeBool, + Optional: true, + Description: "When true, if the search expression contains a UID or a name of a group-with-exclusion object, results will include rules that match at least one member of the \"include\" part and is not a member of the \"except\" part.", + Default: false, + }, + "match_on_any": { + Type: schema.TypeBool, + Optional: true, + Description: "Whether to match on 'Any' object.", + Default: true, + }, + "match_on_group_with_exclusion": { + Type: schema.TypeBool, + Optional: true, + Description: "Whether to match on a group-with-exclusion.", + Default: true, + }, + "match_on_negate": { + Type: schema.TypeBool, + Optional: true, + Description: "Whether to match on a negated cell.", + Default: true, }, }, }, }, + "limit": { + Type: schema.TypeInt, + Optional: true, + Description: "The maximal number of returned results.", + Default: 50, + }, + "offset": { + Type: schema.TypeInt, + Optional: true, + Description: "Number of the results to initially skip.", + Default: 0, + }, "order": { Type: schema.TypeList, Optional: true, @@ -105,104 +103,230 @@ func dataSourceManagementNatRulebase() *schema.Resource { }, }, }, - "name": { - Type: schema.TypeString, - Computed: true, - Description: "Object name. Must be unique in the domain.", - }, - "uid": { - Type: schema.TypeString, - Computed: true, - Description: "Object unique identifier.", - }, - "from": { - Type: schema.TypeInt, - Computed: true, - Description: "From which element number the query was done.", - }, - "to": { - Type: schema.TypeInt, - Computed: true, - Description: "To which element number the query was done.", + "dereference_group_members": { + Type: schema.TypeBool, + Optional: true, + Description: "When true, the source, destination and services & applications parameters are displayed as ranges of IP addresses and port numbers rather than network objects.\nObjects that are not represented using IP addresses or port numbers are presented as objects.\nIn addition, the response of each rule does not contain the parameters: source, source-negate, destination, destination-negate, service and service-negate, but instead it contains the parameters: source-ranges, destination-ranges and service-ranges.\n\nNote: Requesting to show rules as ranges is limited up to 20 rules per request, otherwise an error is returned. If you wish to request more rules, use the offset and limit parameters to limit your request.", + Default: false, }, - "total": { - Type: schema.TypeInt, - Computed: true, - Description: "Total number of elements returned by the query.", + "show_membership": { + Type: schema.TypeBool, + Optional: true, + Description: "N/A", + Default: false, }, "rulebase": { Type: schema.TypeList, Computed: true, - Description: "NAT rulebase.", + Description: "The show rulebase api reply", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "uid": { - Type: schema.TypeString, + "from": { + Type: schema.TypeInt, Computed: true, - Description: "Object unique identifier.", + Description: "From which element number the query was done.", }, - "name": { - Type: schema.TypeString, + "to": { + Type: schema.TypeInt, Computed: true, - Description: "Object name. Must be unique in the domain.", + Description: "To which element number the query was done.", }, - "type": { - Type: schema.TypeString, + "total": { + Type: schema.TypeInt, Computed: true, - Description: "Object type.", + Description: "Total number of elements returned by the query.", }, - "rulebase": { - Type: schema.TypeSet, + "objects_dictionary": { + Type: schema.TypeList, Computed: true, - Description: "Collection of object unique identifiers.", - Elem: &schema.Schema{ - Type: schema.TypeString, + Description: "Level of details in the output corresponds to the number of details for search. This table shows the level of details in the Standard level.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Computed: true, + Description: "Object name. Must be unique in the domain", + }, + "uid": { + Type: schema.TypeString, + Computed: true, + Description: "Object unique identifier.", + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "Object type.", + }, + }, }, }, - }, - }, - }, - "objects_dictionary": { - Type: schema.TypeList, - Computed: true, - Description: "Objects list", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Computed: true, - Description: "Object name.", - }, - "uid": { - Type: schema.TypeString, - Computed: true, - Description: "Object unique identifier.", - }, - "type": { - Type: schema.TypeString, - Computed: true, - Description: "Object type.", - }, - "domain": { - Type: schema.TypeMap, + "rulebase": { + Type: schema.TypeList, + MaxItems: 1, Computed: true, - Description: "Information about the domain that holds the Object.", + Description: "N/A", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ + "uid": { + Type: schema.TypeString, + Computed: true, + Description: "Rules uid.", + }, "name": { Type: schema.TypeString, Computed: true, - Description: "Object name.", + Description: "Rules name.", }, - "uid": { + "original_destination": { Type: schema.TypeString, Computed: true, - Description: "Object unique identifier.", + Description: "Collection of Network objects identified by the name or UID.", + }, + "translated_destination": { + Type: schema.TypeString, + Computed: true, + Description: "True if negate is set for destination.", + }, + "install_on": { + Type: schema.TypeList, + Computed: true, + Description: "Which Gateways identified by the name or UID to install the policy on.", + Elem: schema.TypeString, + }, + "enabled": { + Type: schema.TypeBool, + Computed: true, + Description: "Enable/Disable the rule.", + }, + "original_service": { + Type: schema.TypeString, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + }, + "translated_service": { + Type: schema.TypeString, + Computed: true, + Description: "True if negate is set for service.", + }, + "auto_generated": { + Type: schema.TypeBool, + Computed: true, + Description: "service resource.", + }, + "original_source": { + Type: schema.TypeString, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + }, + "translated_source": { + Type: schema.TypeString, + Computed: true, + Description: "True if negate is set for source.", + }, + "method": { + Type: schema.TypeString, + Computed: true, + Description: "Communities or Directional.", }, - "domain_type": { + "comments": { Type: schema.TypeString, Computed: true, - Description: "Domain type.", + Description: "Comments string.", + }, + "rule_number": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of the rule.", + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "Rules type.", + }, + "rulebase": { + Type: schema.TypeList, + Computed: true, + Description: "N/A", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "uid": { + Type: schema.TypeString, + Computed: true, + Description: "Rules uid.", + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: "Rules name.", + }, + "original_destination": { + Type: schema.TypeString, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + }, + "translated_destination": { + Type: schema.TypeString, + Computed: true, + Description: "True if negate is set for destination.", + }, + "install_on": { + Type: schema.TypeList, + Computed: true, + Description: "Which Gateways identified by the name or UID to install the policy on.", + Elem: schema.TypeString, + }, + "enabled": { + Type: schema.TypeBool, + Computed: true, + Description: "Enable/Disable the rule.", + }, + "original_service": { + Type: schema.TypeString, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + }, + "translated_service": { + Type: schema.TypeString, + Computed: true, + Description: "True if negate is set for service.", + }, + "auto_generated": { + Type: schema.TypeBool, + Computed: true, + Description: "service resource.", + }, + "original_source": { + Type: schema.TypeString, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + }, + "translated_source": { + Type: schema.TypeString, + Computed: true, + Description: "True if negate is set for source.", + }, + "method": { + Type: schema.TypeString, + Computed: true, + Description: "Communities or Directional.", + }, + "comments": { + Type: schema.TypeString, + Computed: true, + Description: "Comments string.", + }, + "rule_number": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of the rule.", + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "Rules type.", + }, + }, + }, }, }, }, @@ -214,206 +338,254 @@ func dataSourceManagementNatRulebase() *schema.Resource { } } -func dataSourceManagementNatRulebaseRead(d *schema.ResourceData, m interface{}) error { - +func dataSourceManagementNatRuleBaseRead(d *schema.ResourceData, m interface{}) error { client := m.(*checkpoint.ApiClient) - payload := make(map[string]interface{}) - - if v, ok := d.GetOk("package"); ok { - payload["package"] = v.(string) - } - + payload := map[string]interface{}{} + payload["package"] = d.Get("package").(string) if v, ok := d.GetOk("filter"); ok { payload["filter"] = v.(string) } + if v, ok := d.GetOk("filter_settings"); ok { + filters, ok := v.(map[string]interface{}) + if ok { + + filtersMapToReturn := make(map[string]interface{}) + packetSearchMap := make(map[string]interface{}) + + if val, ok := filters["search_mode"]; ok { + filtersMapToReturn["search-mode"] = val + } else { + filtersMapToReturn["search-mode"] = "general" + } + + if val, ok := filters["expand_group_members"]; ok { + packetSearchMap["expand-group-members"] = val + } else { + packetSearchMap["expand-group-members"] = false + } + + if val, ok := filters["expand_group_with_exclusion_members"]; ok { + packetSearchMap["expand-group-with-exclusion-members"] = val + } else { + packetSearchMap["expand-group-with-exclusion-members"] = false + } + + if val, ok := filters["match_on_any"]; ok { + packetSearchMap["match-on-any"] = val + } else { + packetSearchMap["match-on-any"] = true + } + + if val, ok := filters["match_on_group_with_exclusion"]; ok { + packetSearchMap["match-on-group-with-exclusion"] = val + } else { + packetSearchMap["match-on-group-with-exclusion"] = true + } + + if val, ok := filters["match_on_negate"]; ok { + packetSearchMap["match-on-negate"] = val + } else { + packetSearchMap["match-on-negate"] = true + } + filtersMapToReturn["packet-search-settings"] = packetSearchMap + payload["filter-settings"] = filtersMapToReturn + } + } if v, ok := d.GetOk("limit"); ok { payload["limit"] = v.(int) } - if v, ok := d.GetOk("offset"); ok { payload["offset"] = v.(int) } - if v, ok := d.GetOk("order"); ok { - orderList := v.([]interface{}) + ordersList, ok := v.([]interface{}) + var ordersDictToReturn []map[string]interface{} - if len(orderList) > 0 { - var orderPayload []map[string]interface{} + if ok { + for i := range ordersList { - for i := range orderList { - payload := make(map[string]interface{}) + objectsMap := ordersList[i].(map[string]interface{}) - if v, ok := d.GetOk("order." + strconv.Itoa(i) + ".asc"); ok { - payload["ASC"] = v.(string) + tempOrder := make(map[string]interface{}) + + if v, _ := objectsMap["asc"]; v != nil && v != "" { + tempOrder["ASC"] = v } - if v, ok := d.GetOk("order." + strconv.Itoa(i) + ".desc"); ok { - payload["DESC"] = v.(string) + if v, _ := objectsMap["desc"]; v != nil && v != "" { + tempOrder["DESC"] = v } - orderPayload = append(orderPayload, payload) + ordersDictToReturn = append(ordersDictToReturn, tempOrder) } - - payload["order"] = orderPayload + payload["order"] = ordersDictToReturn } } + if v, ok := d.GetOk("package"); ok { + payload["package"] = v.(string) + } + if v, ok := d.GetOk("dereference_group_members"); ok { + payload["dereference-group-members"] = v.(bool) + } - if v, ok := d.GetOkExists("use_object_dictionary"); ok { - payload["use-object-dictionary"] = v.(int) + if v, ok := d.GetOk("show_membership"); ok { + payload["show-membership"] = v.(bool) } - if _, ok := d.GetOk("filter_settings"); ok { - filterSettings := make(map[string]interface{}) + showRuleBaseRes, err := client.ApiCall("show-nat-rulebase", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showRuleBaseRes.Success { + return fmt.Errorf(showRuleBaseRes.ErrorMsg) + } + ruleBaseJson := showRuleBaseRes.GetData() + + log.Println("Read ruleBaseJson - Show JSON = ", ruleBaseJson) + var outputRuleBase []interface{} + ruleBaseToReturn := make(map[string]interface{}) + if v := ruleBaseJson["uid"]; v != nil { + _ = d.Set("uid", v) + d.SetId(v.(string)) + } - if v, ok := d.GetOk("filter_settings.search_mode"); ok { - filterSettings["search-mode"] = v.(string) - } + if v := ruleBaseJson["from"]; v != nil { + ruleBaseToReturn["from"] = int(math.Round(v.(float64))) + } else { + ruleBaseToReturn["from"] = 0 + } + if ruleBaseJson["objects-dictionary"] != nil { - if _, ok := d.GetOk("filter_settings.packet_search_settings"); ok { - packetSearchSettings := make(map[string]interface{}) + objectsList, ok := ruleBaseJson["objects-dictionary"].([]interface{}) + var objectDictToReturn []map[string]interface{} - if v, ok := d.GetOkExists("filter_settings.packet_search_settings.expand_group_members"); ok { - packetSearchSettings["expand-group-members"] = v.(bool) - } + if ok { + for i := range objectsList { - if v, ok := d.GetOkExists("filter_settings.packet_search_settings.expand_group_with_exclusion_members"); ok { - packetSearchSettings["expand-group-with-exclusion-members"] = v.(bool) - } + objectsMap := objectsList[i].(map[string]interface{}) - if v, ok := d.GetOkExists("filter_settings.packet_search_settings.match_on_any"); ok { - packetSearchSettings["match-on-any"] = v.(bool) - } + tempObject := make(map[string]interface{}) - if v, ok := d.GetOkExists("filter_settings.packet_search_settings.match_on_group_with_exclusion"); ok { - packetSearchSettings["match-on-group-with-exclusion"] = v.(bool) - } + if v, _ := objectsMap["name"]; v != nil { + tempObject["name"] = v + } - if v, ok := d.GetOkExists("filter_settings.packet_search_settings.match_on_negate"); ok { - packetSearchSettings["match-on-negate"] = v.(bool) - } + if v, _ := objectsMap["uid"]; v != nil { + tempObject["uid"] = v + } - filterSettings["packet-search-settings"] = packetSearchSettings + if v, _ := objectsMap["type"]; v != nil { + tempObject["type"] = v + } + + objectDictToReturn = append(objectDictToReturn, tempObject) + } + ruleBaseToReturn["objects_dictionary"] = objectDictToReturn } + } else { + ruleBaseToReturn["objects_dictionary"] = []map[string]interface{}{} + } - payload["filter_settings"] = filterSettings + if ruleBaseJson["rulebase"] != nil { + ruleBaseDictToReturn := readNatRuleBaseField(ruleBaseJson) + ruleBaseToReturn["rulebase"] = ruleBaseDictToReturn + } else { + ruleBaseToReturn["rulebase"] = []map[string]interface{}{} } - showNatRulebaseRes, err := client.ApiCall("show-nat-rulebase", payload, client.GetSessionID(), true, false) - if err != nil { - return fmt.Errorf(err.Error()) + if v := ruleBaseJson["to"]; v != nil { + ruleBaseToReturn["to"] = int(math.Round(v.(float64))) + } else { + ruleBaseToReturn["to"] = 0 } - if !showNatRulebaseRes.Success { - return fmt.Errorf(showNatRulebaseRes.ErrorMsg) + if v := ruleBaseJson["total"]; v != nil { + ruleBaseToReturn["total"] = int(math.Round(v.(float64))) + } else { + ruleBaseToReturn["total"] = 0 } + outputRuleBase = append(outputRuleBase, ruleBaseToReturn) + _ = d.Set("rulebase", outputRuleBase) + return nil +} - natRulebaseData := showNatRulebaseRes.GetData() - - log.Println("show-nat-rulebase JSON = ", natRulebaseData) +func readNatRuleBaseField(RuleBase map[string]interface{}) []map[string]interface{} { + ruleBaseList, ok := RuleBase["rulebase"].([]interface{}) + var ruleBaseDictToReturn []map[string]interface{} - d.SetId("show-nat-rulebase-" + acctest.RandString(10)) + if ok { + for i := range ruleBaseList { - if v := natRulebaseData["from"]; v != nil { - _ = d.Set("from", v) - } + ruleBaseMap := ruleBaseList[i].(map[string]interface{}) - if v := natRulebaseData["to"]; v != nil { - _ = d.Set("to", v) - } + tempRulebase := make(map[string]interface{}) + if v, _ := ruleBaseMap["uid"]; v != nil { + tempRulebase["uid"] = v + } - if v := natRulebaseData["total"]; v != nil { - _ = d.Set("total", v) - } + if v, _ := ruleBaseMap["name"]; v != nil { + tempRulebase["name"] = v + } - if v := natRulebaseData["objects-dictionary"]; v != nil { - objectsList := v.([]interface{}) - if len(objectsList) > 0 { - var objectsListState []map[string]interface{} - for i := range objectsList { - objectMap := objectsList[i].(map[string]interface{}) - objectMapToAdd := make(map[string]interface{}) + if v, _ := ruleBaseMap["original-destination"]; v != nil { + tempRulebase["original_destination"] = v + } - if v := objectMap["name"]; v != nil { - objectMapToAdd["name"] = v - } + if v, _ := ruleBaseMap["translated-destination"]; v != nil { + tempRulebase["translated_destination"] = v + } - if v := objectMap["uid"]; v != nil { - objectMapToAdd["uid"] = v - } + if v, _ := ruleBaseMap["install-on"]; v != nil { + tempRulebase["install_on"] = v + } - if v := objectMap["type"]; v != nil { - objectMapToAdd["type"] = v - } + if v, _ := ruleBaseMap["enabled"]; v != nil { + tempRulebase["enabled"] = v.(bool) + } - if v := objectMap["domain"]; v != nil { - domainMap := v.(map[string]interface{}) - domainMapToAdd := make(map[string]interface{}) + if v, _ := ruleBaseMap["original-source"]; v != nil { + tempRulebase["original_source"] = v + } - if v := domainMap["name"]; v != nil { - domainMapToAdd["name"] = v - } + if v, _ := ruleBaseMap["translated-source"]; v != nil { + tempRulebase["translated_source"] = v + } - if v := domainMap["uid"]; v != nil { - domainMapToAdd["uid"] = v - } + if v, _ := ruleBaseMap["original-service"]; v != nil { + tempRulebase["original_service"] = v + } - if v := domainMap["domain-type"]; v != nil { - domainMapToAdd["domain_type"] = v - } - objectMapToAdd["domain"] = domainMapToAdd - } - objectsListState = append(objectsListState, objectMapToAdd) + if v, _ := ruleBaseMap["translated-service"]; v != nil { + tempRulebase["translated_service"] = v } - _ = d.Set("objects_dictionary", objectsListState) - } else { - _ = d.Set("objects_dictionary", objectsList) - } - } else { - _ = d.Set("objects_dictionary", nil) - } - if v := natRulebaseData["rulebase"]; v != nil { - rulebaseList := v.([]interface{}) - if len(rulebaseList) > 0 { - var rulebaseListState []map[string]interface{} - for i := range rulebaseList { - ruleMap := rulebaseList[i].(map[string]interface{}) - ruleMapToAdd := make(map[string]interface{}) + if v, _ := ruleBaseMap["type"]; v != nil { + tempRulebase["type"] = v + } + if v, _ := ruleBaseMap["comments"]; v != nil && v != "" { + tempRulebase["comments"] = v + } - if v := ruleMap["name"]; v != nil { - ruleMapToAdd["name"] = v - } + if v, _ := ruleBaseMap["method"]; v != nil { + tempRulebase["method"] = v + } - if v := ruleMap["uid"]; v != nil { - ruleMapToAdd["uid"] = v - } + if v := ruleBaseMap["rule-number"]; v != nil { + tempRulebase["rule_number"] = v + } - if v := ruleMap["type"]; v != nil { - ruleMapToAdd["type"] = v - } + if v, _ := ruleBaseMap["type"]; v != nil { + tempRulebase["type"] = v + } - if v := ruleMap["rulebase"]; v != nil { - rules := v.([]interface{}) - rulesUids := make([]string, 0) - if len(rules) > 0 { - for i := range rules { - ruleJson := rules[i].(map[string]interface{}) - rulesUids = append(rulesUids, ruleJson["uid"].(string)) - } - } - ruleMapToAdd["rulebase"] = rulesUids - } - rulebaseListState = append(rulebaseListState, ruleMapToAdd) + if v, _ := ruleBaseMap["rulebase"]; v != nil { + tempRulebase["rulebase"] = readNatRuleBaseField(ruleBaseMap) } - _ = d.Set("rulebase", rulebaseListState) - } else { - _ = d.Set("rulebase", rulebaseList) + + ruleBaseDictToReturn = append(ruleBaseDictToReturn, tempRulebase) } - } else { - _ = d.Set("rulebase", nil) } - - return nil + return ruleBaseDictToReturn } diff --git a/checkpoint/data_source_checkpoint_management_nat_rulebase_test.go b/checkpoint/data_source_checkpoint_management_nat_rulebase_test.go index d7c94e2c..a567f424 100644 --- a/checkpoint/data_source_checkpoint_management_nat_rulebase_test.go +++ b/checkpoint/data_source_checkpoint_management_nat_rulebase_test.go @@ -48,7 +48,7 @@ func testAccCheckCheckpointNatRulebase(resourceTfName string, res *map[string]in } client := testAccProvider.Meta().(*checkpoint.ApiClient) - response, _ := client.ApiCall("show-nat-rulebase", map[string]interface{}{"package": "Standard", "filter": "Hide NAT", "limit": 1}, client.GetSessionID(), true, false) + response, _ := client.ApiCall("show-nat-rulebase", map[string]interface{}{"package": "Standard", "filter": "Hide NAT", "limit": 1}, client.GetSessionID(), true, client.IsProxyUsed()) if !response.Success { return fmt.Errorf(response.ErrorMsg) } diff --git a/checkpoint/data_source_checkpoint_management_nat_section.go b/checkpoint/data_source_checkpoint_management_nat_section.go index d104a4ff..bcba0923 100644 --- a/checkpoint/data_source_checkpoint_management_nat_section.go +++ b/checkpoint/data_source_checkpoint_management_nat_section.go @@ -47,7 +47,7 @@ func dataSourceManagementNatSectionRead(d *schema.ResourceData, m interface{}) e payload["uid"] = uid } - showNatSectionRes, err := client.ApiCall("show-nat-section", payload, client.GetSessionID(), true, false) + showNatSectionRes, err := client.ApiCall("show-nat-section", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_network.go b/checkpoint/data_source_checkpoint_management_network.go index e268e04c..128961a6 100644 --- a/checkpoint/data_source_checkpoint_management_network.go +++ b/checkpoint/data_source_checkpoint_management_network.go @@ -131,7 +131,7 @@ func dataSourceManagementNetworkRead(d *schema.ResourceData, m interface{}) erro payload["uid"] = uid } - showNetworkRes, err := client.ApiCall("show-network", payload, client.GetSessionID(), true, false) + showNetworkRes, err := client.ApiCall("show-network", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_nuage_data_center_server.go b/checkpoint/data_source_checkpoint_management_nuage_data_center_server.go new file mode 100644 index 00000000..bcc21926 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_nuage_data_center_server.go @@ -0,0 +1,156 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "strconv" + "strings" +) + +func dataSourceManagementNuageDataCenterServer() *schema.Resource { + return &schema.Resource{ + Read: dataSourceNuageDataCenterServerRead, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Object name. Must be unique in the domain.", + }, + "uid": { + Type: schema.TypeString, + Optional: true, + Description: "Object unique identifier.", + }, + "hostname": { + Type: schema.TypeString, + Computed: true, + Description: "IP address or hostname of the Nuage server.", + }, + "username": { + Type: schema.TypeString, + Computed: true, + Description: "Username of the Nuage administrator.", + }, + "organization": { + Type: schema.TypeString, + Computed: true, + Description: "Organization name or enterprise.", + }, + "certificate_fingerprint": { + Type: schema.TypeString, + Computed: true, + Description: "Specify the SHA-1 or SHA-256 fingerprint of the Data Center Server's certificate.", + }, + "unsafe_auto_accept": { + Type: schema.TypeBool, + Computed: true, + Description: "When set to false, the current Data Center Server's certificate should be trusted, either by providing the certificate-fingerprint argument or by relying on a previously trusted certificate of this hostname.\n\nWhen set to true, trust the current Data Center Server's certificate as-is.", + }, + "tags": { + Type: schema.TypeSet, + Computed: true, + Description: "Collection of tag identifiers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "color": { + Type: schema.TypeString, + Computed: true, + Description: "Color of the object. Should be one of existing colors.", + }, + "comments": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func dataSourceNuageDataCenterServerRead(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + var name string + var uid string + + if v, ok := d.GetOk("name"); ok { + name = v.(string) + } + if v, ok := d.GetOk("uid"); ok { + uid = v.(string) + } + payload := make(map[string]interface{}) + + if name != "" { + payload["name"] = name + } else if uid != "" { + payload["uid"] = uid + } + showNuageDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showNuageDataCenterServerRes.Success { + return fmt.Errorf(showNuageDataCenterServerRes.ErrorMsg) + } + nuageDataCenterServer := showNuageDataCenterServerRes.GetData() + + if v := nuageDataCenterServer["uid"]; v != nil { + _ = d.Set("uid", v) + d.SetId(v.(string)) + } + + if v := nuageDataCenterServer["name"]; v != nil { + _ = d.Set("name", v) + } + + if nuageDataCenterServer["properties"] != nil { + propsJson, ok := nuageDataCenterServer["properties"].([]interface{}) + if ok { + for _, prop := range propsJson { + propMap := prop.(map[string]interface{}) + propName := strings.ReplaceAll(propMap["name"].(string), "-", "_") + propValue := propMap["value"] + if propName == "unsafe_auto_accept" { + propValue, _ = strconv.ParseBool(propValue.(string)) + } + _ = d.Set(propName, propValue) + } + } + } + + if nuageDataCenterServer["tags"] != nil { + tagsJson, ok := nuageDataCenterServer["tags"].([]interface{}) + if ok { + tagsIds := make([]string, 0) + if len(tagsJson) > 0 { + for _, tags := range tagsJson { + tags := tags.(map[string]interface{}) + tagsIds = append(tagsIds, tags["name"].(string)) + } + } + _ = d.Set("tags", tagsIds) + } + } else { + _ = d.Set("tags", nil) + } + + if v := nuageDataCenterServer["color"]; v != nil { + _ = d.Set("color", v) + } + + if v := nuageDataCenterServer["comments"]; v != nil { + _ = d.Set("comments", v) + } + + if v := nuageDataCenterServer["ignore-warnings"]; v != nil { + _ = d.Set("ignore_warnings", v) + } + + if v := nuageDataCenterServer["ignore-errors"]; v != nil { + _ = d.Set("ignore_errors", v) + } + + return nil + +} diff --git a/checkpoint/data_source_checkpoint_management_nuage_data_center_server_test.go b/checkpoint/data_source_checkpoint_management_nuage_data_center_server_test.go new file mode 100644 index 00000000..c8450fbf --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_nuage_data_center_server_test.go @@ -0,0 +1,57 @@ +package checkpoint + +import ( + "fmt" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "os" + "testing" +) + +func TestAccDataSourceCheckpointManagementNuageDataCenterServer_basic(t *testing.T) { + + objName := "tfTestManagementDataNuageDataCenterServer_" + acctest.RandString(6) + resourceName := "checkpoint_management_nuage_data_center_server.nuage_data_center_server" + dataSourceName := "data.checkpoint_management_nuage_data_center_server.nuage_data_center_server" + username := "USERNAME" + password := "PASSWORD" + hostname := "MY_HOSTNAME" + organization := "MY_ORG" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceManagementNuageDataCenterServerConfig(objName, username, password, hostname, organization), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), + ), + }, + }, + }) + +} + +func testAccDataSourceManagementNuageDataCenterServerConfig(name string, username string, password string, hostname string, organization string) string { + return fmt.Sprintf(` +resource "checkpoint_management_nuage_data_center_server" "nuage_data_center_server" { + name = "%s" + username = "%s" + password = "%s" + hostname = "%s" + organization = "%s" + unsafe_auto_accept = true + ignore_warnings = true +} + +data "checkpoint_management_nuage_data_center_server" "nuage_data_center_server" { + name = "${checkpoint_management_nuage_data_center_server.nuage_data_center_server.name}" +} +`, name, username, password, hostname, organization) +} diff --git a/checkpoint/data_source_checkpoint_management_openstack_data_center_server.go b/checkpoint/data_source_checkpoint_management_openstack_data_center_server.go new file mode 100644 index 00000000..a99b19e2 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_openstack_data_center_server.go @@ -0,0 +1,151 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "strconv" + "strings" +) + +func dataSourceManagementOpenStackDataCenterServer() *schema.Resource { + return &schema.Resource{ + Read: dataSourceOpenStackDataCenterServerRead, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Object name. Must be unique in the domain.", + }, + "uid": { + Type: schema.TypeString, + Optional: true, + Description: "Object unique identifier.", + }, + "hostname": { + Type: schema.TypeString, + Computed: true, + Description: "URL of the OpenStack server.\nhttp(s)://:/\nExample: https://1.2.3.4:5000/v2.0", + }, + "username": { + Type: schema.TypeString, + Computed: true, + Description: "Username of the OpenStack server.\nTo login to specific domain insert domain name before username.\nExample: /", + }, + "certificate_fingerprint": { + Type: schema.TypeString, + Computed: true, + Description: "Specify the SHA-1 or SHA-256 fingerprint of the Data Center Server's certificate.", + }, + "unsafe_auto_accept": { + Type: schema.TypeBool, + Computed: true, + Description: "When set to false, the current Data Center Server's certificate should be trusted, either by providing the certificate-fingerprint argument or by relying on a previously trusted certificate of this hostname.\n\nWhen set to true, trust the current Data Center Server's certificate as-is.", + }, + "tags": { + Type: schema.TypeSet, + Computed: true, + Description: "Collection of tag identifiers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "color": { + Type: schema.TypeString, + Computed: true, + Description: "Color of the object. Should be one of existing colors.", + }, + "comments": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func dataSourceOpenStackDataCenterServerRead(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + var name string + var uid string + + if v, ok := d.GetOk("name"); ok { + name = v.(string) + } + if v, ok := d.GetOk("uid"); ok { + uid = v.(string) + } + payload := make(map[string]interface{}) + + if name != "" { + payload["name"] = name + } else if uid != "" { + payload["uid"] = uid + } + showOpenStackDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showOpenStackDataCenterServerRes.Success { + return fmt.Errorf(showOpenStackDataCenterServerRes.ErrorMsg) + } + openstackDataCenterServer := showOpenStackDataCenterServerRes.GetData() + + if v := openstackDataCenterServer["uid"]; v != nil { + _ = d.Set("uid", v) + d.SetId(v.(string)) + } + + if v := openstackDataCenterServer["name"]; v != nil { + _ = d.Set("name", v) + } + + if openstackDataCenterServer["properties"] != nil { + propsJson, ok := openstackDataCenterServer["properties"].([]interface{}) + if ok { + for _, prop := range propsJson { + propMap := prop.(map[string]interface{}) + propName := strings.ReplaceAll(propMap["name"].(string), "-", "_") + propValue := propMap["value"] + if propName == "unsafe_auto_accept" { + propValue, _ = strconv.ParseBool(propValue.(string)) + } + _ = d.Set(propName, propValue) + } + } + } + + if openstackDataCenterServer["tags"] != nil { + tagsJson, ok := openstackDataCenterServer["tags"].([]interface{}) + if ok { + tagsIds := make([]string, 0) + if len(tagsJson) > 0 { + for _, tags := range tagsJson { + tags := tags.(map[string]interface{}) + tagsIds = append(tagsIds, tags["name"].(string)) + } + } + _ = d.Set("tags", tagsIds) + } + } else { + _ = d.Set("tags", nil) + } + + if v := openstackDataCenterServer["color"]; v != nil { + _ = d.Set("color", v) + } + + if v := openstackDataCenterServer["comments"]; v != nil { + _ = d.Set("comments", v) + } + + if v := openstackDataCenterServer["ignore-warnings"]; v != nil { + _ = d.Set("ignore_warnings", v) + } + + if v := openstackDataCenterServer["ignore-errors"]; v != nil { + _ = d.Set("ignore_errors", v) + } + + return nil + +} diff --git a/checkpoint/data_source_checkpoint_management_openstack_data_center_server_test.go b/checkpoint/data_source_checkpoint_management_openstack_data_center_server_test.go new file mode 100644 index 00000000..a852ef1a --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_openstack_data_center_server_test.go @@ -0,0 +1,55 @@ +package checkpoint + +import ( + "fmt" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "os" + "testing" +) + +func TestAccDataSourceCheckpointManagementOpenStackDataCenterServer_basic(t *testing.T) { + + objName := "tfTestManagementDataOpenStackDataCenterServer_" + acctest.RandString(6) + resourceName := "checkpoint_management_openstack_data_center_server.openstack_data_center_server" + dataSourceName := "data.checkpoint_management_openstack_data_center_server.openstack_data_center_server" + username := "USERNAME" + password := "PASSWORD" + hostname := "HOSTNAME" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceManagementOpenStackDataCenterServerConfig(objName, username, password, hostname), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), + ), + }, + }, + }) + +} + +func testAccDataSourceManagementOpenStackDataCenterServerConfig(name string, username string, password string, hostname string) string { + return fmt.Sprintf(` +resource "checkpoint_management_openstack_data_center_server" "openstack_data_center_server" { + name = "%s" + username = "%s" + password = "%s" + hostname = "%s" + unsafe_auto_accept = true + ignore_warnings = true +} + +data "checkpoint_management_openstack_data_center_server" "openstack_data_center_server" { + name = "${checkpoint_management_openstack_data_center_server.openstack_data_center_server.name}" +} +`, name, username, password, hostname) +} diff --git a/checkpoint/data_source_checkpoint_management_opsec_application.go b/checkpoint/data_source_checkpoint_management_opsec_application.go index c0e3db9d..3e0a0a97 100644 --- a/checkpoint/data_source_checkpoint_management_opsec_application.go +++ b/checkpoint/data_source_checkpoint_management_opsec_application.go @@ -108,7 +108,7 @@ func dataSourceManagementOpsecApplicationRead(d *schema.ResourceData, m interfac payload["uid"] = uid } - showOpsecApplicationRes, err := client.ApiCall("show-opsec-application", payload, client.GetSessionID(), true, false) + showOpsecApplicationRes, err := client.ApiCall("show-opsec-application", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_package.go b/checkpoint/data_source_checkpoint_management_package.go index 2ad9977d..14e82758 100644 --- a/checkpoint/data_source_checkpoint_management_package.go +++ b/checkpoint/data_source_checkpoint_management_package.go @@ -96,7 +96,7 @@ func dataSourceManagementPackageRead(d *schema.ResourceData, m interface{}) erro payload["uid"] = uid } - showPackageRes, err := client.ApiCall("show-package", payload, client.GetSessionID(), true, false) + showPackageRes, err := client.ApiCall("show-package", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_security_zone.go b/checkpoint/data_source_checkpoint_management_security_zone.go index d8eb6001..0c87ed4f 100644 --- a/checkpoint/data_source_checkpoint_management_security_zone.go +++ b/checkpoint/data_source_checkpoint_management_security_zone.go @@ -58,7 +58,7 @@ func dataSourceManagementSecurityZoneRead(d *schema.ResourceData, m interface{}) payload["uid"] = uid } - showSecurityZoneRes, err := client.ApiCall("show-security-zone", payload, client.GetSessionID(), true, false) + showSecurityZoneRes, err := client.ApiCall("show-security-zone", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_service_citrix_tcp.go b/checkpoint/data_source_checkpoint_management_service_citrix_tcp.go index 785d5687..1663da03 100644 --- a/checkpoint/data_source_checkpoint_management_service_citrix_tcp.go +++ b/checkpoint/data_source_checkpoint_management_service_citrix_tcp.go @@ -63,7 +63,7 @@ func dataSourceManagementServiceCitrixTcpRead(d *schema.ResourceData, m interfac payload["uid"] = uid } - showServiceCitrixTcpRes, err := client.ApiCall("show-service-citrix-tcp", payload, client.GetSessionID(), true, false) + showServiceCitrixTcpRes, err := client.ApiCall("show-service-citrix-tcp", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_service_compound_tcp.go b/checkpoint/data_source_checkpoint_management_service_compound_tcp.go index fcd55325..1e7f48ac 100644 --- a/checkpoint/data_source_checkpoint_management_service_compound_tcp.go +++ b/checkpoint/data_source_checkpoint_management_service_compound_tcp.go @@ -68,7 +68,7 @@ func dataSourceManagementServiceCompoundTcpRead(d *schema.ResourceData, m interf payload["uid"] = uid } - showServiceCompoundTcpRes, err := client.ApiCall("show-service-compound-tcp", payload, client.GetSessionID(), true, false) + showServiceCompoundTcpRes, err := client.ApiCall("show-service-compound-tcp", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_service_dce_rpc.go b/checkpoint/data_source_checkpoint_management_service_dce_rpc.go index c9566e09..b1d53f73 100644 --- a/checkpoint/data_source_checkpoint_management_service_dce_rpc.go +++ b/checkpoint/data_source_checkpoint_management_service_dce_rpc.go @@ -76,7 +76,7 @@ func dataSourceManagementServiceDceRpcRead(d *schema.ResourceData, m interface{} payload["uid"] = uid } - showServiceDceRpcRes, err := client.ApiCall("show-service-dce-rpc", payload, client.GetSessionID(), true, false) + showServiceDceRpcRes, err := client.ApiCall("show-service-dce-rpc", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_service_group.go b/checkpoint/data_source_checkpoint_management_service_group.go index cec2f4f2..e38b34d8 100644 --- a/checkpoint/data_source_checkpoint_management_service_group.go +++ b/checkpoint/data_source_checkpoint_management_service_group.go @@ -73,7 +73,7 @@ func dataSourceManagementServiceGroupRead(d *schema.ResourceData, m interface{}) payload["uid"] = uid } - showServiceGroupRes, err := client.ApiCall("show-service-group", payload, client.GetSessionID(), true, false) + showServiceGroupRes, err := client.ApiCall("show-service-group", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_service_icmp.go b/checkpoint/data_source_checkpoint_management_service_icmp.go index 21bf3786..cb3cff38 100644 --- a/checkpoint/data_source_checkpoint_management_service_icmp.go +++ b/checkpoint/data_source_checkpoint_management_service_icmp.go @@ -80,7 +80,7 @@ func dataSourceManagementServiceIcmpRead(d *schema.ResourceData, m interface{}) payload["uid"] = uid } - showServiceIcmpRes, err := client.ApiCall("show-service-icmp", payload, client.GetSessionID(), true, false) + showServiceIcmpRes, err := client.ApiCall("show-service-icmp", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_service_icmp6.go b/checkpoint/data_source_checkpoint_management_service_icmp6.go index ec057f0e..77c1b55a 100644 --- a/checkpoint/data_source_checkpoint_management_service_icmp6.go +++ b/checkpoint/data_source_checkpoint_management_service_icmp6.go @@ -81,7 +81,7 @@ func dataSourceManagementServiceIcmp6Read(d *schema.ResourceData, m interface{}) payload["uid"] = uid } - showServiceIcmp6Res, err := client.ApiCall("show-service-icmp6", payload, client.GetSessionID(), true, false) + showServiceIcmp6Res, err := client.ApiCall("show-service-icmp6", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_service_other.go b/checkpoint/data_source_checkpoint_management_service_other.go index e9561782..2eceafd1 100644 --- a/checkpoint/data_source_checkpoint_management_service_other.go +++ b/checkpoint/data_source_checkpoint_management_service_other.go @@ -147,7 +147,7 @@ func dataSourceManagementServiceOtherRead(d *schema.ResourceData, m interface{}) payload["uid"] = uid } - showServiceOtherRes, err := client.ApiCall("show-service-other", payload, client.GetSessionID(), true, false) + showServiceOtherRes, err := client.ApiCall("show-service-other", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_service_rpc.go b/checkpoint/data_source_checkpoint_management_service_rpc.go index 701da859..b4929423 100644 --- a/checkpoint/data_source_checkpoint_management_service_rpc.go +++ b/checkpoint/data_source_checkpoint_management_service_rpc.go @@ -75,7 +75,7 @@ func dataSourceManagementServiceRpcRead(d *schema.ResourceData, m interface{}) e payload["uid"] = uid } - showServiceRpcRes, err := client.ApiCall("show-service-rpc", payload, client.GetSessionID(), true, false) + showServiceRpcRes, err := client.ApiCall("show-service-rpc", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_service_sctp.go b/checkpoint/data_source_checkpoint_management_service_sctp.go index a665fd2f..09c0a471 100644 --- a/checkpoint/data_source_checkpoint_management_service_sctp.go +++ b/checkpoint/data_source_checkpoint_management_service_sctp.go @@ -131,7 +131,7 @@ func dataSourceManagementServiceSctpRead(d *schema.ResourceData, m interface{}) payload["uid"] = uid } - showServiceSctpRes, err := client.ApiCall("show-service-sctp", payload, client.GetSessionID(), true, false) + showServiceSctpRes, err := client.ApiCall("show-service-sctp", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_service_tcp.go b/checkpoint/data_source_checkpoint_management_service_tcp.go index d4f8f8da..b0440cf3 100644 --- a/checkpoint/data_source_checkpoint_management_service_tcp.go +++ b/checkpoint/data_source_checkpoint_management_service_tcp.go @@ -145,7 +145,7 @@ func dataSourceManagementServiceTcpRead(d *schema.ResourceData, m interface{}) e payload["uid"] = uid } - showServiceTcpRes, err := client.ApiCall("show-service-tcp", payload, client.GetSessionID(), true, false) + showServiceTcpRes, err := client.ApiCall("show-service-tcp", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_service_udp.go b/checkpoint/data_source_checkpoint_management_service_udp.go index 18f4347b..8b3d3c82 100644 --- a/checkpoint/data_source_checkpoint_management_service_udp.go +++ b/checkpoint/data_source_checkpoint_management_service_udp.go @@ -150,7 +150,7 @@ func dataSourceManagementServiceUdpRead(d *schema.ResourceData, m interface{}) e payload["uid"] = uid } - showServiceUdpRes, err := client.ApiCall("show-service-udp", payload, client.GetSessionID(), true, false) + showServiceUdpRes, err := client.ApiCall("show-service-udp", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_show_objects.go b/checkpoint/data_source_checkpoint_management_show_objects.go index 52cddc75..4999606a 100644 --- a/checkpoint/data_source_checkpoint_management_show_objects.go +++ b/checkpoint/data_source_checkpoint_management_show_objects.go @@ -176,7 +176,7 @@ func dataSourceManagementShowObjectsRead(d *schema.ResourceData, m interface{}) } } - showObjectsRes, err := client.ApiCall("show-objects", payload, client.GetSessionID(), true, false) + showObjectsRes, err := client.ApiCall("show-objects", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_show_updatable_objects_repository_content.go b/checkpoint/data_source_checkpoint_management_show_updatable_objects_repository_content.go index f41475d5..99b1a095 100644 --- a/checkpoint/data_source_checkpoint_management_show_updatable_objects_repository_content.go +++ b/checkpoint/data_source_checkpoint_management_show_updatable_objects_repository_content.go @@ -247,7 +247,7 @@ func dataSourceManagementShowUpdatableObjectsRepositoryContentRead(d *schema.Res } } - showUpdatableObjectsRepositoryContentRes, err := client.ApiCall("show-updatable-objects-repository-content", payload, client.GetSessionID(), true, false) + showUpdatableObjectsRepositoryContentRes, err := client.ApiCall("show-updatable-objects-repository-content", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_simple_cluster.go b/checkpoint/data_source_checkpoint_management_simple_cluster.go index b2e99ace..bf20fc5a 100644 --- a/checkpoint/data_source_checkpoint_management_simple_cluster.go +++ b/checkpoint/data_source_checkpoint_management_simple_cluster.go @@ -198,7 +198,7 @@ func dataSourceManagementSimpleCluster() *schema.Resource { Computed: true, Description: "IPv4 or IPv6 address.", }, - "sic_name": { + "sic_state": { Type: schema.TypeString, Computed: true, Description: "Secure Internal Communication name.", @@ -894,7 +894,7 @@ func dataSourceManagementSimpleClusterRead(d *schema.ResourceData, m interface{} payload["uid"] = uid } - showClusterRes, err := client.ApiCall("show-simple-cluster", payload, client.GetSessionID(), true, false) + showClusterRes, err := client.ApiCall("show-simple-cluster", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -910,7 +910,7 @@ func dataSourceManagementSimpleClusterRead(d *schema.ResourceData, m interface{} totalInterfaces := int(total.(float64)) if totalInterfaces > 50 { payload["limit-interfaces"] = totalInterfaces - showClusterRes, err := client.ApiCall("show-simple-cluster", payload, client.GetSessionID(), true, false) + showClusterRes, err := client.ApiCall("show-simple-cluster", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_simple_gateway.go b/checkpoint/data_source_checkpoint_management_simple_gateway.go index 02e52aec..615b5ad6 100644 --- a/checkpoint/data_source_checkpoint_management_simple_gateway.go +++ b/checkpoint/data_source_checkpoint_management_simple_gateway.go @@ -807,7 +807,7 @@ func dataSourceManagementSimpleGatewayRead(d *schema.ResourceData, m interface{} payload["uid"] = uid } - showGatewayRes, err := client.ApiCall("show-simple-gateway", payload, client.GetSessionID(), true, false) + showGatewayRes, err := client.ApiCall("show-simple-gateway", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_threat_exception.go b/checkpoint/data_source_checkpoint_management_threat_exception.go index a29799a8..b62cdc8f 100644 --- a/checkpoint/data_source_checkpoint_management_threat_exception.go +++ b/checkpoint/data_source_checkpoint_management_threat_exception.go @@ -175,7 +175,7 @@ func dataSourceManagementThreatExceptionRead(d *schema.ResourceData, m interface payload["rule-name"] = v.(string) } - showThreatRuleRes, err := client.ApiCall("show-threat-exception", payload, client.GetSessionID(), true, false) + showThreatRuleRes, err := client.ApiCall("show-threat-exception", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_threat_indicator.go b/checkpoint/data_source_checkpoint_management_threat_indicator.go index b21e98d0..ea9b7312 100644 --- a/checkpoint/data_source_checkpoint_management_threat_indicator.go +++ b/checkpoint/data_source_checkpoint_management_threat_indicator.go @@ -82,7 +82,7 @@ func dataSourceManagementThreatIndicatorRead(d *schema.ResourceData, m interface payload["uid"] = uid } - showThreatIndicatorRes, err := client.ApiCall("show-threat-indicator", payload, client.GetSessionID(), true, false) + showThreatIndicatorRes, err := client.ApiCall("show-threat-indicator", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_threat_profile.go b/checkpoint/data_source_checkpoint_management_threat_profile.go index 205f5d42..ad97e6ad 100644 --- a/checkpoint/data_source_checkpoint_management_threat_profile.go +++ b/checkpoint/data_source_checkpoint_management_threat_profile.go @@ -434,7 +434,7 @@ func dataSourceManagementThreatProfileRead(d *schema.ResourceData, m interface{} payload["uid"] = uid } - showThreatProfileRes, err := client.ApiCall("show-threat-profile", payload, client.GetSessionID(), true, false) + showThreatProfileRes, err := client.ApiCall("show-threat-profile", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_threat_rule.go b/checkpoint/data_source_checkpoint_management_threat_rule.go index 084d27f1..f90ba3cd 100644 --- a/checkpoint/data_source_checkpoint_management_threat_rule.go +++ b/checkpoint/data_source_checkpoint_management_threat_rule.go @@ -150,7 +150,7 @@ func dataSourceManagementThreatRuleRead(d *schema.ResourceData, m interface{}) e payload["uid"] = uid } - showThreatRuleRes, err := client.ApiCall("show-threat-rule", payload, client.GetSessionID(), true, false) + showThreatRuleRes, err := client.ApiCall("show-threat-rule", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_threat_rulebase.go b/checkpoint/data_source_checkpoint_management_threat_rulebase.go new file mode 100644 index 00000000..b15db97e --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_threat_rulebase.go @@ -0,0 +1,622 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "log" + "math" + "strconv" + "strings" +) + +func dataSourceManagementThreatRuleBase() *schema.Resource { + return &schema.Resource{ + Read: dataSourceManagementThreatRuleBaseRead, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Object name.", + }, + "uid": { + Type: schema.TypeString, + Optional: true, + Description: "Object unique identifier.", + }, + "filter": { + Type: schema.TypeString, + Optional: true, + Description: "Search expression to filter the rulebase. The provided text should be exactly the same as it would be given in Smart Console. The logical operators in the expression ('AND', 'OR') should be provided in capital letters. If an operator is not used, the default OR operator applies.", + }, + "filter_settings": { + Type: schema.TypeMap, + Optional: true, + Description: "Sets filter preferences.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "search_mode": { + Type: schema.TypeString, + Optional: true, + Description: "When set to 'general', both the Full Text Search and Packet Search are enabled. In this mode, Packet Search will not match on 'Any' object, a negated cell or a group-with-exclusion. When the search-mode is set to 'packet', by default, the match on 'Any' object, a negated cell or a group-with-exclusion are enabled. packet-search-settings may be provided to change the default behavior.", + }, + "expand_group_members": { + Type: schema.TypeBool, + Optional: true, + Description: "When true, if the search expression contains a UID or a name of a group object, results will include rules that match on at least one member of the group.", + Default: false, + }, + "expand_group_with_exclusion_members": { + Type: schema.TypeBool, + Optional: true, + Description: "When true, if the search expression contains a UID or a name of a group-with-exclusion object, results will include rules that match at least one member of the \"include\" part and is not a member of the \"except\" part.", + Default: false, + }, + "match_on_any": { + Type: schema.TypeBool, + Optional: true, + Description: "Whether to match on 'Any' object.", + Default: true, + }, + "match_on_group_with_exclusion": { + Type: schema.TypeBool, + Optional: true, + Description: "Whether to match on a group-with-exclusion.", + Default: true, + }, + "match_on_negate": { + Type: schema.TypeBool, + Optional: true, + Description: "Whether to match on a negated cell.", + Default: true, + }, + }, + }, + }, + "limit": { + Type: schema.TypeInt, + Optional: true, + Description: "The maximal number of returned results.", + Default: 50, + }, + "offset": { + Type: schema.TypeInt, + Optional: true, + Description: "Number of the results to initially skip.", + Default: 0, + }, + "order": { + Type: schema.TypeList, + Optional: true, + Description: "Sorts the results by search criteria. Automatically sorts the results by Name, in the ascending order.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "asc": { + Type: schema.TypeString, + Optional: true, + Description: "Sorts results by the given field in ascending order.", + }, + "desc": { + Type: schema.TypeString, + Optional: true, + Description: "Sorts results by the given field in descending order.", + }, + }, + }, + }, + "package": { + Type: schema.TypeString, + Optional: true, + Description: "Name of the package.", + }, + "show_as_ranges": { + Type: schema.TypeBool, + Optional: true, + Description: "When true, the source, destination and services & applications parameters are displayed as ranges of IP addresses and port numbers rather than network objects.\nObjects that are not represented using IP addresses or port numbers are presented as objects.\nIn addition, the response of each rule does not contain the parameters: source, source-negate, destination, destination-negate, service and service-negate, but instead it contains the parameters: source-ranges, destination-ranges and service-ranges.\n\nNote: Requesting to show rules as ranges is limited up to 20 rules per request, otherwise an error is returned. If you wish to request more rules, use the offset and limit parameters to limit your request.", + Default: false, + }, + "show_hits": { + Type: schema.TypeBool, + Optional: true, + Description: "N/A", + }, + "hits_settings": { + Type: schema.TypeMap, + Optional: true, + Description: "N/A", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "from_date": { + Type: schema.TypeString, + Optional: true, + Description: "Format: YYYY-MM-DD, YYYY-mm-ddThh:mm:ss.", + }, + "target": { + Type: schema.TypeString, + Optional: true, + Description: "Target gateway name or UID.", + }, + "to_date": { + Type: schema.TypeString, + Optional: true, + Description: "Format: YYYY-MM-DD, YYYY-mm-ddThh:mm:ss.", + }, + }, + }, + }, + "dereference_group_members": { + Type: schema.TypeBool, + Optional: true, + Description: "When true, the source, destination and services & applications parameters are displayed as ranges of IP addresses and port numbers rather than network objects.\nObjects that are not represented using IP addresses or port numbers are presented as objects.\nIn addition, the response of each rule does not contain the parameters: source, source-negate, destination, destination-negate, service and service-negate, but instead it contains the parameters: source-ranges, destination-ranges and service-ranges.\n\nNote: Requesting to show rules as ranges is limited up to 20 rules per request, otherwise an error is returned. If you wish to request more rules, use the offset and limit parameters to limit your request.", + Default: false, + }, + "show_membership": { + Type: schema.TypeBool, + Optional: true, + Description: "N/A", + Default: false, + }, + "rulebase": { + Type: schema.TypeList, + Computed: true, + Description: "The show rulebase api reply", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "from": { + Type: schema.TypeInt, + Computed: true, + Description: "From which element number the query was done.", + }, + "to": { + Type: schema.TypeInt, + Computed: true, + Description: "To which element number the query was done.", + }, + "total": { + Type: schema.TypeInt, + Computed: true, + Description: "Total number of elements returned by the query.", + }, + "objects_dictionary": { + Type: schema.TypeList, + Computed: true, + Description: "Level of details in the output corresponds to the number of details for search. This table shows the level of details in the Standard level.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Computed: true, + Description: "Object name. Must be unique in the domain", + }, + "uid": { + Type: schema.TypeString, + Computed: true, + Description: "Object unique identifier.", + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "Object type.", + }, + }, + }, + }, + "rulebase": { + Type: schema.TypeList, + MaxItems: 1, + Computed: true, + Description: "N/A", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "uid": { + Type: schema.TypeString, + Computed: true, + Description: "Rules uid.", + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: "Rules name.", + }, + "destination": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "destination_negate": { + Type: schema.TypeBool, + Computed: true, + Description: "True if negate is set for destination.", + }, + "install_on": { + Type: schema.TypeList, + Computed: true, + Description: "Which Gateways identified by the name or UID to install the policy on.", + Elem: schema.TypeString, + }, + "enabled": { + Type: schema.TypeBool, + Computed: true, + Description: "Enable/Disable the rule.", + }, + "service": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "service_negate": { + Type: schema.TypeBool, + Computed: true, + Description: "True if negate is set for service.", + }, + "protected_scope": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "protected_scope_negate": { + Type: schema.TypeBool, + Computed: true, + Description: "True if negate is set for service.", + }, + "source": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "source_negate": { + Type: schema.TypeBool, + Computed: true, + Description: "True if negate is set for source.", + }, + "comments": { + Type: schema.TypeString, + Computed: true, + Description: "Comments string.", + }, + "action": { + Type: schema.TypeString, + Computed: true, + Description: "\"Accept\", \"Drop\", \"Ask\", \"Inform\", \"Reject\", \"User Auth\", \"Client Auth\", \"Apply Layer\".", + }, + "track_settings": { + Type: schema.TypeMap, + Computed: true, + Description: "track settings.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "packet_capture": { + Type: schema.TypeBool, + Computed: true, + Description: "N/A", + }, + }, + }, + }, + "rule_number": { + Type: schema.TypeInt, + Computed: true, + Description: "Number of the rule.", + }, + "track": { + Type: schema.TypeString, + Computed: true, + Description: "Track Settings.", + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "Rules type.", + }, + "exceptions": { + Type: schema.TypeList, + Computed: true, + Description: "Collection of Network objects identified by the name or UID.", + Elem: schema.TypeString, + }, + "exceptions_layer": { + Type: schema.TypeString, + Computed: true, + Description: "Rules type.", + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func dataSourceManagementThreatRuleBaseRead(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + + name := d.Get("name").(string) + uid := d.Get("uid").(string) + + payload := map[string]interface{}{} + if name != "" { + payload["name"] = name + } else if uid != "" { + payload["uid"] = uid + } + if v, ok := d.GetOk("filter"); ok { + payload["filter"] = v.(string) + } + if v, ok := d.GetOk("filter_settings"); ok { + filters, ok := v.(map[string]interface{}) + if ok { + + filtersMapToReturn := make(map[string]interface{}) + packetSearchMap := make(map[string]interface{}) + + if val, ok := filters["search_mode"]; ok { + filtersMapToReturn["search-mode"] = val + } else { + filtersMapToReturn["search-mode"] = "general" + } + + if val, ok := filters["expand_group_members"]; ok { + packetSearchMap["expand-group-members"] = val + } else { + packetSearchMap["expand-group-members"] = false + } + + if val, ok := filters["expand_group_with_exclusion_members"]; ok { + packetSearchMap["expand-group-with-exclusion-members"] = val + } else { + packetSearchMap["expand-group-with-exclusion-members"] = false + } + + if val, ok := filters["match_on_any"]; ok { + packetSearchMap["match-on-any"] = val + } else { + packetSearchMap["match-on-any"] = true + } + + if val, ok := filters["match_on_group_with_exclusion"]; ok { + packetSearchMap["match-on-group-with-exclusion"] = val + } else { + packetSearchMap["match-on-group-with-exclusion"] = true + } + + if val, ok := filters["match_on_negate"]; ok { + packetSearchMap["match-on-negate"] = val + } else { + packetSearchMap["match-on-negate"] = true + } + + filtersMapToReturn["packet-search-settings"] = packetSearchMap + payload["filter-settings"] = filtersMapToReturn + } + } + if v, ok := d.GetOk("limit"); ok { + payload["limit"] = v.(int) + } + if v, ok := d.GetOk("offset"); ok { + payload["offset"] = v.(int) + } + if v, ok := d.GetOk("order"); ok { + + ordersList, ok := v.([]interface{}) + var ordersDictToReturn []map[string]interface{} + + if ok { + for i := range ordersList { + + objectsMap := ordersList[i].(map[string]interface{}) + + tempOrder := make(map[string]interface{}) + + if v, _ := objectsMap["asc"]; v != nil && v != "" { + tempOrder["ASC"] = v + } + + if v, _ := objectsMap["desc"]; v != nil && v != "" { + tempOrder["DESC"] = v + } + + ordersDictToReturn = append(ordersDictToReturn, tempOrder) + } + payload["order"] = ordersDictToReturn + } + } + if v, ok := d.GetOk("package"); ok { + payload["package"] = v.(string) + } + if v, ok := d.GetOk("dereference_group_members"); ok { + payload["dereference-group-members"] = v.(bool) + } + + if v, ok := d.GetOk("show_membership"); ok { + payload["show-membership"] = v.(bool) + } + showRuleBaseRes, err := client.ApiCall("show-threat-rulebase", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showRuleBaseRes.Success { + return fmt.Errorf(showRuleBaseRes.ErrorMsg) + } + ruleBaseJson := showRuleBaseRes.GetData() + + log.Println("Read ruleBaseJson - Show JSON = ", ruleBaseJson) + var outputRuleBase []interface{} + ruleBaseToReturn := make(map[string]interface{}) + if v := ruleBaseJson["uid"]; v != nil { + _ = d.Set("uid", v) + d.SetId(v.(string)) + } + + if v := ruleBaseJson["name"]; v != nil { + _ = d.Set("name", v) + } + + if v := ruleBaseJson["from"]; v != nil { + ruleBaseToReturn["from"] = int(math.Round(v.(float64))) + } else { + ruleBaseToReturn["from"] = 0 + } + if ruleBaseJson["objects-dictionary"] != nil { + + objectsList, ok := ruleBaseJson["objects-dictionary"].([]interface{}) + var objectDictToReturn []map[string]interface{} + + if ok { + for i := range objectsList { + + objectsMap := objectsList[i].(map[string]interface{}) + + tempObject := make(map[string]interface{}) + + if v, _ := objectsMap["name"]; v != nil { + tempObject["name"] = v + } + + if v, _ := objectsMap["uid"]; v != nil { + tempObject["uid"] = v + } + + if v, _ := objectsMap["type"]; v != nil { + tempObject["type"] = v + } + + objectDictToReturn = append(objectDictToReturn, tempObject) + } + ruleBaseToReturn["objects_dictionary"] = objectDictToReturn + } + } else { + ruleBaseToReturn["objects_dictionary"] = []map[string]interface{}{} + } + + if ruleBaseJson["rulebase"] != nil { + ruleBaseList, ok := ruleBaseJson["rulebase"].([]interface{}) + var ruleBaseDictToReturn []map[string]interface{} + + if ok { + for i := range ruleBaseList { + + ruleBaseMap := ruleBaseList[i].(map[string]interface{}) + + tempRulebase := make(map[string]interface{}) + if v, _ := ruleBaseMap["uid"]; v != nil { + tempRulebase["uid"] = v + } + + if v, _ := ruleBaseMap["name"]; v != nil { + tempRulebase["name"] = v + } + + if v, _ := ruleBaseMap["destination"]; v != nil { + tempRulebase["destination"] = v + } + + if v, _ := ruleBaseMap["destination-negate"]; v != nil { + tempRulebase["destination_negate"] = v.(bool) + } + + if v, _ := ruleBaseMap["install-on"]; v != nil { + tempRulebase["install_on"] = v + } + + if v, _ := ruleBaseMap["enabled"]; v != nil { + tempRulebase["enabled"] = v.(bool) + } + + if v, _ := ruleBaseMap["source"]; v != nil { + tempRulebase["source"] = v + } + + if v, _ := ruleBaseMap["source-negate"]; v != nil { + tempRulebase["source_negate"] = v.(bool) + } + + if v, _ := ruleBaseMap["service"]; v != nil { + tempRulebase["service"] = v + } + + if v, _ := ruleBaseMap["service-negate"]; v != nil { + tempRulebase["service_negate"] = v.(bool) + } + + if v, _ := ruleBaseMap["type"]; v != nil { + tempRulebase["type"] = v + } + if v, _ := ruleBaseMap["comments"]; v != nil && v != "" { + tempRulebase["comments"] = v + } + if v, _ := ruleBaseMap["track-settings"]; v != nil { + propsJson, ok := ruleBaseMap["track-settings"].(map[string]interface{}) + if ok { + actionSettingsMapToReturn := make(map[string]interface{}) + for field, value := range propsJson { + propName := strings.ReplaceAll(field, "-", "_") + if propName == "packet_capture" { + value = strconv.FormatBool(value.(bool)) + } + actionSettingsMapToReturn[propName] = value + } + tempRulebase["track_settings"] = actionSettingsMapToReturn + } + } + + if v, _ := ruleBaseMap["action"]; v != nil { + tempRulebase["action"] = v + } + + if v, _ := ruleBaseMap["track"]; v != nil { + tempRulebase["track"] = v.(string) + } + + if v := ruleBaseMap["rule-number"]; v != nil { + tempRulebase["rule_number"] = v + } + + if v, _ := ruleBaseMap["type"]; v != nil { + tempRulebase["type"] = v + } + + if v, _ := ruleBaseMap["exceptions"]; v != nil { + tempRulebase["exceptions"] = v + } + + if v, _ := ruleBaseMap["exceptions-layer"]; v != nil { + tempRulebase["exceptions_layer"] = v + } + + if v, _ := ruleBaseMap["protected-scope"]; v != nil { + tempRulebase["protected_scope"] = v + } + + if v, _ := ruleBaseMap["protected-scope-negate"]; v != nil { + tempRulebase["protected_scope_negate"] = v.(bool) + } + ruleBaseDictToReturn = append(ruleBaseDictToReturn, tempRulebase) + } + } + ruleBaseToReturn["rulebase"] = ruleBaseDictToReturn + } else { + ruleBaseToReturn["rulebase"] = []map[string]interface{}{} + } + + if v := ruleBaseJson["to"]; v != nil { + ruleBaseToReturn["to"] = int(math.Round(v.(float64))) + } else { + ruleBaseToReturn["to"] = 0 + } + if v := ruleBaseJson["total"]; v != nil { + ruleBaseToReturn["total"] = int(math.Round(v.(float64))) + } else { + ruleBaseToReturn["total"] = 0 + } + outputRuleBase = append(outputRuleBase, ruleBaseToReturn) + _ = d.Set("rulebase", outputRuleBase) + return nil +} diff --git a/checkpoint/data_source_checkpoint_management_threat_rulebase_test.go b/checkpoint/data_source_checkpoint_management_threat_rulebase_test.go new file mode 100644 index 00000000..71a8e947 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_threat_rulebase_test.go @@ -0,0 +1,87 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + _ "github.com/hashicorp/terraform-plugin-sdk/terraform" + "os" + _ "strings" + "testing" +) + +func TestAccDataSourceCheckpointManagementThreatRulebase_basic(t *testing.T) { + var showObjectsQuery map[string]interface{} + dataSourceShowObjects := "data.checkpoint_management_threat_rulebase.test" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceManagementThreatRulebaseConfig("Standard Threat Prevention", 1), + Check: resource.ComposeTestCheckFunc( + testAccCheckCheckpointThreatRulebase(dataSourceShowObjects, &showObjectsQuery), + testAccCheckCheckpointThreatRulebaseAttributes(&showObjectsQuery), + ), + }, + }, + }) +} + +func testAccCheckCheckpointThreatRulebase(resourceTfName string, res *map[string]interface{}) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[resourceTfName] + if !ok { + return fmt.Errorf("show-threat-rulebase data source not found: %s", resourceTfName) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("show-threat-rulebase data source ID is not set") + } + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + response, _ := client.ApiCall("show-threat-rulebase", map[string]interface{}{"name": "Standard Threat Prevention", "limit": 1}, client.GetSessionID(), true, client.IsProxyUsed()) + if !response.Success { + return fmt.Errorf(response.ErrorMsg) + } + + *res = response.GetData() + + return nil + } +} + +func testAccCheckCheckpointThreatRulebaseAttributes(showThreatRulebaseMap *map[string]interface{}) resource.TestCheckFunc { + return func(s *terraform.State) error { + + showThreatRulebaseMap := *showThreatRulebaseMap + if showThreatRulebaseMap == nil { + return fmt.Errorf("showThreatRulebaseMap is nil") + } + + rulebase := showThreatRulebaseMap["rulebase"].([]interface{}) + + if len(rulebase) != 1 { + return fmt.Errorf("show-threat-rulebase returned wrong number of rulebase objects. exptected for 1, found %d", len(rulebase)) + } + + return nil + } +} + +func testAccDataSourceManagementThreatRulebaseConfig(name string, limit int) string { + return fmt.Sprintf(` +data "checkpoint_management_threat_rulebase" "test" { + name = "%s" + limit = %d +} +`, name, limit) +} diff --git a/checkpoint/data_source_checkpoint_management_time_group.go b/checkpoint/data_source_checkpoint_management_time_group.go index 1c865d63..6338a02b 100644 --- a/checkpoint/data_source_checkpoint_management_time_group.go +++ b/checkpoint/data_source_checkpoint_management_time_group.go @@ -73,7 +73,7 @@ func dataSourceManagementTimeGroupRead(d *schema.ResourceData, m interface{}) er payload["uid"] = uid } - showTimeGroupRes, err := client.ApiCall("show-time-group", payload, client.GetSessionID(), true, false) + showTimeGroupRes, err := client.ApiCall("show-time-group", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_user.go b/checkpoint/data_source_checkpoint_management_user.go index 0997f9d8..af440566 100644 --- a/checkpoint/data_source_checkpoint_management_user.go +++ b/checkpoint/data_source_checkpoint_management_user.go @@ -163,7 +163,7 @@ func dataSourceManagementUserRead(d *schema.ResourceData, m interface{}) error { payload["uid"] = uid } - showUserRes, err := client.ApiCall("show-user", payload, client.GetSessionID(), true, false) + showUserRes, err := client.ApiCall("show-user", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_user_group.go b/checkpoint/data_source_checkpoint_management_user_group.go index 385015aa..6867adce 100644 --- a/checkpoint/data_source_checkpoint_management_user_group.go +++ b/checkpoint/data_source_checkpoint_management_user_group.go @@ -70,7 +70,7 @@ func dataSourceManagementUserGroupRead(d *schema.ResourceData, m interface{}) er payload["uid"] = uid } - showUserGroupRes, err := client.ApiCall("show-user-group", payload, client.GetSessionID(), true, false) + showUserGroupRes, err := client.ApiCall("show-user-group", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_user_template.go b/checkpoint/data_source_checkpoint_management_user_template.go index 75fe4754..4c077bf9 100644 --- a/checkpoint/data_source_checkpoint_management_user_template.go +++ b/checkpoint/data_source_checkpoint_management_user_template.go @@ -157,7 +157,7 @@ func dataSourceManagementUserTemplateRead(d *schema.ResourceData, m interface{}) payload["uid"] = uid } - showUserTemplateRes, err := client.ApiCall("show-user-template", payload, client.GetSessionID(), true, false) + showUserTemplateRes, err := client.ApiCall("show-user-template", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_vmware_data_center_server.go b/checkpoint/data_source_checkpoint_management_vmware_data_center_server.go new file mode 100644 index 00000000..9c44fe1c --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_vmware_data_center_server.go @@ -0,0 +1,160 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "strconv" + "strings" +) + +func dataSourceManagementVMwareDataCenterServer() *schema.Resource { + return &schema.Resource{ + Read: dataSourceVMwareDataCenterServerRead, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + Description: "Object name. Must be unique in the domain.", + }, + "uid": { + Type: schema.TypeString, + Optional: true, + Description: "Object unique identifier.", + }, + "type": { + Type: schema.TypeString, + Computed: true, + Description: "Object type. nsx or nsxt or vmware.", + }, + "hostname": { + Type: schema.TypeString, + Computed: true, + Description: "IP Address or hostname of the vCenter server.", + }, + "username": { + Type: schema.TypeString, + Computed: true, + Description: "Username of the vCenter server", + }, + "certificate_fingerprint": { + Type: schema.TypeString, + Computed: true, + Description: "Specify the SHA-1 or SHA-256 fingerprint of the Data Center Server's certificate.", + }, + "unsafe_auto_accept": { + Type: schema.TypeBool, + Computed: true, + Description: "When set to false, the current Data Center Server's certificate should be trusted, either by providing the certificate-fingerprint argument or by relying on a previously trusted certificate of this hostname.\n\nWhen set to true, trust the current Data Center Server's certificate as-is.", + }, + "tags": { + Type: schema.TypeSet, + Computed: true, + Description: "Collection of tag identifiers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "color": { + Type: schema.TypeString, + Computed: true, + Description: "Color of the object. Should be one of existing colors.", + }, + "comments": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func dataSourceVMwareDataCenterServerRead(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + var name string + var uid string + + if v, ok := d.GetOk("name"); ok { + name = v.(string) + } + if v, ok := d.GetOk("uid"); ok { + uid = v.(string) + } + payload := make(map[string]interface{}) + + if name != "" { + payload["name"] = name + } else if uid != "" { + payload["uid"] = uid + } + showVMwareDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showVMwareDataCenterServerRes.Success { + return fmt.Errorf(showVMwareDataCenterServerRes.ErrorMsg) + } + vmwareDataCenterServer := showVMwareDataCenterServerRes.GetData() + + if v := vmwareDataCenterServer["uid"]; v != nil { + _ = d.Set("uid", v) + d.SetId(v.(string)) + } + + if v := vmwareDataCenterServer["name"]; v != nil { + _ = d.Set("name", v) + } + + if vmwareDataCenterServer["properties"] != nil { + propsJson, ok := vmwareDataCenterServer["properties"].([]interface{}) + if ok { + for _, prop := range propsJson { + propMap := prop.(map[string]interface{}) + propName := strings.ReplaceAll(propMap["name"].(string), "-", "_") + propValue := propMap["value"] + if propName == "unsafe_auto_accept" { + propValue, _ = strconv.ParseBool(propValue.(string)) + } + _ = d.Set(propName, propValue) + } + } + } + + if vmwareDataCenterServer["tags"] != nil { + tagsJson, ok := vmwareDataCenterServer["tags"].([]interface{}) + if ok { + tagsIds := make([]string, 0) + if len(tagsJson) > 0 { + for _, tags := range tagsJson { + tags := tags.(map[string]interface{}) + tagsIds = append(tagsIds, tags["name"].(string)) + } + } + _ = d.Set("tags", tagsIds) + } + } else { + _ = d.Set("tags", nil) + } + + if v := vmwareDataCenterServer["color"]; v != nil { + _ = d.Set("color", v) + } + + if v := vmwareDataCenterServer["data-center-type"]; v != nil { + _ = d.Set("type", v) + } + + if v := vmwareDataCenterServer["comments"]; v != nil { + _ = d.Set("comments", v) + } + + if v := vmwareDataCenterServer["ignore-warnings"]; v != nil { + _ = d.Set("ignore_warnings", v) + } + + if v := vmwareDataCenterServer["ignore-errors"]; v != nil { + _ = d.Set("ignore_errors", v) + } + + return nil + +} diff --git a/checkpoint/data_source_checkpoint_management_vmware_data_center_server_test.go b/checkpoint/data_source_checkpoint_management_vmware_data_center_server_test.go new file mode 100644 index 00000000..212ab056 --- /dev/null +++ b/checkpoint/data_source_checkpoint_management_vmware_data_center_server_test.go @@ -0,0 +1,57 @@ +package checkpoint + +import ( + "fmt" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "os" + "testing" +) + +func TestAccDataSourceCheckpointManagementVMwareDataCenterServer_basic(t *testing.T) { + + objName := "tfTestManagementDataVMwareDataCenterServer_" + acctest.RandString(6) + resourceName := "checkpoint_management_vmware_data_center_server.vmware_data_center_server" + dataSourceName := "data.checkpoint_management_vmware_data_center_server.vmware_data_center_server" + vmType := "vcenter" + username := "USERNAME" + password := "PASSWORD" + hostname := "HOSTNAME" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceManagementVMwareDataCenterServerConfig(objName, vmType, username, password, hostname), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), + ), + }, + }, + }) + +} + +func testAccDataSourceManagementVMwareDataCenterServerConfig(name string, vmType string, username string, password string, hostname string) string { + return fmt.Sprintf(` +resource "checkpoint_management_vmware_data_center_server" "vmware_data_center_server" { + name = "%s" + type = "%s" + username = "%s" + password = "%s" + hostname = "%s" + unsafe_auto_accept = true + ignore_warnings = true +} + +data "checkpoint_management_vmware_data_center_server" "vmware_data_center_server" { + name = "${checkpoint_management_vmware_data_center_server.vmware_data_center_server.name}" +} +`, name, vmType, username, password, hostname) +} diff --git a/checkpoint/data_source_checkpoint_management_vpn_community_meshed.go b/checkpoint/data_source_checkpoint_management_vpn_community_meshed.go index 30191961..08f4555a 100644 --- a/checkpoint/data_source_checkpoint_management_vpn_community_meshed.go +++ b/checkpoint/data_source_checkpoint_management_vpn_community_meshed.go @@ -163,7 +163,7 @@ func dataSourceManagementVpnCommunityMeshedRead(d *schema.ResourceData, m interf payload["uid"] = uid } - showVpnCommunityMeshedRes, err := client.ApiCall("show-vpn-community-meshed", payload, client.GetSessionID(), true, false) + showVpnCommunityMeshedRes, err := client.ApiCall("show-vpn-community-meshed", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_vpn_community_remote_access.go b/checkpoint/data_source_checkpoint_management_vpn_community_remote_access.go index 2ae9f2e2..168ba112 100644 --- a/checkpoint/data_source_checkpoint_management_vpn_community_remote_access.go +++ b/checkpoint/data_source_checkpoint_management_vpn_community_remote_access.go @@ -74,7 +74,7 @@ func dataSourceManagementVpnCommunityRemoteAccessRead(d *schema.ResourceData, m payload["uid"] = uid } - showVpnCommunityRemoteAccessRes, err := client.ApiCall("show-vpn-community-remote-access", payload, client.GetSessionID(), true, false) + showVpnCommunityRemoteAccessRes, err := client.ApiCall("show-vpn-community-remote-access", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_vpn_community_star.go b/checkpoint/data_source_checkpoint_management_vpn_community_star.go index 7b4759e1..41f9f6c5 100644 --- a/checkpoint/data_source_checkpoint_management_vpn_community_star.go +++ b/checkpoint/data_source_checkpoint_management_vpn_community_star.go @@ -175,7 +175,7 @@ func dataSourceManagementVpnCommunityStarRead(d *schema.ResourceData, m interfac payload["uid"] = uid } - showVpnCommunityStarRes, err := client.ApiCall("show-vpn-community-star", payload, client.GetSessionID(), true, false) + showVpnCommunityStarRes, err := client.ApiCall("show-vpn-community-star", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/data_source_checkpoint_management_wildcard.go b/checkpoint/data_source_checkpoint_management_wildcard.go index d031b6d5..0dbeeb3d 100644 --- a/checkpoint/data_source_checkpoint_management_wildcard.go +++ b/checkpoint/data_source_checkpoint_management_wildcard.go @@ -86,7 +86,7 @@ func dataSourceManagementWildcardRead(d *schema.ResourceData, m interface{}) err payload["uid"] = uid } - showWildcardRes, err := client.ApiCall("show-wildcard", payload, client.GetSessionID(), true, false) + showWildcardRes, err := client.ApiCall("show-wildcard", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/provider.go b/checkpoint/provider.go index 6cc678db..e1d5a188 100644 --- a/checkpoint/provider.go +++ b/checkpoint/provider.go @@ -61,6 +61,24 @@ func Provider() terraform.ResourceProvider { DefaultFunc: schema.EnvDefaultFunc("CHECKPOINT_SESSION_FILE_NAME", DefaultSessionFilename), Description: "File name used to store the current session id.", }, + "proxy_host": { + Type: schema.TypeString, + Optional: true, + DefaultFunc: schema.EnvDefaultFunc("CHECKPOINT_PROXY_HOST", checkpoint.DefaultProxyHost), + Description: "HTTP proxy server address (without \"http://\").", + }, + "proxy_port": { + Type: schema.TypeInt, + Optional: true, + DefaultFunc: schema.EnvDefaultFunc("CHECKPOINT_PROXY_PORT", checkpoint.DefaultProxyPort), + Description: "HTTP proxy port.", + }, + "api_key": { + Type: schema.TypeString, + Optional: true, + DefaultFunc: schema.EnvDefaultFunc("CHECKPOINT_API_KEY", ""), + Description: "Administrator API key.", + }, }, ResourcesMap: map[string]*schema.Resource{ "checkpoint_management_host": resourceManagementHost(), @@ -165,6 +183,16 @@ func Provider() terraform.ResourceProvider { "checkpoint_management_simple_cluster": resourceManagementSimpleCluster(), "checkpoint_management_threat_profile": resourceManagementThreatProfile(), "checkpoint_management_generic_data_center_server": resourceManagementGenericDataCenterServer(), + "checkpoint_management_vmware_data_center_server": resourceManagementVMwareDataCenterServer(), + "checkpoint_management_aci_data_center_server": resourceManagementAciDataCenterServer(), + "checkpoint_management_ise_data_center_server": resourceManagementIseDataCenterServer(), + "checkpoint_management_aws_data_center_server": resourceManagementAwsDataCenterServer(), + "checkpoint_management_gcp_data_center_server": resourceManagementGcpDataCenterServer(), + "checkpoint_management_azure_data_center_server": resourceManagementAzureDataCenterServer(), + "checkpoint_management_nuage_data_center_server": resourceManagementNuageDataCenterServer(), + "checkpoint_management_openstack_data_center_server": resourceManagementOpenStackDataCenterServer(), + "checkpoint_management_kubernetes_data_center_server": resourceManagementKubernetesDataCenterServer(), + "checkpoint_management_data_center_query": resourceManagementDataCenterQuery(), }, DataSourcesMap: map[string]*schema.Resource{ "checkpoint_management_data_host": dataSourceManagementHost(), @@ -224,6 +252,21 @@ func Provider() terraform.ResourceProvider { "checkpoint_management_simple_gateway": dataSourceManagementSimpleGateway(), "checkpoint_management_threat_profile": dataSourceManagementThreatProfile(), "checkpoint_management_generic_data_center_server": dataSourceManagementGenericDataCenterServer(), + "checkpoint_management_vmware_data_center_server": dataSourceManagementVMwareDataCenterServer(), + "checkpoint_management_aci_data_center_server": dataSourceManagementAciDataCenterServer(), + "checkpoint_management_ise_data_center_server": dataSourceManagementIseDataCenterServer(), + "checkpoint_management_aws_data_center_server": dataSourceManagementAwsDataCenterServer(), + "checkpoint_management_gcp_data_center_server": dataSourceManagementGcpDataCenterServer(), + "checkpoint_management_azure_data_center_server": dataSourceManagementAzureDataCenterServer(), + "checkpoint_management_nuage_data_center_server": dataSourceManagementNuageDataCenterServer(), + "checkpoint_management_openstack_data_center_server": dataSourceManagementOpenStackDataCenterServer(), + "checkpoint_management_kubernetes_data_center_server": dataSourceManagementKubernetesDataCenterServer(), + "checkpoint_management_data_center_query": dataSourceManagementDataCenterQuery(), + "checkpoint_management_data_center_content": dataSourceManagementDataCenterContent(), + "checkpoint_management_access_rulebase": dataSourceManagementAccessRuleBase(), + "checkpoint_management_nat_rulebase": dataSourceManagementNatRuleBase(), + "checkpoint_management_threat_rulebase": dataSourceManagementThreatRuleBase(), + "checkpoint_management_https_rulebase": dataSourceManagementHttpsRuleBase(), }, ConfigureFunc: providerConfigure, } @@ -239,9 +282,12 @@ func providerConfigure(data *schema.ResourceData) (interface{}, error) { port := data.Get("port").(int) timeout := data.Get("timeout").(int) sessionFileName := data.Get("session_file_name").(string) + proxyHost := data.Get("proxy_host").(string) + proxyPort := data.Get("proxy_port").(int) + apiKey := data.Get("api_key").(string) - if server == "" || username == "" || password == "" { - return nil, fmt.Errorf("checkpoint-provider missing parameters to initialize (server, username, password)") + if server == "" || ((username == "" || password == "") && apiKey == "") { + return nil, fmt.Errorf("checkpoint-provider missing parameters to initialize (server, (username and password) OR api_key)") } args := checkpoint.ApiClientArgs{ @@ -249,8 +295,8 @@ func providerConfigure(data *schema.ResourceData) (interface{}, error) { Fingerprint: "", Sid: "", Server: server, - ProxyHost: "", - ProxyPort: -1, + ProxyHost: proxyHost, + ProxyPort: proxyPort, ApiVersion: "", IgnoreServerCertificate: false, AcceptServerCertificate: false, @@ -275,7 +321,7 @@ func providerConfigure(data *schema.ResourceData) (interface{}, error) { mgmt := checkpoint.APIClient(args) if ok := CheckSession(mgmt, s.Uid); !ok { // session is not valid, need to perform login - s, err = login(mgmt, username, password, domain) + s, err = login(mgmt, username, password, apiKey, domain) if err != nil { log.Println("Failed to perform login") return nil, err @@ -288,7 +334,7 @@ func providerConfigure(data *schema.ResourceData) (interface{}, error) { return mgmt, nil case checkpoint.GaiaContext: gaia := checkpoint.APIClient(args) - _, err := login(gaia, username, password, "") + _, err := login(gaia, username, password, "", "") if err != nil { log.Println("Failed to perform login") return nil, err @@ -299,10 +345,15 @@ func providerConfigure(data *schema.ResourceData) (interface{}, error) { } } -func login(client *checkpoint.ApiClient, username string, pwd string, domain string) (Session, error) { +func login(client *checkpoint.ApiClient, username string, pwd string, apiKey string, domain string) (Session, error) { log.Printf("Perform login") - - loginRes, err := client.Login(username, pwd, false, domain, false, "") + var loginRes checkpoint.APIResponse + var err error + if apiKey != "" { + loginRes, err = client.LoginWithApiKey(apiKey, false, domain, false, "") + } else { + loginRes, err = client.Login(username, pwd, false, domain, false, "") + } if err != nil { localRequestsError := "invalid character '<' looking for beginning of value" if strings.Contains(err.Error(), localRequestsError) { diff --git a/checkpoint/resource_checkpoint_hostname.go b/checkpoint/resource_checkpoint_hostname.go index f819aa6c..92cbf485 100644 --- a/checkpoint/resource_checkpoint_hostname.go +++ b/checkpoint/resource_checkpoint_hostname.go @@ -38,7 +38,7 @@ func hostnameParseSchemaToMap(d *schema.ResourceData) map[string]interface{} { func createHostname(d *schema.ResourceData, m interface{}) error { client := m.(*checkpoint.ApiClient) payload := hostnameParseSchemaToMap(d) - setPIRes, _ := client.ApiCall("set-hostname", payload, client.GetSessionID(), true, false) + setPIRes, _ := client.ApiCall("set-hostname", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !setPIRes.Success { return fmt.Errorf(setPIRes.ErrorMsg) } @@ -52,7 +52,7 @@ func createHostname(d *schema.ResourceData, m interface{}) error { func readHostname(d *schema.ResourceData, m interface{}) error { client := m.(*checkpoint.ApiClient) payload := map[string]interface{}{} - showHostnameRes, _ := client.ApiCall("show-hostname", payload, client.GetSessionID(), true, false) + showHostnameRes, _ := client.ApiCall("show-hostname", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !showHostnameRes.Success { // Handle deletion of an object from other clients - Object not found if objectNotFound(showHostnameRes.GetData()["code"].(string)) { @@ -71,7 +71,7 @@ func readHostname(d *schema.ResourceData, m interface{}) error { func updateHostname(d *schema.ResourceData, m interface{}) error { client := m.(*checkpoint.ApiClient) payload := hostnameParseSchemaToMap(d) - setNetworkRes, _ := client.ApiCall("set-hostname", payload, client.GetSessionID(), true, false) + setNetworkRes, _ := client.ApiCall("set-hostname", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !setNetworkRes.Success { return fmt.Errorf(setNetworkRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_access_layer.go b/checkpoint/resource_checkpoint_management_access_layer.go index ad98371a..4b5eabf8 100644 --- a/checkpoint/resource_checkpoint_management_access_layer.go +++ b/checkpoint/resource_checkpoint_management_access_layer.go @@ -167,7 +167,7 @@ func createManagementAccessLayer(d *schema.ResourceData, m interface{}) error { log.Println("Create AccessLayer - Map = ", accessLayer) - addAccessLayerRes, err := client.ApiCall("add-access-layer", accessLayer, client.GetSessionID(), true, false) + addAccessLayerRes, err := client.ApiCall("add-access-layer", accessLayer, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addAccessLayerRes.Success { if addAccessLayerRes.ErrorMsg != "" { return fmt.Errorf(addAccessLayerRes.ErrorMsg) @@ -188,7 +188,7 @@ func readManagementAccessLayer(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showAccessLayerRes, err := client.ApiCall("show-access-layer", payload, client.GetSessionID(), true, false) + showAccessLayerRes, err := client.ApiCall("show-access-layer", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -340,7 +340,7 @@ func updateManagementAccessLayer(d *schema.ResourceData, m interface{}) error { log.Println("Update AccessLayer - Map = ", accessLayer) - updateAccessLayerRes, err := client.ApiCall("set-access-layer", accessLayer, client.GetSessionID(), true, false) + updateAccessLayerRes, err := client.ApiCall("set-access-layer", accessLayer, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateAccessLayerRes.Success { if updateAccessLayerRes.ErrorMsg != "" { return fmt.Errorf(updateAccessLayerRes.ErrorMsg) @@ -361,7 +361,7 @@ func deleteManagementAccessLayer(d *schema.ResourceData, m interface{}) error { log.Println("Delete AccessLayer") - deleteAccessLayerRes, err := client.ApiCall("delete-access-layer", accessLayerPayload, client.GetSessionID(), true, false) + deleteAccessLayerRes, err := client.ApiCall("delete-access-layer", accessLayerPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteAccessLayerRes.Success { if deleteAccessLayerRes.ErrorMsg != "" { return fmt.Errorf(deleteAccessLayerRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_access_point_name.go b/checkpoint/resource_checkpoint_management_access_point_name.go index 19042177..e6db01af 100644 --- a/checkpoint/resource_checkpoint_management_access_point_name.go +++ b/checkpoint/resource_checkpoint_management_access_point_name.go @@ -133,7 +133,7 @@ func createManagementAccessPointName(d *schema.ResourceData, m interface{}) erro log.Println("Create AccessPointName - Map = ", accessPointName) - addAccessPointNameRes, err := client.ApiCall("add-access-point-name", accessPointName, client.GetSessionID(), true, false) + addAccessPointNameRes, err := client.ApiCall("add-access-point-name", accessPointName, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addAccessPointNameRes.Success { if addAccessPointNameRes.ErrorMsg != "" { return fmt.Errorf(addAccessPointNameRes.ErrorMsg) @@ -154,7 +154,7 @@ func readManagementAccessPointName(d *schema.ResourceData, m interface{}) error "uid": d.Id(), } - showAccessPointNameRes, err := client.ApiCall("show-access-point-name", payload, client.GetSessionID(), true, false) + showAccessPointNameRes, err := client.ApiCall("show-access-point-name", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -281,7 +281,7 @@ func updateManagementAccessPointName(d *schema.ResourceData, m interface{}) erro log.Println("Update AccessPointName - Map = ", accessPointName) - updateAccessPointNameRes, err := client.ApiCall("set-access-point-name", accessPointName, client.GetSessionID(), true, false) + updateAccessPointNameRes, err := client.ApiCall("set-access-point-name", accessPointName, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateAccessPointNameRes.Success { if updateAccessPointNameRes.ErrorMsg != "" { return fmt.Errorf(updateAccessPointNameRes.ErrorMsg) @@ -302,7 +302,7 @@ func deleteManagementAccessPointName(d *schema.ResourceData, m interface{}) erro log.Println("Delete AccessPointName") - deleteAccessPointNameRes, err := client.ApiCall("delete-access-point-name", accessPointNamePayload, client.GetSessionID(), true, false) + deleteAccessPointNameRes, err := client.ApiCall("delete-access-point-name", accessPointNamePayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteAccessPointNameRes.Success { if deleteAccessPointNameRes.ErrorMsg != "" { return fmt.Errorf(deleteAccessPointNameRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_access_role.go b/checkpoint/resource_checkpoint_management_access_role.go index c254eb0e..dcb2890c 100644 --- a/checkpoint/resource_checkpoint_management_access_role.go +++ b/checkpoint/resource_checkpoint_management_access_role.go @@ -233,7 +233,7 @@ func createManagementAccessRole(d *schema.ResourceData, m interface{}) error { log.Println("Create AccessRole - Map = ", accessRole) - addAccessRoleRes, err := client.ApiCall("add-access-role", accessRole, client.GetSessionID(), true, false) + addAccessRoleRes, err := client.ApiCall("add-access-role", accessRole, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addAccessRoleRes.Success { if addAccessRoleRes.ErrorMsg != "" { return fmt.Errorf(addAccessRoleRes.ErrorMsg) @@ -253,7 +253,7 @@ func readManagementAccessRole(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showAccessRoleRes, err := client.ApiCall("show-access-role", payload, client.GetSessionID(), true, false) + showAccessRoleRes, err := client.ApiCall("show-access-role", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -549,7 +549,7 @@ func updateManagementAccessRole(d *schema.ResourceData, m interface{}) error { log.Println("Update AccessRole - Map = ", accessRole) - updateAccessRoleRes, err := client.ApiCall("set-access-role", accessRole, client.GetSessionID(), true, false) + updateAccessRoleRes, err := client.ApiCall("set-access-role", accessRole, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateAccessRoleRes.Success { if updateAccessRoleRes.ErrorMsg != "" { return fmt.Errorf(updateAccessRoleRes.ErrorMsg) @@ -570,7 +570,7 @@ func deleteManagementAccessRole(d *schema.ResourceData, m interface{}) error { log.Println("Delete AccessRole") - deleteAccessRoleRes, err := client.ApiCall("delete-access-role", accessRolePayload, client.GetSessionID(), true, false) + deleteAccessRoleRes, err := client.ApiCall("delete-access-role", accessRolePayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteAccessRoleRes.Success { if deleteAccessRoleRes.ErrorMsg != "" { return fmt.Errorf(deleteAccessRoleRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_access_rule.go b/checkpoint/resource_checkpoint_management_access_rule.go index 3922c754..3d108b34 100644 --- a/checkpoint/resource_checkpoint_management_access_rule.go +++ b/checkpoint/resource_checkpoint_management_access_rule.go @@ -506,7 +506,7 @@ func createManagementAccessRule(d *schema.ResourceData, m interface{}) error { log.Println("Create Access Rule - Map = ", accessRule) - addAccessRuleRes, err := client.ApiCall("add-access-rule", accessRule, client.GetSessionID(), true, false) + addAccessRuleRes, err := client.ApiCall("add-access-rule", accessRule, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addAccessRuleRes.Success { if addAccessRuleRes.ErrorMsg != "" { return fmt.Errorf(addAccessRuleRes.ErrorMsg) @@ -528,7 +528,7 @@ func readManagementAccessRule(d *schema.ResourceData, m interface{}) error { "layer": d.Get("layer"), } - showAccessRuleRes, err := client.ApiCall("show-access-rule", payload, client.GetSessionID(), true, false) + showAccessRuleRes, err := client.ApiCall("show-access-rule", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -1109,7 +1109,7 @@ func updateManagementAccessRule(d *schema.ResourceData, m interface{}) error { log.Println("Update Access Rule - Map = ", accessRule) - updateAccessRuleRes, err := client.ApiCall("set-access-rule", accessRule, client.GetSessionID(), true, false) + updateAccessRuleRes, err := client.ApiCall("set-access-rule", accessRule, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateAccessRuleRes.Success { if updateAccessRuleRes.ErrorMsg != "" { return fmt.Errorf(updateAccessRuleRes.ErrorMsg) @@ -1128,7 +1128,7 @@ func deleteManagementAccessRule(d *schema.ResourceData, m interface{}) error { "layer": d.Get("layer"), } - deleteAccessRuleRes, err := client.ApiCall("delete-access-rule", accessRulePayload, client.GetSessionID(), true, false) + deleteAccessRuleRes, err := client.ApiCall("delete-access-rule", accessRulePayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteAccessRuleRes.Success { if deleteAccessRuleRes.ErrorMsg != "" { return fmt.Errorf(deleteAccessRuleRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_access_section.go b/checkpoint/resource_checkpoint_management_access_section.go index 32d2e08a..e6c3e34f 100644 --- a/checkpoint/resource_checkpoint_management_access_section.go +++ b/checkpoint/resource_checkpoint_management_access_section.go @@ -122,7 +122,7 @@ func createManagementAccessSection(d *schema.ResourceData, m interface{}) error log.Println("Create AccessSection - Map = ", accessSection) - addAccessSectionRes, err := client.ApiCall("add-access-section", accessSection, client.GetSessionID(), true, false) + addAccessSectionRes, err := client.ApiCall("add-access-section", accessSection, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addAccessSectionRes.Success { if addAccessSectionRes.ErrorMsg != "" { return fmt.Errorf(addAccessSectionRes.ErrorMsg) @@ -144,7 +144,7 @@ func readManagementAccessSection(d *schema.ResourceData, m interface{}) error { "layer": d.Get("layer"), } - showAccessSectionRes, err := client.ApiCall("show-access-section", payload, client.GetSessionID(), true, false) + showAccessSectionRes, err := client.ApiCall("show-access-section", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -207,7 +207,7 @@ func updateManagementAccessSection(d *schema.ResourceData, m interface{}) error log.Println("Update AccessSection - Map = ", accessSection) - updateAccessSectionRes, err := client.ApiCall("set-access-section", accessSection, client.GetSessionID(), true, false) + updateAccessSectionRes, err := client.ApiCall("set-access-section", accessSection, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateAccessSectionRes.Success { if updateAccessSectionRes.ErrorMsg != "" { return fmt.Errorf(updateAccessSectionRes.ErrorMsg) @@ -229,7 +229,7 @@ func deleteManagementAccessSection(d *schema.ResourceData, m interface{}) error log.Println("Delete AccessSection") - deleteAccessSectionRes, err := client.ApiCall("delete-access-section", accessSectionPayload, client.GetSessionID(), true, false) + deleteAccessSectionRes, err := client.ApiCall("delete-access-section", accessSectionPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteAccessSectionRes.Success { if deleteAccessSectionRes.ErrorMsg != "" { return fmt.Errorf(deleteAccessSectionRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_aci_data_center_server.go b/checkpoint/resource_checkpoint_management_aci_data_center_server.go new file mode 100644 index 00000000..631f1947 --- /dev/null +++ b/checkpoint/resource_checkpoint_management_aci_data_center_server.go @@ -0,0 +1,360 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "log" + "strconv" + "strings" +) + +func resourceManagementAciDataCenterServer() *schema.Resource { + return &schema.Resource{ + Create: createManagementAciDataCenterServer, + Read: readManagementAciDataCenterServer, + Update: updateManagementAciDataCenterServer, + Delete: deleteManagementAciDataCenterServer, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + Description: "Object name. Must be unique in the domain.", + }, + "urls": { + Type: schema.TypeList, + Required: true, + Description: "Address of APIC cluster members.\nExample: http(s)://.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "username": { + Type: schema.TypeString, + Required: true, + Description: "User ID of the Cisco APIC server.\nWhen using commonLoginLogic Domains use the following syntax:\napic:\\.", + }, + "password": { + Type: schema.TypeString, + Optional: true, + Description: "Password of the Cisco APIC server.", + }, + "password_base64": { + Type: schema.TypeString, + Optional: true, + Description: "Password of the Cisco APIC server encoded in Base64.", + }, + "certificate_fingerprint": { + Type: schema.TypeString, + Optional: true, + Description: "Specify the SHA-1 or SHA-256 fingerprint of the Data Center Server's certificate.", + }, + "unsafe_auto_accept": { + Type: schema.TypeBool, + Optional: true, + Description: "When set to false, the current Data Center Server's certificate should be trusted, either by providing the certificate-fingerprint argument or by relying on a previously trusted certificate of this hostname.\n\nWhen set to true, trust the current Data Center Server's certificate as-is.", + Default: false, + }, + "tags": { + Type: schema.TypeSet, + Optional: true, + Description: "Collection of tag identifiers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "color": { + Type: schema.TypeString, + Optional: true, + Description: "Color of the object. Should be one of existing colors.", + Default: "black", + }, + "comments": { + Type: schema.TypeString, + Optional: true, + Description: "Comments string.", + }, + "ignore_warnings": { + Type: schema.TypeBool, + Optional: true, + Description: "Apply changes ignoring warnings. By Setting this parameter to 'true' test connection failure will be ignored.", + Default: false, + }, + "ignore_errors": { + Type: schema.TypeBool, + Optional: true, + Description: "Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored.", + Default: false, + }, + }, + } +} + +func createManagementAciDataCenterServer(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + + aciDataCenterServer := make(map[string]interface{}) + + if v, ok := d.GetOk("name"); ok { + aciDataCenterServer["name"] = v.(string) + } + + aciDataCenterServer["type"] = "aci" + + if v, ok := d.GetOk("urls"); ok { + aciDataCenterServer["urls"] = v + } + + if v, ok := d.GetOk("username"); ok { + aciDataCenterServer["username"] = v.(string) + } + + if v, ok := d.GetOk("password"); ok { + aciDataCenterServer["password"] = v.(string) + } + + if v, ok := d.GetOk("password_base64"); ok { + aciDataCenterServer["password-base64"] = v.(string) + } + + if v, ok := d.GetOk("certificate_fingerprint"); ok { + aciDataCenterServer["certificate-fingerprint"] = v.(string) + } + + if v, ok := d.GetOk("unsafe_auto_accept"); ok { + aciDataCenterServer["unsafe-auto-accept"] = v.(bool) + } + + if v, ok := d.GetOk("tags"); ok { + aciDataCenterServer["tags"] = v.(*schema.Set).List() + } + + if v, ok := d.GetOk("color"); ok { + aciDataCenterServer["color"] = v.(string) + } + + if v, ok := d.GetOk("comments"); ok { + aciDataCenterServer["comments"] = v.(string) + } + + if v, ok := d.GetOkExists("ignore_warnings"); ok { + aciDataCenterServer["ignore-warnings"] = v.(bool) + } + + if v, ok := d.GetOkExists("ignore_errors"); ok { + aciDataCenterServer["ignore-errors"] = v.(bool) + } + + log.Println("Create aciDataCenterServer - Map = ", aciDataCenterServer) + + addAciDataCenterServerRes, err := client.ApiCall("add-data-center-server", aciDataCenterServer, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !addAciDataCenterServerRes.Success { + if addAciDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(addAciDataCenterServerRes.ErrorMsg) + } + msg := createTaskFailMessage("add-data-center-server", addAciDataCenterServerRes.GetData()) + return fmt.Errorf(msg) + } + payload := map[string]interface{}{ + "name": aciDataCenterServer["name"], + } + showAciDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showAciDataCenterServerRes.Success { + return fmt.Errorf(showAciDataCenterServerRes.ErrorMsg) + } + d.SetId(showAciDataCenterServerRes.GetData()["uid"].(string)) + return readManagementAciDataCenterServer(d, m) +} + +func readManagementAciDataCenterServer(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + payload := map[string]interface{}{ + "uid": d.Id(), + } + + showAciDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showAciDataCenterServerRes.Success { + if objectNotFound(showAciDataCenterServerRes.GetData()["code"].(string)) { + d.SetId("") + return nil + } + return fmt.Errorf(showAciDataCenterServerRes.ErrorMsg) + } + aciDataCenterServer := showAciDataCenterServerRes.GetData() + + if v := aciDataCenterServer["name"]; v != nil { + _ = d.Set("name", v) + } + + if aciDataCenterServer["properties"] != nil { + propsJson, ok := aciDataCenterServer["properties"].([]interface{}) + if ok { + for _, prop := range propsJson { + propMap := prop.(map[string]interface{}) + propName := strings.ReplaceAll(propMap["name"].(string), "-", "_") + propValue := propMap["value"] + if propName == "unsafe_auto_accept" { + propValue, _ = strconv.ParseBool(propValue.(string)) + } + if propName == "urls" { + propValue = strings.Split(propValue.(string), ";") + } + _ = d.Set(propName, propValue) + } + } + } + + if aciDataCenterServer["tags"] != nil { + tagsJson, ok := aciDataCenterServer["tags"].([]interface{}) + if ok { + tagsIds := make([]string, 0) + if len(tagsJson) > 0 { + for _, tags := range tagsJson { + tags := tags.(map[string]interface{}) + tagsIds = append(tagsIds, tags["name"].(string)) + } + } + _ = d.Set("tags", tagsIds) + } + } else { + _ = d.Set("tags", nil) + } + + if v := aciDataCenterServer["color"]; v != nil { + _ = d.Set("color", v) + } + + if v := aciDataCenterServer["comments"]; v != nil { + _ = d.Set("comments", v) + } + + if v := aciDataCenterServer["ignore-warnings"]; v != nil { + _ = d.Set("ignore_warnings", v) + } + + if v := aciDataCenterServer["ignore-errors"]; v != nil { + _ = d.Set("ignore_errors", v) + } + + return nil + +} + +func updateManagementAciDataCenterServer(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + aciDataCenterServer := make(map[string]interface{}) + + if ok := d.HasChange("name"); ok { + oldName, newName := d.GetChange("name") + aciDataCenterServer["name"] = oldName + aciDataCenterServer["new-name"] = newName + } else { + aciDataCenterServer["name"] = d.Get("name") + } + + if d.HasChange("urls") { + aciDataCenterServer["urls"] = d.Get("urls") + } + + if d.HasChange("password") { + aciDataCenterServer["password"] = d.Get("password") + } + + if d.HasChange("password_base64") { + aciDataCenterServer["password-base64"] = d.Get("password_base64") + } + + if d.HasChange("username") { + aciDataCenterServer["username"] = d.Get("username") + if v := d.Get("password"); v != nil && v != "" { + aciDataCenterServer["password"] = v + } + if v := d.Get("password_base64"); v != nil && v != "" { + aciDataCenterServer["password-base64"] = v + } + } + + if d.HasChange("certificate_fingerprint") { + aciDataCenterServer["certificate-fingerprint"] = d.Get("certificate_fingerprint") + } + + if d.HasChange("unsafe_auto_accept") { + aciDataCenterServer["unsafe-auto-accept"] = d.Get("unsafe_auto_accept") + } + + if d.HasChange("tags") { + if v, ok := d.GetOk("tags"); ok { + aciDataCenterServer["tags"] = v.(*schema.Set).List() + } else { + oldTags, _ := d.GetChange("tags") + aciDataCenterServer["tags"] = map[string]interface{}{"remove": oldTags.(*schema.Set).List()} + } + } + + if ok := d.HasChange("color"); ok { + aciDataCenterServer["color"] = d.Get("color") + } + + if ok := d.HasChange("comments"); ok { + aciDataCenterServer["comments"] = d.Get("comments") + } + + if v, ok := d.GetOkExists("ignore_warnings"); ok { + aciDataCenterServer["ignore-warnings"] = v.(bool) + } + + if v, ok := d.GetOkExists("ignore_errors"); ok { + aciDataCenterServer["ignore-errors"] = v.(bool) + } + + log.Println("Update aciDataCenterServer - Map = ", aciDataCenterServer) + + updateAciDataCenterServerRes, err := client.ApiCall("set-data-center-server", aciDataCenterServer, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !updateAciDataCenterServerRes.Success { + if updateAciDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(updateAciDataCenterServerRes.ErrorMsg) + } + msg := createTaskFailMessage("set-data-center-server", updateAciDataCenterServerRes.GetData()) + return fmt.Errorf(msg) + } + + return readManagementAciDataCenterServer(d, m) +} + +func deleteManagementAciDataCenterServer(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + + aciDataCenterServerPayload := map[string]interface{}{ + "uid": d.Id(), + } + + log.Println("Delete aciDataCenterServer") + + deleteAciDataCenterServerRes, err := client.ApiCall("delete-data-center-server", aciDataCenterServerPayload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil || !deleteAciDataCenterServerRes.Success { + if deleteAciDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(deleteAciDataCenterServerRes.ErrorMsg) + } + return fmt.Errorf(err.Error()) + } + d.SetId("") + + return nil +} diff --git a/checkpoint/resource_checkpoint_management_aci_data_center_server_test.go b/checkpoint/resource_checkpoint_management_aci_data_center_server_test.go new file mode 100644 index 00000000..565c4295 --- /dev/null +++ b/checkpoint/resource_checkpoint_management_aci_data_center_server_test.go @@ -0,0 +1,110 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + "os" + "strings" + "testing" +) + +func TestAccCheckpointManagementAciDataCenterServer_basic(t *testing.T) { + + var aciDataCenterServerMap map[string]interface{} + resourceName := "checkpoint_management_aci_data_center_server.test" + objName := "tfTestManagementAciDataCenterServer_" + acctest.RandString(6) + username := "USERNAME" + password := "PASSWORD" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } else if context == "" { + t.Skip("Env CHECKPOINT_CONTEXT must be specified to run this acc test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckpointManagementAciDataCenterServerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccManagementAciDataCenterServerConfig(objName, username, password), + Check: resource.ComposeTestCheckFunc( + testAccCheckCheckpointManagementAciDataCenterServerExists(resourceName, &aciDataCenterServerMap), + testAccCheckCheckpointManagementAciDataCenterServerAttributes(&aciDataCenterServerMap, objName), + ), + }, + }, + }) +} + +func testAccCheckpointManagementAciDataCenterServerDestroy(s *terraform.State) error { + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + for _, rs := range s.RootModule().Resources { + if rs.Type != "checkpoint_management_aci_data_center_server" { + continue + } + if rs.Primary.ID != "" { + res, _ := client.ApiCall("show-data-center-server", map[string]interface{}{"uid": rs.Primary.ID}, client.GetSessionID(), true, false) + if res.Success { + return fmt.Errorf("AciDataCenterServer object (%s) still exists", rs.Primary.ID) + } + } + return nil + } + return nil +} + +func testAccCheckCheckpointManagementAciDataCenterServerExists(resourceTfName string, res *map[string]interface{}) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[resourceTfName] + if !ok { + return fmt.Errorf("Resource not found: %s", resourceTfName) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("AciDataCenterServer ID is not set") + } + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + + response, err := client.ApiCall("show-data-center-server", map[string]interface{}{"uid": rs.Primary.ID}, client.GetSessionID(), true, false) + if !response.Success { + return err + } + + *res = response.GetData() + + return nil + } +} + +func testAccCheckCheckpointManagementAciDataCenterServerAttributes(aciDataCenterServerMap *map[string]interface{}, name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + + aciDataCenterServerName := (*aciDataCenterServerMap)["name"].(string) + if !strings.EqualFold(aciDataCenterServerName, name) { + return fmt.Errorf("name is %s, expected %s", name, aciDataCenterServerName) + } + return nil + } +} + +func testAccManagementAciDataCenterServerConfig(name string, username string, password string) string { + return fmt.Sprintf(` +resource "checkpoint_management_aci_data_center_server" "test" { + name = "%s" + username = "%s" + password = "%s" + urls = ["url1", "url2"] + unsafe_auto_accept = true + ignore_warnings = true +} +`, name, username, password) +} diff --git a/checkpoint/resource_checkpoint_management_address_range.go b/checkpoint/resource_checkpoint_management_address_range.go index 2f427775..d9b3406e 100644 --- a/checkpoint/resource_checkpoint_management_address_range.go +++ b/checkpoint/resource_checkpoint_management_address_range.go @@ -185,7 +185,7 @@ func createManagementAddressRange(d *schema.ResourceData, m interface{}) error { log.Println("Create Address Range - Map = ", addressRange) - addAddressRangeRes, err := client.ApiCall("add-address-range", addressRange, client.GetSessionID(), true, false) + addAddressRangeRes, err := client.ApiCall("add-address-range", addressRange, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addAddressRangeRes.Success { if addAddressRangeRes.ErrorMsg != "" { return fmt.Errorf(addAddressRangeRes.ErrorMsg) @@ -206,7 +206,7 @@ func readManagementAddressRange(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showAddressRangeRes, err := client.ApiCall("show-address-range", payload, client.GetSessionID(), true, false) + showAddressRangeRes, err := client.ApiCall("show-address-range", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -392,7 +392,7 @@ func updateManagementAddressRange(d *schema.ResourceData, m interface{}) error { } log.Println("Update Address Range - Map = ", addressRange) - updateAddressRangeRes, err := client.ApiCall("set-address-range", addressRange, client.GetSessionID(), true, false) + updateAddressRangeRes, err := client.ApiCall("set-address-range", addressRange, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateAddressRangeRes.Success { if updateAddressRangeRes.ErrorMsg != "" { return fmt.Errorf(updateAddressRangeRes.ErrorMsg) @@ -411,7 +411,7 @@ func deleteManagementAddressRange(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - deleteAddressRangeRes, err := client.ApiCall("delete-address-range", addressRangePayload, client.GetSessionID(), true, false) + deleteAddressRangeRes, err := client.ApiCall("delete-address-range", addressRangePayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteAddressRangeRes.Success { if deleteAddressRangeRes.ErrorMsg != "" { return fmt.Errorf(deleteAddressRangeRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_application_site.go b/checkpoint/resource_checkpoint_management_application_site.go index 80af6b95..a172c152 100644 --- a/checkpoint/resource_checkpoint_management_application_site.go +++ b/checkpoint/resource_checkpoint_management_application_site.go @@ -150,7 +150,7 @@ func createManagementApplicationSite(d *schema.ResourceData, m interface{}) erro log.Println("Create ApplicationSite - Map = ", applicationSite) - addApplicationSiteRes, err := client.ApiCall("add-application-site", applicationSite, client.GetSessionID(), true, false) + addApplicationSiteRes, err := client.ApiCall("add-application-site", applicationSite, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addApplicationSiteRes.Success { if addApplicationSiteRes.ErrorMsg != "" { return fmt.Errorf(addApplicationSiteRes.ErrorMsg) @@ -171,7 +171,7 @@ func readManagementApplicationSite(d *schema.ResourceData, m interface{}) error "uid": d.Id(), } - showApplicationSiteRes, err := client.ApiCall("show-application-site", payload, client.GetSessionID(), true, false) + showApplicationSiteRes, err := client.ApiCall("show-application-site", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -349,7 +349,7 @@ func updateManagementApplicationSite(d *schema.ResourceData, m interface{}) erro log.Println("Update ApplicationSite - Map = ", applicationSite) - updateApplicationSiteRes, err := client.ApiCall("set-application-site", applicationSite, client.GetSessionID(), true, false) + updateApplicationSiteRes, err := client.ApiCall("set-application-site", applicationSite, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateApplicationSiteRes.Success { if updateApplicationSiteRes.ErrorMsg != "" { return fmt.Errorf(updateApplicationSiteRes.ErrorMsg) @@ -370,7 +370,7 @@ func deleteManagementApplicationSite(d *schema.ResourceData, m interface{}) erro log.Println("Delete ApplicationSite") - deleteApplicationSiteRes, err := client.ApiCall("delete-application-site", applicationSitePayload, client.GetSessionID(), true, false) + deleteApplicationSiteRes, err := client.ApiCall("delete-application-site", applicationSitePayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteApplicationSiteRes.Success { if deleteApplicationSiteRes.ErrorMsg != "" { return fmt.Errorf(deleteApplicationSiteRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_application_site_category.go b/checkpoint/resource_checkpoint_management_application_site_category.go index 6658d222..17a24187 100644 --- a/checkpoint/resource_checkpoint_management_application_site_category.go +++ b/checkpoint/resource_checkpoint_management_application_site_category.go @@ -97,7 +97,7 @@ func createManagementApplicationSiteCategory(d *schema.ResourceData, m interface log.Println("Create ApplicationSiteCategory - Map = ", applicationSiteCategory) - addApplicationSiteCategoryRes, err := client.ApiCall("add-application-site-category", applicationSiteCategory, client.GetSessionID(), true, false) + addApplicationSiteCategoryRes, err := client.ApiCall("add-application-site-category", applicationSiteCategory, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addApplicationSiteCategoryRes.Success { if addApplicationSiteCategoryRes.ErrorMsg != "" { return fmt.Errorf(addApplicationSiteCategoryRes.ErrorMsg) @@ -118,7 +118,7 @@ func readManagementApplicationSiteCategory(d *schema.ResourceData, m interface{} "uid": d.Id(), } - showApplicationSiteCategoryRes, err := client.ApiCall("show-application-site-category", payload, client.GetSessionID(), true, false) + showApplicationSiteCategoryRes, err := client.ApiCall("show-application-site-category", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -222,7 +222,7 @@ func updateManagementApplicationSiteCategory(d *schema.ResourceData, m interface log.Println("Update ApplicationSiteCategory - Map = ", applicationSiteCategory) - updateApplicationSiteCategoryRes, err := client.ApiCall("set-application-site-category", applicationSiteCategory, client.GetSessionID(), true, false) + updateApplicationSiteCategoryRes, err := client.ApiCall("set-application-site-category", applicationSiteCategory, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateApplicationSiteCategoryRes.Success { if updateApplicationSiteCategoryRes.ErrorMsg != "" { return fmt.Errorf(updateApplicationSiteCategoryRes.ErrorMsg) @@ -243,7 +243,7 @@ func deleteManagementApplicationSiteCategory(d *schema.ResourceData, m interface log.Println("Delete ApplicationSiteCategory") - deleteApplicationSiteCategoryRes, err := client.ApiCall("delete-application-site-category", applicationSiteCategoryPayload, client.GetSessionID(), true, false) + deleteApplicationSiteCategoryRes, err := client.ApiCall("delete-application-site-category", applicationSiteCategoryPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteApplicationSiteCategoryRes.Success { if deleteApplicationSiteCategoryRes.ErrorMsg != "" { return fmt.Errorf(deleteApplicationSiteCategoryRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_application_site_group.go b/checkpoint/resource_checkpoint_management_application_site_group.go index ebe85b49..934322cc 100644 --- a/checkpoint/resource_checkpoint_management_application_site_group.go +++ b/checkpoint/resource_checkpoint_management_application_site_group.go @@ -100,7 +100,7 @@ func createManagementApplicationSiteGroup(d *schema.ResourceData, m interface{}) log.Println("Create ApplicationSiteGroup - Map = ", applicationSiteGroup) - addApplicationSiteGroupRes, err := client.ApiCall("add-application-site-group", applicationSiteGroup, client.GetSessionID(), true, false) + addApplicationSiteGroupRes, err := client.ApiCall("add-application-site-group", applicationSiteGroup, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addApplicationSiteGroupRes.Success { if addApplicationSiteGroupRes.ErrorMsg != "" { return fmt.Errorf(addApplicationSiteGroupRes.ErrorMsg) @@ -121,7 +121,7 @@ func readManagementApplicationSiteGroup(d *schema.ResourceData, m interface{}) e "uid": d.Id(), } - showApplicationSiteGroupRes, err := client.ApiCall("show-application-site-group", payload, client.GetSessionID(), true, false) + showApplicationSiteGroupRes, err := client.ApiCall("show-application-site-group", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -242,7 +242,7 @@ func updateManagementApplicationSiteGroup(d *schema.ResourceData, m interface{}) log.Println("Update ApplicationSiteGroup - Map = ", applicationSiteGroup) - updateApplicationSiteGroupRes, err := client.ApiCall("set-application-site-group", applicationSiteGroup, client.GetSessionID(), true, false) + updateApplicationSiteGroupRes, err := client.ApiCall("set-application-site-group", applicationSiteGroup, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateApplicationSiteGroupRes.Success { if updateApplicationSiteGroupRes.ErrorMsg != "" { return fmt.Errorf(updateApplicationSiteGroupRes.ErrorMsg) @@ -263,7 +263,7 @@ func deleteManagementApplicationSiteGroup(d *schema.ResourceData, m interface{}) log.Println("Delete ApplicationSiteGroup") - deleteApplicationSiteGroupRes, err := client.ApiCall("delete-application-site-group", applicationSiteGroupPayload, client.GetSessionID(), true, false) + deleteApplicationSiteGroupRes, err := client.ApiCall("delete-application-site-group", applicationSiteGroupPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteApplicationSiteGroupRes.Success { if deleteApplicationSiteGroupRes.ErrorMsg != "" { return fmt.Errorf(deleteApplicationSiteGroupRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_aws_data_center_server.go b/checkpoint/resource_checkpoint_management_aws_data_center_server.go new file mode 100644 index 00000000..14e5c559 --- /dev/null +++ b/checkpoint/resource_checkpoint_management_aws_data_center_server.go @@ -0,0 +1,365 @@ +package checkpoint + +import ( + "fmt" + "log" + "strconv" + "strings" + + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func resourceManagementAwsDataCenterServer() *schema.Resource { + return &schema.Resource{ + Create: createManagementAwsDataCenterServer, + Read: readManagementAwsDataCenterServer, + Update: updateManagementAwsDataCenterServer, + Delete: deleteManagementAwsDataCenterServer, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + Description: "Object name. Must be unique in the domain.", + }, + "authentication_method": { + Type: schema.TypeString, + Required: true, + Description: "user-authentication\nUses the Access keys to authenticate.\nrole-authentication\nUses the AWS IAM role to authenticate.\nThis option requires the Security Management Server be deployed in AWS and has an IAM Role.", + }, + "access_key_id": { + Type: schema.TypeString, + Optional: true, + Description: "Access key ID for the AWS account.\nRequired for authentication-method: user-authentication.", + }, + "secret_access_key": { + Type: schema.TypeString, + Optional: true, + Description: "Secret access key for the AWS account.\nRequired for authentication-method: user-authentication.", + }, + "region": { + Type: schema.TypeString, + Required: true, + Description: "Select the AWS region.", + }, + "enable_sts_assume_role": { + Type: schema.TypeBool, + Optional: true, + Description: "Enables the STS Assume Role option. After it is enabled, the sts-role field is mandatory, whereas the sts-external-id is optional.", + Default: false, + }, + "sts_role": { + Type: schema.TypeString, + Optional: true, + Description: "The STS RoleARN of the role to be assumed.\nRequired for enable-sts-assume-role: true.", + }, + "sts_external_id": { + Type: schema.TypeString, + Optional: true, + Description: "An optional STS External-Id to use when assuming the role.", + }, + "tags": { + Type: schema.TypeSet, + Optional: true, + Description: "Collection of tag identifiers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "color": { + Type: schema.TypeString, + Optional: true, + Description: "Color of the object. Should be one of existing colors.", + Default: "black", + }, + "comments": { + Type: schema.TypeString, + Optional: true, + Description: "Comments string.", + }, + "ignore_warnings": { + Type: schema.TypeBool, + Optional: true, + Description: "Apply changes ignoring warnings. By Setting this parameter to 'true' test connection failure will be ignored.", + Default: false, + }, + "ignore_errors": { + Type: schema.TypeBool, + Optional: true, + Description: "Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored.", + Default: false, + }, + }, + } +} + +func createManagementAwsDataCenterServer(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + + awsDataCenterServer := make(map[string]interface{}) + + if v, ok := d.GetOk("name"); ok { + awsDataCenterServer["name"] = v.(string) + } + + awsDataCenterServer["type"] = "aws" + + if v, ok := d.GetOk("authentication_method"); ok { + awsDataCenterServer["authentication-method"] = v.(string) + } + + if v, ok := d.GetOk("access_key_id"); ok { + awsDataCenterServer["access-key-id"] = v.(string) + } + + if v, ok := d.GetOk("secret_access_key"); ok { + awsDataCenterServer["secret-access-key"] = v.(string) + } + + if v, ok := d.GetOk("region"); ok { + awsDataCenterServer["region"] = v.(string) + } + + if v, ok := d.GetOk("enable_sts_assume_role"); ok { + awsDataCenterServer["enable-sts-assume-role"] = v.(string) + } + + if v, ok := d.GetOk("sts_role"); ok { + awsDataCenterServer["sts-role"] = v.(string) + } + + if v, ok := d.GetOk("sts_external_id"); ok { + awsDataCenterServer["custom-value"] = v.(string) + } + + if v, ok := d.GetOk("tags"); ok { + awsDataCenterServer["tags"] = v.(*schema.Set).List() + } + + if v, ok := d.GetOk("color"); ok { + awsDataCenterServer["color"] = v.(string) + } + + if v, ok := d.GetOk("comments"); ok { + awsDataCenterServer["comments"] = v.(string) + } + + if v, ok := d.GetOkExists("ignore_warnings"); ok { + awsDataCenterServer["ignore-warnings"] = v.(bool) + } + + if v, ok := d.GetOkExists("ignore_errors"); ok { + awsDataCenterServer["ignore-errors"] = v.(bool) + } + + log.Println("Create awsDataCenterServer - Map = ", awsDataCenterServer) + + addAwsDataCenterServerRes, err := client.ApiCall("add-data-center-server", awsDataCenterServer, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !addAwsDataCenterServerRes.Success { + if addAwsDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(addAwsDataCenterServerRes.ErrorMsg) + } + msg := createTaskFailMessage("add-data-center-server", addAwsDataCenterServerRes.GetData()) + return fmt.Errorf(msg) + } + payload := map[string]interface{}{ + "name": awsDataCenterServer["name"], + } + showAwsDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showAwsDataCenterServerRes.Success { + return fmt.Errorf(showAwsDataCenterServerRes.ErrorMsg) + } + d.SetId(showAwsDataCenterServerRes.GetData()["uid"].(string)) + return readManagementAwsDataCenterServer(d, m) +} + +func readManagementAwsDataCenterServer(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + payload := map[string]interface{}{ + "uid": d.Id(), + } + + showAwsDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showAwsDataCenterServerRes.Success { + if objectNotFound(showAwsDataCenterServerRes.GetData()["code"].(string)) { + d.SetId("") + return nil + } + return fmt.Errorf(showAwsDataCenterServerRes.ErrorMsg) + } + awsDataCenterServer := showAwsDataCenterServerRes.GetData() + + if v := awsDataCenterServer["name"]; v != nil { + _ = d.Set("name", v) + } + + if awsDataCenterServer["properties"] != nil { + propsJson, ok := awsDataCenterServer["properties"].([]interface{}) + if ok { + for _, prop := range propsJson { + propMap := prop.(map[string]interface{}) + propName := strings.ReplaceAll(propMap["name"].(string), "-", "_") + propValue := propMap["value"] + if propName == "enable_sts_assume_role" { + propValue, _ = strconv.ParseBool(propValue.(string)) + } + _ = d.Set(propName, propValue) + } + } + } + + if awsDataCenterServer["tags"] != nil { + tagsJson, ok := awsDataCenterServer["tags"].([]interface{}) + if ok { + tagsIds := make([]string, 0) + if len(tagsJson) > 0 { + for _, tags := range tagsJson { + tags := tags.(map[string]interface{}) + tagsIds = append(tagsIds, tags["name"].(string)) + } + } + _ = d.Set("tags", tagsIds) + } + } else { + _ = d.Set("tags", nil) + } + + if v := awsDataCenterServer["color"]; v != nil { + _ = d.Set("color", v) + } + + if v := awsDataCenterServer["comments"]; v != nil { + _ = d.Set("comments", v) + } + + if v := awsDataCenterServer["ignore-warnings"]; v != nil { + _ = d.Set("ignore_warnings", v) + } + + if v := awsDataCenterServer["ignore-errors"]; v != nil { + _ = d.Set("ignore_errors", v) + } + + return nil + +} + +func updateManagementAwsDataCenterServer(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + awsDataCenterServer := make(map[string]interface{}) + + if ok := d.HasChange("name"); ok { + oldName, newName := d.GetChange("name") + awsDataCenterServer["name"] = oldName + awsDataCenterServer["new-name"] = newName + } else { + awsDataCenterServer["name"] = d.Get("name") + } + + if ok := d.HasChange("secret_access_key"); ok { + awsDataCenterServer["secret-access-key"] = d.Get("secret_access_key") + } + + if ok := d.HasChange("authentication_method"); ok { + awsDataCenterServer["authentication-method"] = d.Get("authentication_method") + if awsDataCenterServer["authentication-method"] == "user-authentication" { + awsDataCenterServer["secret-access-key"] = d.Get("secret_access_key") + } + } + + if ok := d.HasChange("access_key_id"); ok { + awsDataCenterServer["access-key-id"] = d.Get("access_key_id") + } + + if ok := d.HasChange("region"); ok { + awsDataCenterServer["region"] = d.Get("region") + } + + if ok := d.HasChange("enable_sts_assume_role"); ok { + awsDataCenterServer["enable-sts-assume-role"] = d.Get("enable_sts_assume_role") + } + + if ok := d.HasChange("sts_role"); ok { + awsDataCenterServer["sts-role"] = d.Get("sts_role") + } + + if ok := d.HasChange("sts_external_id"); ok { + awsDataCenterServer["sts-external-id"] = d.Get("sts_external_id") + } + + if d.HasChange("tags") { + if v, ok := d.GetOk("tags"); ok { + awsDataCenterServer["tags"] = v.(*schema.Set).List() + } else { + oldTags, _ := d.GetChange("tags") + awsDataCenterServer["tags"] = map[string]interface{}{"remove": oldTags.(*schema.Set).List()} + } + } + + if ok := d.HasChange("color"); ok { + awsDataCenterServer["color"] = d.Get("color") + } + + if ok := d.HasChange("comments"); ok { + awsDataCenterServer["comments"] = d.Get("comments") + } + + if v, ok := d.GetOkExists("ignore_warnings"); ok { + awsDataCenterServer["ignore-warnings"] = v.(bool) + } + + if v, ok := d.GetOkExists("ignore_errors"); ok { + awsDataCenterServer["ignore-errors"] = v.(bool) + } + + log.Println("Update awsDataCenterServer - Map = ", awsDataCenterServer) + + updateAwsDataCenterServerRes, err := client.ApiCall("set-data-center-server", awsDataCenterServer, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !updateAwsDataCenterServerRes.Success { + if updateAwsDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(updateAwsDataCenterServerRes.ErrorMsg) + } + msg := createTaskFailMessage("set-data-center-server", updateAwsDataCenterServerRes.GetData()) + return fmt.Errorf(msg) + } + + return readManagementAwsDataCenterServer(d, m) +} + +func deleteManagementAwsDataCenterServer(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + + awsDataCenterServerPayload := map[string]interface{}{ + "uid": d.Id(), + } + + log.Println("Delete awsDataCenterServer") + + deleteAwsDataCenterServerRes, err := client.ApiCall("delete-data-center-server", awsDataCenterServerPayload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil || !deleteAwsDataCenterServerRes.Success { + if deleteAwsDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(deleteAwsDataCenterServerRes.ErrorMsg) + } + return fmt.Errorf(err.Error()) + } + d.SetId("") + + return nil +} diff --git a/checkpoint/resource_checkpoint_management_aws_data_center_server_test.go b/checkpoint/resource_checkpoint_management_aws_data_center_server_test.go new file mode 100644 index 00000000..14e5593c --- /dev/null +++ b/checkpoint/resource_checkpoint_management_aws_data_center_server_test.go @@ -0,0 +1,112 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + "os" + "strings" + "testing" +) + +func TestAccCheckpointManagementAwsDataCenterServer_basic(t *testing.T) { + + var awsDataCenterServerMap map[string]interface{} + resourceName := "checkpoint_management_aws_data_center_server.test" + objName := "tfTestManagementAwsDataCenterServer_" + acctest.RandString(6) + authenticationMethod := "user-authentication" + accessKeyId := "MY-KEY-ID" + secretAccessKey := "MY-SECRET-KEY" + region := "us-east-1" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } else if context == "" { + t.Skip("Env CHECKPOINT_CONTEXT must be specified to run this acc test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckpointManagementAwsDataCenterServerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccManagementAwsDataCenterServerConfig(objName, authenticationMethod, accessKeyId, secretAccessKey, region), + Check: resource.ComposeTestCheckFunc( + testAccCheckCheckpointManagementAwsDataCenterServerExists(resourceName, &awsDataCenterServerMap), + testAccCheckCheckpointManagementAwsDataCenterServerAttributes(&awsDataCenterServerMap, objName), + ), + }, + }, + }) +} + +func testAccCheckpointManagementAwsDataCenterServerDestroy(s *terraform.State) error { + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + for _, rs := range s.RootModule().Resources { + if rs.Type != "checkpoint_management_aws_data_center_server" { + continue + } + if rs.Primary.ID != "" { + res, _ := client.ApiCall("show-data-center-server", map[string]interface{}{"uid": rs.Primary.ID}, client.GetSessionID(), true, false) + if res.Success { + return fmt.Errorf("AwsDataCenterServer object (%s) still exists", rs.Primary.ID) + } + } + return nil + } + return nil +} + +func testAccCheckCheckpointManagementAwsDataCenterServerExists(resourceTfName string, res *map[string]interface{}) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[resourceTfName] + if !ok { + return fmt.Errorf("Resource not found: %s", resourceTfName) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("AwsDataCenterServer ID is not set") + } + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + + response, err := client.ApiCall("show-data-center-server", map[string]interface{}{"uid": rs.Primary.ID}, client.GetSessionID(), true, false) + if !response.Success { + return err + } + + *res = response.GetData() + + return nil + } +} + +func testAccCheckCheckpointManagementAwsDataCenterServerAttributes(awsDataCenterServerMap *map[string]interface{}, name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + + awsDataCenterServerName := (*awsDataCenterServerMap)["name"].(string) + if !strings.EqualFold(awsDataCenterServerName, name) { + return fmt.Errorf("name is %s, expected %s", name, awsDataCenterServerName) + } + return nil + } +} + +func testAccManagementAwsDataCenterServerConfig(name string, authenticationMethod string, accessKeyId string, secretAccessKey string, region string) string { + return fmt.Sprintf(` +resource "checkpoint_management_aws_data_center_server" "test" { + name = "%s" + authentication_method = "%s" + access_key_id = "%s" + secret_access_key = "%s" + region = "%s" + ignore_warnings = true +} +`, name, authenticationMethod, accessKeyId, secretAccessKey, region) +} diff --git a/checkpoint/resource_checkpoint_management_azure_data_center_server.go b/checkpoint/resource_checkpoint_management_azure_data_center_server.go new file mode 100644 index 00000000..a04d8159 --- /dev/null +++ b/checkpoint/resource_checkpoint_management_azure_data_center_server.go @@ -0,0 +1,376 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "log" + "strings" +) + +func resourceManagementAzureDataCenterServer() *schema.Resource { + return &schema.Resource{ + Create: createManagementAzureDataCenterServer, + Read: readManagementAzureDataCenterServer, + Update: updateManagementAzureDataCenterServer, + Delete: deleteManagementAzureDataCenterServer, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + Description: "Object name. Must be unique in the domain.", + }, + "authentication_method": { + Type: schema.TypeString, + Required: true, + Description: "user-authentication\nUses the Azure AD User to authenticate.\nservice-principal-authentication\nUses the Service Principal to authenticate.", + }, + "username": { + Type: schema.TypeString, + Optional: true, + Description: "An Azure Active Directory user Format @.\nRequired for authentication-method: user-authentication.", + }, + "password": { + Type: schema.TypeString, + Optional: true, + Description: "Password of the Azure account.\nRequired for authentication-method: user-authentication.", + }, + "password_base64": { + Type: schema.TypeString, + Optional: true, + Description: "Password of the Azure account encoded in Base64.\nRequired for authentication-method: user-authentication.", + }, + "application_id": { + Type: schema.TypeString, + Optional: true, + Description: "The Application ID of the Service Principal, in UUID format.\nRequired for authentication-method: service-principal-authentication.", + }, + "application_key": { + Type: schema.TypeBool, + Optional: true, + Description: "The key created for the Service Principal.\nRequired for authentication-method: service-principal-authentication.", + Default: false, + }, + "directory_id": { + Type: schema.TypeString, + Optional: true, + Description: "The Directory ID of the Azure AD, in UUID format.\nRequired for authentication-method: service-principal-authentication.", + }, + "environment": { + Type: schema.TypeString, + Optional: true, + Description: "Select the Azure Cloud Environment.", + Default: "AzureCloud", + }, + "tags": { + Type: schema.TypeSet, + Optional: true, + Description: "Collection of tag identifiers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "color": { + Type: schema.TypeString, + Optional: true, + Description: "Color of the object. Should be one of existing colors.", + Default: "black", + }, + "comments": { + Type: schema.TypeString, + Optional: true, + Description: "Comments string.", + }, + "ignore_warnings": { + Type: schema.TypeBool, + Optional: true, + Description: "Apply changes ignoring warnings. By Setting this parameter to 'true' test connection failure will be ignored.", + Default: false, + }, + "ignore_errors": { + Type: schema.TypeBool, + Optional: true, + Description: "Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored.", + Default: false, + }, + }, + } +} + +func createManagementAzureDataCenterServer(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + + azureDataCenterServer := make(map[string]interface{}) + + if v, ok := d.GetOk("name"); ok { + azureDataCenterServer["name"] = v.(string) + } + + azureDataCenterServer["type"] = "azure" + + if v, ok := d.GetOk("authentication_method"); ok { + azureDataCenterServer["authentication-method"] = v.(string) + } + + if v, ok := d.GetOk("username"); ok { + azureDataCenterServer["username"] = v.(string) + } + + if v, ok := d.GetOk("password"); ok { + azureDataCenterServer["password"] = v.(string) + } + + if v, ok := d.GetOk("password_base64"); ok { + azureDataCenterServer["password-base64"] = v.(string) + } + + if v, ok := d.GetOk("application_id"); ok { + azureDataCenterServer["application-id"] = v.(string) + } + + if v, ok := d.GetOk("application_key"); ok { + azureDataCenterServer["application-key"] = v.(string) + } + + if v, ok := d.GetOk("directory_id"); ok { + azureDataCenterServer["directory-id"] = v.(string) + } + if v, ok := d.GetOk("environment"); ok { + azureDataCenterServer["environment"] = v.(string) + } + + if v, ok := d.GetOk("tags"); ok { + azureDataCenterServer["tags"] = v.(*schema.Set).List() + } + + if v, ok := d.GetOk("color"); ok { + azureDataCenterServer["color"] = v.(string) + } + + if v, ok := d.GetOk("comments"); ok { + azureDataCenterServer["comments"] = v.(string) + } + + if v, ok := d.GetOkExists("ignore_warnings"); ok { + azureDataCenterServer["ignore-warnings"] = v.(bool) + } + + if v, ok := d.GetOkExists("ignore_errors"); ok { + azureDataCenterServer["ignore-errors"] = v.(bool) + } + + log.Println("Create azureDataCenterServer - Map = ", azureDataCenterServer) + + addAzureDataCenterServerRes, err := client.ApiCall("add-data-center-server", azureDataCenterServer, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !addAzureDataCenterServerRes.Success { + if addAzureDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(addAzureDataCenterServerRes.ErrorMsg) + } + msg := createTaskFailMessage("add-data-center-server", addAzureDataCenterServerRes.GetData()) + return fmt.Errorf(msg) + } + payload := map[string]interface{}{ + "name": azureDataCenterServer["name"], + } + showAzureDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showAzureDataCenterServerRes.Success { + return fmt.Errorf(showAzureDataCenterServerRes.ErrorMsg) + } + d.SetId(showAzureDataCenterServerRes.GetData()["uid"].(string)) + return readManagementAzureDataCenterServer(d, m) +} + +func readManagementAzureDataCenterServer(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + payload := map[string]interface{}{ + "uid": d.Id(), + } + + showAzureDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showAzureDataCenterServerRes.Success { + if objectNotFound(showAzureDataCenterServerRes.GetData()["code"].(string)) { + d.SetId("") + return nil + } + return fmt.Errorf(showAzureDataCenterServerRes.ErrorMsg) + } + azureDataCenterServer := showAzureDataCenterServerRes.GetData() + + if v := azureDataCenterServer["name"]; v != nil { + _ = d.Set("name", v) + } + + if azureDataCenterServer["properties"] != nil { + propsJson, ok := azureDataCenterServer["properties"].([]interface{}) + if ok { + for _, prop := range propsJson { + propMap := prop.(map[string]interface{}) + propName := strings.ReplaceAll(propMap["name"].(string), "-", "_") + propValue := propMap["value"] + _ = d.Set(propName, propValue) + } + } + } + + if azureDataCenterServer["tags"] != nil { + tagsJson, ok := azureDataCenterServer["tags"].([]interface{}) + if ok { + tagsIds := make([]string, 0) + if len(tagsJson) > 0 { + for _, tags := range tagsJson { + tags := tags.(map[string]interface{}) + tagsIds = append(tagsIds, tags["name"].(string)) + } + } + _ = d.Set("tags", tagsIds) + } + } else { + _ = d.Set("tags", nil) + } + + if v := azureDataCenterServer["color"]; v != nil { + _ = d.Set("color", v) + } + + if v := azureDataCenterServer["comments"]; v != nil { + _ = d.Set("comments", v) + } + + if v := azureDataCenterServer["ignore-warnings"]; v != nil { + _ = d.Set("ignore_warnings", v) + } + + if v := azureDataCenterServer["ignore-errors"]; v != nil { + _ = d.Set("ignore_errors", v) + } + + return nil + +} + +func updateManagementAzureDataCenterServer(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + azureDataCenterServer := make(map[string]interface{}) + + if ok := d.HasChange("name"); ok { + oldName, newName := d.GetChange("name") + azureDataCenterServer["name"] = oldName + azureDataCenterServer["new-name"] = newName + } else { + azureDataCenterServer["name"] = d.Get("name") + } + + if ok := d.HasChange("authentication_method"); ok { + azureDataCenterServer["authentication-method"] = d.Get("authentication_method") + } + + if ok := d.HasChange("password"); ok { + azureDataCenterServer["password"] = d.Get("password") + } + + if ok := d.HasChange("password_base64"); ok { + azureDataCenterServer["password-base64"] = d.Get("password_base64") + } + + if d.HasChange("username") { + azureDataCenterServer["username"] = d.Get("username") + if v := d.Get("password"); v != nil && v != "" { + azureDataCenterServer["password"] = v + } + if v := d.Get("password_base64"); v != nil && v != "" { + azureDataCenterServer["password-base64"] = v + } + } + + if ok := d.HasChange("application_id"); ok { + azureDataCenterServer["application-id"] = d.Get("application_id") + } + + if ok := d.HasChange("application_key"); ok { + azureDataCenterServer["application-key"] = d.Get("application_key") + } + + if ok := d.HasChange("directory_id"); ok { + azureDataCenterServer["directory-id"] = d.Get("directory_id") + } + + if ok := d.HasChange("environment"); ok { + azureDataCenterServer["environment"] = d.Get("environment") + } + + if d.HasChange("tags") { + if v, ok := d.GetOk("tags"); ok { + azureDataCenterServer["tags"] = v.(*schema.Set).List() + } else { + oldTags, _ := d.GetChange("tags") + azureDataCenterServer["tags"] = map[string]interface{}{"remove": oldTags.(*schema.Set).List()} + } + } + + if ok := d.HasChange("color"); ok { + azureDataCenterServer["color"] = d.Get("color") + } + + if ok := d.HasChange("comments"); ok { + azureDataCenterServer["comments"] = d.Get("comments") + } + + if v, ok := d.GetOkExists("ignore_warnings"); ok { + azureDataCenterServer["ignore-warnings"] = v.(bool) + } + + if v, ok := d.GetOkExists("ignore_errors"); ok { + azureDataCenterServer["ignore-errors"] = v.(bool) + } + + log.Println("Update azureDataCenterServer - Map = ", azureDataCenterServer) + + updateAzureDataCenterServerRes, err := client.ApiCall("set-data-center-server", azureDataCenterServer, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !updateAzureDataCenterServerRes.Success { + if updateAzureDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(updateAzureDataCenterServerRes.ErrorMsg) + } + msg := createTaskFailMessage("set-data-center-server", updateAzureDataCenterServerRes.GetData()) + return fmt.Errorf(msg) + } + + return readManagementAzureDataCenterServer(d, m) +} + +func deleteManagementAzureDataCenterServer(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + + azureDataCenterServerPayload := map[string]interface{}{ + "uid": d.Id(), + } + + log.Println("Delete azureDataCenterServer") + + deleteAzureDataCenterServerRes, err := client.ApiCall("delete-data-center-server", azureDataCenterServerPayload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil || !deleteAzureDataCenterServerRes.Success { + if deleteAzureDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(deleteAzureDataCenterServerRes.ErrorMsg) + } + return fmt.Errorf(err.Error()) + } + d.SetId("") + + return nil +} diff --git a/checkpoint/resource_checkpoint_management_azure_data_center_server_test.go b/checkpoint/resource_checkpoint_management_azure_data_center_server_test.go new file mode 100644 index 00000000..28ad335c --- /dev/null +++ b/checkpoint/resource_checkpoint_management_azure_data_center_server_test.go @@ -0,0 +1,110 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + "os" + "strings" + "testing" +) + +func TestAccCheckpointManagementAzureDataCenterServer_basic(t *testing.T) { + + var azureDataCenterServerMap map[string]interface{} + resourceName := "checkpoint_management_azure_data_center_server.test" + objName := "tfTestManagementAzureDataCenterServer_" + acctest.RandString(6) + authenticationMethod := "user-authentication" + username := "MY-KEY-ID" + password := "MY-SECRET-KEY" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } else if context == "" { + t.Skip("Env CHECKPOINT_CONTEXT must be specified to run this acc test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckpointManagementAzureDataCenterServerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccManagementAzureDataCenterServerConfig(objName, username, password, authenticationMethod), + Check: resource.ComposeTestCheckFunc( + testAccCheckCheckpointManagementAzureDataCenterServerExists(resourceName, &azureDataCenterServerMap), + testAccCheckCheckpointManagementAzureDataCenterServerAttributes(&azureDataCenterServerMap, objName), + ), + }, + }, + }) +} + +func testAccCheckpointManagementAzureDataCenterServerDestroy(s *terraform.State) error { + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + for _, rs := range s.RootModule().Resources { + if rs.Type != "checkpoint_management_azure_data_center_server" { + continue + } + if rs.Primary.ID != "" { + res, _ := client.ApiCall("show-data-center-server", map[string]interface{}{"uid": rs.Primary.ID}, client.GetSessionID(), true, false) + if res.Success { + return fmt.Errorf("AzureDataCenterServer object (%s) still exists", rs.Primary.ID) + } + } + return nil + } + return nil +} + +func testAccCheckCheckpointManagementAzureDataCenterServerExists(resourceTfName string, res *map[string]interface{}) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[resourceTfName] + if !ok { + return fmt.Errorf("Resource not found: %s", resourceTfName) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("AzureDataCenterServer ID is not set") + } + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + + response, err := client.ApiCall("show-data-center-server", map[string]interface{}{"uid": rs.Primary.ID}, client.GetSessionID(), true, false) + if !response.Success { + return err + } + + *res = response.GetData() + + return nil + } +} + +func testAccCheckCheckpointManagementAzureDataCenterServerAttributes(azureDataCenterServerMap *map[string]interface{}, name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + + azureDataCenterServerName := (*azureDataCenterServerMap)["name"].(string) + if !strings.EqualFold(azureDataCenterServerName, name) { + return fmt.Errorf("name is %s, expected %s", name, azureDataCenterServerName) + } + return nil + } +} + +func testAccManagementAzureDataCenterServerConfig(name string, username string, password string, authenticationMethod string) string { + return fmt.Sprintf(` +resource "checkpoint_management_azure_data_center_server" "test" { + name = "%s" + username = "%s" + password = "%s" + authentication_method = "%s" + ignore_warnings = true +} +`, name, username, password, authenticationMethod) +} diff --git a/checkpoint/resource_checkpoint_management_checkpoint_host.go b/checkpoint/resource_checkpoint_management_checkpoint_host.go index 273c2503..f7f1ac9f 100644 --- a/checkpoint/resource_checkpoint_management_checkpoint_host.go +++ b/checkpoint/resource_checkpoint_management_checkpoint_host.go @@ -708,7 +708,7 @@ func createManagementCheckpointHost(d *schema.ResourceData, m interface{}) error log.Println("Create CheckpointHost - Map = ", checkpointHost) - addCheckpointHostRes, err := client.ApiCall("add-checkpoint-host", checkpointHost, client.GetSessionID(), true, false) + addCheckpointHostRes, err := client.ApiCall("add-checkpoint-host", checkpointHost, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addCheckpointHostRes.Success { if addCheckpointHostRes.ErrorMsg != "" { return fmt.Errorf(addCheckpointHostRes.ErrorMsg) @@ -729,7 +729,7 @@ func readManagementCheckpointHost(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showCheckpointHostRes, err := client.ApiCall("show-checkpoint-host", payload, client.GetSessionID(), true, false) + showCheckpointHostRes, err := client.ApiCall("show-checkpoint-host", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -1396,7 +1396,7 @@ func updateManagementCheckpointHost(d *schema.ResourceData, m interface{}) error log.Println("Update CheckpointHost - Map = ", checkpointHost) - updateCheckpointHostRes, err := client.ApiCall("set-checkpoint-host", checkpointHost, client.GetSessionID(), true, false) + updateCheckpointHostRes, err := client.ApiCall("set-checkpoint-host", checkpointHost, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateCheckpointHostRes.Success { if updateCheckpointHostRes.ErrorMsg != "" { return fmt.Errorf(updateCheckpointHostRes.ErrorMsg) @@ -1416,7 +1416,7 @@ func deleteManagementCheckpointHost(d *schema.ResourceData, m interface{}) error log.Println("Delete CheckpointHost") - deleteCheckpointHostRes, err := client.ApiCall("delete-checkpoint-host", checkpointHostPayload, client.GetSessionID(), true, false) + deleteCheckpointHostRes, err := client.ApiCall("delete-checkpoint-host", checkpointHostPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteCheckpointHostRes.Success { if deleteCheckpointHostRes.ErrorMsg != "" { return fmt.Errorf(deleteCheckpointHostRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_command_add_api_key.go b/checkpoint/resource_checkpoint_management_command_add_api_key.go index 18ca6079..80926c3a 100644 --- a/checkpoint/resource_checkpoint_management_command_add_api_key.go +++ b/checkpoint/resource_checkpoint_management_command_add_api_key.go @@ -28,7 +28,7 @@ func resourceManagementAddApiKey() *schema.Resource { "api_key": { Type: schema.TypeString, Computed: true, - Description: "Represents the API Key to be used for Login.", + Description: "Represents the API Key to be used for commonLoginLogic.", }, }, } @@ -46,7 +46,7 @@ func createManagementAddApiKey(d *schema.ResourceData, m interface{}) error { payload["admin-name"] = v.(string) } - AddApiKeyRes, _ := client.ApiCall("add-api-key", payload, client.GetSessionID(), true, false) + AddApiKeyRes, _ := client.ApiCall("add-api-key", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !AddApiKeyRes.Success { return fmt.Errorf(AddApiKeyRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_add_data_center_object.go b/checkpoint/resource_checkpoint_management_command_add_data_center_object.go index b79d618b..0a357601 100644 --- a/checkpoint/resource_checkpoint_management_command_add_data_center_object.go +++ b/checkpoint/resource_checkpoint_management_command_add_data_center_object.go @@ -136,7 +136,7 @@ func createManagementAddDataCenterObject(d *schema.ResourceData, m interface{}) payload["ignore-errors"] = v.(bool) } - AddDataCenterObjectRes, _ := client.ApiCall("add-data-center-object", payload, client.GetSessionID(), true, false) + AddDataCenterObjectRes, _ := client.ApiCall("add-data-center-object", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !AddDataCenterObjectRes.Success { return fmt.Errorf(AddDataCenterObjectRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_add_threat_protections.go b/checkpoint/resource_checkpoint_management_command_add_threat_protections.go index b1a63834..1ec31d42 100644 --- a/checkpoint/resource_checkpoint_management_command_add_threat_protections.go +++ b/checkpoint/resource_checkpoint_management_command_add_threat_protections.go @@ -46,7 +46,7 @@ func createManagementAddThreatProtections(d *schema.ResourceData, m interface{}) payload["package-path"] = v.(string) } - AddThreatProtectionsRes, _ := client.ApiCall("add-threat-protections", payload, client.GetSessionID(), true, false) + AddThreatProtectionsRes, _ := client.ApiCall("add-threat-protections", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !AddThreatProtectionsRes.Success { return fmt.Errorf(AddThreatProtectionsRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_add_updatable_object.go b/checkpoint/resource_checkpoint_management_command_add_updatable_object.go index 96649a23..da6178d3 100644 --- a/checkpoint/resource_checkpoint_management_command_add_updatable_object.go +++ b/checkpoint/resource_checkpoint_management_command_add_updatable_object.go @@ -93,7 +93,7 @@ func createManagementAddUpdatableObject(d *schema.ResourceData, m interface{}) e payload["ignore-errors"] = v.(bool) } - AddUpdatableObjectRes, _ := client.ApiCall("add-updatable-object", payload, client.GetSessionID(), true, false) + AddUpdatableObjectRes, _ := client.ApiCall("add-updatable-object", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !AddUpdatableObjectRes.Success { return fmt.Errorf(AddUpdatableObjectRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_assign_global_assignment.go b/checkpoint/resource_checkpoint_management_command_assign_global_assignment.go index 38d8209d..d1580ea6 100644 --- a/checkpoint/resource_checkpoint_management_command_assign_global_assignment.go +++ b/checkpoint/resource_checkpoint_management_command_assign_global_assignment.go @@ -55,7 +55,7 @@ func createManagementAssignGlobalAssignment(d *schema.ResourceData, m interface{ payload["global-domains"] = v.(*schema.Set).List() } - AssignGlobalAssignmentRes, _ := client.ApiCall("assign-global-assignment", payload, client.GetSessionID(), true, false) + AssignGlobalAssignmentRes, _ := client.ApiCall("assign-global-assignment", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !AssignGlobalAssignmentRes.Success { return fmt.Errorf(AssignGlobalAssignmentRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_backup_domain.go b/checkpoint/resource_checkpoint_management_command_backup_domain.go index df970edc..5037e590 100644 --- a/checkpoint/resource_checkpoint_management_command_backup_domain.go +++ b/checkpoint/resource_checkpoint_management_command_backup_domain.go @@ -46,7 +46,7 @@ func createManagementBackupDomain(d *schema.ResourceData, m interface{}) error { payload["file-path"] = v.(string) } - BackupDomainRes, _ := client.ApiCall("backup-domain", payload, client.GetSessionID(), true, false) + BackupDomainRes, _ := client.ApiCall("backup-domain", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !BackupDomainRes.Success { return fmt.Errorf(BackupDomainRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_delete_api_key.go b/checkpoint/resource_checkpoint_management_command_delete_api_key.go index 8d07dbde..9cff6796 100644 --- a/checkpoint/resource_checkpoint_management_command_delete_api_key.go +++ b/checkpoint/resource_checkpoint_management_command_delete_api_key.go @@ -51,7 +51,7 @@ func createManagementDeleteApiKey(d *schema.ResourceData, m interface{}) error { payload["admin-name"] = v.(string) } - DeleteApiKeyRes, _ := client.ApiCall("delete-api-key", payload, client.GetSessionID(), true, false) + DeleteApiKeyRes, _ := client.ApiCall("delete-api-key", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !DeleteApiKeyRes.Success { return fmt.Errorf(DeleteApiKeyRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_delete_data_center_object.go b/checkpoint/resource_checkpoint_management_command_delete_data_center_object.go index b0d9cd83..29eb7d5f 100644 --- a/checkpoint/resource_checkpoint_management_command_delete_data_center_object.go +++ b/checkpoint/resource_checkpoint_management_command_delete_data_center_object.go @@ -51,7 +51,7 @@ func createManagementDeleteDataCenterObject(d *schema.ResourceData, m interface{ payload["ignore-errors"] = v.(bool) } - DeleteDataCenterObjectRes, _ := client.ApiCall("delete-data-center-object", payload, client.GetSessionID(), true, false) + DeleteDataCenterObjectRes, _ := client.ApiCall("delete-data-center-object", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !DeleteDataCenterObjectRes.Success { return fmt.Errorf(DeleteDataCenterObjectRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_delete_threat_protections.go b/checkpoint/resource_checkpoint_management_command_delete_threat_protections.go index f6fc267a..eabcc75b 100644 --- a/checkpoint/resource_checkpoint_management_command_delete_threat_protections.go +++ b/checkpoint/resource_checkpoint_management_command_delete_threat_protections.go @@ -36,7 +36,7 @@ func createManagementDeleteThreatProtections(d *schema.ResourceData, m interface payload["package-format"] = v.(string) } - DeleteThreatProtectionsRes, _ := client.ApiCall("delete-threat-protections", payload, client.GetSessionID(), true, false) + DeleteThreatProtectionsRes, _ := client.ApiCall("delete-threat-protections", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !DeleteThreatProtectionsRes.Success { return fmt.Errorf(DeleteThreatProtectionsRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_delete_updatable_object.go b/checkpoint/resource_checkpoint_management_command_delete_updatable_object.go index f7fd1788..b5fbc124 100644 --- a/checkpoint/resource_checkpoint_management_command_delete_updatable_object.go +++ b/checkpoint/resource_checkpoint_management_command_delete_updatable_object.go @@ -51,7 +51,7 @@ func createManagementDeleteUpdatableObject(d *schema.ResourceData, m interface{} payload["ignore-errors"] = v.(bool) } - DeleteUpdatableObjectRes, _ := client.ApiCall("delete-updatable-object", payload, client.GetSessionID(), true, false) + DeleteUpdatableObjectRes, _ := client.ApiCall("delete-updatable-object", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !DeleteUpdatableObjectRes.Success { return fmt.Errorf(DeleteUpdatableObjectRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_discard.go b/checkpoint/resource_checkpoint_management_command_discard.go index dcc7ff5e..4c1706d8 100644 --- a/checkpoint/resource_checkpoint_management_command_discard.go +++ b/checkpoint/resource_checkpoint_management_command_discard.go @@ -20,7 +20,7 @@ func createManagementDiscard(d *schema.ResourceData, m interface{}) error { client := m.(*checkpoint.ApiClient) var payload = map[string]interface{}{} - DiscardRes, _ := client.ApiCall("discard", payload, client.GetSessionID(), true, false) + DiscardRes, _ := client.ApiCall("discard", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !DiscardRes.Success { return fmt.Errorf(DiscardRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_disconnect.go b/checkpoint/resource_checkpoint_management_command_disconnect.go index a008e019..3fe3f23a 100644 --- a/checkpoint/resource_checkpoint_management_command_disconnect.go +++ b/checkpoint/resource_checkpoint_management_command_disconnect.go @@ -31,7 +31,7 @@ func createManagementDisconnect(d *schema.ResourceData, m interface{}) error { payload["discard"] = v.(bool) } - DisconnectRes, _ := client.ApiCall("disconnect", payload, client.GetSessionID(), true, false) + DisconnectRes, _ := client.ApiCall("disconnect", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !DisconnectRes.Success { return fmt.Errorf(DisconnectRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_export.go b/checkpoint/resource_checkpoint_management_command_export.go index 495ab977..1e9c6345 100644 --- a/checkpoint/resource_checkpoint_management_command_export.go +++ b/checkpoint/resource_checkpoint_management_command_export.go @@ -98,7 +98,7 @@ func createManagementExport(d *schema.ResourceData, m interface{}) error { payload["query-limit"] = v.(int) } - ExportRes, _ := client.ApiCall("export", payload, client.GetSessionID(), true, false) + ExportRes, _ := client.ApiCall("export", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !ExportRes.Success { return fmt.Errorf(ExportRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_get_attachment.go b/checkpoint/resource_checkpoint_management_command_get_attachment.go index b4fbb507..fc98830a 100644 --- a/checkpoint/resource_checkpoint_management_command_get_attachment.go +++ b/checkpoint/resource_checkpoint_management_command_get_attachment.go @@ -47,7 +47,7 @@ func createManagementGetAttachment(d *schema.ResourceData, m interface{}) error payload["id"] = v.(string) } - GetAttachmentRes, _ := client.ApiCall("get-attachment", payload, client.GetSessionID(), true, false) + GetAttachmentRes, _ := client.ApiCall("get-attachment", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !GetAttachmentRes.Success { return fmt.Errorf(GetAttachmentRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_ha_full_sync.go b/checkpoint/resource_checkpoint_management_command_ha_full_sync.go index a1417449..b57909a6 100644 --- a/checkpoint/resource_checkpoint_management_command_ha_full_sync.go +++ b/checkpoint/resource_checkpoint_management_command_ha_full_sync.go @@ -47,7 +47,7 @@ func createManagementHaFullSync(d *schema.ResourceData, m interface{}) error { payload["uid"] = v.(string) } - HaFullSyncRes, _ := client.ApiCall("ha-full-sync", payload, client.GetSessionID(), true, false) + HaFullSyncRes, _ := client.ApiCall("ha-full-sync", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !HaFullSyncRes.Success { return fmt.Errorf(HaFullSyncRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_install_database.go b/checkpoint/resource_checkpoint_management_command_install_database.go index cfd07d7d..803dec28 100644 --- a/checkpoint/resource_checkpoint_management_command_install_database.go +++ b/checkpoint/resource_checkpoint_management_command_install_database.go @@ -42,7 +42,7 @@ func createManagementInstallDatabase(d *schema.ResourceData, m interface{}) erro payload["targets"] = v.(*schema.Set).List() } - InstallDatabaseRes, _ := client.ApiCall("install-database", payload, client.GetSessionID(), true, false) + InstallDatabaseRes, _ := client.ApiCall("install-database", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !InstallDatabaseRes.Success { return fmt.Errorf(InstallDatabaseRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_install_policy.go b/checkpoint/resource_checkpoint_management_command_install_policy.go index 451f62a6..519a600a 100644 --- a/checkpoint/resource_checkpoint_management_command_install_policy.go +++ b/checkpoint/resource_checkpoint_management_command_install_policy.go @@ -118,7 +118,7 @@ func createManagementInstallPolicy(d *schema.ResourceData, m interface{}) error payload["revision"] = v.(bool) } - installPolicyRes, _ := client.ApiCall("install-policy", payload, client.GetSessionID(), true, false) + installPolicyRes, _ := client.ApiCall("install-policy", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !installPolicyRes.Success { return fmt.Errorf(installPolicyRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_install_software_package.go b/checkpoint/resource_checkpoint_management_command_install_software_package.go index 5d0cf70c..b0f2897d 100644 --- a/checkpoint/resource_checkpoint_management_command_install_software_package.go +++ b/checkpoint/resource_checkpoint_management_command_install_software_package.go @@ -94,7 +94,7 @@ func createManagementInstallSoftwarePackage(d *schema.ResourceData, m interface{ payload["concurrency-limit"] = v.(int) } - InstallSoftwarePackageRes, _ := client.ApiCall("install-software-package", payload, client.GetSessionID(), true, false) + InstallSoftwarePackageRes, _ := client.ApiCall("install-software-package", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !InstallSoftwarePackageRes.Success { return fmt.Errorf(InstallSoftwarePackageRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_keepalive.go b/checkpoint/resource_checkpoint_management_command_keepalive.go index 34e2f731..53da023f 100644 --- a/checkpoint/resource_checkpoint_management_command_keepalive.go +++ b/checkpoint/resource_checkpoint_management_command_keepalive.go @@ -20,7 +20,7 @@ func createManagementKeepalive(d *schema.ResourceData, m interface{}) error { client := m.(*checkpoint.ApiClient) var payload = map[string]interface{}{} - KeepaliveRes, _ := client.ApiCall("keepalive", payload, client.GetSessionID(), true, false) + KeepaliveRes, _ := client.ApiCall("keepalive", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !KeepaliveRes.Success { return fmt.Errorf(KeepaliveRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_login.go b/checkpoint/resource_checkpoint_management_command_login.go index 480214dc..ac2f7549 100644 --- a/checkpoint/resource_checkpoint_management_command_login.go +++ b/checkpoint/resource_checkpoint_management_command_login.go @@ -40,13 +40,13 @@ func resourceManagementLogin() *schema.Resource { Type: schema.TypeBool, Optional: true, ForceNew: true, - Description: "Login to the last published session. Such login is done with the Read Only permissions.", + Description: "commonLoginLogic to the last published session. Such login is done with the Read Only permissions.", }, "read_only": { Type: schema.TypeBool, Optional: true, ForceNew: true, - Description: "Login with Read Only permissions. This parameter is not considered in case continue-last-session is true.", + Description: "commonLoginLogic with Read Only permissions. This parameter is not considered in case continue-last-session is true.", }, "session_comments": { Type: schema.TypeString, @@ -112,7 +112,7 @@ func createManagementLogin(d *schema.ResourceData, m interface{}) error { payload["session-timeout"] = v.(int) } - loginRes, _ := client.ApiCall("login", payload, "", true, false) + loginRes, _ := client.ApiCall("login", payload, "", true, client.IsProxyUsed()) if !loginRes.Success { return fmt.Errorf(loginRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_logout.go b/checkpoint/resource_checkpoint_management_command_logout.go index 3c270dd6..a9bb29e2 100644 --- a/checkpoint/resource_checkpoint_management_command_logout.go +++ b/checkpoint/resource_checkpoint_management_command_logout.go @@ -29,7 +29,7 @@ func resourceManagementLogout() *schema.Resource { func createManagementLogout(d *schema.ResourceData, m interface{}) error { client := m.(*checkpoint.ApiClient) - logoutRes, _ := client.ApiCall("logout", make(map[string]interface{}), client.GetSessionID(), true, false) + logoutRes, _ := client.ApiCall("logout", make(map[string]interface{}), client.GetSessionID(), true, client.IsProxyUsed()) if !logoutRes.Success { return fmt.Errorf(logoutRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_migrate_export_domain.go b/checkpoint/resource_checkpoint_management_command_migrate_export_domain.go index dc07c1f1..66245b33 100644 --- a/checkpoint/resource_checkpoint_management_command_migrate_export_domain.go +++ b/checkpoint/resource_checkpoint_management_command_migrate_export_domain.go @@ -56,7 +56,7 @@ func createManagementMigrateExportDomain(d *schema.ResourceData, m interface{}) payload["include-logs"] = v.(bool) } - MigrateExportDomainRes, _ := client.ApiCall("migrate-export-domain", payload, client.GetSessionID(), true, false) + MigrateExportDomainRes, _ := client.ApiCall("migrate-export-domain", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !MigrateExportDomainRes.Success { return fmt.Errorf(MigrateExportDomainRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_migrate_import_domain.go b/checkpoint/resource_checkpoint_management_command_migrate_import_domain.go index 3f54c061..209fbcfb 100644 --- a/checkpoint/resource_checkpoint_management_command_migrate_import_domain.go +++ b/checkpoint/resource_checkpoint_management_command_migrate_import_domain.go @@ -76,7 +76,7 @@ func createManagementMigrateImportDomain(d *schema.ResourceData, m interface{}) payload["include-logs"] = v.(bool) } - MigrateImportDomainRes, _ := client.ApiCall("migrate-import-domain", payload, client.GetSessionID(), true, false) + MigrateImportDomainRes, _ := client.ApiCall("migrate-import-domain", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !MigrateImportDomainRes.Success { return fmt.Errorf(MigrateImportDomainRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_publish.go b/checkpoint/resource_checkpoint_management_command_publish.go index 9f48fff4..cd80b240 100644 --- a/checkpoint/resource_checkpoint_management_command_publish.go +++ b/checkpoint/resource_checkpoint_management_command_publish.go @@ -46,7 +46,7 @@ func createManagementPublish(d *schema.ResourceData, m interface{}) error { payload["uid"] = v.(string) } - publishRes, _ := client.ApiCall("publish", payload, client.GetSessionID(), true, false) + publishRes, _ := client.ApiCall("publish", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !publishRes.Success { return fmt.Errorf(publishRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_put_file.go b/checkpoint/resource_checkpoint_management_command_put_file.go index 0bb69a6d..e8e1f30b 100644 --- a/checkpoint/resource_checkpoint_management_command_put_file.go +++ b/checkpoint/resource_checkpoint_management_command_put_file.go @@ -82,7 +82,7 @@ func createManagementPutFile(d *schema.ResourceData, m interface{}) error { payload["comments"] = v.(string) } - PutFileRes, _ := client.ApiCall("put-file", payload, client.GetSessionID(), true, false) + PutFileRes, _ := client.ApiCall("put-file", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !PutFileRes.Success { return fmt.Errorf(PutFileRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_restore_domain.go b/checkpoint/resource_checkpoint_management_command_restore_domain.go index b24e7c68..e6a213c7 100644 --- a/checkpoint/resource_checkpoint_management_command_restore_domain.go +++ b/checkpoint/resource_checkpoint_management_command_restore_domain.go @@ -76,7 +76,7 @@ func createManagementRestoreDomain(d *schema.ResourceData, m interface{}) error payload["verify-only"] = v.(bool) } - RestoreDomainRes, _ := client.ApiCall("restore-domain", payload, client.GetSessionID(), true, false) + RestoreDomainRes, _ := client.ApiCall("restore-domain", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !RestoreDomainRes.Success { return fmt.Errorf(RestoreDomainRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_revert_to_revision.go b/checkpoint/resource_checkpoint_management_command_revert_to_revision.go index 13bf8a19..880128a6 100644 --- a/checkpoint/resource_checkpoint_management_command_revert_to_revision.go +++ b/checkpoint/resource_checkpoint_management_command_revert_to_revision.go @@ -36,7 +36,7 @@ func createManagementRevertToRevision(d *schema.ResourceData, m interface{}) err payload["to-session"] = v.(string) } - RevertToRevisionRes, _ := client.ApiCall("revert-to-revision", payload, client.GetSessionID(), true, false) + RevertToRevisionRes, _ := client.ApiCall("revert-to-revision", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !RevertToRevisionRes.Success { return fmt.Errorf(RevertToRevisionRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_run_ips_update.go b/checkpoint/resource_checkpoint_management_command_run_ips_update.go index 22d3b964..28f42215 100644 --- a/checkpoint/resource_checkpoint_management_command_run_ips_update.go +++ b/checkpoint/resource_checkpoint_management_command_run_ips_update.go @@ -37,7 +37,7 @@ func createManagementRunIpsUpdate(d *schema.ResourceData, m interface{}) error { payload["package-path"] = v.(string) } - runIpsUpdateRes, _ := client.ApiCall("run-ips-update", payload, client.GetSessionID(), true, false) + runIpsUpdateRes, _ := client.ApiCall("run-ips-update", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !runIpsUpdateRes.Success { return fmt.Errorf(runIpsUpdateRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_run_script.go b/checkpoint/resource_checkpoint_management_command_run_script.go index 80f824ae..92553c88 100644 --- a/checkpoint/resource_checkpoint_management_command_run_script.go +++ b/checkpoint/resource_checkpoint_management_command_run_script.go @@ -82,7 +82,7 @@ func createManagementRunScript(d *schema.ResourceData, m interface{}) error { payload["comments"] = v.(string) } - RunScriptRes, _ := client.ApiCall("run-script", payload, client.GetSessionID(), true, false) + RunScriptRes, _ := client.ApiCall("run-script", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !RunScriptRes.Success { return fmt.Errorf(RunScriptRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_run_threat_emulation_file_types_offline_update.go b/checkpoint/resource_checkpoint_management_command_run_threat_emulation_file_types_offline_update.go index 2dfaae38..960df1f9 100644 --- a/checkpoint/resource_checkpoint_management_command_run_threat_emulation_file_types_offline_update.go +++ b/checkpoint/resource_checkpoint_management_command_run_threat_emulation_file_types_offline_update.go @@ -41,7 +41,7 @@ func createManagementRunThreatEmulationFileTypesOfflineUpdate(d *schema.Resource payload["file-raw-data"] = v.(string) } - RunThreatEmulationFileTypesOfflineUpdateRes, _ := client.ApiCall("run-threat-emulation-file-types-offline-update", payload, client.GetSessionID(), true, false) + RunThreatEmulationFileTypesOfflineUpdateRes, _ := client.ApiCall("run-threat-emulation-file-types-offline-update", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !RunThreatEmulationFileTypesOfflineUpdateRes.Success { return fmt.Errorf(RunThreatEmulationFileTypesOfflineUpdateRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_set_api_settings.go b/checkpoint/resource_checkpoint_management_command_set_api_settings.go index 727ac8f8..3919ea27 100644 --- a/checkpoint/resource_checkpoint_management_command_set_api_settings.go +++ b/checkpoint/resource_checkpoint_management_command_set_api_settings.go @@ -41,7 +41,7 @@ func createManagementSetApiSettings(d *schema.ResourceData, m interface{}) error payload["automatic-start"] = v.(bool) } - SetApiSettingsRes, _ := client.ApiCall("set-api-settings", payload, client.GetSessionID(), true, false) + SetApiSettingsRes, _ := client.ApiCall("set-api-settings", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !SetApiSettingsRes.Success { return fmt.Errorf(SetApiSettingsRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_set_automatic_purge.go b/checkpoint/resource_checkpoint_management_command_set_automatic_purge.go index b9e01735..7d5971ef 100644 --- a/checkpoint/resource_checkpoint_management_command_set_automatic_purge.go +++ b/checkpoint/resource_checkpoint_management_command_set_automatic_purge.go @@ -115,7 +115,7 @@ func createManagementSetAutomaticPurge(d *schema.ResourceData, m interface{}) er payload["scheduling"] = res } - SetAutomaticPurgeRes, _ := client.ApiCall("set-automatic-purge", payload, client.GetSessionID(), true, false) + SetAutomaticPurgeRes, _ := client.ApiCall("set-automatic-purge", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !SetAutomaticPurgeRes.Success { return fmt.Errorf(SetAutomaticPurgeRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_set_global_domain.go b/checkpoint/resource_checkpoint_management_command_set_global_domain.go index c8b0d06b..e56d5be0 100644 --- a/checkpoint/resource_checkpoint_management_command_set_global_domain.go +++ b/checkpoint/resource_checkpoint_management_command_set_global_domain.go @@ -120,7 +120,7 @@ func createManagementSetGlobalDomain(d *schema.ResourceData, m interface{}) erro payload["ignore-errors"] = v.(bool) } - SetGlobalDomainRes, _ := client.ApiCall("set-global-domain", payload, client.GetSessionID(), true, false) + SetGlobalDomainRes, _ := client.ApiCall("set-global-domain", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !SetGlobalDomainRes.Success { return fmt.Errorf(SetGlobalDomainRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_set_ha_state.go b/checkpoint/resource_checkpoint_management_command_set_ha_state.go index f11edc51..fe0433aa 100644 --- a/checkpoint/resource_checkpoint_management_command_set_ha_state.go +++ b/checkpoint/resource_checkpoint_management_command_set_ha_state.go @@ -37,7 +37,7 @@ func createManagementSetHaState(d *schema.ResourceData, m interface{}) error { payload["new-state"] = v.(string) } - SetHaStateRes, _ := client.ApiCall("set-ha-state", payload, client.GetSessionID(), true, false) + SetHaStateRes, _ := client.ApiCall("set-ha-state", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !SetHaStateRes.Success { return fmt.Errorf(SetHaStateRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_set_ips_update_schedule.go b/checkpoint/resource_checkpoint_management_command_set_ips_update_schedule.go index b4341499..2b3df4e6 100644 --- a/checkpoint/resource_checkpoint_management_command_set_ips_update_schedule.go +++ b/checkpoint/resource_checkpoint_management_command_set_ips_update_schedule.go @@ -96,7 +96,7 @@ func createManagementSetIpsUpdateSchedule(d *schema.ResourceData, m interface{}) payload["recurrence"] = res } - SetIpsUpdateScheduleRes, _ := client.ApiCall("set-ips-update-schedule", payload, client.GetSessionID(), true, false) + SetIpsUpdateScheduleRes, _ := client.ApiCall("set-ips-update-schedule", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !SetIpsUpdateScheduleRes.Success { return fmt.Errorf(SetIpsUpdateScheduleRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_set_login_message.go b/checkpoint/resource_checkpoint_management_command_set_login_message.go index 18618f00..e665078e 100644 --- a/checkpoint/resource_checkpoint_management_command_set_login_message.go +++ b/checkpoint/resource_checkpoint_management_command_set_login_message.go @@ -17,13 +17,13 @@ func resourceManagementSetLoginMessage() *schema.Resource { Type: schema.TypeString, Optional: true, ForceNew: true, - Description: "Login message header.", + Description: "commonLoginLogic message header.", }, "message": { Type: schema.TypeString, Optional: true, ForceNew: true, - Description: "Login message body.", + Description: "commonLoginLogic message body.", }, "show_message": { Type: schema.TypeBool, @@ -61,7 +61,7 @@ func createManagementSetLoginMessage(d *schema.ResourceData, m interface{}) erro payload["warning"] = v.(bool) } - SetLoginMessageRes, _ := client.ApiCall("set-login-message", payload, client.GetSessionID(), true, false) + SetLoginMessageRes, _ := client.ApiCall("set-login-message", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !SetLoginMessageRes.Success { return fmt.Errorf(SetLoginMessageRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_set_threat_protection.go b/checkpoint/resource_checkpoint_management_command_set_threat_protection.go index 6683cba8..d8e8f30f 100644 --- a/checkpoint/resource_checkpoint_management_command_set_threat_protection.go +++ b/checkpoint/resource_checkpoint_management_command_set_threat_protection.go @@ -112,7 +112,7 @@ func createManagementSetThreatProtection(d *schema.ResourceData, m interface{}) } } - SetThreatProtectionRes, _ := client.ApiCall("set-threat-protection", payload, client.GetSessionID(), true, false) + SetThreatProtectionRes, _ := client.ApiCall("set-threat-protection", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !SetThreatProtectionRes.Success { return fmt.Errorf(SetThreatProtectionRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_uninstall_software_package.go b/checkpoint/resource_checkpoint_management_command_uninstall_software_package.go index 152149ae..51da522e 100644 --- a/checkpoint/resource_checkpoint_management_command_uninstall_software_package.go +++ b/checkpoint/resource_checkpoint_management_command_uninstall_software_package.go @@ -94,7 +94,7 @@ func createManagementUninstallSoftwarePackage(d *schema.ResourceData, m interfac payload["concurrency-limit"] = v.(int) } - UninstallSoftwarePackageRes, _ := client.ApiCall("uninstall-software-package", payload, client.GetSessionID(), true, false) + UninstallSoftwarePackageRes, _ := client.ApiCall("uninstall-software-package", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !UninstallSoftwarePackageRes.Success { return fmt.Errorf(UninstallSoftwarePackageRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_unlock_administrator.go b/checkpoint/resource_checkpoint_management_command_unlock_administrator.go index 8f15c4d5..bfb73390 100644 --- a/checkpoint/resource_checkpoint_management_command_unlock_administrator.go +++ b/checkpoint/resource_checkpoint_management_command_unlock_administrator.go @@ -31,7 +31,7 @@ func createManagementUnlockAdministrator(d *schema.ResourceData, m interface{}) payload["name"] = v.(string) } - UnlockAdministratorRes, _ := client.ApiCall("unlock-administrator", payload, client.GetSessionID(), true, false) + UnlockAdministratorRes, _ := client.ApiCall("unlock-administrator", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !UnlockAdministratorRes.Success { return fmt.Errorf(UnlockAdministratorRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_update_updatable_objects_repository_content.go b/checkpoint/resource_checkpoint_management_command_update_updatable_objects_repository_content.go index df7bad26..921fb5ca 100644 --- a/checkpoint/resource_checkpoint_management_command_update_updatable_objects_repository_content.go +++ b/checkpoint/resource_checkpoint_management_command_update_updatable_objects_repository_content.go @@ -26,7 +26,7 @@ func createManagementUpdateUpdatableObjectsRepositoryContent(d *schema.ResourceD client := m.(*checkpoint.ApiClient) var payload = map[string]interface{}{} - UpdateUpdatableObjectsRepositoryContentRes, _ := client.ApiCall("update-updatable-objects-repository-content", payload, client.GetSessionID(), true, false) + UpdateUpdatableObjectsRepositoryContentRes, _ := client.ApiCall("update-updatable-objects-repository-content", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !UpdateUpdatableObjectsRepositoryContentRes.Success { return fmt.Errorf(UpdateUpdatableObjectsRepositoryContentRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_verify_policy.go b/checkpoint/resource_checkpoint_management_command_verify_policy.go index 91f4cdf3..f7739e93 100644 --- a/checkpoint/resource_checkpoint_management_command_verify_policy.go +++ b/checkpoint/resource_checkpoint_management_command_verify_policy.go @@ -36,7 +36,7 @@ func createManagementVerifyPolicy(d *schema.ResourceData, m interface{}) error { payload["policy-package"] = v.(string) } - VerifyPolicyRes, _ := client.ApiCall("verify-policy", payload, client.GetSessionID(), true, false) + VerifyPolicyRes, _ := client.ApiCall("verify-policy", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !VerifyPolicyRes.Success { return fmt.Errorf(VerifyPolicyRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_verify_revert.go b/checkpoint/resource_checkpoint_management_command_verify_revert.go index 5da2fd34..66fe2fbf 100644 --- a/checkpoint/resource_checkpoint_management_command_verify_revert.go +++ b/checkpoint/resource_checkpoint_management_command_verify_revert.go @@ -36,7 +36,7 @@ func createManagementVerifyRevert(d *schema.ResourceData, m interface{}) error { payload["to-session"] = v.(string) } - VerifyRevertRes, _ := client.ApiCall("verify-revert", payload, client.GetSessionID(), true, false) + VerifyRevertRes, _ := client.ApiCall("verify-revert", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !VerifyRevertRes.Success { return fmt.Errorf(VerifyRevertRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_verify_software_package.go b/checkpoint/resource_checkpoint_management_command_verify_software_package.go index 0f3a9aaa..faeee9bb 100644 --- a/checkpoint/resource_checkpoint_management_command_verify_software_package.go +++ b/checkpoint/resource_checkpoint_management_command_verify_software_package.go @@ -59,7 +59,7 @@ func createManagementVerifySoftwarePackage(d *schema.ResourceData, m interface{} payload["concurrency-limit"] = v.(int) } - VerifySoftwarePackageRes, _ := client.ApiCall("verify-software-package", payload, client.GetSessionID(), true, false) + VerifySoftwarePackageRes, _ := client.ApiCall("verify-software-package", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !VerifySoftwarePackageRes.Success { return fmt.Errorf(VerifySoftwarePackageRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_command_where_used.go b/checkpoint/resource_checkpoint_management_command_where_used.go index 34e72a67..ea043222 100644 --- a/checkpoint/resource_checkpoint_management_command_where_used.go +++ b/checkpoint/resource_checkpoint_management_command_where_used.go @@ -71,7 +71,7 @@ func createManagementWhereUsed(d *schema.ResourceData, m interface{}) error { payload["indirect-max-depth"] = v.(int) } - WhereUsedRes, _ := client.ApiCall("where-used", payload, client.GetSessionID(), true, false) + WhereUsedRes, _ := client.ApiCall("where-used", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !WhereUsedRes.Success { return fmt.Errorf(WhereUsedRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_data_center_query.go b/checkpoint/resource_checkpoint_management_data_center_query.go new file mode 100644 index 00000000..2db651da --- /dev/null +++ b/checkpoint/resource_checkpoint_management_data_center_query.go @@ -0,0 +1,402 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "log" + + "strconv" +) + +func resourceManagementDataCenterQuery() *schema.Resource { + return &schema.Resource{ + Create: createManagementDataCenterQuery, + Read: readManagementDataCenterQuery, + Update: updateManagementDataCenterQuery, + Delete: deleteManagementDataCenterQuery, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + Description: "Object name.", + }, + "data_centers": { + Type: schema.TypeList, + Optional: true, + Description: "Collection of Data Center servers identified by the name or UID. Use \"All\" to select all data centers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "query_rules": { + Type: schema.TypeList, + Optional: true, + Description: "Data Center Query Rules.
There is an 'AND' operation between multiple Query Rules.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key_type": { + Type: schema.TypeString, + Optional: true, + Description: "The type of the \"key\" parameter.
Use \"predefined\" for these keys: type-in-data-center, name-in-data-center, and ip-address.
Use \"tag\" to query the Data Center tag�s property.", + }, + "key": { + Type: schema.TypeString, + Optional: true, + Description: "Defines in which Data Center property to query.
For key-type \"predefined\", use these keys: type-in-data-center, name-in-data-center, and ip-address.
For key-type \"tag\", use the Data Center tag key to query.
Keys are case-insensitive.", + }, + "values": { + Type: schema.TypeList, + Optional: true, + Description: "The value(s) of the Data Center property to match the Query Rule.
Values are case-insensitive.
There is an 'OR' operation between multiple values.
For key-type \"predefined\" and key 'ip-address', the values must be an IPv4 or IPv6 address.
For key-type \"tag\", the values must be the Data Center tag values.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + }, + }, + "tags": { + Type: schema.TypeSet, + Optional: true, + Description: "Collection of tag identifiers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "color": { + Type: schema.TypeString, + Optional: true, + Description: "Color of the object. Should be one of existing colors.", + Default: "black", + }, + "comments": { + Type: schema.TypeString, + Optional: true, + Description: "Comments string.", + }, + "ignore_warnings": { + Type: schema.TypeBool, + Optional: true, + Description: "Apply changes ignoring warnings.", + Default: false, + }, + "ignore_errors": { + Type: schema.TypeBool, + Optional: true, + Description: "Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored.", + Default: false, + }, + }, + } +} + +func createManagementDataCenterQuery(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + + dataCenterQuery := make(map[string]interface{}) + + if v, ok := d.GetOk("name"); ok { + dataCenterQuery["name"] = v.(string) + } + + if v, ok := d.GetOk("data_centers"); ok { + dataCentersList := v.([]interface{}) + if len(dataCentersList) == 1 && dataCentersList[0] == "All" { + dataCenterQuery["data-centers"] = "All" + } else { + dataCenterQuery["data-centers"] = v + } + } + + if v, ok := d.GetOk("query_rules"); ok { + + queryRulesList := v.([]interface{}) + + if len(queryRulesList) > 0 { + + var queryRulesPayload []map[string]interface{} + + for i := range queryRulesList { + + Payload := make(map[string]interface{}) + + if v, ok := d.GetOk("query_rules." + strconv.Itoa(i) + ".key_type"); ok { + Payload["key-type"] = v.(string) + } + if v, ok := d.GetOk("query_rules." + strconv.Itoa(i) + ".key"); ok { + Payload["key"] = v.(string) + } + if v, ok := d.GetOk("query_rules." + strconv.Itoa(i) + ".values"); ok { + Payload["values"] = v + } + queryRulesPayload = append(queryRulesPayload, Payload) + } + dataCenterQuery["query-rules"] = queryRulesPayload + } + } + + if v, ok := d.GetOk("tags"); ok { + dataCenterQuery["tags"] = v.(*schema.Set).List() + } + + if v, ok := d.GetOk("color"); ok { + dataCenterQuery["color"] = v.(string) + } + + if v, ok := d.GetOk("comments"); ok { + dataCenterQuery["comments"] = v.(string) + } + + if v, ok := d.GetOkExists("ignore_warnings"); ok { + dataCenterQuery["ignore-warnings"] = v.(bool) + } + + if v, ok := d.GetOkExists("ignore_errors"); ok { + dataCenterQuery["ignore-errors"] = v.(bool) + } + + log.Println("Create DataCenterQuery - Map = ", dataCenterQuery) + + addDataCenterQueryRes, err := client.ApiCall("add-data-center-query", dataCenterQuery, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil || !addDataCenterQueryRes.Success { + if addDataCenterQueryRes.ErrorMsg != "" { + return fmt.Errorf(addDataCenterQueryRes.ErrorMsg) + } + return fmt.Errorf(err.Error()) + } + + d.SetId(addDataCenterQueryRes.GetData()["uid"].(string)) + + return readManagementDataCenterQuery(d, m) +} + +func readManagementDataCenterQuery(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + + payload := map[string]interface{}{ + "uid": d.Id(), + } + + showDataCenterQueryRes, err := client.ApiCall("show-data-center-query", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showDataCenterQueryRes.Success { + if objectNotFound(showDataCenterQueryRes.GetData()["code"].(string)) { + d.SetId("") + return nil + } + return fmt.Errorf(showDataCenterQueryRes.ErrorMsg) + } + + dataCenterQuery := showDataCenterQueryRes.GetData() + + KeysToFixedKeys := getKeysToFixedKeys() + + log.Println("Read DataCenterQuery - Show JSON = ", dataCenterQuery) + + if v := dataCenterQuery["name"]; v != nil { + _ = d.Set("name", v) + } + + if dataCenterQuery["data-centers"] != nil { + dataCentersJson, ok := dataCenterQuery["data-centers"].([]interface{}) + if ok { + dataCentersIds := make([]string, 0) + if len(dataCentersJson) > 0 { + for _, data_centers := range dataCentersJson { + data_centers := data_centers.(map[string]interface{}) + dataCentersIds = append(dataCentersIds, data_centers["name"].(string)) + } + _ = d.Set("data_centers", dataCentersIds) + } else { + _ = d.Set("data_centers", []string{"All"}) + } + } + } + + if dataCenterQuery["query-rules"] != nil { + + queryRulesList, ok := dataCenterQuery["query-rules"].([]interface{}) + + if ok { + + if len(queryRulesList) > 0 { + + var queryRulesListToReturn []map[string]interface{} + + for i := range queryRulesList { + + queryRulesMap := queryRulesList[i].(map[string]interface{}) + + queryRulesMapToAdd := make(map[string]interface{}) + + if v, _ := queryRulesMap["key-type"]; v != nil { + keyType := v.(string) + if newType, ok := KeysToFixedKeys[keyType]; ok { + queryRulesMapToAdd["key_type"] = newType + } else { + queryRulesMapToAdd["key_type"] = v + } + } + if v, _ := queryRulesMap["key"]; v != nil { + key := v.(string) + if newType, ok := KeysToFixedKeys[key]; ok { + queryRulesMapToAdd["key"] = newType + } else { + queryRulesMapToAdd["key"] = v + } + } + if v, _ := queryRulesMap["values"]; v != nil { + queryRulesMapToAdd["values"] = v + } + queryRulesListToReturn = append(queryRulesListToReturn, queryRulesMapToAdd) + } + _ = d.Set("query_rules", queryRulesListToReturn) + } + } + } + + if dataCenterQuery["tags"] != nil { + tagsJson, ok := dataCenterQuery["tags"].([]interface{}) + if ok { + tagsIds := make([]string, 0) + if len(tagsJson) > 0 { + for _, tags := range tagsJson { + tags := tags.(map[string]interface{}) + tagsIds = append(tagsIds, tags["name"].(string)) + } + } + _ = d.Set("tags", tagsIds) + } + } else { + _ = d.Set("tags", nil) + } + + if v := dataCenterQuery["color"]; v != nil { + _ = d.Set("color", v) + } + + if v := dataCenterQuery["comments"]; v != nil { + _ = d.Set("comments", v) + } + + if v := dataCenterQuery["ignore-warnings"]; v != nil { + _ = d.Set("ignore_warnings", v) + } + + if v := dataCenterQuery["ignore-errors"]; v != nil { + _ = d.Set("ignore_errors", v) + } + + return nil + +} + +func updateManagementDataCenterQuery(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + dataCenterQuery := make(map[string]interface{}) + + if ok := d.HasChange("name"); ok { + oldName, newName := d.GetChange("name") + dataCenterQuery["name"] = oldName + dataCenterQuery["new-name"] = newName + } else { + dataCenterQuery["name"] = d.Get("name") + } + + if d.HasChange("data_centers") { + if v, ok := d.GetOk("data_centers"); ok { + dataCentersList := v.([]interface{}) + if len(dataCentersList) == 1 && dataCentersList[0] == "All" { + dataCenterQuery["data-centers"] = "All" + } else { + dataCenterQuery["data-centers"] = v + } + } + } + + if d.HasChange("query_rules") { + + if v, ok := d.GetOk("query_rules"); ok { + + queryRulesList := v.([]interface{}) + + var queryRulesPayload []map[string]interface{} + + for i := range queryRulesList { + + Payload := make(map[string]interface{}) + Payload["key-type"] = d.Get("query_rules." + strconv.Itoa(i) + ".key_type") + Payload["key"] = d.Get("query_rules." + strconv.Itoa(i) + ".key") + Payload["values"] = d.Get("query_rules." + strconv.Itoa(i) + ".values") + queryRulesPayload = append(queryRulesPayload, Payload) + } + dataCenterQuery["query-rules"] = queryRulesPayload + } else { + dataCenterQuery["query-rules"] = nil + } + } + + if d.HasChange("tags") { + if v, ok := d.GetOk("tags"); ok { + dataCenterQuery["tags"] = v.(*schema.Set).List() + } else { + oldTags, _ := d.GetChange("tags") + dataCenterQuery["tags"] = map[string]interface{}{"remove": oldTags.(*schema.Set).List()} + } + } + + if ok := d.HasChange("color"); ok { + dataCenterQuery["color"] = d.Get("color") + } + + if ok := d.HasChange("comments"); ok { + dataCenterQuery["comments"] = d.Get("comments") + } + + if v, ok := d.GetOkExists("ignore_warnings"); ok { + dataCenterQuery["ignore-warnings"] = v.(bool) + } + + if v, ok := d.GetOkExists("ignore_errors"); ok { + dataCenterQuery["ignore-errors"] = v.(bool) + } + + log.Println("Update DataCenterQuery - Map = ", dataCenterQuery) + + updateDataCenterQueryRes, err := client.ApiCall("set-data-center-query", dataCenterQuery, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil || !updateDataCenterQueryRes.Success { + if updateDataCenterQueryRes.ErrorMsg != "" { + return fmt.Errorf(updateDataCenterQueryRes.ErrorMsg) + } + return fmt.Errorf(err.Error()) + } + + return readManagementDataCenterQuery(d, m) +} + +func deleteManagementDataCenterQuery(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + + dataCenterQueryPayload := map[string]interface{}{ + "uid": d.Id(), + } + + log.Println("Delete DataCenterQuery") + + deleteDataCenterQueryRes, err := client.ApiCall("delete-data-center-query", dataCenterQueryPayload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil || !deleteDataCenterQueryRes.Success { + if deleteDataCenterQueryRes.ErrorMsg != "" { + return fmt.Errorf(deleteDataCenterQueryRes.ErrorMsg) + } + return fmt.Errorf(err.Error()) + } + d.SetId("") + + return nil +} diff --git a/checkpoint/resource_checkpoint_management_data_center_query_test.go b/checkpoint/resource_checkpoint_management_data_center_query_test.go new file mode 100644 index 00000000..b467c220 --- /dev/null +++ b/checkpoint/resource_checkpoint_management_data_center_query_test.go @@ -0,0 +1,106 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + "os" + "strings" + "testing" +) + +func TestAccCheckpointManagementDataCenterQuery_basic(t *testing.T) { + var dataCenterQueryMap map[string]interface{} + resourceName := "checkpoint_management_data_center_query.test" + objName := "tfTestManagementDataCenterQuery_" + acctest.RandString(6) + firstVal := "value1" + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckpointManagementDataCenterQueryDestroy, + Steps: []resource.TestStep{ + { + Config: testAccManagementDataCenterQueryConfig(objName, firstVal), + Check: resource.ComposeTestCheckFunc( + testAccCheckCheckpointManagementDataCenterQueryExists(resourceName, &dataCenterQueryMap), + testAccCheckCheckpointManagementDataCenterQueryAttributes(&dataCenterQueryMap, objName), + ), + }, + }, + }) +} + +func testAccCheckpointManagementDataCenterQueryDestroy(s *terraform.State) error { + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + for _, rs := range s.RootModule().Resources { + if rs.Type != "checkpoint_management_data_center_query" { + continue + } + if rs.Primary.ID != "" { + res, _ := client.ApiCall("show-data-center-query", map[string]interface{}{"uid": rs.Primary.ID}, client.GetSessionID(), true, false) + if res.Success { + return fmt.Errorf("DataCenterQuery object (%s) still exists", rs.Primary.ID) + } + } + return nil + } + return nil +} + +func testAccCheckCheckpointManagementDataCenterQueryExists(resourceTfName string, res *map[string]interface{}) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[resourceTfName] + if !ok { + return fmt.Errorf("Resource not found: %s", resourceTfName) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("DataCenterQuery ID is not set") + } + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + + response, err := client.ApiCall("show-data-center-query", map[string]interface{}{"uid": rs.Primary.ID}, client.GetSessionID(), true, false) + if !response.Success { + return err + } + + *res = response.GetData() + + return nil + } +} + +func testAccCheckCheckpointManagementDataCenterQueryAttributes(dataCenterQueryMap *map[string]interface{}, name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + + dataCenterQueryName := (*dataCenterQueryMap)["name"].(string) + if !strings.EqualFold(dataCenterQueryName, name) { + return fmt.Errorf("name is %s, expected %s", name, dataCenterQueryName) + } + return nil + } +} + +func testAccManagementDataCenterQueryConfig(name string, firstVal string) string { + return fmt.Sprintf(` +resource "checkpoint_management_data_center_query" "test" { + name = "%s" + data_centers = ["All"] + query_rules { + key_type = "predefined" + key = "name-in-data-center" + values = ["%s"] + } +} +`, name, firstVal) +} diff --git a/checkpoint/resource_checkpoint_management_dns_domain.go b/checkpoint/resource_checkpoint_management_dns_domain.go index f6378fd5..8f6a043d 100644 --- a/checkpoint/resource_checkpoint_management_dns_domain.go +++ b/checkpoint/resource_checkpoint_management_dns_domain.go @@ -97,7 +97,7 @@ func createManagementDnsDomain(d *schema.ResourceData, m interface{}) error { log.Println("Create DnsDomain - Map = ", dnsDomain) - addDnsDomainRes, err := client.ApiCall("add-dns-domain", dnsDomain, client.GetSessionID(), true, false) + addDnsDomainRes, err := client.ApiCall("add-dns-domain", dnsDomain, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addDnsDomainRes.Success { if addDnsDomainRes.ErrorMsg != "" { return fmt.Errorf(addDnsDomainRes.ErrorMsg) @@ -118,7 +118,7 @@ func readManagementDnsDomain(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showDnsDomainRes, err := client.ApiCall("show-dns-domain", payload, client.GetSessionID(), true, false) + showDnsDomainRes, err := client.ApiCall("show-dns-domain", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -222,7 +222,7 @@ func updateManagementDnsDomain(d *schema.ResourceData, m interface{}) error { log.Println("Update DnsDomain - Map = ", dnsDomain) - updateDnsDomainRes, err := client.ApiCall("set-dns-domain", dnsDomain, client.GetSessionID(), true, false) + updateDnsDomainRes, err := client.ApiCall("set-dns-domain", dnsDomain, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateDnsDomainRes.Success { if updateDnsDomainRes.ErrorMsg != "" { return fmt.Errorf(updateDnsDomainRes.ErrorMsg) @@ -243,7 +243,7 @@ func deleteManagementDnsDomain(d *schema.ResourceData, m interface{}) error { log.Println("Delete DnsDomain") - deleteDnsDomainRes, err := client.ApiCall("delete-dns-domain", dnsDomainPayload, client.GetSessionID(), true, false) + deleteDnsDomainRes, err := client.ApiCall("delete-dns-domain", dnsDomainPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteDnsDomainRes.Success { if deleteDnsDomainRes.ErrorMsg != "" { return fmt.Errorf(deleteDnsDomainRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_dynamic_object.go b/checkpoint/resource_checkpoint_management_dynamic_object.go index 49ca0f40..3320a9d9 100644 --- a/checkpoint/resource_checkpoint_management_dynamic_object.go +++ b/checkpoint/resource_checkpoint_management_dynamic_object.go @@ -88,7 +88,7 @@ func createManagementDynamicObject(d *schema.ResourceData, m interface{}) error log.Println("Create DynamicObject - Map = ", dynamicObject) - addDynamicObjectRes, err := client.ApiCall("add-dynamic-object", dynamicObject, client.GetSessionID(), true, false) + addDynamicObjectRes, err := client.ApiCall("add-dynamic-object", dynamicObject, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addDynamicObjectRes.Success { if addDynamicObjectRes.ErrorMsg != "" { return fmt.Errorf(addDynamicObjectRes.ErrorMsg) @@ -109,7 +109,7 @@ func readManagementDynamicObject(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showDynamicObjectRes, err := client.ApiCall("show-dynamic-object", payload, client.GetSessionID(), true, false) + showDynamicObjectRes, err := client.ApiCall("show-dynamic-object", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -205,7 +205,7 @@ func updateManagementDynamicObject(d *schema.ResourceData, m interface{}) error log.Println("Update DynamicObject - Map = ", dynamicObject) - updateDynamicObjectRes, err := client.ApiCall("set-dynamic-object", dynamicObject, client.GetSessionID(), true, false) + updateDynamicObjectRes, err := client.ApiCall("set-dynamic-object", dynamicObject, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateDynamicObjectRes.Success { if updateDynamicObjectRes.ErrorMsg != "" { return fmt.Errorf(updateDynamicObjectRes.ErrorMsg) @@ -226,7 +226,7 @@ func deleteManagementDynamicObject(d *schema.ResourceData, m interface{}) error log.Println("Delete DynamicObject") - deleteDynamicObjectRes, err := client.ApiCall("delete-dynamic-object", dynamicObjectPayload, client.GetSessionID(), true, false) + deleteDynamicObjectRes, err := client.ApiCall("delete-dynamic-object", dynamicObjectPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteDynamicObjectRes.Success { if deleteDynamicObjectRes.ErrorMsg != "" { return fmt.Errorf(deleteDynamicObjectRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_exception_group.go b/checkpoint/resource_checkpoint_management_exception_group.go index 9658f007..f5374f5f 100644 --- a/checkpoint/resource_checkpoint_management_exception_group.go +++ b/checkpoint/resource_checkpoint_management_exception_group.go @@ -186,7 +186,7 @@ func createManagementExceptionGroup(d *schema.ResourceData, m interface{}) error log.Println("Create ExceptionGroup - Map = ", exceptionGroup) - addExceptionGroupRes, err := client.ApiCall("add-exception-group", exceptionGroup, client.GetSessionID(), true, false) + addExceptionGroupRes, err := client.ApiCall("add-exception-group", exceptionGroup, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addExceptionGroupRes.Success { if addExceptionGroupRes.ErrorMsg != "" { return fmt.Errorf(addExceptionGroupRes.ErrorMsg) @@ -207,7 +207,7 @@ func readManagementExceptionGroup(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showExceptionGroupRes, err := client.ApiCall("show-exception-group", payload, client.GetSessionID(), true, false) + showExceptionGroupRes, err := client.ApiCall("show-exception-group", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -390,7 +390,7 @@ func updateManagementExceptionGroup(d *schema.ResourceData, m interface{}) error log.Println("Update ExceptionGroup - Map = ", exceptionGroup) - updateExceptionGroupRes, err := client.ApiCall("set-exception-group", exceptionGroup, client.GetSessionID(), true, false) + updateExceptionGroupRes, err := client.ApiCall("set-exception-group", exceptionGroup, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateExceptionGroupRes.Success { if updateExceptionGroupRes.ErrorMsg != "" { return fmt.Errorf(updateExceptionGroupRes.ErrorMsg) @@ -411,7 +411,7 @@ func deleteManagementExceptionGroup(d *schema.ResourceData, m interface{}) error log.Println("Delete ExceptionGroup") - deleteExceptionGroupRes, err := client.ApiCall("delete-exception-group", exceptionGroupPayload, client.GetSessionID(), true, false) + deleteExceptionGroupRes, err := client.ApiCall("delete-exception-group", exceptionGroupPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteExceptionGroupRes.Success { if deleteExceptionGroupRes.ErrorMsg != "" { return fmt.Errorf(deleteExceptionGroupRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_gcp_data_center_server.go b/checkpoint/resource_checkpoint_management_gcp_data_center_server.go new file mode 100644 index 00000000..b7f51e43 --- /dev/null +++ b/checkpoint/resource_checkpoint_management_gcp_data_center_server.go @@ -0,0 +1,294 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "log" + "strings" +) + +func resourceManagementGcpDataCenterServer() *schema.Resource { + return &schema.Resource{ + Create: createManagementGcpDataCenterServer, + Read: readManagementGcpDataCenterServer, + Update: updateManagementGcpDataCenterServer, + Delete: deleteManagementGcpDataCenterServer, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + Description: "Object name. Must be unique in the domain.", + }, + "authentication_method": { + Type: schema.TypeString, + Required: true, + Description: "key-authentication\nUses the Service Account private key file to authenticate.\nvm-instance-authentication\nUses the Service Account VM Instance to authenticate.\nThis option requires the Security Management Server deployed in a GCP, and runs as a Service Account with the required permissions.", + }, + "private_key": { + Type: schema.TypeString, + Optional: true, + Description: "A Service Account Key JSON file, encoded in base64.\nRequired for authentication-method: key-authentication.", + }, + "tags": { + Type: schema.TypeSet, + Optional: true, + Description: "Collection of tag identifiers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "color": { + Type: schema.TypeString, + Optional: true, + Description: "Color of the object. Should be one of existing colors.", + Default: "black", + }, + "comments": { + Type: schema.TypeString, + Optional: true, + Description: "Comments string.", + }, + "ignore_warnings": { + Type: schema.TypeBool, + Optional: true, + Description: "Apply changes ignoring warnings. By Setting this parameter to 'true' test connection failure will be ignored.", + Default: false, + }, + "ignore_errors": { + Type: schema.TypeBool, + Optional: true, + Description: "Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored.", + Default: false, + }, + }, + } +} + +func createManagementGcpDataCenterServer(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + + gcpDataCenterServer := make(map[string]interface{}) + + if v, ok := d.GetOk("name"); ok { + gcpDataCenterServer["name"] = v.(string) + } + + gcpDataCenterServer["type"] = "gcp" + + if v, ok := d.GetOk("authentication_method"); ok { + gcpDataCenterServer["authentication-method"] = v.(string) + } + + if v, ok := d.GetOk("private_key"); ok { + gcpDataCenterServer["private-key"] = v.(string) + } + + if v, ok := d.GetOk("tags"); ok { + gcpDataCenterServer["tags"] = v.(*schema.Set).List() + } + + if v, ok := d.GetOk("color"); ok { + gcpDataCenterServer["color"] = v.(string) + } + + if v, ok := d.GetOk("comments"); ok { + gcpDataCenterServer["comments"] = v.(string) + } + + if v, ok := d.GetOkExists("ignore_warnings"); ok { + gcpDataCenterServer["ignore-warnings"] = v.(bool) + } + + if v, ok := d.GetOkExists("ignore_errors"); ok { + gcpDataCenterServer["ignore-errors"] = v.(bool) + } + + log.Println("Create gcpDataCenterServer - Map = ", gcpDataCenterServer) + + addGcpDataCenterServerRes, err := client.ApiCall("add-data-center-server", gcpDataCenterServer, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !addGcpDataCenterServerRes.Success { + if addGcpDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(addGcpDataCenterServerRes.ErrorMsg) + } + msg := createTaskFailMessage("add-data-center-server", addGcpDataCenterServerRes.GetData()) + return fmt.Errorf(msg) + } + payload := map[string]interface{}{ + "name": gcpDataCenterServer["name"], + } + showGcpDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showGcpDataCenterServerRes.Success { + return fmt.Errorf(showGcpDataCenterServerRes.ErrorMsg) + } + d.SetId(showGcpDataCenterServerRes.GetData()["uid"].(string)) + return readManagementGcpDataCenterServer(d, m) +} + +func readManagementGcpDataCenterServer(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + payload := map[string]interface{}{ + "uid": d.Id(), + } + + showGcpDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showGcpDataCenterServerRes.Success { + if objectNotFound(showGcpDataCenterServerRes.GetData()["code"].(string)) { + d.SetId("") + return nil + } + return fmt.Errorf(showGcpDataCenterServerRes.ErrorMsg) + } + gcpDataCenterServer := showGcpDataCenterServerRes.GetData() + + if v := gcpDataCenterServer["name"]; v != nil { + _ = d.Set("name", v) + } + + if gcpDataCenterServer["properties"] != nil { + propsJson, ok := gcpDataCenterServer["properties"].([]interface{}) + if ok { + for _, prop := range propsJson { + propMap := prop.(map[string]interface{}) + propName := strings.ReplaceAll(propMap["name"].(string), "-", "_") + propValue := propMap["value"] + _ = d.Set(propName, propValue) + } + } + } + + if gcpDataCenterServer["tags"] != nil { + tagsJson, ok := gcpDataCenterServer["tags"].([]interface{}) + if ok { + tagsIds := make([]string, 0) + if len(tagsJson) > 0 { + for _, tags := range tagsJson { + tags := tags.(map[string]interface{}) + tagsIds = append(tagsIds, tags["name"].(string)) + } + } + _ = d.Set("tags", tagsIds) + } + } else { + _ = d.Set("tags", nil) + } + + if v := gcpDataCenterServer["color"]; v != nil { + _ = d.Set("color", v) + } + + if v := gcpDataCenterServer["comments"]; v != nil { + _ = d.Set("comments", v) + } + + if v := gcpDataCenterServer["ignore-warnings"]; v != nil { + _ = d.Set("ignore_warnings", v) + } + + if v := gcpDataCenterServer["ignore-errors"]; v != nil { + _ = d.Set("ignore_errors", v) + } + + return nil + +} + +func updateManagementGcpDataCenterServer(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + gcpDataCenterServer := make(map[string]interface{}) + + if ok := d.HasChange("name"); ok { + oldName, newName := d.GetChange("name") + gcpDataCenterServer["name"] = oldName + gcpDataCenterServer["new-name"] = newName + } else { + gcpDataCenterServer["name"] = d.Get("name") + } + + if ok := d.HasChange("private_key"); ok { + gcpDataCenterServer["private-key"] = d.Get("private_key") + } + + if ok := d.HasChange("authentication_method"); ok { + gcpDataCenterServer["authentication-method"] = d.Get("authentication_method") + if gcpDataCenterServer["authentication-method"] == "key-authentication" { + gcpDataCenterServer["private-key"] = d.Get("private_key") + } + } + + if d.HasChange("tags") { + if v, ok := d.GetOk("tags"); ok { + gcpDataCenterServer["tags"] = v.(*schema.Set).List() + } else { + oldTags, _ := d.GetChange("tags") + gcpDataCenterServer["tags"] = map[string]interface{}{"remove": oldTags.(*schema.Set).List()} + } + } + + if ok := d.HasChange("color"); ok { + gcpDataCenterServer["color"] = d.Get("color") + } + + if ok := d.HasChange("comments"); ok { + gcpDataCenterServer["comments"] = d.Get("comments") + } + + if v, ok := d.GetOkExists("ignore_warnings"); ok { + gcpDataCenterServer["ignore-warnings"] = v.(bool) + } + + if v, ok := d.GetOkExists("ignore_errors"); ok { + gcpDataCenterServer["ignore-errors"] = v.(bool) + } + + log.Println("Update gcpDataCenterServer - Map = ", gcpDataCenterServer) + + updateGcpDataCenterServerRes, err := client.ApiCall("set-data-center-server", gcpDataCenterServer, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !updateGcpDataCenterServerRes.Success { + if updateGcpDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(updateGcpDataCenterServerRes.ErrorMsg) + } + msg := createTaskFailMessage("set-data-center-server", updateGcpDataCenterServerRes.GetData()) + return fmt.Errorf(msg) + } + + return readManagementGcpDataCenterServer(d, m) +} + +func deleteManagementGcpDataCenterServer(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + + gcpDataCenterServerPayload := map[string]interface{}{ + "uid": d.Id(), + } + + log.Println("Delete gcpDataCenterServer") + + deleteGcpDataCenterServerRes, err := client.ApiCall("delete-data-center-server", gcpDataCenterServerPayload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil || !deleteGcpDataCenterServerRes.Success { + if deleteGcpDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(deleteGcpDataCenterServerRes.ErrorMsg) + } + return fmt.Errorf(err.Error()) + } + d.SetId("") + + return nil +} diff --git a/checkpoint/resource_checkpoint_management_gcp_data_center_server_test.go b/checkpoint/resource_checkpoint_management_gcp_data_center_server_test.go new file mode 100644 index 00000000..137d3db7 --- /dev/null +++ b/checkpoint/resource_checkpoint_management_gcp_data_center_server_test.go @@ -0,0 +1,108 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + "os" + "strings" + "testing" +) + +func TestAccCheckpointManagementGcpDataCenterServer_basic(t *testing.T) { + + var gcpDataCenterServerMap map[string]interface{} + resourceName := "checkpoint_management_gcp_data_center_server.test" + objName := "tfTestManagementGcpDataCenterServer_" + acctest.RandString(6) + authenticationMethod := "key-authentication" + privateKey := "MYKEY.json" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } else if context == "" { + t.Skip("Env CHECKPOINT_CONTEXT must be specified to run this acc test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckpointManagementGcpDataCenterServerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccManagementGcpDataCenterServerConfig(objName, authenticationMethod, privateKey), + Check: resource.ComposeTestCheckFunc( + testAccCheckCheckpointManagementGcpDataCenterServerExists(resourceName, &gcpDataCenterServerMap), + testAccCheckCheckpointManagementGcpDataCenterServerAttributes(&gcpDataCenterServerMap, objName), + ), + }, + }, + }) +} + +func testAccCheckpointManagementGcpDataCenterServerDestroy(s *terraform.State) error { + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + for _, rs := range s.RootModule().Resources { + if rs.Type != "checkpoint_management_gcp_data_center_server" { + continue + } + if rs.Primary.ID != "" { + res, _ := client.ApiCall("show-data-center-server", map[string]interface{}{"uid": rs.Primary.ID}, client.GetSessionID(), true, false) + if res.Success { + return fmt.Errorf("GcpDataCenterServer object (%s) still exists", rs.Primary.ID) + } + } + return nil + } + return nil +} + +func testAccCheckCheckpointManagementGcpDataCenterServerExists(resourceTfName string, res *map[string]interface{}) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[resourceTfName] + if !ok { + return fmt.Errorf("Resource not found: %s", resourceTfName) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("GcpDataCenterServer ID is not set") + } + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + + response, err := client.ApiCall("show-data-center-server", map[string]interface{}{"uid": rs.Primary.ID}, client.GetSessionID(), true, false) + if !response.Success { + return err + } + + *res = response.GetData() + + return nil + } +} + +func testAccCheckCheckpointManagementGcpDataCenterServerAttributes(gcpDataCenterServerMap *map[string]interface{}, name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + + gcpDataCenterServerName := (*gcpDataCenterServerMap)["name"].(string) + if !strings.EqualFold(gcpDataCenterServerName, name) { + return fmt.Errorf("name is %s, expected %s", name, gcpDataCenterServerName) + } + return nil + } +} + +func testAccManagementGcpDataCenterServerConfig(name string, authenticationMethod string, privateKey string) string { + return fmt.Sprintf(` +resource "checkpoint_management_gcp_data_center_server" "test" { + name = "%s" + authentication_method = "%s" + private_key = "%s" + ignore_warnings = true +} +`, name, authenticationMethod, privateKey) +} diff --git a/checkpoint/resource_checkpoint_management_generic_data_center_server.go b/checkpoint/resource_checkpoint_management_generic_data_center_server.go index 1908104d..b0c32176 100644 --- a/checkpoint/resource_checkpoint_management_generic_data_center_server.go +++ b/checkpoint/resource_checkpoint_management_generic_data_center_server.go @@ -138,7 +138,7 @@ func createManagementGenericDataCenterServer(d *schema.ResourceData, m interface log.Println("Create genericDataCenterServer - Map = ", genericDataCenterServer) - addGenericDataCenterServerRes, err := client.ApiCall("add-data-center-server", genericDataCenterServer, client.GetSessionID(), true, false) + addGenericDataCenterServerRes, err := client.ApiCall("add-data-center-server", genericDataCenterServer, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -152,7 +152,7 @@ func createManagementGenericDataCenterServer(d *schema.ResourceData, m interface payload := map[string]interface{}{ "name": genericDataCenterServer["name"], } - showGenericDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, false) + showGenericDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -172,7 +172,7 @@ func readManagementGenericDataCenterServer(d *schema.ResourceData, m interface{} payload := map[string]interface{}{ "uid": d.Id(), } - showGenericDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), false, false) + showGenericDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), false, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -301,7 +301,7 @@ func updateManagementGenericDataCenterServer(d *schema.ResourceData, m interface log.Println("Update genericDataCenterServer - Map = ", genericDataCenterServer) - updateGenericDataCenterServerRes, err := client.ApiCall("set-data-center-server", genericDataCenterServer, client.GetSessionID(), true, false) + updateGenericDataCenterServerRes, err := client.ApiCall("set-data-center-server", genericDataCenterServer, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -326,7 +326,7 @@ func deleteManagementGenericDataCenterServer(d *schema.ResourceData, m interface log.Println("Delete genericDataCenterServer") - deleteGenericDataCenterServerRes, err := client.ApiCall("delete-data-center-server", genericDataCenterServerPayload, client.GetSessionID(), true, false) + deleteGenericDataCenterServerRes, err := client.ApiCall("delete-data-center-server", genericDataCenterServerPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteGenericDataCenterServerRes.Success { if deleteGenericDataCenterServerRes.ErrorMsg != "" { return fmt.Errorf(deleteGenericDataCenterServerRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_generic_data_center_server_test.go b/checkpoint/resource_checkpoint_management_generic_data_center_server_test.go index 108593cc..12f125e9 100644 --- a/checkpoint/resource_checkpoint_management_generic_data_center_server_test.go +++ b/checkpoint/resource_checkpoint_management_generic_data_center_server_test.go @@ -16,7 +16,7 @@ func TestAccCheckpointManagementGenericDataCenterServer_basic(t *testing.T) { var genericDataCenterServerMap map[string]interface{} resourceName := "checkpoint_management_generic_data_center_server.test" objName := "tfTestManagementGenericDataCenterServer_" + acctest.RandString(6) - url := "/home/admin/test.json" + url := "MY_URL" interval := "60" context := os.Getenv("CHECKPOINT_CONTEXT") @@ -102,6 +102,7 @@ resource "checkpoint_management_generic_data_center_server" "test" { name = "%s" url = "%s" interval = "%s" + ignore_warnings = true } `, name, url, interval) } diff --git a/checkpoint/resource_checkpoint_management_group.go b/checkpoint/resource_checkpoint_management_group.go index c4868839..e60c011d 100644 --- a/checkpoint/resource_checkpoint_management_group.go +++ b/checkpoint/resource_checkpoint_management_group.go @@ -95,7 +95,7 @@ func createManagementGroup(d *schema.ResourceData, m interface{}) error { log.Println("Create Group - Map = ", group) - addGroupRes, err := client.ApiCall("add-group", group, client.GetSessionID(), true, false) + addGroupRes, err := client.ApiCall("add-group", group, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addGroupRes.Success { if addGroupRes.ErrorMsg != "" { return fmt.Errorf(addGroupRes.ErrorMsg) @@ -116,7 +116,7 @@ func readManagementGroup(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showGroupRes, err := client.ApiCall("show-group", payload, client.GetSessionID(), true, false) + showGroupRes, err := client.ApiCall("show-group", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -221,7 +221,7 @@ func updateManagementGroup(d *schema.ResourceData, m interface{}) error { } log.Println("Update Group - Map = ", group) - setGroupRes, _ := client.ApiCall("set-group", group, client.GetSessionID(), true, false) + setGroupRes, _ := client.ApiCall("set-group", group, client.GetSessionID(), true, client.IsProxyUsed()) if !setGroupRes.Success { return fmt.Errorf(setGroupRes.ErrorMsg) } @@ -234,7 +234,7 @@ func deleteManagementGroup(d *schema.ResourceData, m interface{}) error { payload := map[string]interface{}{ "uid": d.Id(), } - deleteGroupRes, _ := client.ApiCall("delete-group", payload, client.GetSessionID(), true, false) + deleteGroupRes, _ := client.ApiCall("delete-group", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !deleteGroupRes.Success { return fmt.Errorf(deleteGroupRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_group_with_exclusion.go b/checkpoint/resource_checkpoint_management_group_with_exclusion.go index 60738d9e..80070847 100644 --- a/checkpoint/resource_checkpoint_management_group_with_exclusion.go +++ b/checkpoint/resource_checkpoint_management_group_with_exclusion.go @@ -106,7 +106,7 @@ func createManagementGroupWithExclusion(d *schema.ResourceData, m interface{}) e log.Println("Create GroupWithExclusion - Map = ", groupWithExclusion) - addGroupWithExclusionRes, err := client.ApiCall("add-group-with-exclusion", groupWithExclusion, client.GetSessionID(), true, false) + addGroupWithExclusionRes, err := client.ApiCall("add-group-with-exclusion", groupWithExclusion, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addGroupWithExclusionRes.Success { if addGroupWithExclusionRes.ErrorMsg != "" { return fmt.Errorf(addGroupWithExclusionRes.ErrorMsg) @@ -127,7 +127,7 @@ func readManagementGroupWithExclusion(d *schema.ResourceData, m interface{}) err "uid": d.Id(), } - showGroupWithExclusionRes, err := client.ApiCall("show-group-with-exclusion", payload, client.GetSessionID(), true, false) + showGroupWithExclusionRes, err := client.ApiCall("show-group-with-exclusion", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -239,7 +239,7 @@ func updateManagementGroupWithExclusion(d *schema.ResourceData, m interface{}) e log.Println("Update GroupWithExclusion - Map = ", groupWithExclusion) - updateGroupWithExclusionRes, err := client.ApiCall("set-group-with-exclusion", groupWithExclusion, client.GetSessionID(), true, false) + updateGroupWithExclusionRes, err := client.ApiCall("set-group-with-exclusion", groupWithExclusion, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateGroupWithExclusionRes.Success { if updateGroupWithExclusionRes.ErrorMsg != "" { return fmt.Errorf(updateGroupWithExclusionRes.ErrorMsg) @@ -260,7 +260,7 @@ func deleteManagementGroupWithExclusion(d *schema.ResourceData, m interface{}) e log.Println("Delete GroupWithExclusion") - deleteGroupWithExclusionRes, err := client.ApiCall("delete-group-with-exclusion", groupWithExclusionPayload, client.GetSessionID(), true, false) + deleteGroupWithExclusionRes, err := client.ApiCall("delete-group-with-exclusion", groupWithExclusionPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteGroupWithExclusionRes.Success { if deleteGroupWithExclusionRes.ErrorMsg != "" { return fmt.Errorf(deleteGroupWithExclusionRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_gsn_handover_group.go b/checkpoint/resource_checkpoint_management_gsn_handover_group.go index 94f38924..37b0dea0 100644 --- a/checkpoint/resource_checkpoint_management_gsn_handover_group.go +++ b/checkpoint/resource_checkpoint_management_gsn_handover_group.go @@ -115,7 +115,7 @@ func createManagementGsnHandoverGroup(d *schema.ResourceData, m interface{}) err log.Println("Create GsnHandoverGroup - Map = ", gsnHandoverGroup) - addGsnHandoverGroupRes, err := client.ApiCall("add-gsn-handover-group", gsnHandoverGroup, client.GetSessionID(), true, false) + addGsnHandoverGroupRes, err := client.ApiCall("add-gsn-handover-group", gsnHandoverGroup, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addGsnHandoverGroupRes.Success { if addGsnHandoverGroupRes.ErrorMsg != "" { return fmt.Errorf(addGsnHandoverGroupRes.ErrorMsg) @@ -136,7 +136,7 @@ func readManagementGsnHandoverGroup(d *schema.ResourceData, m interface{}) error "uid": d.Id(), } - showGsnHandoverGroupRes, err := client.ApiCall("show-gsn-handover-group", payload, client.GetSessionID(), true, false) + showGsnHandoverGroupRes, err := client.ApiCall("show-gsn-handover-group", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -264,7 +264,7 @@ func updateManagementGsnHandoverGroup(d *schema.ResourceData, m interface{}) err log.Println("Update GsnHandoverGroup - Map = ", gsnHandoverGroup) - updateGsnHandoverGroupRes, err := client.ApiCall("set-gsn-handover-group", gsnHandoverGroup, client.GetSessionID(), true, false) + updateGsnHandoverGroupRes, err := client.ApiCall("set-gsn-handover-group", gsnHandoverGroup, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateGsnHandoverGroupRes.Success { if updateGsnHandoverGroupRes.ErrorMsg != "" { return fmt.Errorf(updateGsnHandoverGroupRes.ErrorMsg) @@ -285,7 +285,7 @@ func deleteManagementGsnHandoverGroup(d *schema.ResourceData, m interface{}) err log.Println("Delete GsnHandoverGroup") - deleteGsnHandoverGroupRes, err := client.ApiCall("delete-gsn-handover-group", gsnHandoverGroupPayload, client.GetSessionID(), true, false) + deleteGsnHandoverGroupRes, err := client.ApiCall("delete-gsn-handover-group", gsnHandoverGroupPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteGsnHandoverGroupRes.Success { if deleteGsnHandoverGroupRes.ErrorMsg != "" { return fmt.Errorf(deleteGsnHandoverGroupRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_host.go b/checkpoint/resource_checkpoint_management_host.go index e1a40d97..8440c91f 100644 --- a/checkpoint/resource_checkpoint_management_host.go +++ b/checkpoint/resource_checkpoint_management_host.go @@ -383,7 +383,7 @@ func createManagementHost(d *schema.ResourceData, m interface{}) error { log.Println("Create Host - Map = ", host) - addHostRes, err := client.ApiCall("add-host", host, client.GetSessionID(), true, false) + addHostRes, err := client.ApiCall("add-host", host, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addHostRes.Success { if addHostRes.ErrorMsg != "" { return fmt.Errorf(addHostRes.ErrorMsg) @@ -404,7 +404,7 @@ func readManagementHost(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showHostRes, err := client.ApiCall("show-host", payload, client.GetSessionID(), true, false) + showHostRes, err := client.ApiCall("show-host", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -572,7 +572,7 @@ func readManagementHost(d *schema.ResourceData, m interface{}) error { payload := map[string]interface{}{ "uid": v, } - showProtectedByRes, err := client.ApiCall("show-object", payload, client.GetSessionID(), true, false) + showProtectedByRes, err := client.ApiCall("show-object", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !showProtectedByRes.Success { if showProtectedByRes.ErrorMsg != "" { return fmt.Errorf(showProtectedByRes.ErrorMsg) @@ -791,7 +791,7 @@ func updateManagementHost(d *schema.ResourceData, m interface{}) error { } log.Println("Update Host - Map = ", host) - updateHostRes, err := client.ApiCall("set-host", host, client.GetSessionID(), true, false) + updateHostRes, err := client.ApiCall("set-host", host, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateHostRes.Success { if updateHostRes.ErrorMsg != "" { return fmt.Errorf(updateHostRes.ErrorMsg) @@ -810,7 +810,7 @@ func deleteManagementHost(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - deleteHostRes, err := client.ApiCall("delete-host", hostPayload, client.GetSessionID(), true, false) + deleteHostRes, err := client.ApiCall("delete-host", hostPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteHostRes.Success { if deleteHostRes.ErrorMsg != "" { return fmt.Errorf(deleteHostRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_https_layer.go b/checkpoint/resource_checkpoint_management_https_layer.go index d420bffc..5b72ce85 100644 --- a/checkpoint/resource_checkpoint_management_https_layer.go +++ b/checkpoint/resource_checkpoint_management_https_layer.go @@ -98,7 +98,7 @@ func createManagementHttpsLayer(d *schema.ResourceData, m interface{}) error { log.Println("Create HttpsLayer - Map = ", httpsLayer) - addHttpsLayerRes, err := client.ApiCall("add-https-layer", httpsLayer, client.GetSessionID(), true, false) + addHttpsLayerRes, err := client.ApiCall("add-https-layer", httpsLayer, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addHttpsLayerRes.Success { if addHttpsLayerRes.ErrorMsg != "" { return fmt.Errorf(addHttpsLayerRes.ErrorMsg) @@ -119,7 +119,7 @@ func readManagementHttpsLayer(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showHttpsLayerRes, err := client.ApiCall("show-https-layer", payload, client.GetSessionID(), true, false) + showHttpsLayerRes, err := client.ApiCall("show-https-layer", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -223,7 +223,7 @@ func updateManagementHttpsLayer(d *schema.ResourceData, m interface{}) error { log.Println("Update HttpsLayer - Map = ", httpsLayer) - updateHttpsLayerRes, err := client.ApiCall("set-https-layer", httpsLayer, client.GetSessionID(), true, false) + updateHttpsLayerRes, err := client.ApiCall("set-https-layer", httpsLayer, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateHttpsLayerRes.Success { if updateHttpsLayerRes.ErrorMsg != "" { return fmt.Errorf(updateHttpsLayerRes.ErrorMsg) @@ -244,7 +244,7 @@ func deleteManagementHttpsLayer(d *schema.ResourceData, m interface{}) error { log.Println("Delete HttpsLayer") - deleteHttpsLayerRes, err := client.ApiCall("delete-https-layer", httpsLayerPayload, client.GetSessionID(), true, false) + deleteHttpsLayerRes, err := client.ApiCall("delete-https-layer", httpsLayerPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteHttpsLayerRes.Success { if deleteHttpsLayerRes.ErrorMsg != "" { return fmt.Errorf(deleteHttpsLayerRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_https_rule.go b/checkpoint/resource_checkpoint_management_https_rule.go index 09664b89..fca91110 100644 --- a/checkpoint/resource_checkpoint_management_https_rule.go +++ b/checkpoint/resource_checkpoint_management_https_rule.go @@ -266,7 +266,7 @@ func createManagementHttpsRule(d *schema.ResourceData, m interface{}) error { } log.Println("Create HttpsRule - Map = ", httpsRule) - addHttpsRuleRes, err := client.ApiCall("add-https-rule", httpsRule, client.GetSessionID(), true, false) + addHttpsRuleRes, err := client.ApiCall("add-https-rule", httpsRule, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addHttpsRuleRes.Success { if addHttpsRuleRes.ErrorMsg != "" { return fmt.Errorf(addHttpsRuleRes.ErrorMsg) @@ -288,7 +288,7 @@ func readManagementHttpsRule(d *schema.ResourceData, m interface{}) error { "layer": d.Get("layer"), } - showHttpsRuleRes, err := client.ApiCall("show-https-rule", payload, client.GetSessionID(), true, false) + showHttpsRuleRes, err := client.ApiCall("show-https-rule", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -589,7 +589,7 @@ func updateManagementHttpsRule(d *schema.ResourceData, m interface{}) error { log.Println("Update HttpsRule - Map = ", httpsRule) - updateHttpsRuleRes, err := client.ApiCall("set-https-rule", httpsRule, client.GetSessionID(), true, false) + updateHttpsRuleRes, err := client.ApiCall("set-https-rule", httpsRule, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateHttpsRuleRes.Success { if updateHttpsRuleRes.ErrorMsg != "" { return fmt.Errorf(updateHttpsRuleRes.ErrorMsg) @@ -611,7 +611,7 @@ func deleteManagementHttpsRule(d *schema.ResourceData, m interface{}) error { log.Println("Delete HttpsRule") - deleteHttpsRuleRes, err := client.ApiCall("delete-https-rule", httpsRulePayload, client.GetSessionID(), true, false) + deleteHttpsRuleRes, err := client.ApiCall("delete-https-rule", httpsRulePayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteHttpsRuleRes.Success { if deleteHttpsRuleRes.ErrorMsg != "" { return fmt.Errorf(deleteHttpsRuleRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_https_section.go b/checkpoint/resource_checkpoint_management_https_section.go index 8631ef7d..eff9bd95 100644 --- a/checkpoint/resource_checkpoint_management_https_section.go +++ b/checkpoint/resource_checkpoint_management_https_section.go @@ -109,7 +109,7 @@ func createManagementHttpsSection(d *schema.ResourceData, m interface{}) error { } log.Println("Create HttpsSection - Map = ", httpsSection) - addHttpsSectionRes, err := client.ApiCall("add-https-section", httpsSection, client.GetSessionID(), true, false) + addHttpsSectionRes, err := client.ApiCall("add-https-section", httpsSection, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addHttpsSectionRes.Success { if addHttpsSectionRes.ErrorMsg != "" { return fmt.Errorf(addHttpsSectionRes.ErrorMsg) @@ -131,7 +131,7 @@ func readManagementHttpsSection(d *schema.ResourceData, m interface{}) error { "layer": d.Get("layer"), } - showHttpsSectionRes, err := client.ApiCall("show-https-section", payload, client.GetSessionID(), true, false) + showHttpsSectionRes, err := client.ApiCall("show-https-section", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -186,7 +186,7 @@ func updateManagementHttpsSection(d *schema.ResourceData, m interface{}) error { log.Println("Update HttpsSection - Map = ", httpsSection) - updateHttpsSectionRes, err := client.ApiCall("set-https-section", httpsSection, client.GetSessionID(), true, false) + updateHttpsSectionRes, err := client.ApiCall("set-https-section", httpsSection, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateHttpsSectionRes.Success { if updateHttpsSectionRes.ErrorMsg != "" { return fmt.Errorf(updateHttpsSectionRes.ErrorMsg) @@ -208,7 +208,7 @@ func deleteManagementHttpsSection(d *schema.ResourceData, m interface{}) error { log.Println("Delete HttpsSection") - deleteHttpsSectionRes, err := client.ApiCall("delete-https-section", httpsSectionPayload, client.GetSessionID(), true, false) + deleteHttpsSectionRes, err := client.ApiCall("delete-https-section", httpsSectionPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteHttpsSectionRes.Success { if deleteHttpsSectionRes.ErrorMsg != "" { return fmt.Errorf(deleteHttpsSectionRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_identity_tag.go b/checkpoint/resource_checkpoint_management_identity_tag.go index d13ba93f..93bada9e 100644 --- a/checkpoint/resource_checkpoint_management_identity_tag.go +++ b/checkpoint/resource_checkpoint_management_identity_tag.go @@ -94,7 +94,7 @@ func createManagementIdentityTag(d *schema.ResourceData, m interface{}) error { log.Println("Create IdentityTag - Map = ", identityTag) - addIdentityTagRes, err := client.ApiCall("add-identity-tag", identityTag, client.GetSessionID(), true, false) + addIdentityTagRes, err := client.ApiCall("add-identity-tag", identityTag, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addIdentityTagRes.Success { if addIdentityTagRes.ErrorMsg != "" { return fmt.Errorf(addIdentityTagRes.ErrorMsg) @@ -115,7 +115,7 @@ func readManagementIdentityTag(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showIdentityTagRes, err := client.ApiCall("show-identity-tag", payload, client.GetSessionID(), true, false) + showIdentityTagRes, err := client.ApiCall("show-identity-tag", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -210,7 +210,7 @@ func updateManagementIdentityTag(d *schema.ResourceData, m interface{}) error { log.Println("Update IdentityTag - Map = ", identityTag) - updateIdentityTagRes, err := client.ApiCall("set-identity-tag", identityTag, client.GetSessionID(), true, false) + updateIdentityTagRes, err := client.ApiCall("set-identity-tag", identityTag, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateIdentityTagRes.Success { if updateIdentityTagRes.ErrorMsg != "" { return fmt.Errorf(updateIdentityTagRes.ErrorMsg) @@ -231,7 +231,7 @@ func deleteManagementIdentityTag(d *schema.ResourceData, m interface{}) error { log.Println("Delete IdentityTag") - deleteIdentityTagRes, err := client.ApiCall("delete-identity-tag", identityTagPayload, client.GetSessionID(), true, false) + deleteIdentityTagRes, err := client.ApiCall("delete-identity-tag", identityTagPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteIdentityTagRes.Success { if deleteIdentityTagRes.ErrorMsg != "" { return fmt.Errorf(deleteIdentityTagRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_ise_data_center_server.go b/checkpoint/resource_checkpoint_management_ise_data_center_server.go new file mode 100644 index 00000000..b16d9f62 --- /dev/null +++ b/checkpoint/resource_checkpoint_management_ise_data_center_server.go @@ -0,0 +1,360 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "log" + "strconv" + "strings" +) + +func resourceManagementIseDataCenterServer() *schema.Resource { + return &schema.Resource{ + Create: createManagementIseDataCenterServer, + Read: readManagementIseDataCenterServer, + Update: updateManagementIseDataCenterServer, + Delete: deleteManagementIseDataCenterServer, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + Description: "Object name. Must be unique in the domain.", + }, + "hostnames": { + Type: schema.TypeList, + Required: true, + Description: "Address of ISE administrator hostnames.\nExample: http(s)://.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "username": { + Type: schema.TypeString, + Required: true, + Description: "User ID of the ISE administrator server.\nWhen using commonLoginLogic Domains use the following syntax:\napic:\\.", + }, + "password": { + Type: schema.TypeString, + Optional: true, + Description: "Password of the ISE administrator server.", + }, + "password_base64": { + Type: schema.TypeString, + Optional: true, + Description: "Password of the Cisco ISE administrator encoded in Base64.", + }, + "certificate_fingerprint": { + Type: schema.TypeString, + Optional: true, + Description: "Specify the SHA-1 or SHA-256 fingerprint of the Data Center Server's certificate.", + }, + "unsafe_auto_accept": { + Type: schema.TypeBool, + Optional: true, + Description: "When set to false, the current Data Center Server's certificate should be trusted, either by providing the certificate-fingerprint argument or by relying on a previously trusted certificate of this hostname.\n\nWhen set to true, trust the current Data Center Server's certificate as-is.", + Default: false, + }, + "tags": { + Type: schema.TypeSet, + Optional: true, + Description: "Collection of tag identifiers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "color": { + Type: schema.TypeString, + Optional: true, + Description: "Color of the object. Should be one of existing colors.", + Default: "black", + }, + "comments": { + Type: schema.TypeString, + Optional: true, + Description: "Comments string.", + }, + "ignore_warnings": { + Type: schema.TypeBool, + Optional: true, + Description: "Apply changes ignoring warnings. By Setting this parameter to 'true' test connection failure will be ignored.", + Default: false, + }, + "ignore_errors": { + Type: schema.TypeBool, + Optional: true, + Description: "Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored.", + Default: false, + }, + }, + } +} + +func createManagementIseDataCenterServer(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + + iseDataCenterServer := make(map[string]interface{}) + + if v, ok := d.GetOk("name"); ok { + iseDataCenterServer["name"] = v.(string) + } + + iseDataCenterServer["type"] = "ise" + + if v, ok := d.GetOk("hostnames"); ok { + iseDataCenterServer["hostnames"] = v + } + + if v, ok := d.GetOk("username"); ok { + iseDataCenterServer["username"] = v.(string) + } + + if v, ok := d.GetOk("password"); ok { + iseDataCenterServer["password"] = v.(string) + } + + if v, ok := d.GetOk("password_base64"); ok { + iseDataCenterServer["password-base64"] = v.(string) + } + + if v, ok := d.GetOk("certificate_fingerprint"); ok { + iseDataCenterServer["certificate-fingerprint"] = v.(string) + } + + if v, ok := d.GetOk("unsafe_auto_accept"); ok { + iseDataCenterServer["unsafe-auto-accept"] = v.(bool) + } + + if v, ok := d.GetOk("tags"); ok { + iseDataCenterServer["tags"] = v.(*schema.Set).List() + } + + if v, ok := d.GetOk("color"); ok { + iseDataCenterServer["color"] = v.(string) + } + + if v, ok := d.GetOk("comments"); ok { + iseDataCenterServer["comments"] = v.(string) + } + + if v, ok := d.GetOkExists("ignore_warnings"); ok { + iseDataCenterServer["ignore-warnings"] = v.(bool) + } + + if v, ok := d.GetOkExists("ignore_errors"); ok { + iseDataCenterServer["ignore-errors"] = v.(bool) + } + + log.Println("Create iseDataCenterServer - Map = ", iseDataCenterServer) + + addIseDataCenterServerRes, err := client.ApiCall("add-data-center-server", iseDataCenterServer, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !addIseDataCenterServerRes.Success { + if addIseDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(addIseDataCenterServerRes.ErrorMsg) + } + msg := createTaskFailMessage("add-data-center-server", addIseDataCenterServerRes.GetData()) + return fmt.Errorf(msg) + } + payload := map[string]interface{}{ + "name": iseDataCenterServer["name"], + } + showIseDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showIseDataCenterServerRes.Success { + return fmt.Errorf(showIseDataCenterServerRes.ErrorMsg) + } + d.SetId(showIseDataCenterServerRes.GetData()["uid"].(string)) + return readManagementIseDataCenterServer(d, m) +} + +func readManagementIseDataCenterServer(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + payload := map[string]interface{}{ + "uid": d.Id(), + } + + showIseDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showIseDataCenterServerRes.Success { + if objectNotFound(showIseDataCenterServerRes.GetData()["code"].(string)) { + d.SetId("") + return nil + } + return fmt.Errorf(showIseDataCenterServerRes.ErrorMsg) + } + iseDataCenterServer := showIseDataCenterServerRes.GetData() + + if v := iseDataCenterServer["name"]; v != nil { + _ = d.Set("name", v) + } + + if iseDataCenterServer["properties"] != nil { + propsJson, ok := iseDataCenterServer["properties"].([]interface{}) + if ok { + for _, prop := range propsJson { + propMap := prop.(map[string]interface{}) + propName := strings.ReplaceAll(propMap["name"].(string), "-", "_") + propValue := propMap["value"] + if propName == "unsafe_auto_accept" { + propValue, _ = strconv.ParseBool(propValue.(string)) + } + if propName == "hostnames" { + propValue = strings.Split(propValue.(string), ";") + } + _ = d.Set(propName, propValue) + } + } + } + + if iseDataCenterServer["tags"] != nil { + tagsJson, ok := iseDataCenterServer["tags"].([]interface{}) + if ok { + tagsIds := make([]string, 0) + if len(tagsJson) > 0 { + for _, tags := range tagsJson { + tags := tags.(map[string]interface{}) + tagsIds = append(tagsIds, tags["name"].(string)) + } + } + _ = d.Set("tags", tagsIds) + } + } else { + _ = d.Set("tags", nil) + } + + if v := iseDataCenterServer["color"]; v != nil { + _ = d.Set("color", v) + } + + if v := iseDataCenterServer["comments"]; v != nil { + _ = d.Set("comments", v) + } + + if v := iseDataCenterServer["ignore-warnings"]; v != nil { + _ = d.Set("ignore_warnings", v) + } + + if v := iseDataCenterServer["ignore-errors"]; v != nil { + _ = d.Set("ignore_errors", v) + } + + return nil + +} + +func updateManagementIseDataCenterServer(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + iseDataCenterServer := make(map[string]interface{}) + + if ok := d.HasChange("name"); ok { + oldName, newName := d.GetChange("name") + iseDataCenterServer["name"] = oldName + iseDataCenterServer["new-name"] = newName + } else { + iseDataCenterServer["name"] = d.Get("name") + } + + if d.HasChange("hostnames") { + iseDataCenterServer["hostnames"] = d.Get("hostnames") + } + + if d.HasChange("password") { + iseDataCenterServer["password"] = d.Get("password") + } + + if d.HasChange("password_base64") { + iseDataCenterServer["password-base64"] = d.Get("password_base64") + } + + if d.HasChange("username") { + iseDataCenterServer["username"] = d.Get("username") + if v := d.Get("password"); v != nil && v != "" { + iseDataCenterServer["password"] = v + } + if v := d.Get("password_base64"); v != nil && v != "" { + iseDataCenterServer["password-base64"] = v + } + } + + if d.HasChange("certificate_fingerprint") { + iseDataCenterServer["certificate-fingerprint"] = d.Get("certificate_fingerprint") + } + + if d.HasChange("unsafe_auto_accept") { + iseDataCenterServer["unsafe-auto-accept"] = d.Get("unsafe_auto_accept") + } + + if d.HasChange("tags") { + if v, ok := d.GetOk("tags"); ok { + iseDataCenterServer["tags"] = v.(*schema.Set).List() + } else { + oldTags, _ := d.GetChange("tags") + iseDataCenterServer["tags"] = map[string]interface{}{"remove": oldTags.(*schema.Set).List()} + } + } + + if ok := d.HasChange("color"); ok { + iseDataCenterServer["color"] = d.Get("color") + } + + if ok := d.HasChange("comments"); ok { + iseDataCenterServer["comments"] = d.Get("comments") + } + + if v, ok := d.GetOkExists("ignore_warnings"); ok { + iseDataCenterServer["ignore-warnings"] = v.(bool) + } + + if v, ok := d.GetOkExists("ignore_errors"); ok { + iseDataCenterServer["ignore-errors"] = v.(bool) + } + + log.Println("Update iseDataCenterServer - Map = ", iseDataCenterServer) + + updateIseDataCenterServerRes, err := client.ApiCall("set-data-center-server", iseDataCenterServer, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !updateIseDataCenterServerRes.Success { + if updateIseDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(updateIseDataCenterServerRes.ErrorMsg) + } + msg := createTaskFailMessage("set-data-center-server", updateIseDataCenterServerRes.GetData()) + return fmt.Errorf(msg) + } + + return readManagementIseDataCenterServer(d, m) +} + +func deleteManagementIseDataCenterServer(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + + iseDataCenterServerPayload := map[string]interface{}{ + "uid": d.Id(), + } + + log.Println("Delete iseDataCenterServer") + + deleteIseDataCenterServerRes, err := client.ApiCall("delete-data-center-server", iseDataCenterServerPayload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil || !deleteIseDataCenterServerRes.Success { + if deleteIseDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(deleteIseDataCenterServerRes.ErrorMsg) + } + return fmt.Errorf(err.Error()) + } + d.SetId("") + + return nil +} diff --git a/checkpoint/resource_checkpoint_management_ise_data_center_server_test.go b/checkpoint/resource_checkpoint_management_ise_data_center_server_test.go new file mode 100644 index 00000000..0cadb41d --- /dev/null +++ b/checkpoint/resource_checkpoint_management_ise_data_center_server_test.go @@ -0,0 +1,110 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + "os" + "strings" + "testing" +) + +func TestAccCheckpointManagementIseDataCenterServer_basic(t *testing.T) { + + var iseDataCenterServerMap map[string]interface{} + resourceName := "checkpoint_management_ise_data_center_server.test" + objName := "tfTestManagementIseDataCenterServer_" + acctest.RandString(6) + username := "USERNAME" + password := "PASSWORD" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } else if context == "" { + t.Skip("Env CHECKPOINT_CONTEXT must be specified to run this acc test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckpointManagementIseDataCenterServerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccManagementIseDataCenterServerConfig(objName, username, password), + Check: resource.ComposeTestCheckFunc( + testAccCheckCheckpointManagementIseDataCenterServerExists(resourceName, &iseDataCenterServerMap), + testAccCheckCheckpointManagementIseDataCenterServerAttributes(&iseDataCenterServerMap, objName), + ), + }, + }, + }) +} + +func testAccCheckpointManagementIseDataCenterServerDestroy(s *terraform.State) error { + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + for _, rs := range s.RootModule().Resources { + if rs.Type != "checkpoint_management_ise_data_center_server" { + continue + } + if rs.Primary.ID != "" { + res, _ := client.ApiCall("show-data-center-server", map[string]interface{}{"uid": rs.Primary.ID}, client.GetSessionID(), true, false) + if res.Success { + return fmt.Errorf("IseDataCenterServer object (%s) still exists", rs.Primary.ID) + } + } + return nil + } + return nil +} + +func testAccCheckCheckpointManagementIseDataCenterServerExists(resourceTfName string, res *map[string]interface{}) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[resourceTfName] + if !ok { + return fmt.Errorf("Resource not found: %s", resourceTfName) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("IseDataCenterServer ID is not set") + } + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + + response, err := client.ApiCall("show-data-center-server", map[string]interface{}{"uid": rs.Primary.ID}, client.GetSessionID(), true, false) + if !response.Success { + return err + } + + *res = response.GetData() + + return nil + } +} + +func testAccCheckCheckpointManagementIseDataCenterServerAttributes(iseDataCenterServerMap *map[string]interface{}, name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + + iseDataCenterServerName := (*iseDataCenterServerMap)["name"].(string) + if !strings.EqualFold(iseDataCenterServerName, name) { + return fmt.Errorf("name is %s, expected %s", name, iseDataCenterServerName) + } + return nil + } +} + +func testAccManagementIseDataCenterServerConfig(name string, username string, password string) string { + return fmt.Sprintf(` +resource "checkpoint_management_ise_data_center_server" "test" { + name = "%s" + username = "%s" + password = "%s" + hostnames = ["host1", "host2"] + unsafe_auto_accept = true + ignore_warnings = true +} +`, name, username, password) +} diff --git a/checkpoint/resource_checkpoint_management_kubernetes_data_center_server.go b/checkpoint/resource_checkpoint_management_kubernetes_data_center_server.go new file mode 100644 index 00000000..eacb2579 --- /dev/null +++ b/checkpoint/resource_checkpoint_management_kubernetes_data_center_server.go @@ -0,0 +1,324 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "log" + "strconv" + "strings" +) + +func resourceManagementKubernetesDataCenterServer() *schema.Resource { + return &schema.Resource{ + Create: createManagementKubernetesDataCenterServer, + Read: readManagementKubernetesDataCenterServer, + Update: updateManagementKubernetesDataCenterServer, + Delete: deleteManagementKubernetesDataCenterServer, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + Description: "Object name. Must be unique in the domain.", + }, + "hostname": { + Type: schema.TypeString, + Required: true, + Description: "IP address or hostname of the Kubernetes server.", + }, + "token_file": { + Type: schema.TypeString, + Required: true, + Description: "Kubernetes access token encoded in base64.", + }, + "ca_certificate": { + Type: schema.TypeString, + Optional: true, + Description: "The Kubernetes public certificate key encoded in base64.", + }, + "unsafe_auto_accept": { + Type: schema.TypeBool, + Optional: true, + Description: "When set to false, the current Data Center Server's certificate should be trusted, either by providing the certificate-fingerprint argument or by relying on a previously trusted certificate of this hostname.\n\nWhen set to true, trust the current Data Center Server's certificate as-is.", + Default: false, + }, + "tags": { + Type: schema.TypeSet, + Optional: true, + Description: "Collection of tag identifiers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "color": { + Type: schema.TypeString, + Optional: true, + Description: "Color of the object. Should be one of existing colors.", + Default: "black", + }, + "comments": { + Type: schema.TypeString, + Optional: true, + Description: "Comments string.", + }, + "ignore_warnings": { + Type: schema.TypeBool, + Optional: true, + Description: "Apply changes ignoring warnings. By Setting this parameter to 'true' test connection failure will be ignored.", + Default: false, + }, + "ignore_errors": { + Type: schema.TypeBool, + Optional: true, + Description: "Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored.", + Default: false, + }, + }, + } +} + +func createManagementKubernetesDataCenterServer(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + + kubernetesDataCenterServer := make(map[string]interface{}) + + if v, ok := d.GetOk("name"); ok { + kubernetesDataCenterServer["name"] = v.(string) + } + + kubernetesDataCenterServer["type"] = "kubernetes" + + if v, ok := d.GetOk("hostname"); ok { + kubernetesDataCenterServer["hostname"] = v.(string) + } + + if v, ok := d.GetOk("token_file"); ok { + kubernetesDataCenterServer["token-file"] = v.(string) + } + + if v, ok := d.GetOk("ca_certificate"); ok { + kubernetesDataCenterServer["ca-certificate"] = v.(string) + } + + if v, ok := d.GetOk("unsafe_auto_accept"); ok { + kubernetesDataCenterServer["unsafe-auto-accept"] = v.(bool) + } + + if v, ok := d.GetOk("tags"); ok { + kubernetesDataCenterServer["tags"] = v.(*schema.Set).List() + } + + if v, ok := d.GetOk("color"); ok { + kubernetesDataCenterServer["color"] = v.(string) + } + + if v, ok := d.GetOk("comments"); ok { + kubernetesDataCenterServer["comments"] = v.(string) + } + + if v, ok := d.GetOkExists("ignore_warnings"); ok { + kubernetesDataCenterServer["ignore-warnings"] = v.(bool) + } + + if v, ok := d.GetOkExists("ignore_errors"); ok { + kubernetesDataCenterServer["ignore-errors"] = v.(bool) + } + + log.Println("Create kubernetesDataCenterServer - Map = ", kubernetesDataCenterServer) + + addKubernetesDataCenterServerRes, err := client.ApiCall("add-data-center-server", kubernetesDataCenterServer, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !addKubernetesDataCenterServerRes.Success { + if addKubernetesDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(addKubernetesDataCenterServerRes.ErrorMsg) + } + msg := createTaskFailMessage("add-data-center-server", addKubernetesDataCenterServerRes.GetData()) + return fmt.Errorf(msg) + } + payload := map[string]interface{}{ + "name": kubernetesDataCenterServer["name"], + } + showKubernetesDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showKubernetesDataCenterServerRes.Success { + return fmt.Errorf(showKubernetesDataCenterServerRes.ErrorMsg) + } + d.SetId(showKubernetesDataCenterServerRes.GetData()["uid"].(string)) + return readManagementKubernetesDataCenterServer(d, m) +} + +func readManagementKubernetesDataCenterServer(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + payload := map[string]interface{}{ + "uid": d.Id(), + } + + showKubernetesDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showKubernetesDataCenterServerRes.Success { + if objectNotFound(showKubernetesDataCenterServerRes.GetData()["code"].(string)) { + d.SetId("") + return nil + } + return fmt.Errorf(showKubernetesDataCenterServerRes.ErrorMsg) + } + kubernetesDataCenterServer := showKubernetesDataCenterServerRes.GetData() + + if v := kubernetesDataCenterServer["name"]; v != nil { + _ = d.Set("name", v) + } + + if kubernetesDataCenterServer["properties"] != nil { + propsJson, ok := kubernetesDataCenterServer["properties"].([]interface{}) + if ok { + for _, prop := range propsJson { + propMap := prop.(map[string]interface{}) + if propMap["name"] != nil { + propName := strings.ReplaceAll(propMap["name"].(string), "-", "_") + propValue := propMap["value"] + if propName == "unsafe_auto_accept" { + propValue, _ = strconv.ParseBool(propValue.(string)) + } + _ = d.Set(propName, propValue) + } + } + } + } + + if kubernetesDataCenterServer["tags"] != nil { + tagsJson, ok := kubernetesDataCenterServer["tags"].([]interface{}) + if ok { + tagsIds := make([]string, 0) + if len(tagsJson) > 0 { + for _, tags := range tagsJson { + tags := tags.(map[string]interface{}) + tagsIds = append(tagsIds, tags["name"].(string)) + } + } + _ = d.Set("tags", tagsIds) + } + } else { + _ = d.Set("tags", nil) + } + + if v := kubernetesDataCenterServer["color"]; v != nil { + _ = d.Set("color", v) + } + + if v := kubernetesDataCenterServer["comments"]; v != nil { + _ = d.Set("comments", v) + } + + if v := kubernetesDataCenterServer["ignore-warnings"]; v != nil { + _ = d.Set("ignore_warnings", v) + } + + if v := kubernetesDataCenterServer["ignore-errors"]; v != nil { + _ = d.Set("ignore_errors", v) + } + + return nil + +} + +func updateManagementKubernetesDataCenterServer(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + kubernetesDataCenterServer := make(map[string]interface{}) + + if ok := d.HasChange("name"); ok { + oldName, newName := d.GetChange("name") + kubernetesDataCenterServer["name"] = oldName + kubernetesDataCenterServer["new-name"] = newName + } else { + kubernetesDataCenterServer["name"] = d.Get("name") + } + + if d.HasChange("hostname") { + kubernetesDataCenterServer["hostname"] = d.Get("hostname") + } + + if d.HasChange("token_file") { + kubernetesDataCenterServer["token-file"] = d.Get("token_file") + } + + if d.HasChange("ca_certificate") { + kubernetesDataCenterServer["ca-certificate"] = d.Get("ca_certificate") + } + + if d.HasChange("unsafe_auto_accept") { + kubernetesDataCenterServer["unsafe-auto-accept"] = d.Get("unsafe_auto_accept") + } + + if d.HasChange("tags") { + if v, ok := d.GetOk("tags"); ok { + kubernetesDataCenterServer["tags"] = v.(*schema.Set).List() + } else { + oldTags, _ := d.GetChange("tags") + kubernetesDataCenterServer["tags"] = map[string]interface{}{"remove": oldTags.(*schema.Set).List()} + } + } + + if ok := d.HasChange("color"); ok { + kubernetesDataCenterServer["color"] = d.Get("color") + } + + if ok := d.HasChange("comments"); ok { + kubernetesDataCenterServer["comments"] = d.Get("comments") + } + + if v, ok := d.GetOkExists("ignore_warnings"); ok { + kubernetesDataCenterServer["ignore-warnings"] = v.(bool) + } + + if v, ok := d.GetOkExists("ignore_errors"); ok { + kubernetesDataCenterServer["ignore-errors"] = v.(bool) + } + + log.Println("Update kubernetesDataCenterServer - Map = ", kubernetesDataCenterServer) + + updateKubernetesDataCenterServerRes, err := client.ApiCall("set-data-center-server", kubernetesDataCenterServer, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !updateKubernetesDataCenterServerRes.Success { + if updateKubernetesDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(updateKubernetesDataCenterServerRes.ErrorMsg) + } + msg := createTaskFailMessage("set-data-center-server", updateKubernetesDataCenterServerRes.GetData()) + return fmt.Errorf(msg) + } + + return readManagementKubernetesDataCenterServer(d, m) +} + +func deleteManagementKubernetesDataCenterServer(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + + kubernetesDataCenterServerPayload := map[string]interface{}{ + "uid": d.Id(), + } + + log.Println("Delete kubernetesDataCenterServer") + + deleteKubernetesDataCenterServerRes, err := client.ApiCall("delete-data-center-server", kubernetesDataCenterServerPayload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil || !deleteKubernetesDataCenterServerRes.Success { + if deleteKubernetesDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(deleteKubernetesDataCenterServerRes.ErrorMsg) + } + return fmt.Errorf(err.Error()) + } + d.SetId("") + + return nil +} diff --git a/checkpoint/resource_checkpoint_management_kubernetes_data_center_server_test.go b/checkpoint/resource_checkpoint_management_kubernetes_data_center_server_test.go new file mode 100644 index 00000000..fb673ebf --- /dev/null +++ b/checkpoint/resource_checkpoint_management_kubernetes_data_center_server_test.go @@ -0,0 +1,109 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + "os" + "strings" + "testing" +) + +func TestAccCheckpointManagementKubernetesDataCenterServer_basic(t *testing.T) { + + var kubernetesDataCenterServerMap map[string]interface{} + resourceName := "checkpoint_management_kubernetes_data_center_server.test" + objName := "tfTestManagementKubernetesDataCenterServer_" + acctest.RandString(6) + hostname := "MY_HOSTNAME" + token_file := "MY_TOKEN" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } else if context == "" { + t.Skip("Env CHECKPOINT_CONTEXT must be specified to run this acc test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckpointManagementKubernetesDataCenterServerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccManagementKubernetesDataCenterServerConfig(objName, hostname, token_file), + Check: resource.ComposeTestCheckFunc( + testAccCheckCheckpointManagementKubernetesDataCenterServerExists(resourceName, &kubernetesDataCenterServerMap), + testAccCheckCheckpointManagementKubernetesDataCenterServerAttributes(&kubernetesDataCenterServerMap, objName), + ), + }, + }, + }) +} + +func testAccCheckpointManagementKubernetesDataCenterServerDestroy(s *terraform.State) error { + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + for _, rs := range s.RootModule().Resources { + if rs.Type != "checkpoint_management_kubernetes_data_center_server" { + continue + } + if rs.Primary.ID != "" { + res, _ := client.ApiCall("show-data-center-server", map[string]interface{}{"uid": rs.Primary.ID}, client.GetSessionID(), true, false) + if res.Success { + return fmt.Errorf("KubernetesDataCenterServer object (%s) still exists", rs.Primary.ID) + } + } + return nil + } + return nil +} + +func testAccCheckCheckpointManagementKubernetesDataCenterServerExists(resourceTfName string, res *map[string]interface{}) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[resourceTfName] + if !ok { + return fmt.Errorf("Resource not found: %s", resourceTfName) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("KubernetesDataCenterServer ID is not set") + } + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + + response, err := client.ApiCall("show-data-center-server", map[string]interface{}{"uid": rs.Primary.ID}, client.GetSessionID(), true, false) + if !response.Success { + return err + } + + *res = response.GetData() + + return nil + } +} + +func testAccCheckCheckpointManagementKubernetesDataCenterServerAttributes(kubernetesDataCenterServerMap *map[string]interface{}, name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + + kubernetesDataCenterServerName := (*kubernetesDataCenterServerMap)["name"].(string) + if !strings.EqualFold(kubernetesDataCenterServerName, name) { + return fmt.Errorf("name is %s, expected %s", name, kubernetesDataCenterServerName) + } + return nil + } +} + +func testAccManagementKubernetesDataCenterServerConfig(name string, hostname string, token_file string) string { + return fmt.Sprintf(` +resource "checkpoint_management_kubernetes_data_center_server" "test" { + name = "%s" + hostname = "%s" + token_file = "%s" + unsafe_auto_accept = true + ignore_warnings = true +} +`, name, hostname, token_file) +} diff --git a/checkpoint/resource_checkpoint_management_mds.go b/checkpoint/resource_checkpoint_management_mds.go index 00c22d49..afd304f9 100644 --- a/checkpoint/resource_checkpoint_management_mds.go +++ b/checkpoint/resource_checkpoint_management_mds.go @@ -194,7 +194,7 @@ func createManagementMds(d *schema.ResourceData, m interface{}) error { log.Println("Create Mds - Map = ", mds) - addMdsRes, err := client.ApiCall("add-mds", mds, client.GetSessionID(), true, false) + addMdsRes, err := client.ApiCall("add-mds", mds, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addMdsRes.Success { if addMdsRes.ErrorMsg != "" { return fmt.Errorf(addMdsRes.ErrorMsg) @@ -215,7 +215,7 @@ func readManagementMds(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showMdsRes, err := client.ApiCall("show-mds", payload, client.GetSessionID(), true, false) + showMdsRes, err := client.ApiCall("show-mds", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -409,7 +409,7 @@ func updateManagementMds(d *schema.ResourceData, m interface{}) error { log.Println("Update Mds - Map = ", mds) - updateMdsRes, err := client.ApiCall("set-mds", mds, client.GetSessionID(), true, false) + updateMdsRes, err := client.ApiCall("set-mds", mds, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateMdsRes.Success { if updateMdsRes.ErrorMsg != "" { return fmt.Errorf(updateMdsRes.ErrorMsg) @@ -430,7 +430,7 @@ func deleteManagementMds(d *schema.ResourceData, m interface{}) error { log.Println("Delete Mds") - deleteMdsRes, err := client.ApiCall("delete-mds", mdsPayload, client.GetSessionID(), true, false) + deleteMdsRes, err := client.ApiCall("delete-mds", mdsPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteMdsRes.Success { if deleteMdsRes.ErrorMsg != "" { return fmt.Errorf(deleteMdsRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_multicast_address_range.go b/checkpoint/resource_checkpoint_management_multicast_address_range.go index aea03886..2f93f2db 100644 --- a/checkpoint/resource_checkpoint_management_multicast_address_range.go +++ b/checkpoint/resource_checkpoint_management_multicast_address_range.go @@ -142,7 +142,7 @@ func createManagementMulticastAddressRange(d *schema.ResourceData, m interface{} log.Println("Create MulticastAddressRange - Map = ", multicastAddressRange) - addMulticastAddressRangeRes, err := client.ApiCall("add-multicast-address-range", multicastAddressRange, client.GetSessionID(), true, false) + addMulticastAddressRangeRes, err := client.ApiCall("add-multicast-address-range", multicastAddressRange, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addMulticastAddressRangeRes.Success { if addMulticastAddressRangeRes.ErrorMsg != "" { return fmt.Errorf(addMulticastAddressRangeRes.ErrorMsg) @@ -163,7 +163,7 @@ func readManagementMulticastAddressRange(d *schema.ResourceData, m interface{}) "uid": d.Id(), } - showMulticastAddressRangeRes, err := client.ApiCall("show-multicast-address-range", payload, client.GetSessionID(), true, false) + showMulticastAddressRangeRes, err := client.ApiCall("show-multicast-address-range", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -307,7 +307,7 @@ func updateManagementMulticastAddressRange(d *schema.ResourceData, m interface{} log.Println("Update MulticastAddressRange - Map = ", multicastAddressRange) - updateMulticastAddressRangeRes, err := client.ApiCall("set-multicast-address-range", multicastAddressRange, client.GetSessionID(), true, false) + updateMulticastAddressRangeRes, err := client.ApiCall("set-multicast-address-range", multicastAddressRange, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateMulticastAddressRangeRes.Success { if updateMulticastAddressRangeRes.ErrorMsg != "" { return fmt.Errorf(updateMulticastAddressRangeRes.ErrorMsg) @@ -328,7 +328,7 @@ func deleteManagementMulticastAddressRange(d *schema.ResourceData, m interface{} log.Println("Delete MulticastAddressRange") - deleteMulticastAddressRangeRes, err := client.ApiCall("delete-multicast-address-range", multicastAddressRangePayload, client.GetSessionID(), true, false) + deleteMulticastAddressRangeRes, err := client.ApiCall("delete-multicast-address-range", multicastAddressRangePayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteMulticastAddressRangeRes.Success { if deleteMulticastAddressRangeRes.ErrorMsg != "" { return fmt.Errorf(deleteMulticastAddressRangeRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_nat_rule.go b/checkpoint/resource_checkpoint_management_nat_rule.go index 17bed00e..3b0d1021 100644 --- a/checkpoint/resource_checkpoint_management_nat_rule.go +++ b/checkpoint/resource_checkpoint_management_nat_rule.go @@ -232,7 +232,7 @@ func createManagementNatRule(d *schema.ResourceData, m interface{}) error { log.Println("Create NAT Rule - Map = ", natRule) - addNatRuleRes, err := client.ApiCall("add-nat-rule", natRule, client.GetSessionID(), true, false) + addNatRuleRes, err := client.ApiCall("add-nat-rule", natRule, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addNatRuleRes.Success { if addNatRuleRes.ErrorMsg != "" { return fmt.Errorf(addNatRuleRes.ErrorMsg) @@ -254,7 +254,7 @@ func readManagementNatRule(d *schema.ResourceData, m interface{}) error { "package": d.Get("package"), } - showNatRuleRes, err := client.ApiCall("show-nat-rule", payload, client.GetSessionID(), true, false) + showNatRuleRes, err := client.ApiCall("show-nat-rule", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -430,7 +430,7 @@ func updateManagementNatRule(d *schema.ResourceData, m interface{}) error { log.Println("Update NAT Rule - Map = ", natRule) - updateNatRuleRes, err := client.ApiCall("set-nat-rule", natRule, client.GetSessionID(), true, false) + updateNatRuleRes, err := client.ApiCall("set-nat-rule", natRule, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateNatRuleRes.Success { if updateNatRuleRes.ErrorMsg != "" { return fmt.Errorf(updateNatRuleRes.ErrorMsg) @@ -449,7 +449,7 @@ func deleteManagementNatRule(d *schema.ResourceData, m interface{}) error { "package": d.Get("package"), } - deleteAccessRuleRes, err := client.ApiCall("delete-nat-rule", natRulePayload, client.GetSessionID(), true, false) + deleteAccessRuleRes, err := client.ApiCall("delete-nat-rule", natRulePayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteAccessRuleRes.Success { if deleteAccessRuleRes.ErrorMsg != "" { return fmt.Errorf(deleteAccessRuleRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_nat_section.go b/checkpoint/resource_checkpoint_management_nat_section.go index 0a2a3299..e2225d1f 100644 --- a/checkpoint/resource_checkpoint_management_nat_section.go +++ b/checkpoint/resource_checkpoint_management_nat_section.go @@ -119,7 +119,7 @@ func createManagementNatSection(d *schema.ResourceData, m interface{}) error { log.Println("Create NAT section - Map = ", natSection) - addNatSectionRes, err := client.ApiCall("add-nat-section", natSection, client.GetSessionID(), true, false) + addNatSectionRes, err := client.ApiCall("add-nat-section", natSection, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addNatSectionRes.Success { if addNatSectionRes.ErrorMsg != "" { return fmt.Errorf(addNatSectionRes.ErrorMsg) @@ -141,7 +141,7 @@ func readManagementNatSection(d *schema.ResourceData, m interface{}) error { "package": d.Get("package"), } - showNatSectionRes, err := client.ApiCall("show-nat-section", payload, client.GetSessionID(), true, false) + showNatSectionRes, err := client.ApiCall("show-nat-section", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -186,7 +186,7 @@ func updateManagementNatSection(d *schema.ResourceData, m interface{}) error { log.Println("Update NAT section - Map = ", natSection) - updateNatSectionRes, err := client.ApiCall("set-nat-section", natSection, client.GetSessionID(), true, false) + updateNatSectionRes, err := client.ApiCall("set-nat-section", natSection, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateNatSectionRes.Success { if updateNatSectionRes.ErrorMsg != "" { return fmt.Errorf(updateNatSectionRes.ErrorMsg) @@ -208,7 +208,7 @@ func deleteManagementNatSection(d *schema.ResourceData, m interface{}) error { log.Println("Delete NAT section") - deleteNatSectionRes, err := client.ApiCall("delete-nat-section", natSectionPayload, client.GetSessionID(), true, false) + deleteNatSectionRes, err := client.ApiCall("delete-nat-section", natSectionPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteNatSectionRes.Success { if deleteNatSectionRes.ErrorMsg != "" { return fmt.Errorf(deleteNatSectionRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_nat_section_test.go b/checkpoint/resource_checkpoint_management_nat_section_test.go index 6af5f4df..31f0bff0 100644 --- a/checkpoint/resource_checkpoint_management_nat_section_test.go +++ b/checkpoint/resource_checkpoint_management_nat_section_test.go @@ -48,7 +48,7 @@ func testAccCheckpointManagementNatSectionDestroy(s *terraform.State) error { continue } if rs.Primary.ID != "" { - res, _ := client.ApiCall("show-nat-section", map[string]interface{}{"uid": rs.Primary.ID, "package": "Standard"}, client.GetSessionID(), true, false) + res, _ := client.ApiCall("show-nat-section", map[string]interface{}{"uid": rs.Primary.ID, "package": "Standard"}, client.GetSessionID(), true, client.IsProxyUsed()) if res.Success { return fmt.Errorf("NAT section object (%s) still exists", rs.Primary.ID) } @@ -72,7 +72,7 @@ func testAccCheckCheckpointManagementNatSectionExists(resourceTfName string, res client := testAccProvider.Meta().(*checkpoint.ApiClient) - response, err := client.ApiCall("show-nat-section", map[string]interface{}{"uid": rs.Primary.ID, "package": "Standard"}, client.GetSessionID(), true, false) + response, err := client.ApiCall("show-nat-section", map[string]interface{}{"uid": rs.Primary.ID, "package": "Standard"}, client.GetSessionID(), true, client.IsProxyUsed()) if !response.Success { return err } diff --git a/checkpoint/resource_checkpoint_management_network.go b/checkpoint/resource_checkpoint_management_network.go index d661de59..39adf41c 100644 --- a/checkpoint/resource_checkpoint_management_network.go +++ b/checkpoint/resource_checkpoint_management_network.go @@ -192,7 +192,7 @@ func createManagementNetwork(d *schema.ResourceData, m interface{}) error { log.Println("Create Network - Map = ", network) - addNetworkRes, err := client.ApiCall("add-network", network, client.GetSessionID(), true, false) + addNetworkRes, err := client.ApiCall("add-network", network, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addNetworkRes.Success { if addNetworkRes.ErrorMsg != "" { return fmt.Errorf(addNetworkRes.ErrorMsg) @@ -213,7 +213,7 @@ func readManagementNetwork(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showNetworkRes, err := client.ApiCall("show-network", payload, client.GetSessionID(), true, false) + showNetworkRes, err := client.ApiCall("show-network", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -408,7 +408,7 @@ func updateManagementNetwork(d *schema.ResourceData, m interface{}) error { } log.Println("Update Network - Map = ", network) - setNetworkRes, _ := client.ApiCall("set-network", network, client.GetSessionID(), true, false) + setNetworkRes, _ := client.ApiCall("set-network", network, client.GetSessionID(), true, client.IsProxyUsed()) if !setNetworkRes.Success { return fmt.Errorf(setNetworkRes.ErrorMsg) } @@ -421,7 +421,7 @@ func deleteManagementNetwork(d *schema.ResourceData, m interface{}) error { payload := map[string]interface{}{ "uid": d.Id(), } - deleteNetworkRes, _ := client.ApiCall("delete-network", payload, client.GetSessionID(), true, false) + deleteNetworkRes, _ := client.ApiCall("delete-network", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !deleteNetworkRes.Success { return fmt.Errorf(deleteNetworkRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_nuage_data_center_server.go b/checkpoint/resource_checkpoint_management_nuage_data_center_server.go new file mode 100644 index 00000000..ddb998a4 --- /dev/null +++ b/checkpoint/resource_checkpoint_management_nuage_data_center_server.go @@ -0,0 +1,368 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "log" + "strconv" + "strings" +) + +func resourceManagementNuageDataCenterServer() *schema.Resource { + return &schema.Resource{ + Create: createManagementNuageDataCenterServer, + Read: readManagementNuageDataCenterServer, + Update: updateManagementNuageDataCenterServer, + Delete: deleteManagementNuageDataCenterServer, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + Description: "Object name. Must be unique in the domain.", + }, + "hostname": { + Type: schema.TypeString, + Required: true, + Description: "IP address or hostname of the Nuage server.", + }, + "username": { + Type: schema.TypeString, + Required: true, + Description: "Username of the Nuage administrator.", + }, + "organization": { + Type: schema.TypeString, + Required: true, + Description: "Organization name or enterprise.", + }, + "password": { + Type: schema.TypeString, + Optional: true, + Description: "Password of the Nuage administrator.", + }, + "password_base64": { + Type: schema.TypeString, + Optional: true, + Description: "Password of the Nuage administrator encoded in Base64.", + }, + "certificate_fingerprint": { + Type: schema.TypeString, + Optional: true, + Description: "Specify the SHA-1 or SHA-256 fingerprint of the Data Center Server's certificate.", + }, + "unsafe_auto_accept": { + Type: schema.TypeBool, + Optional: true, + Description: "When set to false, the current Data Center Server's certificate should be trusted, either by providing the certificate-fingerprint argument or by relying on a previously trusted certificate of this hostname.\n\nWhen set to true, trust the current Data Center Server's certificate as-is.", + Default: false, + }, + "tags": { + Type: schema.TypeSet, + Optional: true, + Description: "Collection of tag identifiers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "color": { + Type: schema.TypeString, + Optional: true, + Description: "Color of the object. Should be one of existing colors.", + Default: "black", + }, + "comments": { + Type: schema.TypeString, + Optional: true, + Description: "Comments string.", + }, + "ignore_warnings": { + Type: schema.TypeBool, + Optional: true, + Description: "Apply changes ignoring warnings. By Setting this parameter to 'true' test connection failure will be ignored.", + Default: false, + }, + "ignore_errors": { + Type: schema.TypeBool, + Optional: true, + Description: "Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored.", + Default: false, + }, + }, + } +} + +func createManagementNuageDataCenterServer(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + + nuageDataCenterServer := make(map[string]interface{}) + + if v, ok := d.GetOk("name"); ok { + nuageDataCenterServer["name"] = v.(string) + } + + nuageDataCenterServer["type"] = "nuage" + + if v, ok := d.GetOk("hostname"); ok { + nuageDataCenterServer["hostname"] = v.(string) + } + + if v, ok := d.GetOk("username"); ok { + nuageDataCenterServer["username"] = v.(string) + } + + if v, ok := d.GetOk("organization"); ok { + nuageDataCenterServer["organization"] = v.(string) + } + + if v, ok := d.GetOk("password"); ok { + nuageDataCenterServer["password"] = v.(string) + } + + if v, ok := d.GetOk("password_base64"); ok { + nuageDataCenterServer["password-base64"] = v.(string) + } + + if v, ok := d.GetOk("certificate_fingerprint"); ok { + nuageDataCenterServer["certificate-fingerprint"] = v.(string) + } + + if v, ok := d.GetOk("unsafe_auto_accept"); ok { + nuageDataCenterServer["unsafe-auto-accept"] = v.(bool) + } + + if v, ok := d.GetOk("tags"); ok { + nuageDataCenterServer["tags"] = v.(*schema.Set).List() + } + + if v, ok := d.GetOk("color"); ok { + nuageDataCenterServer["color"] = v.(string) + } + + if v, ok := d.GetOk("comments"); ok { + nuageDataCenterServer["comments"] = v.(string) + } + + if v, ok := d.GetOkExists("ignore_warnings"); ok { + nuageDataCenterServer["ignore-warnings"] = v.(bool) + } + + if v, ok := d.GetOkExists("ignore_errors"); ok { + nuageDataCenterServer["ignore-errors"] = v.(bool) + } + + log.Println("Create nuageDataCenterServer - Map = ", nuageDataCenterServer) + + addNuageDataCenterServerRes, err := client.ApiCall("add-data-center-server", nuageDataCenterServer, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !addNuageDataCenterServerRes.Success { + if addNuageDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(addNuageDataCenterServerRes.ErrorMsg) + } + msg := createTaskFailMessage("add-data-center-server", addNuageDataCenterServerRes.GetData()) + return fmt.Errorf(msg) + } + payload := map[string]interface{}{ + "name": nuageDataCenterServer["name"], + } + showNuageDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showNuageDataCenterServerRes.Success { + return fmt.Errorf(showNuageDataCenterServerRes.ErrorMsg) + } + d.SetId(showNuageDataCenterServerRes.GetData()["uid"].(string)) + return readManagementNuageDataCenterServer(d, m) +} + +func readManagementNuageDataCenterServer(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + payload := map[string]interface{}{ + "uid": d.Id(), + } + + showNuageDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showNuageDataCenterServerRes.Success { + if objectNotFound(showNuageDataCenterServerRes.GetData()["code"].(string)) { + d.SetId("") + return nil + } + return fmt.Errorf(showNuageDataCenterServerRes.ErrorMsg) + } + nuageDataCenterServer := showNuageDataCenterServerRes.GetData() + + if v := nuageDataCenterServer["name"]; v != nil { + _ = d.Set("name", v) + } + + if nuageDataCenterServer["properties"] != nil { + propsJson, ok := nuageDataCenterServer["properties"].([]interface{}) + if ok { + for _, prop := range propsJson { + propMap := prop.(map[string]interface{}) + propName := strings.ReplaceAll(propMap["name"].(string), "-", "_") + propValue := propMap["value"] + if propName == "unsafe_auto_accept" { + propValue, _ = strconv.ParseBool(propValue.(string)) + } + _ = d.Set(propName, propValue) + } + } + } + + if nuageDataCenterServer["tags"] != nil { + tagsJson, ok := nuageDataCenterServer["tags"].([]interface{}) + if ok { + tagsIds := make([]string, 0) + if len(tagsJson) > 0 { + for _, tags := range tagsJson { + tags := tags.(map[string]interface{}) + tagsIds = append(tagsIds, tags["name"].(string)) + } + } + _ = d.Set("tags", tagsIds) + } + } else { + _ = d.Set("tags", nil) + } + + if v := nuageDataCenterServer["color"]; v != nil { + _ = d.Set("color", v) + } + + if v := nuageDataCenterServer["comments"]; v != nil { + _ = d.Set("comments", v) + } + + if v := nuageDataCenterServer["ignore-warnings"]; v != nil { + _ = d.Set("ignore_warnings", v) + } + + if v := nuageDataCenterServer["ignore-errors"]; v != nil { + _ = d.Set("ignore_errors", v) + } + + return nil + +} + +func updateManagementNuageDataCenterServer(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + nuageDataCenterServer := make(map[string]interface{}) + + if ok := d.HasChange("name"); ok { + oldName, newName := d.GetChange("name") + nuageDataCenterServer["name"] = oldName + nuageDataCenterServer["new-name"] = newName + } else { + nuageDataCenterServer["name"] = d.Get("name") + } + + if d.HasChange("organization") { + nuageDataCenterServer["organization"] = d.Get("organization") + } + + if d.HasChange("hostname") { + nuageDataCenterServer["hostname"] = d.Get("hostname") + } + + if d.HasChange("password") { + nuageDataCenterServer["password"] = d.Get("password") + } + + if d.HasChange("password_base64") { + nuageDataCenterServer["password-base64"] = d.Get("password_base64") + } + + if d.HasChange("username") { + nuageDataCenterServer["username"] = d.Get("username") + if v := d.Get("password"); v != nil && v != "" { + nuageDataCenterServer["password"] = v + } + if v := d.Get("password_base64"); v != nil && v != "" { + nuageDataCenterServer["password-base64"] = v + } + } + + if d.HasChange("certificate_fingerprint") { + nuageDataCenterServer["certificate-fingerprint"] = d.Get("certificate_fingerprint") + } + + if d.HasChange("unsafe_auto_accept") { + nuageDataCenterServer["unsafe-auto-accept"] = d.Get("unsafe_auto_accept") + } + + if d.HasChange("tags") { + if v, ok := d.GetOk("tags"); ok { + nuageDataCenterServer["tags"] = v.(*schema.Set).List() + } else { + oldTags, _ := d.GetChange("tags") + nuageDataCenterServer["tags"] = map[string]interface{}{"remove": oldTags.(*schema.Set).List()} + } + } + + if ok := d.HasChange("color"); ok { + nuageDataCenterServer["color"] = d.Get("color") + } + + if ok := d.HasChange("comments"); ok { + nuageDataCenterServer["comments"] = d.Get("comments") + } + + if v, ok := d.GetOkExists("ignore_warnings"); ok { + nuageDataCenterServer["ignore-warnings"] = v.(bool) + } + + if v, ok := d.GetOkExists("ignore_errors"); ok { + nuageDataCenterServer["ignore-errors"] = v.(bool) + } + + log.Println("Update nuageDataCenterServer - Map = ", nuageDataCenterServer) + + updateNuageDataCenterServerRes, err := client.ApiCall("set-data-center-server", nuageDataCenterServer, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !updateNuageDataCenterServerRes.Success { + if updateNuageDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(updateNuageDataCenterServerRes.ErrorMsg) + } + msg := createTaskFailMessage("set-data-center-server", updateNuageDataCenterServerRes.GetData()) + return fmt.Errorf(msg) + } + + return readManagementNuageDataCenterServer(d, m) +} + +func deleteManagementNuageDataCenterServer(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + + nuageDataCenterServerPayload := map[string]interface{}{ + "uid": d.Id(), + } + + log.Println("Delete nuageDataCenterServer") + + deleteNuageDataCenterServerRes, err := client.ApiCall("delete-data-center-server", nuageDataCenterServerPayload, client.GetSessionID(), true, client.IsProxyUsed()) + + if err != nil || !deleteNuageDataCenterServerRes.Success { + if deleteNuageDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(deleteNuageDataCenterServerRes.ErrorMsg) + } + return fmt.Errorf(err.Error()) + } + d.SetId("") + + return nil +} diff --git a/checkpoint/resource_checkpoint_management_nuage_data_center_server_test.go b/checkpoint/resource_checkpoint_management_nuage_data_center_server_test.go new file mode 100644 index 00000000..2908b8d6 --- /dev/null +++ b/checkpoint/resource_checkpoint_management_nuage_data_center_server_test.go @@ -0,0 +1,113 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + "os" + "strings" + "testing" +) + +func TestAccCheckpointManagementNuageDataCenterServer_basic(t *testing.T) { + + var nuageDataCenterServerMap map[string]interface{} + resourceName := "checkpoint_management_nuage_data_center_server.test" + objName := "tfTestManagementNuageDataCenterServer_" + acctest.RandString(6) + username := "USERNAME" + password := "PASSWORD" + hostname := "MY_HOSTNAME" + organization := "MY_ORG" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } else if context == "" { + t.Skip("Env CHECKPOINT_CONTEXT must be specified to run this acc test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckpointManagementNuageDataCenterServerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccManagementNuageDataCenterServerConfig(objName, username, password, hostname, organization), + Check: resource.ComposeTestCheckFunc( + testAccCheckCheckpointManagementNuageDataCenterServerExists(resourceName, &nuageDataCenterServerMap), + testAccCheckCheckpointManagementNuageDataCenterServerAttributes(&nuageDataCenterServerMap, objName), + ), + }, + }, + }) +} + +func testAccCheckpointManagementNuageDataCenterServerDestroy(s *terraform.State) error { + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + for _, rs := range s.RootModule().Resources { + if rs.Type != "checkpoint_management_nuage_data_center_server" { + continue + } + if rs.Primary.ID != "" { + res, _ := client.ApiCall("show-data-center-server", map[string]interface{}{"uid": rs.Primary.ID}, client.GetSessionID(), true, false) + if res.Success { + return fmt.Errorf("NuageDataCenterServer object (%s) still exists", rs.Primary.ID) + } + } + return nil + } + return nil +} + +func testAccCheckCheckpointManagementNuageDataCenterServerExists(resourceTfName string, res *map[string]interface{}) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[resourceTfName] + if !ok { + return fmt.Errorf("Resource not found: %s", resourceTfName) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("NuageDataCenterServer ID is not set") + } + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + + response, err := client.ApiCall("show-data-center-server", map[string]interface{}{"uid": rs.Primary.ID}, client.GetSessionID(), true, false) + if !response.Success { + return err + } + + *res = response.GetData() + + return nil + } +} + +func testAccCheckCheckpointManagementNuageDataCenterServerAttributes(nuageDataCenterServerMap *map[string]interface{}, name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + + nuageDataCenterServerName := (*nuageDataCenterServerMap)["name"].(string) + if !strings.EqualFold(nuageDataCenterServerName, name) { + return fmt.Errorf("name is %s, expected %s", name, nuageDataCenterServerName) + } + return nil + } +} + +func testAccManagementNuageDataCenterServerConfig(name string, username string, password string, hostname string, organization string) string { + return fmt.Sprintf(` +resource "checkpoint_management_nuage_data_center_server" "test" { + name = "%s" + username = "%s" + password = "%s" + hostname = "%s" + organization = "%s" + unsafe_auto_accept = true + ignore_warnings = true +} +`, name, username, password, hostname, organization) +} diff --git a/checkpoint/resource_checkpoint_management_openstack_data_center_server.go b/checkpoint/resource_checkpoint_management_openstack_data_center_server.go new file mode 100644 index 00000000..0a5b18c7 --- /dev/null +++ b/checkpoint/resource_checkpoint_management_openstack_data_center_server.go @@ -0,0 +1,354 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "log" + "strconv" + "strings" +) + +func resourceManagementOpenStackDataCenterServer() *schema.Resource { + return &schema.Resource{ + Create: createManagementOpenStackDataCenterServer, + Read: readManagementOpenStackDataCenterServer, + Update: updateManagementOpenStackDataCenterServer, + Delete: deleteManagementOpenStackDataCenterServer, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + Description: "Object name. Must be unique in the domain.", + }, + "hostname": { + Type: schema.TypeString, + Required: true, + Description: "URL of the OpenStack server.\nhttp(s)://:/\nExample: https://1.2.3.4:5000/v2.0", + }, + "username": { + Type: schema.TypeString, + Required: true, + Description: "Username of the OpenStack server.\nTo login to specific domain insert domain name before username.\nExample: /", + }, + "password": { + Type: schema.TypeString, + Optional: true, + Description: "Password of the OpenStack server.", + }, + "password_base64": { + Type: schema.TypeString, + Optional: true, + Description: "Password of the OpenStack server encoded in Base64.", + }, + "certificate_fingerprint": { + Type: schema.TypeString, + Optional: true, + Description: "Specify the SHA-1 or SHA-256 fingerprint of the Data Center Server's certificate.", + }, + "unsafe_auto_accept": { + Type: schema.TypeBool, + Optional: true, + Description: "When set to false, the current Data Center Server's certificate should be trusted, either by providing the certificate-fingerprint argument or by relying on a previously trusted certificate of this hostname.\n\nWhen set to true, trust the current Data Center Server's certificate as-is.", + Default: false, + }, + "tags": { + Type: schema.TypeSet, + Optional: true, + Description: "Collection of tag identifiers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "color": { + Type: schema.TypeString, + Optional: true, + Description: "Color of the object. Should be one of existing colors.", + Default: "black", + }, + "comments": { + Type: schema.TypeString, + Optional: true, + Description: "Comments string.", + }, + "ignore_warnings": { + Type: schema.TypeBool, + Optional: true, + Description: "Apply changes ignoring warnings. By Setting this parameter to 'true' test connection failure will be ignored.", + Default: false, + }, + "ignore_errors": { + Type: schema.TypeBool, + Optional: true, + Description: "Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored.", + Default: false, + }, + }, + } +} + +func createManagementOpenStackDataCenterServer(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + + openstackDataCenterServer := make(map[string]interface{}) + + if v, ok := d.GetOk("name"); ok { + openstackDataCenterServer["name"] = v.(string) + } + + openstackDataCenterServer["type"] = "openstack" + + if v, ok := d.GetOk("hostname"); ok { + openstackDataCenterServer["hostname"] = v.(string) + } + + if v, ok := d.GetOk("username"); ok { + openstackDataCenterServer["username"] = v.(string) + } + + if v, ok := d.GetOk("password"); ok { + openstackDataCenterServer["password"] = v.(string) + } + + if v, ok := d.GetOk("password_base64"); ok { + openstackDataCenterServer["password-base64"] = v.(string) + } + + if v, ok := d.GetOk("certificate_fingerprint"); ok { + openstackDataCenterServer["certificate-fingerprint"] = v.(string) + } + + if v, ok := d.GetOk("unsafe_auto_accept"); ok { + openstackDataCenterServer["unsafe-auto-accept"] = v.(bool) + } + + if v, ok := d.GetOk("tags"); ok { + openstackDataCenterServer["tags"] = v.(*schema.Set).List() + } + + if v, ok := d.GetOk("color"); ok { + openstackDataCenterServer["color"] = v.(string) + } + + if v, ok := d.GetOk("comments"); ok { + openstackDataCenterServer["comments"] = v.(string) + } + + if v, ok := d.GetOkExists("ignore_warnings"); ok { + openstackDataCenterServer["ignore-warnings"] = v.(bool) + } + + if v, ok := d.GetOkExists("ignore_errors"); ok { + openstackDataCenterServer["ignore-errors"] = v.(bool) + } + + log.Println("Create openstackDataCenterServer - Map = ", openstackDataCenterServer) + + addOpenStackDataCenterServerRes, err := client.ApiCall("add-data-center-server", openstackDataCenterServer, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !addOpenStackDataCenterServerRes.Success { + if addOpenStackDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(addOpenStackDataCenterServerRes.ErrorMsg) + } + msg := createTaskFailMessage("add-data-center-server", addOpenStackDataCenterServerRes.GetData()) + return fmt.Errorf(msg) + } + payload := map[string]interface{}{ + "name": openstackDataCenterServer["name"], + } + showOpenStackDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showOpenStackDataCenterServerRes.Success { + return fmt.Errorf(showOpenStackDataCenterServerRes.ErrorMsg) + } + d.SetId(showOpenStackDataCenterServerRes.GetData()["uid"].(string)) + return readManagementOpenStackDataCenterServer(d, m) +} + +func readManagementOpenStackDataCenterServer(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + payload := map[string]interface{}{ + "uid": d.Id(), + } + + showOpenStackDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showOpenStackDataCenterServerRes.Success { + if objectNotFound(showOpenStackDataCenterServerRes.GetData()["code"].(string)) { + d.SetId("") + return nil + } + return fmt.Errorf(showOpenStackDataCenterServerRes.ErrorMsg) + } + openstackDataCenterServer := showOpenStackDataCenterServerRes.GetData() + + if v := openstackDataCenterServer["name"]; v != nil { + _ = d.Set("name", v) + } + + if openstackDataCenterServer["properties"] != nil { + propsJson, ok := openstackDataCenterServer["properties"].([]interface{}) + if ok { + for _, prop := range propsJson { + propMap := prop.(map[string]interface{}) + propName := strings.ReplaceAll(propMap["name"].(string), "-", "_") + propValue := propMap["value"] + if propName == "unsafe_auto_accept" { + propValue, _ = strconv.ParseBool(propValue.(string)) + } + _ = d.Set(propName, propValue) + } + } + } + + if openstackDataCenterServer["tags"] != nil { + tagsJson, ok := openstackDataCenterServer["tags"].([]interface{}) + if ok { + tagsIds := make([]string, 0) + if len(tagsJson) > 0 { + for _, tags := range tagsJson { + tags := tags.(map[string]interface{}) + tagsIds = append(tagsIds, tags["name"].(string)) + } + } + _ = d.Set("tags", tagsIds) + } + } else { + _ = d.Set("tags", nil) + } + + if v := openstackDataCenterServer["color"]; v != nil { + _ = d.Set("color", v) + } + + if v := openstackDataCenterServer["comments"]; v != nil { + _ = d.Set("comments", v) + } + + if v := openstackDataCenterServer["ignore-warnings"]; v != nil { + _ = d.Set("ignore_warnings", v) + } + + if v := openstackDataCenterServer["ignore-errors"]; v != nil { + _ = d.Set("ignore_errors", v) + } + + return nil + +} + +func updateManagementOpenStackDataCenterServer(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + openstackDataCenterServer := make(map[string]interface{}) + + if ok := d.HasChange("name"); ok { + oldName, newName := d.GetChange("name") + openstackDataCenterServer["name"] = oldName + openstackDataCenterServer["new-name"] = newName + } else { + openstackDataCenterServer["name"] = d.Get("name") + } + + if d.HasChange("hostname") { + openstackDataCenterServer["hostname"] = d.Get("hostname") + } + + if d.HasChange("password") { + openstackDataCenterServer["password"] = d.Get("password") + } + + if d.HasChange("password_base64") { + openstackDataCenterServer["password-base64"] = d.Get("password_base64") + } + + if d.HasChange("username") { + openstackDataCenterServer["username"] = d.Get("username") + if v := d.Get("password"); v != nil && v != "" { + openstackDataCenterServer["password"] = v + } + if v := d.Get("password_base64"); v != nil && v != "" { + openstackDataCenterServer["password-base64"] = v + } + } + + if d.HasChange("certificate_fingerprint") { + openstackDataCenterServer["certificate-fingerprint"] = d.Get("certificate_fingerprint") + } + + if d.HasChange("unsafe_auto_accept") { + openstackDataCenterServer["unsafe-auto-accept"] = d.Get("unsafe_auto_accept") + } + + if d.HasChange("tags") { + if v, ok := d.GetOk("tags"); ok { + openstackDataCenterServer["tags"] = v.(*schema.Set).List() + } else { + oldTags, _ := d.GetChange("tags") + openstackDataCenterServer["tags"] = map[string]interface{}{"remove": oldTags.(*schema.Set).List()} + } + } + + if ok := d.HasChange("color"); ok { + openstackDataCenterServer["color"] = d.Get("color") + } + + if ok := d.HasChange("comments"); ok { + openstackDataCenterServer["comments"] = d.Get("comments") + } + + if v, ok := d.GetOkExists("ignore_warnings"); ok { + openstackDataCenterServer["ignore-warnings"] = v.(bool) + } + + if v, ok := d.GetOkExists("ignore_errors"); ok { + openstackDataCenterServer["ignore-errors"] = v.(bool) + } + + log.Println("Update openstackDataCenterServer - Map = ", openstackDataCenterServer) + + updateOpenStackDataCenterServerRes, err := client.ApiCall("set-data-center-server", openstackDataCenterServer, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !updateOpenStackDataCenterServerRes.Success { + if updateOpenStackDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(updateOpenStackDataCenterServerRes.ErrorMsg) + } + msg := createTaskFailMessage("set-data-center-server", updateOpenStackDataCenterServerRes.GetData()) + return fmt.Errorf(msg) + } + + return readManagementOpenStackDataCenterServer(d, m) +} + +func deleteManagementOpenStackDataCenterServer(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + + openstackDataCenterServerPayload := map[string]interface{}{ + "uid": d.Id(), + } + + log.Println("Delete openstackDataCenterServer") + + deleteOpenStackDataCenterServerRes, err := client.ApiCall("delete-data-center-server", openstackDataCenterServerPayload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil || !deleteOpenStackDataCenterServerRes.Success { + if deleteOpenStackDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(deleteOpenStackDataCenterServerRes.ErrorMsg) + } + return fmt.Errorf(err.Error()) + } + d.SetId("") + + return nil +} diff --git a/checkpoint/resource_checkpoint_management_openstack_data_center_server_test.go b/checkpoint/resource_checkpoint_management_openstack_data_center_server_test.go new file mode 100644 index 00000000..c57ebe4e --- /dev/null +++ b/checkpoint/resource_checkpoint_management_openstack_data_center_server_test.go @@ -0,0 +1,111 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + "os" + "strings" + "testing" +) + +func TestAccCheckpointManagementOpenStackDataCenterServer_basic(t *testing.T) { + + var openstackDataCenterServerMap map[string]interface{} + resourceName := "checkpoint_management_openstack_data_center_server.test" + objName := "tfTestManagementOpenStackDataCenterServer_" + acctest.RandString(6) + username := "USERNAME" + password := "PASSWORD" + hostname := "HOSTNAME" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } else if context == "" { + t.Skip("Env CHECKPOINT_CONTEXT must be specified to run this acc test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckpointManagementOpenStackDataCenterServerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccManagementOpenStackDataCenterServerConfig(objName, username, password, hostname), + Check: resource.ComposeTestCheckFunc( + testAccCheckCheckpointManagementOpenStackDataCenterServerExists(resourceName, &openstackDataCenterServerMap), + testAccCheckCheckpointManagementOpenStackDataCenterServerAttributes(&openstackDataCenterServerMap, objName), + ), + }, + }, + }) +} + +func testAccCheckpointManagementOpenStackDataCenterServerDestroy(s *terraform.State) error { + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + for _, rs := range s.RootModule().Resources { + if rs.Type != "checkpoint_management_openstack_data_center_server" { + continue + } + if rs.Primary.ID != "" { + res, _ := client.ApiCall("show-data-center-server", map[string]interface{}{"uid": rs.Primary.ID}, client.GetSessionID(), true, false) + if res.Success { + return fmt.Errorf("OpenStackDataCenterServer object (%s) still exists", rs.Primary.ID) + } + } + return nil + } + return nil +} + +func testAccCheckCheckpointManagementOpenStackDataCenterServerExists(resourceTfName string, res *map[string]interface{}) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[resourceTfName] + if !ok { + return fmt.Errorf("Resource not found: %s", resourceTfName) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("OpenStackDataCenterServer ID is not set") + } + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + + response, err := client.ApiCall("show-data-center-server", map[string]interface{}{"uid": rs.Primary.ID}, client.GetSessionID(), true, false) + if !response.Success { + return err + } + + *res = response.GetData() + + return nil + } +} + +func testAccCheckCheckpointManagementOpenStackDataCenterServerAttributes(openstackDataCenterServerMap *map[string]interface{}, name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + + openstackDataCenterServerName := (*openstackDataCenterServerMap)["name"].(string) + if !strings.EqualFold(openstackDataCenterServerName, name) { + return fmt.Errorf("name is %s, expected %s", name, openstackDataCenterServerName) + } + return nil + } +} + +func testAccManagementOpenStackDataCenterServerConfig(name string, username string, password string, hostname string) string { + return fmt.Sprintf(` +resource "checkpoint_management_openstack_data_center_server" "test" { + name = "%s" + username = "%s" + password = "%s" + hostname = "%s" + unsafe_auto_accept = true + ignore_warnings = true +} +`, name, username, password, hostname) +} diff --git a/checkpoint/resource_checkpoint_management_opsec_application.go b/checkpoint/resource_checkpoint_management_opsec_application.go index f9044e13..bb59feab 100644 --- a/checkpoint/resource_checkpoint_management_opsec_application.go +++ b/checkpoint/resource_checkpoint_management_opsec_application.go @@ -189,7 +189,7 @@ func createManagementOpsecApplication(d *schema.ResourceData, m interface{}) err log.Println("Create OpsecApplication - Map = ", opsecApplication) - addOpsecApplicationRes, err := client.ApiCall("add-opsec-application", opsecApplication, client.GetSessionID(), true, false) + addOpsecApplicationRes, err := client.ApiCall("add-opsec-application", opsecApplication, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addOpsecApplicationRes.Success { if addOpsecApplicationRes.ErrorMsg != "" { return fmt.Errorf(addOpsecApplicationRes.ErrorMsg) @@ -210,7 +210,7 @@ func readManagementOpsecApplication(d *schema.ResourceData, m interface{}) error "uid": d.Id(), } - showOpsecApplicationRes, err := client.ApiCall("show-opsec-application", payload, client.GetSessionID(), true, false) + showOpsecApplicationRes, err := client.ApiCall("show-opsec-application", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -400,7 +400,7 @@ func updateManagementOpsecApplication(d *schema.ResourceData, m interface{}) err log.Println("Update OpsecApplication - Map = ", opsecApplication) - updateOpsecApplicationRes, err := client.ApiCall("set-opsec-application", opsecApplication, client.GetSessionID(), true, false) + updateOpsecApplicationRes, err := client.ApiCall("set-opsec-application", opsecApplication, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateOpsecApplicationRes.Success { if updateOpsecApplicationRes.ErrorMsg != "" { return fmt.Errorf(updateOpsecApplicationRes.ErrorMsg) @@ -421,7 +421,7 @@ func deleteManagementOpsecApplication(d *schema.ResourceData, m interface{}) err log.Println("Delete OpsecApplication") - deleteOpsecApplicationRes, err := client.ApiCall("delete-opsec-application", opsecApplicationPayload, client.GetSessionID(), true, false) + deleteOpsecApplicationRes, err := client.ApiCall("delete-opsec-application", opsecApplicationPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteOpsecApplicationRes.Success { if deleteOpsecApplicationRes.ErrorMsg != "" { return fmt.Errorf(deleteOpsecApplicationRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_package.go b/checkpoint/resource_checkpoint_management_package.go index 409894e6..bf8c941b 100644 --- a/checkpoint/resource_checkpoint_management_package.go +++ b/checkpoint/resource_checkpoint_management_package.go @@ -149,7 +149,7 @@ func createManagementPackage(d *schema.ResourceData, m interface{}) error { log.Println("Create Package - Map = ", _package) - addPackageRes, err := client.ApiCall("add-package", _package, client.GetSessionID(), true, false) + addPackageRes, err := client.ApiCall("add-package", _package, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addPackageRes.Success { if addPackageRes.ErrorMsg != "" { return fmt.Errorf(addPackageRes.ErrorMsg) @@ -170,7 +170,7 @@ func readManagementPackage(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showPackageRes, err := client.ApiCall("show-package", payload, client.GetSessionID(), true, false) + showPackageRes, err := client.ApiCall("show-package", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -336,7 +336,7 @@ func updateManagementPackage(d *schema.ResourceData, m interface{}) error { } log.Println("Update Package - Map = ", _package) - updatePackageRes, err := client.ApiCall("set-package", _package, client.GetSessionID(), true, false) + updatePackageRes, err := client.ApiCall("set-package", _package, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updatePackageRes.Success { if updatePackageRes.ErrorMsg != "" { return fmt.Errorf(updatePackageRes.ErrorMsg) @@ -355,7 +355,7 @@ func deleteManagementPackage(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - deletePackageRes, err := client.ApiCall("delete-package", packagePayload, client.GetSessionID(), true, false) + deletePackageRes, err := client.ApiCall("delete-package", packagePayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deletePackageRes.Success { if deletePackageRes.ErrorMsg != "" { return fmt.Errorf(deletePackageRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_security_zone.go b/checkpoint/resource_checkpoint_management_security_zone.go index 82de2737..78c7543f 100644 --- a/checkpoint/resource_checkpoint_management_security_zone.go +++ b/checkpoint/resource_checkpoint_management_security_zone.go @@ -88,7 +88,7 @@ func createManagementSecurityZone(d *schema.ResourceData, m interface{}) error { log.Println("Create SecurityZone - Map = ", securityZone) - addSecurityZoneRes, err := client.ApiCall("add-security-zone", securityZone, client.GetSessionID(), true, false) + addSecurityZoneRes, err := client.ApiCall("add-security-zone", securityZone, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addSecurityZoneRes.Success { if addSecurityZoneRes.ErrorMsg != "" { return fmt.Errorf(addSecurityZoneRes.ErrorMsg) @@ -109,7 +109,7 @@ func readManagementSecurityZone(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showSecurityZoneRes, err := client.ApiCall("show-security-zone", payload, client.GetSessionID(), true, false) + showSecurityZoneRes, err := client.ApiCall("show-security-zone", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -205,7 +205,7 @@ func updateManagementSecurityZone(d *schema.ResourceData, m interface{}) error { log.Println("Update SecurityZone - Map = ", securityZone) - updateSecurityZoneRes, err := client.ApiCall("set-security-zone", securityZone, client.GetSessionID(), true, false) + updateSecurityZoneRes, err := client.ApiCall("set-security-zone", securityZone, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateSecurityZoneRes.Success { if updateSecurityZoneRes.ErrorMsg != "" { return fmt.Errorf(updateSecurityZoneRes.ErrorMsg) @@ -226,7 +226,7 @@ func deleteManagementSecurityZone(d *schema.ResourceData, m interface{}) error { log.Println("Delete SecurityZone") - deleteSecurityZoneRes, err := client.ApiCall("delete-security-zone", securityZonePayload, client.GetSessionID(), true, false) + deleteSecurityZoneRes, err := client.ApiCall("delete-security-zone", securityZonePayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteSecurityZoneRes.Success { if deleteSecurityZoneRes.ErrorMsg != "" { return fmt.Errorf(deleteSecurityZoneRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_service_citrix_tcp.go b/checkpoint/resource_checkpoint_management_service_citrix_tcp.go index ef0cfc46..4d7854b9 100644 --- a/checkpoint/resource_checkpoint_management_service_citrix_tcp.go +++ b/checkpoint/resource_checkpoint_management_service_citrix_tcp.go @@ -94,7 +94,7 @@ func createManagementServiceCitrixTcp(d *schema.ResourceData, m interface{}) err log.Println("Create ServiceCitrixTcp - Map = ", serviceCitrixTcp) - addServiceCitrixTcpRes, err := client.ApiCall("add-service-citrix-tcp", serviceCitrixTcp, client.GetSessionID(), true, false) + addServiceCitrixTcpRes, err := client.ApiCall("add-service-citrix-tcp", serviceCitrixTcp, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addServiceCitrixTcpRes.Success { if addServiceCitrixTcpRes.ErrorMsg != "" { return fmt.Errorf(addServiceCitrixTcpRes.ErrorMsg) @@ -115,7 +115,7 @@ func readManagementServiceCitrixTcp(d *schema.ResourceData, m interface{}) error "uid": d.Id(), } - showServiceCitrixTcpRes, err := client.ApiCall("show-service-citrix-tcp", payload, client.GetSessionID(), true, false) + showServiceCitrixTcpRes, err := client.ApiCall("show-service-citrix-tcp", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -210,7 +210,7 @@ func updateManagementServiceCitrixTcp(d *schema.ResourceData, m interface{}) err log.Println("Update ServiceCitrixTcp - Map = ", serviceCitrixTcp) - updateServiceCitrixTcpRes, err := client.ApiCall("set-service-citrix-tcp", serviceCitrixTcp, client.GetSessionID(), true, false) + updateServiceCitrixTcpRes, err := client.ApiCall("set-service-citrix-tcp", serviceCitrixTcp, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateServiceCitrixTcpRes.Success { if updateServiceCitrixTcpRes.ErrorMsg != "" { return fmt.Errorf(updateServiceCitrixTcpRes.ErrorMsg) @@ -231,7 +231,7 @@ func deleteManagementServiceCitrixTcp(d *schema.ResourceData, m interface{}) err log.Println("Delete ServiceCitrixTcp") - deleteServiceCitrixTcpRes, err := client.ApiCall("delete-service-citrix-tcp", serviceCitrixTcpPayload, client.GetSessionID(), true, false) + deleteServiceCitrixTcpRes, err := client.ApiCall("delete-service-citrix-tcp", serviceCitrixTcpPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteServiceCitrixTcpRes.Success { if deleteServiceCitrixTcpRes.ErrorMsg != "" { return fmt.Errorf(deleteServiceCitrixTcpRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_service_compound_tcp.go b/checkpoint/resource_checkpoint_management_service_compound_tcp.go index 66769aaa..d19236bf 100644 --- a/checkpoint/resource_checkpoint_management_service_compound_tcp.go +++ b/checkpoint/resource_checkpoint_management_service_compound_tcp.go @@ -105,7 +105,7 @@ func createManagementServiceCompoundTcp(d *schema.ResourceData, m interface{}) e log.Println("Create ServiceCompoundTcp - Map = ", serviceCompoundTcp) - addServiceCompoundTcpRes, err := client.ApiCall("add-service-compound-tcp", serviceCompoundTcp, client.GetSessionID(), true, false) + addServiceCompoundTcpRes, err := client.ApiCall("add-service-compound-tcp", serviceCompoundTcp, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addServiceCompoundTcpRes.Success { if addServiceCompoundTcpRes.ErrorMsg != "" { return fmt.Errorf(addServiceCompoundTcpRes.ErrorMsg) @@ -126,7 +126,7 @@ func readManagementServiceCompoundTcp(d *schema.ResourceData, m interface{}) err "uid": d.Id(), } - showServiceCompoundTcpRes, err := client.ApiCall("show-service-compound-tcp", payload, client.GetSessionID(), true, false) + showServiceCompoundTcpRes, err := client.ApiCall("show-service-compound-tcp", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -229,7 +229,7 @@ func updateManagementServiceCompoundTcp(d *schema.ResourceData, m interface{}) e log.Println("Update ServiceCompoundTcp - Map = ", serviceCompoundTcp) - updateServiceCompoundTcpRes, err := client.ApiCall("set-service-compound-tcp", serviceCompoundTcp, client.GetSessionID(), true, false) + updateServiceCompoundTcpRes, err := client.ApiCall("set-service-compound-tcp", serviceCompoundTcp, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateServiceCompoundTcpRes.Success { if updateServiceCompoundTcpRes.ErrorMsg != "" { return fmt.Errorf(updateServiceCompoundTcpRes.ErrorMsg) @@ -250,7 +250,7 @@ func deleteManagementServiceCompoundTcp(d *schema.ResourceData, m interface{}) e log.Println("Delete ServiceCompoundTcp") - deleteServiceCompoundTcpRes, err := client.ApiCall("delete-service-compound-tcp", serviceCompoundTcpPayload, client.GetSessionID(), true, false) + deleteServiceCompoundTcpRes, err := client.ApiCall("delete-service-compound-tcp", serviceCompoundTcpPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteServiceCompoundTcpRes.Success { if deleteServiceCompoundTcpRes.ErrorMsg != "" { return fmt.Errorf(deleteServiceCompoundTcpRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_service_dce_rpc.go b/checkpoint/resource_checkpoint_management_service_dce_rpc.go index a8f835da..f9268439 100644 --- a/checkpoint/resource_checkpoint_management_service_dce_rpc.go +++ b/checkpoint/resource_checkpoint_management_service_dce_rpc.go @@ -106,7 +106,7 @@ func createManagementServiceDceRpc(d *schema.ResourceData, m interface{}) error log.Println("Create ServiceDceRpc - Map = ", serviceDceRpc) - addServiceDceRpcRes, err := client.ApiCall("add-service-dce-rpc", serviceDceRpc, client.GetSessionID(), true, false) + addServiceDceRpcRes, err := client.ApiCall("add-service-dce-rpc", serviceDceRpc, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addServiceDceRpcRes.Success { if addServiceDceRpcRes.ErrorMsg != "" { return fmt.Errorf(addServiceDceRpcRes.ErrorMsg) @@ -127,7 +127,7 @@ func readManagementServiceDceRpc(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showServiceDceRpcRes, err := client.ApiCall("show-service-dce-rpc", payload, client.GetSessionID(), true, false) + showServiceDceRpcRes, err := client.ApiCall("show-service-dce-rpc", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -239,7 +239,7 @@ func updateManagementServiceDceRpc(d *schema.ResourceData, m interface{}) error log.Println("Update ServiceDceRpc - Map = ", serviceDceRpc) - updateServiceDceRpcRes, err := client.ApiCall("set-service-dce-rpc", serviceDceRpc, client.GetSessionID(), true, false) + updateServiceDceRpcRes, err := client.ApiCall("set-service-dce-rpc", serviceDceRpc, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateServiceDceRpcRes.Success { if updateServiceDceRpcRes.ErrorMsg != "" { return fmt.Errorf(updateServiceDceRpcRes.ErrorMsg) @@ -260,7 +260,7 @@ func deleteManagementServiceDceRpc(d *schema.ResourceData, m interface{}) error log.Println("Delete ServiceDceRpc") - deleteServiceDceRpcRes, err := client.ApiCall("delete-service-dce-rpc", serviceDceRpcPayload, client.GetSessionID(), true, false) + deleteServiceDceRpcRes, err := client.ApiCall("delete-service-dce-rpc", serviceDceRpcPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteServiceDceRpcRes.Success { if deleteServiceDceRpcRes.ErrorMsg != "" { return fmt.Errorf(deleteServiceDceRpcRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_service_group.go b/checkpoint/resource_checkpoint_management_service_group.go index 0544974c..708d087a 100644 --- a/checkpoint/resource_checkpoint_management_service_group.go +++ b/checkpoint/resource_checkpoint_management_service_group.go @@ -95,7 +95,7 @@ func createManagementServiceGroup(d *schema.ResourceData, m interface{}) error { log.Println("Create Service Group - Map = ", serviceGroup) - addServiceGroupRes, err := client.ApiCall("add-service-group", serviceGroup, client.GetSessionID(), true, false) + addServiceGroupRes, err := client.ApiCall("add-service-group", serviceGroup, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addServiceGroupRes.Success { if addServiceGroupRes.ErrorMsg != "" { return fmt.Errorf(addServiceGroupRes.ErrorMsg) @@ -116,7 +116,7 @@ func readManagementServiceGroup(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showServiceGroupRes, err := client.ApiCall("show-service-group", payload, client.GetSessionID(), true, false) + showServiceGroupRes, err := client.ApiCall("show-service-group", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -221,7 +221,7 @@ func updateManagementServiceGroup(d *schema.ResourceData, m interface{}) error { } log.Println("Update Service Group - Map = ", serviceGroup) - setserviceGroupRes, _ := client.ApiCall("set-service-group", serviceGroup, client.GetSessionID(), true, false) + setserviceGroupRes, _ := client.ApiCall("set-service-group", serviceGroup, client.GetSessionID(), true, client.IsProxyUsed()) if !setserviceGroupRes.Success { return fmt.Errorf(setserviceGroupRes.ErrorMsg) } @@ -234,7 +234,7 @@ func deleteManagementServiceGroup(d *schema.ResourceData, m interface{}) error { payload := map[string]interface{}{ "uid": d.Id(), } - deleteServiceGroupRes, _ := client.ApiCall("delete-service-group", payload, client.GetSessionID(), true, false) + deleteServiceGroupRes, _ := client.ApiCall("delete-service-group", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !deleteServiceGroupRes.Success { return fmt.Errorf(deleteServiceGroupRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_service_icmp.go b/checkpoint/resource_checkpoint_management_service_icmp.go index 4de0022a..360f8ed9 100644 --- a/checkpoint/resource_checkpoint_management_service_icmp.go +++ b/checkpoint/resource_checkpoint_management_service_icmp.go @@ -118,7 +118,7 @@ func createManagementServiceIcmp(d *schema.ResourceData, m interface{}) error { log.Println("Create ServiceIcmp - Map = ", serviceIcmp) - addServiceIcmpRes, err := client.ApiCall("add-service-icmp", serviceIcmp, client.GetSessionID(), true, false) + addServiceIcmpRes, err := client.ApiCall("add-service-icmp", serviceIcmp, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addServiceIcmpRes.Success { if addServiceIcmpRes.ErrorMsg != "" { return fmt.Errorf(addServiceIcmpRes.ErrorMsg) @@ -139,7 +139,7 @@ func readManagementServiceIcmp(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showServiceIcmpRes, err := client.ApiCall("show-service-icmp", payload, client.GetSessionID(), true, false) + showServiceIcmpRes, err := client.ApiCall("show-service-icmp", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -259,7 +259,7 @@ func updateManagementServiceIcmp(d *schema.ResourceData, m interface{}) error { log.Println("Update ServiceIcmp - Map = ", serviceIcmp) - updateServiceIcmpRes, err := client.ApiCall("set-service-icmp", serviceIcmp, client.GetSessionID(), true, false) + updateServiceIcmpRes, err := client.ApiCall("set-service-icmp", serviceIcmp, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateServiceIcmpRes.Success { if updateServiceIcmpRes.ErrorMsg != "" { return fmt.Errorf(updateServiceIcmpRes.ErrorMsg) @@ -280,7 +280,7 @@ func deleteManagementServiceIcmp(d *schema.ResourceData, m interface{}) error { log.Println("Delete ServiceIcmp") - deleteServiceIcmpRes, err := client.ApiCall("delete-service-icmp", serviceIcmpPayload, client.GetSessionID(), true, false) + deleteServiceIcmpRes, err := client.ApiCall("delete-service-icmp", serviceIcmpPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteServiceIcmpRes.Success { if deleteServiceIcmpRes.ErrorMsg != "" { return fmt.Errorf(deleteServiceIcmpRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_service_icmp6.go b/checkpoint/resource_checkpoint_management_service_icmp6.go index 00197862..4a100aed 100644 --- a/checkpoint/resource_checkpoint_management_service_icmp6.go +++ b/checkpoint/resource_checkpoint_management_service_icmp6.go @@ -115,7 +115,7 @@ func createManagementServiceIcmp6(d *schema.ResourceData, m interface{}) error { log.Println("Create ServiceIcmp6 - Map = ", serviceIcmp6) - addServiceIcmp6Res, err := client.ApiCall("add-service-icmp6", serviceIcmp6, client.GetSessionID(), true, false) + addServiceIcmp6Res, err := client.ApiCall("add-service-icmp6", serviceIcmp6, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addServiceIcmp6Res.Success { if addServiceIcmp6Res.ErrorMsg != "" { return fmt.Errorf(addServiceIcmp6Res.ErrorMsg) @@ -136,7 +136,7 @@ func readManagementServiceIcmp6(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showServiceIcmp6Res, err := client.ApiCall("show-service-icmp6", payload, client.GetSessionID(), true, false) + showServiceIcmp6Res, err := client.ApiCall("show-service-icmp6", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -256,7 +256,7 @@ func updateManagementServiceIcmp6(d *schema.ResourceData, m interface{}) error { log.Println("Update ServiceIcmp6 - Map = ", serviceIcmp6) - updateServiceIcmp6Res, err := client.ApiCall("set-service-icmp6", serviceIcmp6, client.GetSessionID(), true, false) + updateServiceIcmp6Res, err := client.ApiCall("set-service-icmp6", serviceIcmp6, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateServiceIcmp6Res.Success { if updateServiceIcmp6Res.ErrorMsg != "" { return fmt.Errorf(updateServiceIcmp6Res.ErrorMsg) @@ -277,7 +277,7 @@ func deleteManagementServiceIcmp6(d *schema.ResourceData, m interface{}) error { log.Println("Delete ServiceIcmp6") - deleteServiceIcmp6Res, err := client.ApiCall("delete-service-icmp6", serviceIcmp6Payload, client.GetSessionID(), true, false) + deleteServiceIcmp6Res, err := client.ApiCall("delete-service-icmp6", serviceIcmp6Payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteServiceIcmp6Res.Success { if deleteServiceIcmp6Res.ErrorMsg != "" { return fmt.Errorf(deleteServiceIcmp6Res.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_service_other.go b/checkpoint/resource_checkpoint_management_service_other.go index 566838b0..c4b8ed24 100644 --- a/checkpoint/resource_checkpoint_management_service_other.go +++ b/checkpoint/resource_checkpoint_management_service_other.go @@ -235,7 +235,7 @@ func createManagementServiceOther(d *schema.ResourceData, m interface{}) error { log.Println("Create ServiceOther - Map = ", serviceOther) - addServiceOtherRes, err := client.ApiCall("add-service-other", serviceOther, client.GetSessionID(), true, false) + addServiceOtherRes, err := client.ApiCall("add-service-other", serviceOther, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addServiceOtherRes.Success { if addServiceOtherRes.ErrorMsg != "" { return fmt.Errorf(addServiceOtherRes.ErrorMsg) @@ -256,7 +256,7 @@ func readManagementServiceOther(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showServiceOtherRes, err := client.ApiCall("show-service-other", payload, client.GetSessionID(), true, false) + showServiceOtherRes, err := client.ApiCall("show-service-other", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -492,7 +492,7 @@ func updateManagementServiceOther(d *schema.ResourceData, m interface{}) error { log.Println("Update ServiceOther - Map = ", serviceOther) - updateServiceOtherRes, err := client.ApiCall("set-service-other", serviceOther, client.GetSessionID(), true, false) + updateServiceOtherRes, err := client.ApiCall("set-service-other", serviceOther, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateServiceOtherRes.Success { if updateServiceOtherRes.ErrorMsg != "" { return fmt.Errorf(updateServiceOtherRes.ErrorMsg) @@ -513,7 +513,7 @@ func deleteManagementServiceOther(d *schema.ResourceData, m interface{}) error { log.Println("Delete ServiceOther") - deleteServiceOtherRes, err := client.ApiCall("delete-service-other", serviceOtherPayload, client.GetSessionID(), true, false) + deleteServiceOtherRes, err := client.ApiCall("delete-service-other", serviceOtherPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteServiceOtherRes.Success { if deleteServiceOtherRes.ErrorMsg != "" { return fmt.Errorf(deleteServiceOtherRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_service_rpc.go b/checkpoint/resource_checkpoint_management_service_rpc.go index 8e8d6518..1930c69e 100644 --- a/checkpoint/resource_checkpoint_management_service_rpc.go +++ b/checkpoint/resource_checkpoint_management_service_rpc.go @@ -106,7 +106,7 @@ func createManagementServiceRpc(d *schema.ResourceData, m interface{}) error { log.Println("Create ServiceRpc - Map = ", serviceRpc) - addServiceRpcRes, err := client.ApiCall("add-service-rpc", serviceRpc, client.GetSessionID(), true, false) + addServiceRpcRes, err := client.ApiCall("add-service-rpc", serviceRpc, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addServiceRpcRes.Success { if addServiceRpcRes.ErrorMsg != "" { return fmt.Errorf(addServiceRpcRes.ErrorMsg) @@ -127,7 +127,7 @@ func readManagementServiceRpc(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showServiceRpcRes, err := client.ApiCall("show-service-rpc", payload, client.GetSessionID(), true, false) + showServiceRpcRes, err := client.ApiCall("show-service-rpc", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -239,7 +239,7 @@ func updateManagementServiceRpc(d *schema.ResourceData, m interface{}) error { log.Println("Update ServiceRpc - Map = ", serviceRpc) - updateServiceRpcRes, err := client.ApiCall("set-service-rpc", serviceRpc, client.GetSessionID(), true, false) + updateServiceRpcRes, err := client.ApiCall("set-service-rpc", serviceRpc, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateServiceRpcRes.Success { if updateServiceRpcRes.ErrorMsg != "" { return fmt.Errorf(updateServiceRpcRes.ErrorMsg) @@ -260,7 +260,7 @@ func deleteManagementServiceRpc(d *schema.ResourceData, m interface{}) error { log.Println("Delete ServiceRpc") - deleteServiceRpcRes, err := client.ApiCall("delete-service-rpc", serviceRpcPayload, client.GetSessionID(), true, false) + deleteServiceRpcRes, err := client.ApiCall("delete-service-rpc", serviceRpcPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteServiceRpcRes.Success { if deleteServiceRpcRes.ErrorMsg != "" { return fmt.Errorf(deleteServiceRpcRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_service_sctp.go b/checkpoint/resource_checkpoint_management_service_sctp.go index 55d6b26f..b7958b02 100644 --- a/checkpoint/resource_checkpoint_management_service_sctp.go +++ b/checkpoint/resource_checkpoint_management_service_sctp.go @@ -205,7 +205,7 @@ func createManagementServiceSctp(d *schema.ResourceData, m interface{}) error { log.Println("Create ServiceSctp - Map = ", serviceSctp) - addServiceSctpRes, err := client.ApiCall("add-service-sctp", serviceSctp, client.GetSessionID(), true, false) + addServiceSctpRes, err := client.ApiCall("add-service-sctp", serviceSctp, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addServiceSctpRes.Success { if addServiceSctpRes.ErrorMsg != "" { return fmt.Errorf(addServiceSctpRes.ErrorMsg) @@ -226,7 +226,7 @@ func readManagementServiceSctp(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showServiceSctpRes, err := client.ApiCall("show-service-sctp", payload, client.GetSessionID(), true, false) + showServiceSctpRes, err := client.ApiCall("show-service-sctp", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -433,7 +433,7 @@ func updateManagementServiceSctp(d *schema.ResourceData, m interface{}) error { log.Println("Update ServiceSctp - Map = ", serviceSctp) - updateServiceSctpRes, err := client.ApiCall("set-service-sctp", serviceSctp, client.GetSessionID(), true, false) + updateServiceSctpRes, err := client.ApiCall("set-service-sctp", serviceSctp, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateServiceSctpRes.Success { if updateServiceSctpRes.ErrorMsg != "" { return fmt.Errorf(updateServiceSctpRes.ErrorMsg) @@ -454,7 +454,7 @@ func deleteManagementServiceSctp(d *schema.ResourceData, m interface{}) error { log.Println("Delete ServiceSctp") - deleteServiceSctpRes, err := client.ApiCall("delete-service-sctp", serviceSctpPayload, client.GetSessionID(), true, false) + deleteServiceSctpRes, err := client.ApiCall("delete-service-sctp", serviceSctpPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteServiceSctpRes.Success { if deleteServiceSctpRes.ErrorMsg != "" { return fmt.Errorf(deleteServiceSctpRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_service_tcp.go b/checkpoint/resource_checkpoint_management_service_tcp.go index 9605d449..a88b4256 100644 --- a/checkpoint/resource_checkpoint_management_service_tcp.go +++ b/checkpoint/resource_checkpoint_management_service_tcp.go @@ -219,7 +219,7 @@ func createManagementServiceTcp(d *schema.ResourceData, m interface{}) error { log.Println("Create Service Tcp - Map = ", serviceTcp) - addServiceTcpRes, err := client.ApiCall("add-service-tcp", serviceTcp, client.GetSessionID(), true, false) + addServiceTcpRes, err := client.ApiCall("add-service-tcp", serviceTcp, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addServiceTcpRes.Success { if addServiceTcpRes.ErrorMsg != "" { return fmt.Errorf(addServiceTcpRes.ErrorMsg) @@ -240,7 +240,7 @@ func readManagementServiceTcp(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showServiceTcpRes, err := client.ApiCall("show-service-tcp", payload, client.GetSessionID(), true, false) + showServiceTcpRes, err := client.ApiCall("show-service-tcp", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -457,7 +457,7 @@ func updateManagementServiceTcp(d *schema.ResourceData, m interface{}) error { } log.Println("Update Service Tcp - Map = ", serviceTcp) - setServiceTcpRes, _ := client.ApiCall("set-service-tcp", serviceTcp, client.GetSessionID(), true, false) + setServiceTcpRes, _ := client.ApiCall("set-service-tcp", serviceTcp, client.GetSessionID(), true, client.IsProxyUsed()) if !setServiceTcpRes.Success { return fmt.Errorf(setServiceTcpRes.ErrorMsg) } @@ -470,7 +470,7 @@ func deleteManagementServiceTcp(d *schema.ResourceData, m interface{}) error { payload := map[string]interface{}{ "uid": d.Id(), } - deleteServiceTcpRes, _ := client.ApiCall("delete-service-tcp", payload, client.GetSessionID(), true, false) + deleteServiceTcpRes, _ := client.ApiCall("delete-service-tcp", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !deleteServiceTcpRes.Success { return fmt.Errorf(deleteServiceTcpRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_service_udp.go b/checkpoint/resource_checkpoint_management_service_udp.go index 0a962e18..6c2bd846 100644 --- a/checkpoint/resource_checkpoint_management_service_udp.go +++ b/checkpoint/resource_checkpoint_management_service_udp.go @@ -228,7 +228,7 @@ func createManagementServiceUdp(d *schema.ResourceData, m interface{}) error { log.Println("Create Service Udp - Map = ", serviceUdp) - addServiceUdpRes, err := client.ApiCall("add-service-udp", serviceUdp, client.GetSessionID(), true, false) + addServiceUdpRes, err := client.ApiCall("add-service-udp", serviceUdp, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addServiceUdpRes.Success { if addServiceUdpRes.ErrorMsg != "" { return fmt.Errorf(addServiceUdpRes.ErrorMsg) @@ -249,7 +249,7 @@ func readManagementServiceUdp(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showServiceUdpRes, err := client.ApiCall("show-service-udp", payload, client.GetSessionID(), true, false) + showServiceUdpRes, err := client.ApiCall("show-service-udp", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -473,7 +473,7 @@ func updateManagementServiceUdp(d *schema.ResourceData, m interface{}) error { } log.Println("Update Service Udp - Map = ", serviceUdp) - setServiceUdpRes, _ := client.ApiCall("set-service-udp", serviceUdp, client.GetSessionID(), true, false) + setServiceUdpRes, _ := client.ApiCall("set-service-udp", serviceUdp, client.GetSessionID(), true, client.IsProxyUsed()) if !setServiceUdpRes.Success { return fmt.Errorf(setServiceUdpRes.ErrorMsg) } @@ -486,7 +486,7 @@ func deleteManagementServiceUdp(d *schema.ResourceData, m interface{}) error { payload := map[string]interface{}{ "uid": d.Id(), } - deleteServiceUdpRes, _ := client.ApiCall("delete-service-udp", payload, client.GetSessionID(), true, false) + deleteServiceUdpRes, _ := client.ApiCall("delete-service-udp", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !deleteServiceUdpRes.Success { return fmt.Errorf(deleteServiceUdpRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_management_simple_cluster.go b/checkpoint/resource_checkpoint_management_simple_cluster.go index ac7ccea2..b2522078 100644 --- a/checkpoint/resource_checkpoint_management_simple_cluster.go +++ b/checkpoint/resource_checkpoint_management_simple_cluster.go @@ -210,7 +210,12 @@ func resourceManagementSimpleCluster() *schema.Resource { Optional: true, Description: "SIC one time password.", }, - "sic_name": { + "priority": { + Type: schema.TypeInt, + Computed: true, + Description: "The member priority on the cluster.", + }, + "sic_state": { Type: schema.TypeString, Computed: true, Description: "Secure Internal Communication name.", @@ -1208,7 +1213,7 @@ func createManagementSimpleCluster(d *schema.ResourceData, m interface{}) error log.Println("Create Simple Cluster - Map = ", cluster) - addClusterRes, err := client.ApiCall("add-simple-cluster", cluster, client.GetSessionID(), true, false) + addClusterRes, err := client.ApiCall("add-simple-cluster", cluster, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -1221,7 +1226,7 @@ func createManagementSimpleCluster(d *schema.ResourceData, m interface{}) error } // add-simple-cluster returns task-id. Call show-simple-cluster for object uid. - showClusterRes, err := client.ApiCall("show-simple-cluster", map[string]interface{}{"name": d.Get("name")}, client.GetSessionID(), true, false) + showClusterRes, err := client.ApiCall("show-simple-cluster", map[string]interface{}{"name": d.Get("name")}, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -1241,7 +1246,7 @@ func readManagementSimpleCluster(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showClusterRes, err := client.ApiCall("show-simple-cluster", payload, client.GetSessionID(), true, false) + showClusterRes, err := client.ApiCall("show-simple-cluster", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -1261,7 +1266,7 @@ func readManagementSimpleCluster(d *schema.ResourceData, m interface{}) error { totalInterfaces := int(total.(float64)) if totalInterfaces > 50 { payload["limit-interfaces"] = totalInterfaces - showClusterRes, err := client.ApiCall("show-simple-cluster", payload, client.GetSessionID(), true, false) + showClusterRes, err := client.ApiCall("show-simple-cluster", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -1394,6 +1399,9 @@ func readManagementSimpleCluster(d *schema.ResourceData, m interface{}) error { if v, _ := memberJson["name"]; v != nil { memberState["name"] = v } + if v, _ := memberJson["priority"]; v != nil { + memberState["priority"] = v + } if v, _ := memberJson["ip-address"]; v != nil { memberState["ip_address"] = v } @@ -1407,6 +1415,7 @@ func readManagementSimpleCluster(d *schema.ResourceData, m interface{}) error { if v, _ := memberInterfaceJson["name"]; v != nil { memberInterfaceState["name"] = v } + if v, _ := memberInterfaceJson["ipv4-address"]; v != nil { memberInterfaceState["ipv4_address"] = v } @@ -1886,6 +1895,10 @@ func updateManagementSimpleCluster(d *schema.ResourceData, m interface{}) error memberPayload["ip-address"] = v } + if v, ok := d.GetOk("members." + strconv.Itoa(i) + ".priority"); ok { + memberPayload["priority"] = v + } + if v, ok := d.GetOk("members." + strconv.Itoa(i) + ".one_time_password"); ok { memberPayload["one-time-password"] = v } @@ -2264,7 +2277,7 @@ func updateManagementSimpleCluster(d *schema.ResourceData, m interface{}) error } log.Println("Update Simple Cluster - Map = ", cluster) - updateSimpleClusterRes, err := client.ApiCall("set-simple-cluster", cluster, client.GetSessionID(), true, false) + updateSimpleClusterRes, err := client.ApiCall("set-simple-cluster", cluster, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -2287,7 +2300,7 @@ func deleteManagementSimpleCluster(d *schema.ResourceData, m interface{}) error "uid": d.Id(), } - deleteClusterRes, err := client.ApiCall("delete-simple-cluster", payload, client.GetSessionID(), true, false) + deleteClusterRes, err := client.ApiCall("delete-simple-cluster", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteClusterRes.Success { if deleteClusterRes.ErrorMsg != "" { return fmt.Errorf(deleteClusterRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_simple_gateway.go b/checkpoint/resource_checkpoint_management_simple_gateway.go index b048a1ba..ee381e60 100644 --- a/checkpoint/resource_checkpoint_management_simple_gateway.go +++ b/checkpoint/resource_checkpoint_management_simple_gateway.go @@ -1313,7 +1313,7 @@ func createManagementSimpleGateway(d *schema.ResourceData, m interface{}) error log.Println("Create Simple Gateway - Map = ", gateway) - addGatewayRes, err := client.ApiCall("add-simple-gateway", gateway, client.GetSessionID(), true, false) + addGatewayRes, err := client.ApiCall("add-simple-gateway", gateway, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addGatewayRes.Success { if addGatewayRes.ErrorMsg != "" { return fmt.Errorf(addGatewayRes.ErrorMsg) @@ -1333,7 +1333,7 @@ func readManagementSimpleGateway(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showGatewayRes, err := client.ApiCall("show-simple-gateway", payload, client.GetSessionID(), true, false) + showGatewayRes, err := client.ApiCall("show-simple-gateway", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -2428,7 +2428,7 @@ func updateManagementSimpleGateway(d *schema.ResourceData, m interface{}) error } log.Println("Update Simple Gateway - Map = ", gateway) - updateSimpleGatewayRes, err := client.ApiCall("set-simple-gateway", gateway, client.GetSessionID(), true, false) + updateSimpleGatewayRes, err := client.ApiCall("set-simple-gateway", gateway, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateSimpleGatewayRes.Success { if updateSimpleGatewayRes.ErrorMsg != "" { return fmt.Errorf(updateSimpleGatewayRes.ErrorMsg) @@ -2447,7 +2447,7 @@ func deleteManagementSimpleGateway(d *schema.ResourceData, m interface{}) error "uid": d.Id(), } - deleteGatewayRes, err := client.ApiCall("delete-simple-gateway", gatewayPayload, client.GetSessionID(), true, false) + deleteGatewayRes, err := client.ApiCall("delete-simple-gateway", gatewayPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteGatewayRes.Success { if deleteGatewayRes.ErrorMsg != "" { return fmt.Errorf(deleteGatewayRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_threat_exception.go b/checkpoint/resource_checkpoint_management_threat_exception.go index 9a6e63a7..b0a365db 100644 --- a/checkpoint/resource_checkpoint_management_threat_exception.go +++ b/checkpoint/resource_checkpoint_management_threat_exception.go @@ -328,7 +328,7 @@ func createManagementThreatException(d *schema.ResourceData, m interface{}) erro log.Println("Create Threat Exception - Map = ", threatException) - addThreatExceptionRes, err := client.ApiCall("add-threat-exception", threatException, client.GetSessionID(), true, false) + addThreatExceptionRes, err := client.ApiCall("add-threat-exception", threatException, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addThreatExceptionRes.Success { if addThreatExceptionRes.ErrorMsg != "" { return fmt.Errorf(addThreatExceptionRes.ErrorMsg) @@ -366,7 +366,7 @@ func readManagementThreatException(d *schema.ResourceData, m interface{}) error payload["rule-name"] = v.(string) } - showThreatRuleRes, err := client.ApiCall("show-threat-exception", payload, client.GetSessionID(), true, false) + showThreatRuleRes, err := client.ApiCall("show-threat-exception", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -682,7 +682,7 @@ func updateManagementThreatException(d *schema.ResourceData, m interface{}) erro log.Println("Update Threat Exception - Map = ", threatException) - updateThreatExceptionRes, err := client.ApiCall("set-threat-exception", threatException, client.GetSessionID(), true, false) + updateThreatExceptionRes, err := client.ApiCall("set-threat-exception", threatException, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateThreatExceptionRes.Success { if updateThreatExceptionRes.ErrorMsg != "" { return fmt.Errorf(updateThreatExceptionRes.ErrorMsg) @@ -716,7 +716,7 @@ func deleteManagementThreatException(d *schema.ResourceData, m interface{}) erro threatExceptionPayload["rule-name"] = v } - deleteThreatExceptionRes, err := client.ApiCall("delete-threat-exception", threatExceptionPayload, client.GetSessionID(), true, false) + deleteThreatExceptionRes, err := client.ApiCall("delete-threat-exception", threatExceptionPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteThreatExceptionRes.Success { if deleteThreatExceptionRes.ErrorMsg != "" { return fmt.Errorf(deleteThreatExceptionRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_threat_indicator.go b/checkpoint/resource_checkpoint_management_threat_indicator.go index 6811b247..336465de 100644 --- a/checkpoint/resource_checkpoint_management_threat_indicator.go +++ b/checkpoint/resource_checkpoint_management_threat_indicator.go @@ -283,7 +283,7 @@ func createManagementThreatIndicator(d *schema.ResourceData, m interface{}) erro log.Println("Create Threat Indicator - Map = ", threatIndicator) - threatIndicatorRes, err := client.ApiCall("add-threat-indicator", threatIndicator, client.GetSessionID(), true, false) + threatIndicatorRes, err := client.ApiCall("add-threat-indicator", threatIndicator, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -304,7 +304,7 @@ func createManagementThreatIndicator(d *schema.ResourceData, m interface{}) erro "name": d.Get("name"), } - showThreatIndicatorRes, err := client.ApiCall("show-threat-indicator", payload, client.GetSessionID(), true, false) + showThreatIndicatorRes, err := client.ApiCall("show-threat-indicator", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -329,7 +329,7 @@ func readManagementThreatIndicator(d *schema.ResourceData, m interface{}) error "name": d.Get("name"), } - showThreatIndicatorRes, err := client.ApiCall("show-threat-indicator", payload, client.GetSessionID(), true, false) + showThreatIndicatorRes, err := client.ApiCall("show-threat-indicator", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -487,7 +487,7 @@ func updateManagementThreatIndicator(d *schema.ResourceData, m interface{}) erro } log.Println("Update Threat Indicator - Map = ", threatIndicator) - updateThreatIndicatorRes, err := client.ApiCall("set-threat-indicator", threatIndicator, client.GetSessionID(), true, false) + updateThreatIndicatorRes, err := client.ApiCall("set-threat-indicator", threatIndicator, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateThreatIndicatorRes.Success { if updateThreatIndicatorRes.ErrorMsg != "" { return fmt.Errorf(updateThreatIndicatorRes.ErrorMsg) @@ -506,7 +506,7 @@ func deleteManagementThreatIndicator(d *schema.ResourceData, m interface{}) erro "name": d.Get("name"), } - deleteThreatIndicatorRes, err := client.ApiCall("delete-threat-indicator", threatIndicatorPayload, client.GetSessionID(), true, false) + deleteThreatIndicatorRes, err := client.ApiCall("delete-threat-indicator", threatIndicatorPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteThreatIndicatorRes.Success { if deleteThreatIndicatorRes.ErrorMsg != "" { return fmt.Errorf(deleteThreatIndicatorRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_threat_profile.go b/checkpoint/resource_checkpoint_management_threat_profile.go index 3746bb0c..8d93c886 100644 --- a/checkpoint/resource_checkpoint_management_threat_profile.go +++ b/checkpoint/resource_checkpoint_management_threat_profile.go @@ -680,7 +680,7 @@ func createManagementThreatProfile(d *schema.ResourceData, m interface{}) error log.Println("Create Threat Profile - Map = ", threatProfile) - threatProfileRes, err := client.ApiCall("add-threat-profile", threatProfile, client.GetSessionID(), true, false) + threatProfileRes, err := client.ApiCall("add-threat-profile", threatProfile, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -692,7 +692,7 @@ func createManagementThreatProfile(d *schema.ResourceData, m interface{}) error return fmt.Errorf(msg) } - showThreatProfileRes, err := client.ApiCall("show-threat-profile", map[string]interface{}{"name": d.Get("name")}, client.GetSessionID(), true, false) + showThreatProfileRes, err := client.ApiCall("show-threat-profile", map[string]interface{}{"name": d.Get("name")}, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -713,7 +713,7 @@ func readManagementThreatProfile(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showThreatProfileRes, err := client.ApiCall("show-threat-profile", payload, client.GetSessionID(), true, false) + showThreatProfileRes, err := client.ApiCall("show-threat-profile", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -1344,7 +1344,7 @@ func updateManagementThreatProfile(d *schema.ResourceData, m interface{}) error log.Println("Update Threat Profile - Map = ", threatProfile) - threatProfileRes, err := client.ApiCall("set-threat-profile", threatProfile, client.GetSessionID(), true, false) + threatProfileRes, err := client.ApiCall("set-threat-profile", threatProfile, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -1368,7 +1368,7 @@ func deleteManagementThreatProfile(d *schema.ResourceData, m interface{}) error "uid": d.Id(), } - deleteThreatProfileRes, err := client.ApiCall("delete-threat-profile", threatProfilePayload, client.GetSessionID(), true, false) + deleteThreatProfileRes, err := client.ApiCall("delete-threat-profile", threatProfilePayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) diff --git a/checkpoint/resource_checkpoint_management_threat_rule.go b/checkpoint/resource_checkpoint_management_threat_rule.go index d556e466..e2a34574 100644 --- a/checkpoint/resource_checkpoint_management_threat_rule.go +++ b/checkpoint/resource_checkpoint_management_threat_rule.go @@ -301,7 +301,7 @@ func createManagementThreatRule(d *schema.ResourceData, m interface{}) error { log.Println("Create Threat Rule - Map = ", threatRule) - addThreatRuleRes, err := client.ApiCall("add-threat-rule", threatRule, client.GetSessionID(), true, false) + addThreatRuleRes, err := client.ApiCall("add-threat-rule", threatRule, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addThreatRuleRes.Success { if addThreatRuleRes.ErrorMsg != "" { return fmt.Errorf(addThreatRuleRes.ErrorMsg) @@ -323,7 +323,7 @@ func readManagementThreatRule(d *schema.ResourceData, m interface{}) error { "layer": d.Get("layer"), } - showThreatRuleRes, err := client.ApiCall("show-threat-rule", payload, client.GetSessionID(), true, false) + showThreatRuleRes, err := client.ApiCall("show-threat-rule", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -624,7 +624,7 @@ func updateManagementThreatRule(d *schema.ResourceData, m interface{}) error { log.Println("Update Threat Rule - Map = ", threatRule) - updateThreatRuleRes, err := client.ApiCall("set-threat-rule", threatRule, client.GetSessionID(), true, false) + updateThreatRuleRes, err := client.ApiCall("set-threat-rule", threatRule, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateThreatRuleRes.Success { if updateThreatRuleRes.ErrorMsg != "" { return fmt.Errorf(updateThreatRuleRes.ErrorMsg) @@ -642,7 +642,7 @@ func deleteManagementThreatRule(d *schema.ResourceData, m interface{}) error { "layer": d.Get("layer"), } - deleteThreatRuleRes, err := client.ApiCall("delete-threat-rule", threatRulePayload, client.GetSessionID(), true, false) + deleteThreatRuleRes, err := client.ApiCall("delete-threat-rule", threatRulePayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteThreatRuleRes.Success { if deleteThreatRuleRes.ErrorMsg != "" { return fmt.Errorf(deleteThreatRuleRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_time_group.go b/checkpoint/resource_checkpoint_management_time_group.go index a06939ac..975beef6 100644 --- a/checkpoint/resource_checkpoint_management_time_group.go +++ b/checkpoint/resource_checkpoint_management_time_group.go @@ -100,7 +100,7 @@ func createManagementTimeGroup(d *schema.ResourceData, m interface{}) error { log.Println("Create TimeGroup - Map = ", timeGroup) - addTimeGroupRes, err := client.ApiCall("add-time-group", timeGroup, client.GetSessionID(), true, false) + addTimeGroupRes, err := client.ApiCall("add-time-group", timeGroup, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addTimeGroupRes.Success { if addTimeGroupRes.ErrorMsg != "" { return fmt.Errorf(addTimeGroupRes.ErrorMsg) @@ -121,7 +121,7 @@ func readManagementTimeGroup(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showTimeGroupRes, err := client.ApiCall("show-time-group", payload, client.GetSessionID(), true, false) + showTimeGroupRes, err := client.ApiCall("show-time-group", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -242,7 +242,7 @@ func updateManagementTimeGroup(d *schema.ResourceData, m interface{}) error { log.Println("Update TimeGroup - Map = ", timeGroup) - updateTimeGroupRes, err := client.ApiCall("set-time-group", timeGroup, client.GetSessionID(), true, false) + updateTimeGroupRes, err := client.ApiCall("set-time-group", timeGroup, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateTimeGroupRes.Success { if updateTimeGroupRes.ErrorMsg != "" { return fmt.Errorf(updateTimeGroupRes.ErrorMsg) @@ -263,7 +263,7 @@ func deleteManagementTimeGroup(d *schema.ResourceData, m interface{}) error { log.Println("Delete TimeGroup") - deleteTimeGroupRes, err := client.ApiCall("delete-time-group", timeGroupPayload, client.GetSessionID(), true, false) + deleteTimeGroupRes, err := client.ApiCall("delete-time-group", timeGroupPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteTimeGroupRes.Success { if deleteTimeGroupRes.ErrorMsg != "" { return fmt.Errorf(deleteTimeGroupRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_user.go b/checkpoint/resource_checkpoint_management_user.go index f35d0c2a..7279bfcf 100644 --- a/checkpoint/resource_checkpoint_management_user.go +++ b/checkpoint/resource_checkpoint_management_user.go @@ -286,7 +286,7 @@ func createManagementUser(d *schema.ResourceData, m interface{}) error { log.Println("Create User - Map = ", user) - addUserRes, err := client.ApiCall("add-user", user, client.GetSessionID(), true, false) + addUserRes, err := client.ApiCall("add-user", user, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addUserRes.Success { if addUserRes.ErrorMsg != "" { return fmt.Errorf(addUserRes.ErrorMsg) @@ -307,7 +307,7 @@ func readManagementUser(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showUserRes, err := client.ApiCall("show-user", payload, client.GetSessionID(), true, false) + showUserRes, err := client.ApiCall("show-user", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -587,7 +587,7 @@ func updateManagementUser(d *schema.ResourceData, m interface{}) error { log.Println("Update User - Map = ", user) - updateUserRes, err := client.ApiCall("set-user", user, client.GetSessionID(), true, false) + updateUserRes, err := client.ApiCall("set-user", user, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateUserRes.Success { if updateUserRes.ErrorMsg != "" { return fmt.Errorf(updateUserRes.ErrorMsg) @@ -608,7 +608,7 @@ func deleteManagementUser(d *schema.ResourceData, m interface{}) error { log.Println("Delete User") - deleteUserRes, err := client.ApiCall("delete-user", userPayload, client.GetSessionID(), true, false) + deleteUserRes, err := client.ApiCall("delete-user", userPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteUserRes.Success { if deleteUserRes.ErrorMsg != "" { return fmt.Errorf(deleteUserRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_user_group.go b/checkpoint/resource_checkpoint_management_user_group.go index a67662c3..bbf44ffd 100644 --- a/checkpoint/resource_checkpoint_management_user_group.go +++ b/checkpoint/resource_checkpoint_management_user_group.go @@ -106,7 +106,7 @@ func createManagementUserGroup(d *schema.ResourceData, m interface{}) error { log.Println("Create UserGroup - Map = ", userGroup) - addUserGroupRes, err := client.ApiCall("add-user-group", userGroup, client.GetSessionID(), true, false) + addUserGroupRes, err := client.ApiCall("add-user-group", userGroup, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addUserGroupRes.Success { if addUserGroupRes.ErrorMsg != "" { return fmt.Errorf(addUserGroupRes.ErrorMsg) @@ -127,7 +127,7 @@ func readManagementUserGroup(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showUserGroupRes, err := client.ApiCall("show-user-group", payload, client.GetSessionID(), true, false) + showUserGroupRes, err := client.ApiCall("show-user-group", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -247,7 +247,7 @@ func updateManagementUserGroup(d *schema.ResourceData, m interface{}) error { log.Println("Update UserGroup - Map = ", userGroup) - updateUserGroupRes, err := client.ApiCall("set-user-group", userGroup, client.GetSessionID(), true, false) + updateUserGroupRes, err := client.ApiCall("set-user-group", userGroup, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateUserGroupRes.Success { if updateUserGroupRes.ErrorMsg != "" { return fmt.Errorf(updateUserGroupRes.ErrorMsg) @@ -268,7 +268,7 @@ func deleteManagementUserGroup(d *schema.ResourceData, m interface{}) error { log.Println("Delete UserGroup") - deleteUserGroupRes, err := client.ApiCall("delete-user-group", userGroupPayload, client.GetSessionID(), true, false) + deleteUserGroupRes, err := client.ApiCall("delete-user-group", userGroupPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteUserGroupRes.Success { if deleteUserGroupRes.ErrorMsg != "" { return fmt.Errorf(deleteUserGroupRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_user_template.go b/checkpoint/resource_checkpoint_management_user_template.go index c3ddb749..13992c5f 100644 --- a/checkpoint/resource_checkpoint_management_user_template.go +++ b/checkpoint/resource_checkpoint_management_user_template.go @@ -254,7 +254,7 @@ func createManagementUserTemplate(d *schema.ResourceData, m interface{}) error { log.Println("Create UserTemplate - Map = ", userTemplate) - addUserTemplateRes, err := client.ApiCall("add-user-template", userTemplate, client.GetSessionID(), true, false) + addUserTemplateRes, err := client.ApiCall("add-user-template", userTemplate, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addUserTemplateRes.Success { if addUserTemplateRes.ErrorMsg != "" { return fmt.Errorf(addUserTemplateRes.ErrorMsg) @@ -275,7 +275,7 @@ func readManagementUserTemplate(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showUserTemplateRes, err := client.ApiCall("show-user-template", payload, client.GetSessionID(), true, false) + showUserTemplateRes, err := client.ApiCall("show-user-template", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -555,7 +555,7 @@ func updateManagementUserTemplate(d *schema.ResourceData, m interface{}) error { log.Println("Update UserTemplate - Map = ", userTemplate) - updateUserTemplateRes, err := client.ApiCall("set-user-template", userTemplate, client.GetSessionID(), true, false) + updateUserTemplateRes, err := client.ApiCall("set-user-template", userTemplate, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateUserTemplateRes.Success { if updateUserTemplateRes.ErrorMsg != "" { return fmt.Errorf(updateUserTemplateRes.ErrorMsg) @@ -576,7 +576,7 @@ func deleteManagementUserTemplate(d *schema.ResourceData, m interface{}) error { log.Println("Delete UserTemplate") - deleteUserTemplateRes, err := client.ApiCall("delete-user-template", userTemplatePayload, client.GetSessionID(), true, false) + deleteUserTemplateRes, err := client.ApiCall("delete-user-template", userTemplatePayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteUserTemplateRes.Success { if deleteUserTemplateRes.ErrorMsg != "" { return fmt.Errorf(deleteUserTemplateRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_vmware_data_center_server.go b/checkpoint/resource_checkpoint_management_vmware_data_center_server.go new file mode 100644 index 00000000..6519f87b --- /dev/null +++ b/checkpoint/resource_checkpoint_management_vmware_data_center_server.go @@ -0,0 +1,365 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "log" + "strconv" + "strings" +) + +func resourceManagementVMwareDataCenterServer() *schema.Resource { + return &schema.Resource{ + Create: createManagementVMwareDataCenterServer, + Read: readManagementVMwareDataCenterServer, + Update: updateManagementVMwareDataCenterServer, + Delete: deleteManagementVMwareDataCenterServer, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Schema: map[string]*schema.Schema{ + "type": { + Type: schema.TypeString, + Required: true, + Description: "VMWare object type. nsx or nsxt or vcenter.", + }, + "name": { + Type: schema.TypeString, + Required: true, + Description: "Object name. Must be unique in the domain.", + }, + "hostname": { + Type: schema.TypeString, + Required: true, + Description: "IP Address or hostname of the vCenter server.", + }, + "username": { + Type: schema.TypeString, + Required: true, + Description: "Username of the vCenter server", + }, + "password": { + Type: schema.TypeString, + Optional: true, + Description: "Password of the vCenter server.", + }, + "password_base64": { + Type: schema.TypeString, + Optional: true, + Description: "Password of the vCenter server encoded in Base64.", + }, + "certificate_fingerprint": { + Type: schema.TypeString, + Optional: true, + Description: "Specify the SHA-1 or SHA-256 fingerprint of the Data Center Server's certificate.", + }, + "unsafe_auto_accept": { + Type: schema.TypeBool, + Optional: true, + Description: "When set to false, the current Data Center Server's certificate should be trusted, either by providing the certificate-fingerprint argument or by relying on a previously trusted certificate of this hostname.\n\nWhen set to true, trust the current Data Center Server's certificate as-is.", + Default: false, + }, + "tags": { + Type: schema.TypeSet, + Optional: true, + Description: "Collection of tag identifiers.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "color": { + Type: schema.TypeString, + Optional: true, + Description: "Color of the object. Should be one of existing colors.", + Default: "black", + }, + "comments": { + Type: schema.TypeString, + Optional: true, + Description: "Comments string.", + }, + "ignore_warnings": { + Type: schema.TypeBool, + Optional: true, + Description: "Apply changes ignoring warnings. By Setting this parameter to 'true' test connection failure will be ignored.", + Default: false, + }, + "ignore_errors": { + Type: schema.TypeBool, + Optional: true, + Description: "Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored.", + Default: false, + }, + }, + } +} + +func createManagementVMwareDataCenterServer(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + + vmwareDataCenterServer := make(map[string]interface{}) + + if v, ok := d.GetOk("name"); ok { + vmwareDataCenterServer["name"] = v.(string) + } + + if v, ok := d.GetOk("type"); ok { + vmwareDataCenterServer["type"] = v.(string) + } + + if v, ok := d.GetOk("hostname"); ok { + vmwareDataCenterServer["hostname"] = v.(string) + } + + if v, ok := d.GetOk("username"); ok { + vmwareDataCenterServer["username"] = v.(string) + } + + if v, ok := d.GetOk("password"); ok { + vmwareDataCenterServer["password"] = v.(string) + } + + if v, ok := d.GetOk("password_base64"); ok { + vmwareDataCenterServer["password-base64"] = v.(string) + } + + if v, ok := d.GetOk("certificate_fingerprint"); ok { + vmwareDataCenterServer["certificate-fingerprint"] = v.(string) + } + + if v, ok := d.GetOk("unsafe_auto_accept"); ok { + vmwareDataCenterServer["unsafe-auto-accept"] = v.(bool) + } + + if v, ok := d.GetOk("tags"); ok { + vmwareDataCenterServer["tags"] = v.(*schema.Set).List() + } + + if v, ok := d.GetOk("color"); ok { + vmwareDataCenterServer["color"] = v.(string) + } + + if v, ok := d.GetOk("comments"); ok { + vmwareDataCenterServer["comments"] = v.(string) + } + + if v, ok := d.GetOkExists("ignore_warnings"); ok { + vmwareDataCenterServer["ignore-warnings"] = v.(bool) + } + + if v, ok := d.GetOkExists("ignore_errors"); ok { + vmwareDataCenterServer["ignore-errors"] = v.(bool) + } + + log.Println("Create vmwareDataCenterServer - Map = ", vmwareDataCenterServer) + + addVMwareDataCenterServerRes, err := client.ApiCall("add-data-center-server", vmwareDataCenterServer, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !addVMwareDataCenterServerRes.Success { + if addVMwareDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(addVMwareDataCenterServerRes.ErrorMsg) + } + msg := createTaskFailMessage("add-data-center-server", addVMwareDataCenterServerRes.GetData()) + return fmt.Errorf(msg) + } + payload := map[string]interface{}{ + "name": vmwareDataCenterServer["name"], + } + showVMwareDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showVMwareDataCenterServerRes.Success { + return fmt.Errorf(showVMwareDataCenterServerRes.ErrorMsg) + } + d.SetId(showVMwareDataCenterServerRes.GetData()["uid"].(string)) + return readManagementVMwareDataCenterServer(d, m) +} + +func readManagementVMwareDataCenterServer(d *schema.ResourceData, m interface{}) error { + client := m.(*checkpoint.ApiClient) + payload := map[string]interface{}{ + "uid": d.Id(), + } + + showVMwareDataCenterServerRes, err := client.ApiCall("show-data-center-server", payload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !showVMwareDataCenterServerRes.Success { + if objectNotFound(showVMwareDataCenterServerRes.GetData()["code"].(string)) { + d.SetId("") + return nil + } + return fmt.Errorf(showVMwareDataCenterServerRes.ErrorMsg) + } + vmwareDataCenterServer := showVMwareDataCenterServerRes.GetData() + + if v := vmwareDataCenterServer["name"]; v != nil { + _ = d.Set("name", v) + } + + if vmwareDataCenterServer["properties"] != nil { + propsJson, ok := vmwareDataCenterServer["properties"].([]interface{}) + if ok { + for _, prop := range propsJson { + propMap := prop.(map[string]interface{}) + propName := strings.ReplaceAll(propMap["name"].(string), "-", "_") + propValue := propMap["value"] + if propName == "unsafe_auto_accept" { + propValue, _ = strconv.ParseBool(propValue.(string)) + } + _ = d.Set(propName, propValue) + } + } + } + + if vmwareDataCenterServer["tags"] != nil { + tagsJson, ok := vmwareDataCenterServer["tags"].([]interface{}) + if ok { + tagsIds := make([]string, 0) + if len(tagsJson) > 0 { + for _, tags := range tagsJson { + tags := tags.(map[string]interface{}) + tagsIds = append(tagsIds, tags["name"].(string)) + } + } + _ = d.Set("tags", tagsIds) + } + } else { + _ = d.Set("tags", nil) + } + + if v := vmwareDataCenterServer["color"]; v != nil { + _ = d.Set("color", v) + } + + if v := vmwareDataCenterServer["data-center-type"]; v != nil { + _ = d.Set("type", v) + } + + if v := vmwareDataCenterServer["comments"]; v != nil { + _ = d.Set("comments", v) + } + + if v := vmwareDataCenterServer["ignore-warnings"]; v != nil { + _ = d.Set("ignore_warnings", v) + } + + if v := vmwareDataCenterServer["ignore-errors"]; v != nil { + _ = d.Set("ignore_errors", v) + } + + return nil + +} + +func updateManagementVMwareDataCenterServer(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + vmwareDataCenterServer := make(map[string]interface{}) + + if ok := d.HasChange("name"); ok { + oldName, newName := d.GetChange("name") + vmwareDataCenterServer["name"] = oldName + vmwareDataCenterServer["new-name"] = newName + } else { + vmwareDataCenterServer["name"] = d.Get("name") + } + + if d.HasChange("hostname") { + vmwareDataCenterServer["hostname"] = d.Get("hostname") + } + + if d.HasChange("password") { + vmwareDataCenterServer["password"] = d.Get("password") + } + + if d.HasChange("password_base64") { + vmwareDataCenterServer["password-base64"] = d.Get("password_base64") + } + + if d.HasChange("username") { + vmwareDataCenterServer["username"] = d.Get("username") + if v := d.Get("password"); v != nil && v != "" { + vmwareDataCenterServer["password"] = v + } + if v := d.Get("password_base64"); v != nil && v != "" { + vmwareDataCenterServer["password-base64"] = v + } + } + + if d.HasChange("certificate_fingerprint") { + vmwareDataCenterServer["certificate-fingerprint"] = d.Get("certificate_fingerprint") + } + + if d.HasChange("unsafe_auto_accept") { + vmwareDataCenterServer["unsafe-auto-accept"] = d.Get("unsafe_auto_accept") + } + + if d.HasChange("tags") { + if v, ok := d.GetOk("tags"); ok { + vmwareDataCenterServer["tags"] = v.(*schema.Set).List() + } else { + oldTags, _ := d.GetChange("tags") + vmwareDataCenterServer["tags"] = map[string]interface{}{"remove": oldTags.(*schema.Set).List()} + } + } + + if ok := d.HasChange("color"); ok { + vmwareDataCenterServer["color"] = d.Get("color") + } + + if ok := d.HasChange("comments"); ok { + vmwareDataCenterServer["comments"] = d.Get("comments") + } + + if v, ok := d.GetOkExists("ignore_warnings"); ok { + vmwareDataCenterServer["ignore-warnings"] = v.(bool) + } + + if v, ok := d.GetOkExists("ignore_errors"); ok { + vmwareDataCenterServer["ignore-errors"] = v.(bool) + } + + log.Println("Update vmwareDataCenterServer - Map = ", vmwareDataCenterServer) + + updateVMwareDataCenterServerRes, err := client.ApiCall("set-data-center-server", vmwareDataCenterServer, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil { + return fmt.Errorf(err.Error()) + } + if !updateVMwareDataCenterServerRes.Success { + if updateVMwareDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(updateVMwareDataCenterServerRes.ErrorMsg) + } + msg := createTaskFailMessage("set-data-center-server", updateVMwareDataCenterServerRes.GetData()) + return fmt.Errorf(msg) + } + + return readManagementVMwareDataCenterServer(d, m) +} + +func deleteManagementVMwareDataCenterServer(d *schema.ResourceData, m interface{}) error { + + client := m.(*checkpoint.ApiClient) + + vmwareDataCenterServerPayload := map[string]interface{}{ + "uid": d.Id(), + } + + log.Println("Delete vmwareDataCenterServer") + + deleteVMwareDataCenterServerRes, err := client.ApiCall("delete-data-center-server", vmwareDataCenterServerPayload, client.GetSessionID(), true, client.IsProxyUsed()) + if err != nil || !deleteVMwareDataCenterServerRes.Success { + if deleteVMwareDataCenterServerRes.ErrorMsg != "" { + return fmt.Errorf(deleteVMwareDataCenterServerRes.ErrorMsg) + } + return fmt.Errorf(err.Error()) + } + d.SetId("") + + return nil +} diff --git a/checkpoint/resource_checkpoint_management_vmware_data_center_server_test.go b/checkpoint/resource_checkpoint_management_vmware_data_center_server_test.go new file mode 100644 index 00000000..0eba79f2 --- /dev/null +++ b/checkpoint/resource_checkpoint_management_vmware_data_center_server_test.go @@ -0,0 +1,113 @@ +package checkpoint + +import ( + "fmt" + checkpoint "github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + "os" + "strings" + "testing" +) + +func TestAccCheckpointManagementVMwareDataCenterServer_basic(t *testing.T) { + + var vmwareDataCenterServerMap map[string]interface{} + resourceName := "checkpoint_management_vmware_data_center_server.test" + objName := "tfTestManagementVMwareDataCenterServer_" + acctest.RandString(6) + vmType := "vcenter" + username := "USERNAME" + password := "PASSWORD" + hostname := "HOSTNAME" + + context := os.Getenv("CHECKPOINT_CONTEXT") + if context != "web_api" { + t.Skip("Skipping management test") + } else if context == "" { + t.Skip("Env CHECKPOINT_CONTEXT must be specified to run this acc test") + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckpointManagementVMwareDataCenterServerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccManagementVMwareDataCenterServerConfig(objName, vmType, username, password, hostname), + Check: resource.ComposeTestCheckFunc( + testAccCheckCheckpointManagementVMwareDataCenterServerExists(resourceName, &vmwareDataCenterServerMap), + testAccCheckCheckpointManagementVMwareDataCenterServerAttributes(&vmwareDataCenterServerMap, objName), + ), + }, + }, + }) +} + +func testAccCheckpointManagementVMwareDataCenterServerDestroy(s *terraform.State) error { + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + for _, rs := range s.RootModule().Resources { + if rs.Type != "checkpoint_management_vmware_data_center_server" { + continue + } + if rs.Primary.ID != "" { + res, _ := client.ApiCall("show-data-center-server", map[string]interface{}{"uid": rs.Primary.ID}, client.GetSessionID(), true, false) + if res.Success { + return fmt.Errorf("VMwareDataCenterServer object (%s) still exists", rs.Primary.ID) + } + } + return nil + } + return nil +} + +func testAccCheckCheckpointManagementVMwareDataCenterServerExists(resourceTfName string, res *map[string]interface{}) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[resourceTfName] + if !ok { + return fmt.Errorf("Resource not found: %s", resourceTfName) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("VMwareDataCenterServer ID is not set") + } + + client := testAccProvider.Meta().(*checkpoint.ApiClient) + + response, err := client.ApiCall("show-data-center-server", map[string]interface{}{"uid": rs.Primary.ID}, client.GetSessionID(), true, false) + if !response.Success { + return err + } + + *res = response.GetData() + + return nil + } +} + +func testAccCheckCheckpointManagementVMwareDataCenterServerAttributes(vmwareDataCenterServerMap *map[string]interface{}, name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + + vmwareDataCenterServerName := (*vmwareDataCenterServerMap)["name"].(string) + if !strings.EqualFold(vmwareDataCenterServerName, name) { + return fmt.Errorf("name is %s, expected %s", name, vmwareDataCenterServerName) + } + return nil + } +} + +func testAccManagementVMwareDataCenterServerConfig(name string, vmType string, username string, password string, hostname string) string { + return fmt.Sprintf(` +resource "checkpoint_management_vmware_data_center_server" "test" { + name = "%s" + type = "%s" + username = "%s" + password = "%s" + hostname = "%s" + unsafe_auto_accept = true + ignore_warnings = true +} +`, name, vmType, username, password, hostname) +} diff --git a/checkpoint/resource_checkpoint_management_vpn_community_meshed.go b/checkpoint/resource_checkpoint_management_vpn_community_meshed.go index d49b3d2a..ec031953 100644 --- a/checkpoint/resource_checkpoint_management_vpn_community_meshed.go +++ b/checkpoint/resource_checkpoint_management_vpn_community_meshed.go @@ -293,7 +293,7 @@ func createManagementVpnCommunityMeshed(d *schema.ResourceData, m interface{}) e log.Println("Create VpnCommunityMeshed - Map = ", vpnCommunityMeshed) - addVpnCommunityMeshedRes, err := client.ApiCall("add-vpn-community-meshed", vpnCommunityMeshed, client.GetSessionID(), true, false) + addVpnCommunityMeshedRes, err := client.ApiCall("add-vpn-community-meshed", vpnCommunityMeshed, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addVpnCommunityMeshedRes.Success { if addVpnCommunityMeshedRes.ErrorMsg != "" { return fmt.Errorf(addVpnCommunityMeshedRes.ErrorMsg) @@ -314,7 +314,7 @@ func readManagementVpnCommunityMeshed(d *schema.ResourceData, m interface{}) err "uid": d.Id(), } - showVpnCommunityMeshedRes, err := client.ApiCall("show-vpn-community-meshed", payload, client.GetSessionID(), true, false) + showVpnCommunityMeshedRes, err := client.ApiCall("show-vpn-community-meshed", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -669,7 +669,7 @@ func updateManagementVpnCommunityMeshed(d *schema.ResourceData, m interface{}) e log.Println("Update VpnCommunityMeshed - Map = ", vpnCommunityMeshed) - updateVpnCommunityMeshedRes, err := client.ApiCall("set-vpn-community-meshed", vpnCommunityMeshed, client.GetSessionID(), true, false) + updateVpnCommunityMeshedRes, err := client.ApiCall("set-vpn-community-meshed", vpnCommunityMeshed, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateVpnCommunityMeshedRes.Success { if updateVpnCommunityMeshedRes.ErrorMsg != "" { return fmt.Errorf(updateVpnCommunityMeshedRes.ErrorMsg) @@ -690,7 +690,7 @@ func deleteManagementVpnCommunityMeshed(d *schema.ResourceData, m interface{}) e log.Println("Delete VpnCommunityMeshed") - deleteVpnCommunityMeshedRes, err := client.ApiCall("delete-vpn-community-meshed", vpnCommunityMeshedPayload, client.GetSessionID(), true, false) + deleteVpnCommunityMeshedRes, err := client.ApiCall("delete-vpn-community-meshed", vpnCommunityMeshedPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteVpnCommunityMeshedRes.Success { if deleteVpnCommunityMeshedRes.ErrorMsg != "" { return fmt.Errorf(deleteVpnCommunityMeshedRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_vpn_community_remote_access.go b/checkpoint/resource_checkpoint_management_vpn_community_remote_access.go index da073cd6..d194da1a 100644 --- a/checkpoint/resource_checkpoint_management_vpn_community_remote_access.go +++ b/checkpoint/resource_checkpoint_management_vpn_community_remote_access.go @@ -106,7 +106,7 @@ func createManagementVpnCommunityRemoteAccess(d *schema.ResourceData, m interfac payload["ignore-errors"] = v.(bool) } - SetVpnCommunityRemoteAccessRes, _ := client.ApiCall("set-vpn-community-remote-access", payload, client.GetSessionID(), true, false) + SetVpnCommunityRemoteAccessRes, _ := client.ApiCall("set-vpn-community-remote-access", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !SetVpnCommunityRemoteAccessRes.Success { return fmt.Errorf(SetVpnCommunityRemoteAccessRes.ErrorMsg) } @@ -172,7 +172,7 @@ func updateManagementVpnCommunityRemoteAccess(d *schema.ResourceData, m interfac payload["ignore-errors"] = v.(bool) } - SetVpnCommunityRemoteAccessRes, _ := client.ApiCall("set-vpn-community-remote-access", payload, client.GetSessionID(), true, false) + SetVpnCommunityRemoteAccessRes, _ := client.ApiCall("set-vpn-community-remote-access", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !SetVpnCommunityRemoteAccessRes.Success { return fmt.Errorf(SetVpnCommunityRemoteAccessRes.ErrorMsg) } @@ -187,7 +187,7 @@ func readManagementVpnCommunityRemoteAccess(d *schema.ResourceData, m interface{ "uid": d.Id(), } - showVpnCommunityRemoteAccessRes, err := client.ApiCall("show-vpn-community-remote-access", payload, client.GetSessionID(), true, false) + showVpnCommunityRemoteAccessRes, err := client.ApiCall("show-vpn-community-remote-access", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } diff --git a/checkpoint/resource_checkpoint_management_vpn_community_star.go b/checkpoint/resource_checkpoint_management_vpn_community_star.go index 73c9b082..010faa85 100644 --- a/checkpoint/resource_checkpoint_management_vpn_community_star.go +++ b/checkpoint/resource_checkpoint_management_vpn_community_star.go @@ -315,7 +315,7 @@ func createManagementVpnCommunityStar(d *schema.ResourceData, m interface{}) err log.Println("Create VpnCommunityStar - Map = ", vpnCommunityStar) - addVpnCommunityStarRes, err := client.ApiCall("add-vpn-community-star", vpnCommunityStar, client.GetSessionID(), true, false) + addVpnCommunityStarRes, err := client.ApiCall("add-vpn-community-star", vpnCommunityStar, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addVpnCommunityStarRes.Success { if addVpnCommunityStarRes.ErrorMsg != "" { return fmt.Errorf(addVpnCommunityStarRes.ErrorMsg) @@ -336,7 +336,7 @@ func readManagementVpnCommunityStar(d *schema.ResourceData, m interface{}) error "uid": d.Id(), } - showVpnCommunityStarRes, err := client.ApiCall("show-vpn-community-star", payload, client.GetSessionID(), true, false) + showVpnCommunityStarRes, err := client.ApiCall("show-vpn-community-star", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -724,7 +724,7 @@ func updateManagementVpnCommunityStar(d *schema.ResourceData, m interface{}) err log.Println("Update VpnCommunityStar - Map = ", vpnCommunityStar) - updateVpnCommunityStarRes, err := client.ApiCall("set-vpn-community-star", vpnCommunityStar, client.GetSessionID(), true, false) + updateVpnCommunityStarRes, err := client.ApiCall("set-vpn-community-star", vpnCommunityStar, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateVpnCommunityStarRes.Success { if updateVpnCommunityStarRes.ErrorMsg != "" { return fmt.Errorf(updateVpnCommunityStarRes.ErrorMsg) @@ -745,7 +745,7 @@ func deleteManagementVpnCommunityStar(d *schema.ResourceData, m interface{}) err log.Println("Delete VpnCommunityStar") - deleteVpnCommunityStarRes, err := client.ApiCall("delete-vpn-community-star", vpnCommunityStarPayload, client.GetSessionID(), true, false) + deleteVpnCommunityStarRes, err := client.ApiCall("delete-vpn-community-star", vpnCommunityStarPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteVpnCommunityStarRes.Success { if deleteVpnCommunityStarRes.ErrorMsg != "" { return fmt.Errorf(deleteVpnCommunityStarRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_management_wildcard.go b/checkpoint/resource_checkpoint_management_wildcard.go index 34625435..cd6d0f27 100644 --- a/checkpoint/resource_checkpoint_management_wildcard.go +++ b/checkpoint/resource_checkpoint_management_wildcard.go @@ -124,7 +124,7 @@ func createManagementWildcard(d *schema.ResourceData, m interface{}) error { log.Println("Create Wildcard - Map = ", wildcard) - addWildcardRes, err := client.ApiCall("add-wildcard", wildcard, client.GetSessionID(), true, false) + addWildcardRes, err := client.ApiCall("add-wildcard", wildcard, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addWildcardRes.Success { if addWildcardRes.ErrorMsg != "" { return fmt.Errorf(addWildcardRes.ErrorMsg) @@ -145,7 +145,7 @@ func readManagementWildcard(d *schema.ResourceData, m interface{}) error { "uid": d.Id(), } - showWildcardRes, err := client.ApiCall("show-wildcard", payload, client.GetSessionID(), true, false) + showWildcardRes, err := client.ApiCall("show-wildcard", payload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil { return fmt.Errorf(err.Error()) } @@ -273,7 +273,7 @@ func updateManagementWildcard(d *schema.ResourceData, m interface{}) error { log.Println("Update Wildcard - Map = ", wildcard) - updateWildcardRes, err := client.ApiCall("set-wildcard", wildcard, client.GetSessionID(), true, false) + updateWildcardRes, err := client.ApiCall("set-wildcard", wildcard, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !updateWildcardRes.Success { if updateWildcardRes.ErrorMsg != "" { return fmt.Errorf(updateWildcardRes.ErrorMsg) @@ -294,7 +294,7 @@ func deleteManagementWildcard(d *schema.ResourceData, m interface{}) error { log.Println("Delete Wildcard") - deleteWildcardRes, err := client.ApiCall("delete-wildcard", wildcardPayload, client.GetSessionID(), true, false) + deleteWildcardRes, err := client.ApiCall("delete-wildcard", wildcardPayload, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !deleteWildcardRes.Success { if deleteWildcardRes.ErrorMsg != "" { return fmt.Errorf(deleteWildcardRes.ErrorMsg) diff --git a/checkpoint/resource_checkpoint_physical_interface.go b/checkpoint/resource_checkpoint_physical_interface.go index 349e275a..c35184bc 100644 --- a/checkpoint/resource_checkpoint_physical_interface.go +++ b/checkpoint/resource_checkpoint_physical_interface.go @@ -280,7 +280,7 @@ func createPhysicalInterface(d *schema.ResourceData, m interface{}) error { payload["ipv4-mask-length"] = v.(int) } - setPIRes, _ := client.ApiCall("set-physical-interface", payload, client.GetSessionID(), true, false) + setPIRes, _ := client.ApiCall("set-physical-interface", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !setPIRes.Success { return fmt.Errorf(setPIRes.ErrorMsg) } @@ -296,7 +296,7 @@ func readPhysicalInterface(d *schema.ResourceData, m interface{}) error { payload := map[string]interface{}{ "name": d.Get("name"), } - showPIRes, _ := client.ApiCall("show-physical-interface", payload, client.GetSessionID(), true, false) + showPIRes, _ := client.ApiCall("show-physical-interface", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !showPIRes.Success { // Handle deletion of an object from other clients - Object not found if objectNotFound(showPIRes.GetData()["code"].(string)) { @@ -353,7 +353,7 @@ func updatePhysicalInterface(d *schema.ResourceData, m interface{}) error { payload["ipv4-mask-length"] = d.Get("ipv4_mask_length") } - setNetworkRes, _ := client.ApiCall("set-physical-interface", payload, client.GetSessionID(), true, false) + setNetworkRes, _ := client.ApiCall("set-physical-interface", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !setNetworkRes.Success { return fmt.Errorf(setNetworkRes.ErrorMsg) } diff --git a/checkpoint/resource_checkpoint_put_file.go b/checkpoint/resource_checkpoint_put_file.go index 55c61849..e4faf701 100644 --- a/checkpoint/resource_checkpoint_put_file.go +++ b/checkpoint/resource_checkpoint_put_file.go @@ -51,7 +51,7 @@ func putFileParseSchemaToMap(d *schema.ResourceData) map[string]interface{} { func createPutFile(d *schema.ResourceData, m interface{}) error { client := m.(*checkpoint.ApiClient) payload := putFileParseSchemaToMap(d) - setPIRes, _ := client.ApiCall("put-file", payload, client.GetSessionID(), true, false) + setPIRes, _ := client.ApiCall("put-file", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !setPIRes.Success { return fmt.Errorf(setPIRes.ErrorMsg) } @@ -69,7 +69,7 @@ func readPutFile(d *schema.ResourceData, m interface{}) error { func updatePutFile(d *schema.ResourceData, m interface{}) error { client := m.(*checkpoint.ApiClient) payload := putFileParseSchemaToMap(d) - setNetworkRes, _ := client.ApiCall("put-file", payload, client.GetSessionID(), true, false) + setNetworkRes, _ := client.ApiCall("put-file", payload, client.GetSessionID(), true, client.IsProxyUsed()) if !setNetworkRes.Success { return fmt.Errorf(setNetworkRes.ErrorMsg) } diff --git a/checkpoint/utils.go b/checkpoint/utils.go index 28cd85e9..1f5c8d21 100644 --- a/checkpoint/utils.go +++ b/checkpoint/utils.go @@ -135,3 +135,14 @@ func getTypeToSource() map[string]string { } return TypeToSource } + +func getKeysToFixedKeys() map[string]string { + KeysToFixedKeys := map[string]string{ + "PREDEFINED": "predefined", + "Type in Data Center": "type-in-data-center", + "Name in Data Center": "name-in-data-center", + "IP Address": "ip-address", + "TAG": "tag", + } + return KeysToFixedKeys +} diff --git a/commands/before_tests/before_tests.go b/commands/before_tests/before_tests.go index 1d1cf129..e9bbbda2 100644 --- a/commands/before_tests/before_tests.go +++ b/commands/before_tests/before_tests.go @@ -16,7 +16,7 @@ func addApplicationSite(client checkpoint.ApiClient) error { "url-list": []string{"www.cnet.com"}, } - addApplicationSiteRes, err := client.ApiCall("add-application-site", applicationSite, client.GetSessionID(), true, false) + addApplicationSiteRes, err := client.ApiCall("add-application-site", applicationSite, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addApplicationSiteRes.Success { if addApplicationSiteRes.ErrorMsg != "" { return fmt.Errorf(addApplicationSiteRes.ErrorMsg) @@ -33,7 +33,7 @@ func addApplicationSiteCategory(client checkpoint.ApiClient) error { "name": "New Application Site Category 1", } - addApplicationSiteRes, err := client.ApiCall("add-application-site-category", applicationSiteCategory, client.GetSessionID(), true, false) + addApplicationSiteRes, err := client.ApiCall("add-application-site-category", applicationSiteCategory, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addApplicationSiteRes.Success { if addApplicationSiteRes.ErrorMsg != "" { return fmt.Errorf(addApplicationSiteRes.ErrorMsg) @@ -51,7 +51,7 @@ func addHost(client checkpoint.ApiClient) error { "ipv4-address": "10.0.0.1", } - addHostRes, err := client.ApiCall("add-host", host, client.GetSessionID(), true, false) + addHostRes, err := client.ApiCall("add-host", host, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addHostRes.Success { if addHostRes.ErrorMsg != "" { return fmt.Errorf(addHostRes.ErrorMsg) @@ -64,7 +64,7 @@ func addHost(client checkpoint.ApiClient) error { "ipv4-address": "10.0.0.2", } - addHost1Res, err := client.ApiCall("add-host", host1, client.GetSessionID(), true, false) + addHost1Res, err := client.ApiCall("add-host", host1, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addHost1Res.Success { if addHost1Res.ErrorMsg != "" { return fmt.Errorf(addHost1Res.ErrorMsg) @@ -77,7 +77,7 @@ func addHost(client checkpoint.ApiClient) error { "ipv4-address": "10.0.0.3", } - addHost2Res, err := client.ApiCall("add-host", host2, client.GetSessionID(), true, false) + addHost2Res, err := client.ApiCall("add-host", host2, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addHost2Res.Success { if addHost2Res.ErrorMsg != "" { return fmt.Errorf(addHost2Res.ErrorMsg) @@ -94,7 +94,7 @@ func addGroup(client checkpoint.ApiClient) error { "name": "new group 1", } - addGroupRes, err := client.ApiCall("add-group", group, client.GetSessionID(), true, false) + addGroupRes, err := client.ApiCall("add-group", group, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addGroupRes.Success { if addGroupRes.ErrorMsg != "" { return fmt.Errorf(addGroupRes.ErrorMsg) @@ -106,7 +106,7 @@ func addGroup(client checkpoint.ApiClient) error { "name": "new group 2", } - addGroup1Res, err := client.ApiCall("add-group", group1, client.GetSessionID(), true, false) + addGroup1Res, err := client.ApiCall("add-group", group1, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addGroup1Res.Success { if addGroup1Res.ErrorMsg != "" { return fmt.Errorf(addGroup1Res.ErrorMsg) @@ -123,7 +123,7 @@ func addThreatLayer(client checkpoint.ApiClient) error { "name": "New Layer 1", } - addThreatLayerRes, err := client.ApiCall("add-threat-layer", threatLayer, client.GetSessionID(), true, false) + addThreatLayerRes, err := client.ApiCall("add-threat-layer", threatLayer, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addThreatLayerRes.Success { if addThreatLayerRes.ErrorMsg != "" { return fmt.Errorf(addThreatLayerRes.ErrorMsg) @@ -142,7 +142,7 @@ func addThreatRule(client checkpoint.ApiClient) error { "name": "First threat rule", } - addThreatRuleRes, err := client.ApiCall("add-threat-rule", threatRule, client.GetSessionID(), true, false) + addThreatRuleRes, err := client.ApiCall("add-threat-rule", threatRule, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addThreatRuleRes.Success { if addThreatRuleRes.ErrorMsg != "" { return fmt.Errorf(addThreatRuleRes.ErrorMsg) @@ -159,7 +159,7 @@ func addExceptionGroup(client checkpoint.ApiClient) error { "name": "exception_group_2", } - addExceptionGroupeRes, err := client.ApiCall("add-exception-group", exceptionGroup, client.GetSessionID(), true, false) + addExceptionGroupeRes, err := client.ApiCall("add-exception-group", exceptionGroup, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addExceptionGroupeRes.Success { if addExceptionGroupeRes.ErrorMsg != "" { return fmt.Errorf(addExceptionGroupeRes.ErrorMsg) @@ -176,7 +176,7 @@ func addHTTPSLayer(client checkpoint.ApiClient) error { "name": "New Layer 2", } - addHTTPSLayerRes, err := client.ApiCall("add-https-layer", HTTPSLayer, client.GetSessionID(), true, false) + addHTTPSLayerRes, err := client.ApiCall("add-https-layer", HTTPSLayer, client.GetSessionID(), true, client.IsProxyUsed()) if err != nil || !addHTTPSLayerRes.Success { if addHTTPSLayerRes.ErrorMsg != "" { return fmt.Errorf(addHTTPSLayerRes.ErrorMsg) @@ -194,7 +194,7 @@ func addHTTPSLayer(client checkpoint.ApiClient) error { // "ipAddress4": "10.0.0.1", // } // -// addMdsRes, err := client.ApiCall("add-generic-object", mds, client.GetSessionID(), true, false) +// addMdsRes, err := client.ApiCall("add-generic-object", mds, client.GetSessionID(), true, client.IsProxyUsed()) // if err != nil || !addMdsRes.Success { // if addMdsRes.ErrorMsg != "" { // return fmt.Errorf(addMdsRes.ErrorMsg) @@ -211,7 +211,7 @@ func addHTTPSLayer(client checkpoint.ApiClient) error { // "name" : "New Application Site Category 1", // } // -// addApplicationSiteRes, err := client.ApiCall("add-application-site-category", applicationSiteCategory, client.GetSessionID(), true, false) +// addApplicationSiteRes, err := client.ApiCall("add-application-site-category", applicationSiteCategory, client.GetSessionID(), true, client.IsProxyUsed()) // if err != nil || !addApplicationSiteRes.Success { // if addApplicationSiteRes.ErrorMsg != "" { // return fmt.Errorf(addApplicationSiteRes.ErrorMsg) @@ -269,7 +269,7 @@ func main() { log.Fatalf("error: %s", err) } - publishRes, err := apiClient.ApiCall("publish", map[string]interface{}{}, apiClient.GetSessionID(), true, false) + publishRes, err := apiClient.ApiCall("publish", map[string]interface{}{}, apiClient.GetSessionID(), true, apiClient.IsProxyUsed()) if err != nil { log.Fatalf("error: %s", err) } diff --git a/commands/commands_utils.go b/commands/commands_utils.go index 1a78315c..70bde17d 100644 --- a/commands/commands_utils.go +++ b/commands/commands_utils.go @@ -57,6 +57,7 @@ func InitClient() (checkpoint.ApiClient, error) { // Default values port := checkpoint.DefaultPort timeout := checkpoint.TimeOut + proxyPort := checkpoint.DefaultProxyPort // Get credentials from Environment variables server := os.Getenv("CHECKPOINT_SERVER") @@ -65,6 +66,9 @@ func InitClient() (checkpoint.ApiClient, error) { portVal := os.Getenv("CHECKPOINT_PORT") timeoutVal := os.Getenv("CHECKPOINT_TIMEOUT") sessionFileName := os.Getenv("CHECKPOINT_SESSION_FILE_NAME") + proxyHost := os.Getenv("CHECKPOINT_PROXY_HOST") + proxyPortStr := os.Getenv("CHECKPOINT_PROXY_PORT") + apiKey := os.Getenv("CHECKPOINT_API_KEY") var err error if portVal != "" { @@ -74,6 +78,13 @@ func InitClient() (checkpoint.ApiClient, error) { } } + if proxyPortStr != "" { + proxyPort, err = strconv.Atoi(proxyPortStr) + if err != nil { + return checkpoint.ApiClient{}, fmt.Errorf("failed to parse CHECKPOINT_PROXY_PORT to integer") + } + } + if timeoutVal != "" { timeoutInteger, err := strconv.Atoi(timeoutVal) if err != nil { @@ -86,8 +97,8 @@ func InitClient() (checkpoint.ApiClient, error) { sessionFileName = DefaultFilename } - if server == "" || username == "" || password == "" { - return checkpoint.ApiClient{}, fmt.Errorf("missing at least one required parameter to initialize API client (CHECKPOINT_SERVER, CHECKPOINT_USERNAME, CHECKPOINT_PASSWORD)") + if server == "" || ((username == "" || password == "") && apiKey == "") { + return checkpoint.ApiClient{}, fmt.Errorf("missing at least one required parameter to initialize API client (CHECKPOINT_SERVER, (CHECKPOINT_USERNAME and CHECKPOINT_PASSWORD) OR CHECKPOINT_API_KEY)") } // install policy/publish - only on management api @@ -102,8 +113,8 @@ func InitClient() (checkpoint.ApiClient, error) { Fingerprint: "", Sid: "", Server: server, - ProxyHost: "", - ProxyPort: -1, + ProxyHost: proxyHost, + ProxyPort: proxyPort, ApiVersion: "", IgnoreServerCertificate: false, AcceptServerCertificate: false, diff --git a/commands/install_policy/install_policy.go b/commands/install_policy/install_policy.go index da056ddd..dca492f8 100644 --- a/commands/install_policy/install_policy.go +++ b/commands/install_policy/install_policy.go @@ -39,7 +39,7 @@ func main() { "targets": targets, } - installPolicyRes, err := apiClient.ApiCall("install-policy", payload, apiClient.GetSessionID(), true, false) + installPolicyRes, err := apiClient.ApiCall("install-policy", payload, apiClient.GetSessionID(), true, apiClient.IsProxyUsed()) if err != nil { fmt.Println("Install policy error: " + err.Error()) os.Exit(1) diff --git a/commands/logout/logout.go b/commands/logout/logout.go index 09a0bf6b..71fcda77 100644 --- a/commands/logout/logout.go +++ b/commands/logout/logout.go @@ -13,7 +13,7 @@ func main() { os.Exit(1) } - logoutRes, err := apiClient.ApiCall("logout", make(map[string]interface{}), apiClient.GetSessionID(), true, false) + logoutRes, err := apiClient.ApiCall("logout", make(map[string]interface{}), apiClient.GetSessionID(), true, apiClient.IsProxyUsed()) if err != nil { fmt.Println("logout error: " + err.Error()) os.Exit(1) diff --git a/commands/publish/publish.go b/commands/publish/publish.go index 3e00cfe1..f08a9565 100644 --- a/commands/publish/publish.go +++ b/commands/publish/publish.go @@ -13,7 +13,7 @@ func main() { os.Exit(1) } - publishRes, err := apiClient.ApiCall("publish", map[string]interface{}{}, apiClient.GetSessionID(), true, false) + publishRes, err := apiClient.ApiCall("publish", map[string]interface{}{}, apiClient.GetSessionID(), true, apiClient.IsProxyUsed()) if err != nil { fmt.Println("Publish error: " + err.Error()) os.Exit(1) diff --git a/vendor/github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles/APIClient.go b/vendor/github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles/APIClient.go index ee48b8c5..a54eb03d 100644 --- a/vendor/github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles/APIClient.go +++ b/vendor/github.com/CheckPointSW/cp-mgmt-api-go-sdk/APIFiles/APIClient.go @@ -5,7 +5,7 @@ version 1.0 A library for communicating with Check Point's management server using Golang written by: Check Point software technologies inc. June 2019 -tested with Check Point R80.20 (tested with take hero2 198) +tested with Check Point R81.20 ----------------------------------------------------------------------------- @@ -30,57 +30,64 @@ import ( ) const ( - InProgress string = "in progress" - DefaultPort int = 443 - Limit int = 50 - Filename string = "fingerprints.json" - TimeOut time.Duration = time.Second * 10 - SleepTime time.Duration = time.Second * 2 - GaiaContext string = "gaia_api" - WebContext string = "web_api" + InProgress string = "in progress" + DefaultPort int = 443 + Limit int = 50 + Filename string = "fingerprints.json" + TimeOut time.Duration = time.Second * 10 + SleepTime time.Duration = time.Second * 2 + GaiaContext string = "gaia_api" + WebContext string = "web_api" + DefaultProxyPort = -1 + DefaultProxyHost = "" ) // Check Point API Client (Management/GAIA) type ApiClient struct { - port int - isPortDefault_ bool - fingerprint string - sid string - server string - domain string - proxyHost string - proxyPort int - apiVersion string - ignoreServerCertificate bool + port int + isPortDefault_ bool + fingerprint string + sid string + server string + domain string + proxyHost string + proxyPort int + isProxyUsed bool + apiVersion string + ignoreServerCertificate bool acceptServerCertificate bool - debugFile string - httpDebugLevel string - context string - autoPublish bool - timeout time.Duration - sleep time.Duration - userAgent string + debugFile string + httpDebugLevel string + context string + autoPublish bool + timeout time.Duration + sleep time.Duration + userAgent string } // Api Client constructor // Input ApiClientArgs // Returns new client instance func APIClient(apiCA ApiClientArgs) *ApiClient { - isPortDefault := false + isPortDefault := false + proxyUsed := false if apiCA.Port == -1 || apiCA.Port == DefaultPort { apiCA.Port = DefaultPort isPortDefault = true } + if apiCA.ProxyPort != DefaultProxyPort && apiCA.ProxyHost != DefaultProxyHost { + proxyUsed = true + } // The context of using the client - defaults to web api if apiCA.Context == "" { apiCA.Context = WebContext } - if apiCA.Timeout == -1 || apiCA.Timeout == TimeOut{ - apiCA.Timeout = TimeOut - }else{ + if apiCA.Timeout == -1 || apiCA.Timeout == TimeOut { + apiCA.Timeout = TimeOut + } else { apiCA.Timeout = apiCA.Timeout * time.Second } @@ -89,24 +96,25 @@ func APIClient(apiCA ApiClientArgs) *ApiClient { } return &ApiClient{ - port: apiCA.Port, - isPortDefault_: isPortDefault, - fingerprint: apiCA.Fingerprint, - sid: apiCA.Sid, - server: apiCA.Server, - domain: "", - proxyHost: apiCA.ProxyHost, - proxyPort: apiCA.ProxyPort, - apiVersion: apiCA.ApiVersion, + port: apiCA.Port, + isPortDefault_: isPortDefault, + fingerprint: apiCA.Fingerprint, + sid: apiCA.Sid, + server: apiCA.Server, + domain: "", + proxyHost: apiCA.ProxyHost, + proxyPort: apiCA.ProxyPort, + isProxyUsed: proxyUsed, + apiVersion: apiCA.ApiVersion, ignoreServerCertificate: apiCA.IgnoreServerCertificate, acceptServerCertificate: apiCA.AcceptServerCertificate, - debugFile: apiCA.DebugFile, - httpDebugLevel: apiCA.HttpDebugLevel, - context: apiCA.Context, - autoPublish: apiCA.AutoPublish, - timeout: apiCA.Timeout, - sleep: apiCA.Sleep, - userAgent: apiCA.UserAgent, + debugFile: apiCA.DebugFile, + httpDebugLevel: apiCA.HttpDebugLevel, + context: apiCA.Context, + autoPublish: apiCA.AutoPublish, + timeout: apiCA.Timeout, + sleep: apiCA.Sleep, + userAgent: apiCA.UserAgent, } } @@ -120,7 +128,6 @@ func (c *ApiClient) GetContext() string { return c.context } - func (c *ApiClient) GetAutoPublish() bool { return c.autoPublish } @@ -135,6 +142,11 @@ func (c *ApiClient) IsPortDefault() bool { return c.isPortDefault_ } +// Returns true if client use proxy +func (c *ApiClient) IsProxyUsed() bool { + return c.isProxyUsed +} + // Set API port func (c *ApiClient) SetPort(portToSet int) { if portToSet == DefaultPort { @@ -155,13 +167,11 @@ func (c *ApiClient) SetTimeout(timeout time.Duration) { c.timeout = timeout } - // Returns session id func (c *ApiClient) GetSessionID() string { return c.sid } - /* Performs a 'login' API call to management server @@ -174,12 +184,36 @@ payload: [optional] More settings for the login command returns: APIResponse, error side-effects: updates the class's uid and server variables - */ +*/ func (c *ApiClient) Login(username string, password string, continueLastSession bool, domain string, readOnly bool, payload string) (APIResponse, error) { credentials := map[string]interface{}{ - "user": username, - "password": password, + "user": username, + "password": password, + } + return c.commonLoginLogic(credentials, continueLastSession, domain, readOnly, payload) +} + +/* +performs a 'login' API call to the management server + +api_key: Check Point api-key +continue_last_session: [optional] It is possible to continue the last Check Point session +or to create a new one +domain: [optional] The name, UID or IP-Address of the domain to login. +read_only: [optional] Login with Read Only permissions. This parameter is not considered in case +continue-last-session is true. +payload: [optional] More settings for the login command +returns: APIResponse object +side-effects: updates the class's uid and server variables +*/ +func (c *ApiClient) LoginWithApiKey(apiKey string, continueLastSession bool, domain string, readOnly bool, payload string) (APIResponse, error) { + credentials := map[string]interface{}{ + "api-key": apiKey, } + return c.commonLoginLogic(credentials, continueLastSession, domain, readOnly, payload) +} + +func (c *ApiClient) commonLoginLogic(credentials map[string]interface{}, continueLastSession bool, domain string, readOnly bool, payload string) (APIResponse, error) { if c.context == WebContext { credentials["continue-last-session"] = continueLastSession @@ -218,7 +252,7 @@ useProxy: Determines if the user wants to use the proxy server and port provider return: APIResponse object side-effects: updates the class's uid and server variables - */ +*/ func (c *ApiClient) ApiCall(command string, payload map[string]interface{}, sid string, waitForTask bool, useProxy bool) (APIResponse, error) { fp, errFP := getFingerprint(c.server, c.port) if errFP != nil { @@ -277,7 +311,7 @@ func (c *ApiClient) ApiCall(command string, payload map[string]interface{}, sid var url string if c.apiVersion == "" { url = "/" + c.context + "/" + command - }else { + } else { url = "/" + c.context + "/" + "v" + c.apiVersion + "/" + command } @@ -287,7 +321,7 @@ func (c *ApiClient) ApiCall(command string, payload map[string]interface{}, sid spotReader := bytes.NewReader(_data) - req, err := http.NewRequest("POST", "https://" + c.server + ":" + strconv.Itoa(c.port) + url, spotReader) + req, err := http.NewRequest("POST", "https://"+c.server+":"+strconv.Itoa(c.port)+url, spotReader) if err != nil { return APIResponse{}, err } @@ -308,53 +342,53 @@ func (c *ApiClient) ApiCall(command string, payload map[string]interface{}, sid return APIResponse{}, err } - if !res.Success{ - fullErrorMsg := "failed to execute API call" + - "\nStatus: " + res.StatusCode + - "\nCode: " + res.GetData()["code"].(string) + - "\nMessage: " + res.GetData()["message"].(string) + if !res.Success { + fullErrorMsg := "failed to execute API call" + + "\nStatus: " + res.StatusCode + + "\nCode: " + res.GetData()["code"].(string) + + "\nMessage: " + res.GetData()["message"].(string) - if errorMsg := res.data["errors"]; errorMsg != nil { + if errorMsg := res.data["errors"]; errorMsg != nil { fullErrorMsg += "\nErrors: " - errorMsgType := reflect.TypeOf(errorMsg).Kind() - if errorMsgType == reflect.String { + errorMsgType := reflect.TypeOf(errorMsg).Kind() + if errorMsgType == reflect.String { fullErrorMsg += errorMsg.(string) + "\n" } else { errorsList := res.data["errors"].([]interface{}) for i := range errorsList { - fullErrorMsg += "\n" + strconv.Itoa(i + 1) + ". " + errorsList[i].(map[string]interface{})["message"].(string) + fullErrorMsg += "\n" + strconv.Itoa(i+1) + ". " + errorsList[i].(map[string]interface{})["message"].(string) } } - } + } - if warningMsg := res.data["warnings"]; warningMsg != nil { - fullErrorMsg += "\nWarnings: " - warningMsgType := reflect.TypeOf(warningMsg).Kind() - if warningMsgType == reflect.String { + if warningMsg := res.data["warnings"]; warningMsg != nil { + fullErrorMsg += "\nWarnings: " + warningMsgType := reflect.TypeOf(warningMsg).Kind() + if warningMsgType == reflect.String { fullErrorMsg += warningMsg.(string) + "\n" } else { warningsList := res.data["warnings"].([]interface{}) for i := range warningsList { - fullErrorMsg += "\n" + strconv.Itoa(i + 1) + ". " + warningsList[i].(map[string]interface{})["message"].(string) + fullErrorMsg += "\n" + strconv.Itoa(i+1) + ". " + warningsList[i].(map[string]interface{})["message"].(string) } } - } - - if blockingError := res.data["blocking-errors"]; blockingError != nil { - fullErrorMsg += "\nBlocking errors: " - warningMsgType := reflect.TypeOf(blockingError).Kind() - if warningMsgType == reflect.String { - fullErrorMsg += blockingError.(string) + "\n" - } else { - blockingErrorsList := res.data["blocking-errors"].([]interface{}) - for i := range blockingErrorsList { - fullErrorMsg += "\n" + strconv.Itoa(i + 1) + ". " + blockingErrorsList[i].(map[string]interface{})["message"].(string) - } - } - } - - res.ErrorMsg = fullErrorMsg - } + } + + if blockingError := res.data["blocking-errors"]; blockingError != nil { + fullErrorMsg += "\nBlocking errors: " + warningMsgType := reflect.TypeOf(blockingError).Kind() + if warningMsgType == reflect.String { + fullErrorMsg += blockingError.(string) + "\n" + } else { + blockingErrorsList := res.data["blocking-errors"].([]interface{}) + for i := range blockingErrorsList { + fullErrorMsg += "\n" + strconv.Itoa(i+1) + ". " + blockingErrorsList[i].(map[string]interface{})["message"].(string) + } + } + } + + res.ErrorMsg = fullErrorMsg + } if waitForTask == true && res.Success && command != "show-task" { if _, ok := res.data["task-id"]; ok { @@ -448,7 +482,6 @@ returns: an APIResponse object as detailed above */ func (c *ApiClient) genApiQuery(command string, detailsLevel string, containerKeys []string, payload map[string]interface{}, err_output *error) []APIResponse { - const objLimit int = Limit var finished bool = false @@ -536,7 +569,6 @@ func (c *ApiClient) genApiQuery(command string, detailsLevel string, containerKe return serverResponse } - /** When the server needs to perform an API call that may take a long time (e.g. run-script, install-policy, publish), the server responds with a 'task-id'. @@ -669,7 +701,7 @@ func checkTasksStatus(taskResult *APIResponse) { @===================@ | FINGERPRINT AREA | @===================@ - */ +*/ /** This function checks if the server's certificate is stored in the local fingerprints file. @@ -716,7 +748,7 @@ func (c *ApiClient) CheckFingerprint() (bool, error) { } else { fmt.Fprintf(os.Stderr, "The server's fingerprint is different from your local record of this server's fingerprint.\n You maybe a victim to a Man-in-the-Middle attack, please beware.\n") } - fmt.Fprintf(os.Stderr, "Server's fingerprint: %s\n", (serverFp), ) + fmt.Fprintf(os.Stderr, "Server's fingerprint: %s\n", (serverFp)) if c.askYesOrNoQuestion("Do you accept this fingerprint?\n") { if c.saveFingerprintToFile(c.server, serverFp) == nil { @@ -854,6 +886,6 @@ func (c *ApiClient) createEmptyJsonFile(name string) error { func (c *ApiClient) askYesOrNoQuestion(question string) bool { fmt.Println(question) var answer string - _,_ = fmt.Scanln(&answer) + _, _ = fmt.Scanln(&answer) return strings.ToLower(answer) == "y" || strings.ToLower(answer) == "yes" } diff --git a/website/checkpoint.erb b/website/checkpoint.erb index 566540ab..ad234f28 100644 --- a/website/checkpoint.erb +++ b/website/checkpoint.erb @@ -308,7 +308,37 @@ checkpoint_management_threat_profile > - checkpoint_management_threat_profile + checkpoint_management_generic_data_center_server + + > + checkpoint_management_vmware_data_center_server + + > + checkpoint_management_aws_data_center_server + + > + checkpoint_management_gcp_data_center_server + + > + checkpoint_management_azure_data_center_server + + > + checkpoint_management_aci_data_center_server + + > + checkpoint_management_ise_data_center_server + + > + checkpoint_management_nuage_data_center_server + + > + checkpoint_management_openstack_data_center_server + + > + checkpoint_management_kubernetes_data_center_server + + > + checkpoint_management_data_center_query @@ -500,7 +530,52 @@ checkpoint_management_threat_profile > - checkpoint_management_threat_profile + checkpoint_management_generic_data_center_server + + > + checkpoint_management_vmware_data_center_server + + > + checkpoint_management_aws_data_center_server + + > + checkpoint_management_gcp_data_center_server + + > + checkpoint_management_azure_data_center_server + + > + checkpoint_management_aci_data_center_server + + > + checkpoint_management_ise_data_center_server + + > + checkpoint_management_nuage_data_center_server + + > + checkpoint_management_openstack_data_center_server + + > + checkpoint_management_kubernetes_data_center_server + + > + checkpoint_management_data_center_query + + > + checkpoint_management_data_center_content + + > + checkpoint_management_access_rulebase + + > + checkpoint_management_nat_rulebase + + > + checkpoint_management_threat_rulebase + + > + checkpoint_management_https_rulebase diff --git a/website/docs/d/checkpoint_management_access_rulebase.html.markdown b/website/docs/d/checkpoint_management_access_rulebase.html.markdown new file mode 100644 index 00000000..dd51144b --- /dev/null +++ b/website/docs/d/checkpoint_management_access_rulebase.html.markdown @@ -0,0 +1,56 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_access_rulebase" +sidebar_current: "docs-checkpoint-data-source-checkpoint-management-access-rulebase" +description: |- This resource allows you to execute Check Point Access Rule Base. +--- + +# Data Source: checkpoint_management_access_rulebase + +Use this data source to get information on an existing access RuleBase. + +## Example Usage + +```hcl +data "checkpoint_management_access_rulebase" "access_rulebase" { + name = "Network" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Optional) Object name. Must be unique in the domain. +* `uid` - (Optional) Object unique identifier. +* `filter` - APN name. +* `filter_settings` - Enable enforce end user domain. filter_settings blocks are documented below. +* `limit` - The maximal number of returned results. +* `offset` - Number of the results to initially skip. +* `order` - Sorts the results by search criteria. Automatically sorts the results by Name, in the ascending order. orders blocks are documented below. +* `package` - Name of the package. +* `show_as_ranges` - When true, the source, destination and services & applications parameters are displayed as ranges of IP addresses and port numbers rather than network objects. Objects that are not represented using IP addresses or port numbers are presented as objects. In addition, the response of each rule does not contain the parameters: source, source-negate, destination, destination-negate, service and service-negate, but instead it contains the parameters:source-ranges, destination-ranges and service-ranges. Note: Requesting to show rules as ranges is limited up to 20 rules per request, otherwise an error is returned. If you wish to request more rules, use the offset and limit parameters to limit your request. +* `show_hits` - show hits. +* `hits_settings` - hits_settings blocks are documented below. +* `dereference_group_members` - Indicates whether to dereference "members" field by details level for every object in reply. +* `show_membership` - Indicates whether to calculate and show "groups" field for every object in reply. + +`filter_settings` supports the following: + +* `search_mode` - When set to 'general', both the Full Text Search and Packet Search are enabled. In this mode, Packet Search will not match on 'Any' object, a negated cell or a group-with-exclusion. When the search-mode is set to 'packet', by default, the match on 'Any' object, a negated cell or a group-with-exclusion are enabled. packet-search-settings may be provided to change the default behavior. +* `expand_group_members` - (Optional, can only be used when search_mode is set to "packet") When true, if the search expression contains a UID or a name of a group object, results will include rules that match on at least one member of the group. +* `expand_group_with_exclusion_members` - (Optional, can only be used when search_mode is set to "packet") When true, if the search expression contains a UID or a name of a group-with-exclusion object, results will include rules that match at least one member of the "include" part and is not a member of the "except" part. +* `match_on_any` - (Optional, can only be used when search_mode is set to "packet") Whether to match on 'Any' object. +* `match_on_group_with_exclusion` - (Optional, can only be used when search_mode is set to "packet") Whether to match on a group-with-exclusion. +* `match_on_negate` - (Optional, can only be used when search_mode is set to "packet") Whether to match on a negated cell. + +`order` supports the following: + +* `asc` - (Optional) Sorts results by the given field in ascending order. +* `desc` - (Optional) Sorts results by the given field in descending order. + +`hits_settings` supports the following: + +* `from-date` - Format: YYYY-MM-DD, YYYY-mm-ddThh:mm:ss. +* `target` - Target gateway name or UID. +* `to-date` - Format: YYYY-MM-DD, YYYY-mm-ddThh:mm:ss. diff --git a/website/docs/d/checkpoint_management_aci_data_center_server.html.markdown b/website/docs/d/checkpoint_management_aci_data_center_server.html.markdown new file mode 100644 index 00000000..fbca6b8f --- /dev/null +++ b/website/docs/d/checkpoint_management_aci_data_center_server.html.markdown @@ -0,0 +1,32 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_aci_data_center_server" +sidebar_current: "docs-checkpoint-Resource-checkpoint-management-aci-data-center-server" +description: |- Use this data source to get information on an existing Cisco APIC data center server. +--- + +# Resource: checkpoint_management_aci_data_center_server + +Use this data source to get information on an existing Cisco APIC Data Center Server. + +## Example Usage + +```hcl +resource "checkpoint_management_aci_data_center_server" "testAci" { + name = "MyAci" + username = "USERNAME" + password = "PASSWORD" + urls = ["url1", "url2"] +} + +data "checkpoint_management_aci_data_center_server" "data_aci_data_center_server" { + name = "${checkpoint_management_aci_data_center_server.testAci.name}" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Optional) Object name. +* `uid` - (Optional) Object unique identifier. diff --git a/website/docs/d/checkpoint_management_aws_data_center_server.html.markdown b/website/docs/d/checkpoint_management_aws_data_center_server.html.markdown new file mode 100644 index 00000000..84501c09 --- /dev/null +++ b/website/docs/d/checkpoint_management_aws_data_center_server.html.markdown @@ -0,0 +1,32 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_aws_data_center_server" +sidebar_current: "docs-checkpoint-Resource-checkpoint-management-aws-data-center-server" +description: |- Use this data source to get information on an existing AWS data center server. +--- + +# Resource: checkpoint_management_aws_data_center_server + +Use this data source to get information on an existing AWS Data Center Server. + +## Example Usage + +```hcl +resource "checkpoint_management_aws_data_center_server" "testAws" { + authenticationMethod = "user-authentication" + accessKeyId = "MY-KEY-ID" + secretAccessKey = "MY-SECRET-KEY" + region = "us-east-1" +} + +data "checkpoint_management_aws_data_center_server" "data_aws_data_center_server" { + name = "${checkpoint_management_aws_data_center_server.testAws.name}" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Optional) Object name. +* `uid` - (Optional) Object unique identifier. diff --git a/website/docs/d/checkpoint_management_azure_data_center_server.html.markdown b/website/docs/d/checkpoint_management_azure_data_center_server.html.markdown new file mode 100644 index 00000000..7e147d74 --- /dev/null +++ b/website/docs/d/checkpoint_management_azure_data_center_server.html.markdown @@ -0,0 +1,32 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_azure_data_center_server" +sidebar_current: "docs-checkpoint-Resource-checkpoint-management-azure-data-center-server" +description: |- Use this data source to get information on an existing azure data center server. +--- + +# Resource: checkpoint_management_azure_data_center_server + +Use this data source to get information on an existing Microsoft Azure Data Center Server. + +## Example Usage + +```hcl +resource "checkpoint_management_azure_data_center_server" "testAzure" { + name = "myAzure" + authentication_method = "user-authentication" + username = "MY-KEY-ID" + password = "MY-SECRET-KEY" +} + +data "checkpoint_management_azure_data_center_server" "data_azure_data_center_server" { + name = "${checkpoint_management_azure_data_center_server.testAzure.name}" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Optional) Object name. +* `uid` - (Optional) Object unique identifier. diff --git a/website/docs/d/checkpoint_management_data_access_role.html.markdown b/website/docs/d/checkpoint_management_data_access_role.html.markdown index d5b36ff3..5f5431a8 100644 --- a/website/docs/d/checkpoint_management_data_access_role.html.markdown +++ b/website/docs/d/checkpoint_management_data_access_role.html.markdown @@ -34,5 +34,5 @@ data "checkpoint_management_data_access_role" "data_access_role" { The following arguments are supported: -* `name` - (Required if uid is not given) Object name. -* `uid` - (Required name uid is not given) Object unique identifier. +* `name` - (Optional) Object name. +* `uid` - (Optional) Object unique identifier. diff --git a/website/docs/d/checkpoint_management_data_center_content.html.markdown b/website/docs/d/checkpoint_management_data_center_content.html.markdown new file mode 100644 index 00000000..53967516 --- /dev/null +++ b/website/docs/d/checkpoint_management_data_center_content.html.markdown @@ -0,0 +1,47 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_data_center_content" +sidebar_current: "docs-checkpoint-data-source-checkpoint-management-data_center_content" +description: |- Use this data source to get information on an existing Check Point data center content. +--- + +# Data Source: checkpoint_management_data_center_content + +Use this data source to get information on an existing Check Point data center content. + +## Example Usage + +```hcl +data "checkpoint_management_data_center_content" "test" { + name = "Network" + filter = { + text = "TEXT_TO_FIND" + uri = "DATA_CENTER_URI" + } + limit = 100 +} +``` + +## Argument Reference + +The following arguments are supported: + +* `data_center_name` - (Optional) Name of the Data Center Server where to search for objects. +* `data_center_uid` - (Optional) Unique identifier of the Data Center Server where to search for objects. +* `limit` - The maximal number of returned results. +* `offset` - Number of the results to initially skip. +* `order` - Sorts the results by search criteria. Automatically sorts the results by Name, in the ascending order. + orders blocks are documented below. +* `uid_in_data_center` - Return result matching the unique identifier of the object on the Data Center Server. +* `filter` - Return results matching the specified filter. + +`filter` supports the following: + +* `text` - (Optional) Return results containing the specified text value. +* `uri` - (Optional) Return results under the specified Data Center Object (identified by URI). +* `parent_uid_in_data_center` - (Optional) Return results under the specified Data Center Object (identified by UID). + +`order` supports the following: + +* `asc` - (Optional) Sorts results by the given field in ascending order. +* `desc` - (Optional) Sorts results by the given field in descending order. diff --git a/website/docs/d/checkpoint_management_data_center_query.html.markdown b/website/docs/d/checkpoint_management_data_center_query.html.markdown new file mode 100644 index 00000000..3043ceb3 --- /dev/null +++ b/website/docs/d/checkpoint_management_data_center_query.html.markdown @@ -0,0 +1,35 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_data_center_query" +sidebar_current: "docs-checkpoint-resource-checkpoint-management-data-center-query" +description: |- Use this data source to get information on an existing Check Point Data Center Query. +--- + +# checkpoint_management_data_center_query + +Use this data source to get information on an existing Check Point Data Center Query. + +## Example Usage + +```hcl +resource "checkpoint_management_data_center_query" "testQuery" { + name = "myQuery" + data_centers = ["All"] + query_rules { + key_type = "predefined" + key = "name-in-data-center" + values = ["firstVal", "secondVal"] + } +} + +data "checkpoint_management_data_center_query" "data_center_query" { + name = "${checkpoint_management_data_center_query.testQuery.name}" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Optional) Object name. +* `uid` - (Optional) Object unique identifier. diff --git a/website/docs/d/checkpoint_management_gcp_data_center_server.html.markdown b/website/docs/d/checkpoint_management_gcp_data_center_server.html.markdown new file mode 100644 index 00000000..609e50fd --- /dev/null +++ b/website/docs/d/checkpoint_management_gcp_data_center_server.html.markdown @@ -0,0 +1,32 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_gcp_data_center_server" +sidebar_current: "docs-checkpoint-Resource-checkpoint-management-gcp-data-center-server" +description: |- Use this data source to get information on an existing Google Cloud Platform Data Center Server. +--- + +# Resource: checkpoint_management_gcp_data_center_server + +Use this data source to get information on an existing Google Cloud Platform Data Center Server. + +## Example Usage + +```hcl +resource "checkpoint_management_gcp_data_center_server" "testGcp" { + name = "myGcp" + authentication_method = "key-authentication" + private_key = "MYKEY.json" + ignore_warnings = true +} + +data "checkpoint_management_gcp_data_center_server" "data_gcp_data_center_server" { + name = "${checkpoint_management_gcp_data_center_server.testGcp.name}" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Optional) Object name. +* `uid` - (Optional) Object unique identifier. diff --git a/website/docs/d/checkpoint_management_https_rulebase.html.markdown b/website/docs/d/checkpoint_management_https_rulebase.html.markdown new file mode 100644 index 00000000..6b12dc14 --- /dev/null +++ b/website/docs/d/checkpoint_management_https_rulebase.html.markdown @@ -0,0 +1,47 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_https_rulebase" +sidebar_current: "docs-checkpoint-data-source-checkpoint-management-https-rulebase" +description: |- This resource allows you to execute Check Point Https Rule Base. +--- + +# Data Source: checkpoint_management_https_rulebase + +Use this data source to get information on an existing https RuleBase. + +## Example Usage + +```hcl +data "checkpoint_management_rulebase" "https_rulebase" { + name = "Default Layer" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) Object name. Must be unique in the domain. +* `uid` - (Optional) Object unique identifier. +* `filter` - Search expression to filter the rulebase. The provided text should be exactly the same as it would be given in Smart Console. The logical operators in the expression ('AND', 'OR') should be provided in capital letters. If an operator is not used, the default OR operator applies. +* `filter_settings` - Enable enforce end user domain. filter_settings blocks are documented below. +* `limit` - The maximal number of returned results. +* `offset` - Number of the results to initially skip. +* `order` - Sorts the results by search criteria. Automatically sorts the results by Name, in the ascending order. orders blocks are documented below. +* `package` - Name of the package. +* `dereference_group_members` - Indicates whether to dereference "members" field by details level for every object in reply. +* `show_membership` - Indicates whether to calculate and show "groups" field for every object in reply. + +`filter_settings` supports the following: + +* `search_mode` - When set to 'general', both the Full Text Search and Packet Search are enabled. In this mode, Packet Search will not match on 'Any' object, a negated cell or a group-with-exclusion. When the search-mode is set to 'packet', by default, the match on 'Any' object, a negated cell or a group-with-exclusion are enabled. packet-search-settings may be provided to change the default behavior. +* `expand_group_members` - (Optional, can only be used when search_mode is set to "packet") When true, if the search expression contains a UID or a name of a group object, results will include rules that match on at least one member of the group. +* `expand_group_with_exclusion_members` - (Optional, can only be used when search_mode is set to "packet") When true, if the search expression contains a UID or a name of a group-with-exclusion object, results will include rules that match at least one member of the "include" part and is not a member of the "except" part. +* `match_on_any` - (Optional, can only be used when search_mode is set to "packet") Whether to match on 'Any' object. +* `match_on_group_with_exclusion` - (Optional, can only be used when search_mode is set to "packet") Whether to match on a group-with-exclusion. +* `match_on_negate` - (Optional, can only be used when search_mode is set to "packet") Whether to match on a negated cell. + +`order` supports the following: + +* `asc` - (Optional) Sorts results by the given field in ascending order. +* `desc` - (Optional) Sorts results by the given field in descending order. diff --git a/website/docs/d/checkpoint_management_ise_data_center_server.html.markdown b/website/docs/d/checkpoint_management_ise_data_center_server.html.markdown new file mode 100644 index 00000000..90cd8f17 --- /dev/null +++ b/website/docs/d/checkpoint_management_ise_data_center_server.html.markdown @@ -0,0 +1,32 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_ise_data_center_server" +sidebar_current: "docs-checkpoint-Resource-checkpoint-management-ise-data-center-server" +description: |- Use this data source to get information on an existing Cisco ISE data center server. +--- + +# Resource: checkpoint_management_ise_data_center_server + +Use this data source to get information on an existing Cisco ISE Data Center Server. + +## Example Usage + +```hcl +resource "checkpoint_management_ise_data_center_server" "testIse" { + name = "MyIse" + username = "USERNAME" + password = "PASSWORD" + hostnames = ["host1", "host2"] +} + +data "checkpoint_management_ise_data_center_server" "data_ise_data_center_server" { + name = "${checkpoint_management_ise_data_center_server.testIse.name}" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Optional) Object name. +* `uid` - (Optional) Object unique identifier. diff --git a/website/docs/d/checkpoint_management_kubernetes_data_center_server.html.markdown b/website/docs/d/checkpoint_management_kubernetes_data_center_server.html.markdown new file mode 100644 index 00000000..882e97dc --- /dev/null +++ b/website/docs/d/checkpoint_management_kubernetes_data_center_server.html.markdown @@ -0,0 +1,31 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_kubernetes_data_center_server" +sidebar_current: "docs-checkpoint-Resource-checkpoint-management-kubernetes-data-center-server" +description: |- Use this data source to get information on an existing Kubernetes Data Center Server. +--- + +# Resource: checkpoint_management_kubernetes_data_center_server + +Use this data source to get information on an existing Kubernetes Data Center Server. + +## Example Usage + +```hcl +resource "checkpoint_management_kubernetes_data_center_server" "testKubernetes" { + name = "MyKubernetes" + hostname = "MY_HOSTNAME" + token_file = "MY_TOKEN" +} + +data "checkpoint_management_kubernetes_data_center_server" "data_kubernetes_data_center_server" { + name = "${checkpoint_management_kubernetes_data_center_server.testKubernetes.name}" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Optional) Object name. +* `uid` - (Optional) Object unique identifier. diff --git a/website/docs/d/checkpoint_management_nat_rulebase.html.markdown b/website/docs/d/checkpoint_management_nat_rulebase.html.markdown new file mode 100644 index 00000000..b17e237f --- /dev/null +++ b/website/docs/d/checkpoint_management_nat_rulebase.html.markdown @@ -0,0 +1,57 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_nat_rulebase" +sidebar_current: "docs-checkpoint-data-source-checkpoint-management-nat-rulebase" +description: |- This resource allows you to execute Check Point Nat Rule Base. +--- + +# Data Source: checkpoint_management_nat_rulebase + +Use this data source to get information on an existing nat RuleBase. + +## Example Usage + +```hcl +data "checkpoint_management_nat_rulebase" "nat_rulebase" { + package = "Standard" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `package` - (Required) Name of the package. +* `filter` - APN name. +* `filter_settings` - Enable enforce end user domain. filter_settings blocks are documented below. +* `limit` - The maximal number of returned results. +* `offset` - Number of the results to initially skip. +* `order` - Sorts the results by search criteria. Automatically sorts the results by Name, in the ascending order. + orders blocks are documented below. +* `dereference_group_members` - Indicates whether to dereference "members" field by details level for every object in + reply. +* `show_membership` - Indicates whether to calculate and show "groups" field for every object in reply. + +`filter_settings` supports the following: + +* `search_mode` - When set to 'general', both the Full Text Search and Packet Search are enabled. In this mode, Packet + Search will not match on 'Any' object, a negated cell or a group-with-exclusion. When the search-mode is set to ' + packet', by default, the match on 'Any' object, a negated cell or a group-with-exclusion are enabled. + packet-search-settings may be provided to change the default behavior. +* `expand_group_members` - (Optional, can only be used when search_mode is set to "packet") When true, if the search + expression contains a UID or a name of a group object, results will include rules that match on at least one member of + the group. +* `expand_group_with_exclusion_members` - (Optional, can only be used when search_mode is set to "packet") When true, if + the search expression contains a UID or a name of a group-with-exclusion object, results will include rules that match + at least one member of the "include" part and is not a member of the "except" part. +* `match_on_any` - (Optional, can only be used when search_mode is set to "packet") Whether to match on 'Any' object. +* `match_on_group_with_exclusion` - (Optional, can only be used when search_mode is set to "packet") Whether to match on + a group-with-exclusion. +* `match_on_negate` - (Optional, can only be used when search_mode is set to "packet") Whether to match on a negated + cell. + +`order` supports the following: + +* `asc` - (Optional) Sorts results by the given field in ascending order. +* `desc` - (Optional) Sorts results by the given field in descending order. + diff --git a/website/docs/d/checkpoint_management_nuage_data_center_server.html.markdown b/website/docs/d/checkpoint_management_nuage_data_center_server.html.markdown new file mode 100644 index 00000000..992a298e --- /dev/null +++ b/website/docs/d/checkpoint_management_nuage_data_center_server.html.markdown @@ -0,0 +1,33 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_nuage_data_center_server" +sidebar_current: "docs-checkpoint-Resource-checkpoint-management-nuage-data-center-server" +description: |- Use this data source to get information on an existing Nuage Data Center Server. +--- + +# Resource: checkpoint_management_nuage_data_center_server + +Use this data source to get information on an existing Nuage Data Center Server. + +## Example Usage + +```hcl +resource "checkpoint_management_nuage_data_center_server" "testNuage" { + name = "MyNuage" + organization = "MY_ORG" + username = "USERNAME" + password = "PASSWORD" + hostname = "HOSTNAME" +} + +data "checkpoint_management_nuage_data_center_server" "data_nuage_data_center_server" { + name = "${checkpoint_management_nuage_data_center_server.testNuage.name}" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Optional) Object name. +* `uid` - (Optional) Object unique identifier. diff --git a/website/docs/d/checkpoint_management_openstack_data_center_server.html.markdown b/website/docs/d/checkpoint_management_openstack_data_center_server.html.markdown new file mode 100644 index 00000000..f970faf2 --- /dev/null +++ b/website/docs/d/checkpoint_management_openstack_data_center_server.html.markdown @@ -0,0 +1,32 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_openstack_data_center_server" +sidebar_current: "docs-checkpoint-Resource-checkpoint-management-openstack-data-center-server" +description: |- Use this data source to get information on an existing OpenStack Data Center Server. +--- + +# Resource: checkpoint_management_openstack_data_center_server + +Use this data source to get information on an existing OpenStack Data Center Server. + +## Example Usage + +```hcl +resource "checkpoint_management_openstack_data_center_server" "testOpenStack" { + name = "MyOpenStack" + username = "USERNAME" + password = "PASSWORD" + hostname = "HOSTNAME" +} + +data "checkpoint_management_openstack_data_center_server" "data_openstack_data_center_server" { + name = "${checkpoint_management_openstack_data_center_server.testOpenStack.name}" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Optional) Object name. +* `uid` - (Optional) Object unique identifier. diff --git a/website/docs/d/checkpoint_management_threat_rulebase.html.markdown b/website/docs/d/checkpoint_management_threat_rulebase.html.markdown new file mode 100644 index 00000000..27b437ba --- /dev/null +++ b/website/docs/d/checkpoint_management_threat_rulebase.html.markdown @@ -0,0 +1,47 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_threat_rulebase" +sidebar_current: "docs-checkpoint-data-source-checkpoint-management-threat-rulebase" +description: |- This resource allows you to execute Check Point Threat Rule Base. +--- + +# Data Source: checkpoint_management_threat_rulebase + +Use this data source to get information on an existing threat RuleBase. + +## Example Usage + +```hcl +data "checkpoint_management_rulebase" "threat_rulebase" { + name = "Standard Threat Prevention" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Optional) Object name. Must be unique in the domain. +* `uid` - (Optional) Object unique identifier. +* `filter` - Search expression to filter the rulebase. The provided text should be exactly the same as it would be given in Smart Console. The logical operators in the expression ('AND', 'OR') should be provided in capital letters. If an operator is not used, the default OR operator applies. +* `filter_settings` - Enable enforce end user domain. filter_settings blocks are documented below. +* `limit` - The maximal number of returned results. +* `offset` - Number of the results to initially skip. +* `order` - Sorts the results by search criteria. Automatically sorts the results by Name, in the ascending order. orders blocks are documented below. +* `package` - Name of the package. +* `dereference_group_members` - Indicates whether to dereference "members" field by details level for every object in reply. +* `show_membership` - Indicates whether to calculate and show "groups" field for every object in reply. + +`filter_settings` supports the following: + +* `search_mode` - When set to 'general', both the Full Text Search and Packet Search are enabled. In this mode, Packet Search will not match on 'Any' object, a negated cell or a group-with-exclusion. When the search-mode is set to 'packet', by default, the match on 'Any' object, a negated cell or a group-with-exclusion are enabled. packet-search-settings may be provided to change the default behavior. +* `expand_group_members` - (Optional, can only be used when search_mode is set to "packet") When true, if the search expression contains a UID or a name of a group object, results will include rules that match on at least one member of the group. +* `expand_group_with_exclusion_members` - (Optional, can only be used when search_mode is set to "packet") When true, if the search expression contains a UID or a name of a group-with-exclusion object, results will include rules that match at least one member of the "include" part and is not a member of the "except" part. +* `match_on_any` - (Optional, can only be used when search_mode is set to "packet") Whether to match on 'Any' object. +* `match_on_group_with_exclusion` - (Optional, can only be used when search_mode is set to "packet") Whether to match on a group-with-exclusion. +* `match_on_negate` - (Optional, can only be used when search_mode is set to "packet") Whether to match on a negated cell. + +`order` supports the following: + +* `asc` - (Optional) Sorts results by the given field in ascending order. +* `desc` - (Optional) Sorts results by the given field in descending order. diff --git a/website/docs/d/checkpoint_management_vmware_data_center_server.html.markdown b/website/docs/d/checkpoint_management_vmware_data_center_server.html.markdown new file mode 100644 index 00000000..2ff7b6fc --- /dev/null +++ b/website/docs/d/checkpoint_management_vmware_data_center_server.html.markdown @@ -0,0 +1,33 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_vmware_data_center_server" +sidebar_current: "docs-checkpoint-Resource-checkpoint-management-vmware-data-center-server" +description: |- Use this data source to get information on an existing VMware Data Center Server. +--- + +# Resource: checkpoint_management_vmware_data_center_server + +Use this data source to get information on an existing VMware Data Center Server. + +## Example Usage + +```hcl +resource "checkpoint_management_vmware_data_center_server" "testVMware" { + name = "MyVMware" + type = "vcenter" + username = "USERNAME" + password = "PASSWORD" + hostname = "HOSTNAME" +} + +data "checkpoint_management_vmware_data_center_server" "data_vmware_data_center_server" { + name = "${checkpoint_management_vmware_data_center_server.testVMware.name}" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Optional) Object name. +* `uid` - (Optional) Object unique identifier. diff --git a/website/docs/index.html.markdown b/website/docs/index.html.markdown index 1ba1b3ab..364848d0 100644 --- a/website/docs/index.html.markdown +++ b/website/docs/index.html.markdown @@ -60,6 +60,8 @@ The following arguments are supported: the `CHECKPOINT_USERNAME` environment variable. * `password` - (Optional) Check Point Management admin password. It must be provided, but can also be defined via the `CHECKPOINT_PASSWORD` environment variable. +* `api_key` - (Optional) Check Point Management admin api key. this can also be defined via + the `CHECKPOINT_API_KEY` environment variable. * `context` - (Optional) Check Point access context - `web_api` or `gaia_api`. This can also be defined via the `CHECKPOINT_CONTEXT` environment variable. Default value is `web_api`. * `domain` - (Optional) Login to specific domain. Domain can be identified by name or UID. This can also be defined via @@ -70,6 +72,10 @@ The following arguments are supported: environment variable. Default value is `443`. * `session_file_name` - (Optional) Session file name used to store the current session id. this can also be defined via the `CHECKPOINT_SESSION_FILE_NAME` environment variable. default value is `sid.json`. +* `proxy_host` - (Optional) Proxy host used for proxy connections. this can also be defined via + the `CHECKPOINT_PROXY_HOST` environment variable. +* `proxy_port` - (Optional) Proxy port used for proxy connections. this can also be defined via + the `CHECKPOINT_PROXY_PORT` environment variable. ## Authentication @@ -80,7 +86,7 @@ The Check Point provider offers providing credentials for authentication. The fo ### Static credentials -Usage: +Usage with username and password: ```hcl provider "checkpoint" { @@ -91,6 +97,15 @@ provider "checkpoint" { domain = "Domain Name" } ``` +Usage with api key: +```hcl +provider "checkpoint" { + server = "192.0.2.1" + api_key = "tBdloE9eOYzzSQicNxS7mA==" + context = "web_api" + domain = "Domain Name" +} +``` Or for GAIA API: diff --git a/website/docs/r/checkpoint_management_access_rule.html.markdown b/website/docs/r/checkpoint_management_access_rule.html.markdown index 9477540b..092ed9f3 100644 --- a/website/docs/r/checkpoint_management_access_rule.html.markdown +++ b/website/docs/r/checkpoint_management_access_rule.html.markdown @@ -147,5 +147,5 @@ The following arguments are supported: `checkpoint_management_access_rule` can be imported by using the following format: LAYER_NAME;RULE_UID ``` -$ terraform import checkpoint_management_access_rule.example Network;9423d36f-2d66-4754-b9e2-e9f4493751d3 +$ terraform import checkpoint_management_access_rule.example "Network;9423d36f-2d66-4754-b9e2-e9f4493751d3" ``` \ No newline at end of file diff --git a/website/docs/r/checkpoint_management_aci_data_center_server.html.markdown b/website/docs/r/checkpoint_management_aci_data_center_server.html.markdown new file mode 100644 index 00000000..c66b566d --- /dev/null +++ b/website/docs/r/checkpoint_management_aci_data_center_server.html.markdown @@ -0,0 +1,38 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_aci_data_center_server" +sidebar_current: "docs-checkpoint-Resource-checkpoint-management-aci-data-center-server" +description: |- This resource allows you to execute Check Point aci data center server. +--- + +# Resource: checkpoint_management_aci_data_center_server + +This resource allows you to execute Check Point Cisco APIC Data Center Server. + +## Example Usage + +```hcl +resource "checkpoint_management_aci_data_center_server" "testAci" { + name = "MyAci" + username = "USERNAME" + password = "PASSWORD" + urls = ["url1", "url2"] +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) Object name. +* `urls` - (Required) Address of APIC cluster members. Example: http(s)://. +* `username` - (Required) User ID of the Cisco APIC server. When using Login Domains use the following syntax:apic:\. +* `password` - (Optional) Password of the Cisco APIC server. +* `password_base64` - (Optional) Password of the Cisco APIC server encoded in Base64. +* `certificate_fingerprint` - (Optional) Specify the SHA-1 or SHA-256 fingerprint of the Data Center Server's certificate. +* `unsafe_auto_accept` - (Optional) When set to false, the current Data Center Server's certificate should be trusted, either by providing the certificate-fingerprint argument or by relying on a previously trusted certificate of this hostname. When set to true, trust the current Data Center Server's certificate as-is. +* `tags` - (Optional) Collection of tag identifiers. tags blocks are documented below. +* `color` - (Optional) Color of the object. Should be one of existing colors. +* `comments` - (Optional) Comments string. +* `ignore_warnings` - (Optional) Apply changes ignoring warnings. +* `ignore_errors` - (Optional) Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored. diff --git a/website/docs/r/checkpoint_management_aws_data_center_server.html.markdown b/website/docs/r/checkpoint_management_aws_data_center_server.html.markdown new file mode 100644 index 00000000..a65c997f --- /dev/null +++ b/website/docs/r/checkpoint_management_aws_data_center_server.html.markdown @@ -0,0 +1,39 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_aws_data_center_server" +sidebar_current: "docs-checkpoint-Resource-checkpoint-management-aws-data-center-server" +description: |- This resource allows you to execute Check Point aws data center server. +--- + +# Resource: checkpoint_management_aws_data_center_server + +This resource allows you to execute Check Point AWS Data Center Server. + +## Example Usage + +```hcl +resource "checkpoint_management_aws_data_center_server" "testAws" { + authenticationMethod = "user-authentication" + accessKeyId = "MY-KEY-ID" + secretAccessKey = "MY-SECRET-KEY" + region = "us-east-1" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) Object name. +* `authentication_method` - (Required) user-authentication Uses the Access keys to authenticate. role-authentication Uses the AWS IAM role to authenticate. This option requires the Security Management Server be deployed in AWS and has an IAM Role. +* `access_key_id` - (Required for authentication-method: user-authentication) Access key ID for the AWS account. Required for authentication-method:user-authentication. +* `secret_access_key` - (Required for authentication-method: user-authentication) Secret access key for the AWS account. Required for authentication-method:user-authentication. +* `region` - (Optional) Select the AWS region. +* `enable_sts_assume_role` - (Optional) Enables the STS Assume Role option. After it is enabled, the sts-role field is mandatory, whereas the sts-external-id is optional. +* `sts_role` - (Required for enable-sts-assume-role: true) Enables the STS Assume Role option. After it is enabled, the sts-role field is mandatory, whereas the sts-external-id is optional. +* `sts_external_id` - (Optional) An optional STS External-Id to use when assuming the role. +* `tags` - (Optional) Collection of tag identifiers. tags blocks are documented below. +* `color` - (Optional) Color of the object. Should be one of existing colors. +* `comments` - (Optional) Comments string. +* `ignore_warnings` - (Optional) Apply changes ignoring warnings. +* `ignore_errors` - (Optional) Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored. diff --git a/website/docs/r/checkpoint_management_azure_data_center_server.html.markdown b/website/docs/r/checkpoint_management_azure_data_center_server.html.markdown new file mode 100644 index 00000000..83a4e6dc --- /dev/null +++ b/website/docs/r/checkpoint_management_azure_data_center_server.html.markdown @@ -0,0 +1,40 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_azure_data_center_server" +sidebar_current: "docs-checkpoint-Resource-checkpoint-management-azure-data-center-server" +description: |- This resource allows you to execute Check Point azure data center server. +--- + +# Resource: checkpoint_management_azure_data_center_server + +This resource allows you to execute Check Point Azure Data Center Server. + +## Example Usage + +```hcl +resource "checkpoint_management_azure_data_center_server" "testAzure" { + name = "myAzure" + authentication_method = "user-authentication" + username = "MY-KEY-ID" + password = "MY-SECRET-KEY" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) Object name. +* `authentication_method` - (Required) user-authentication Uses the Azure AD User to authenticate. service-principal-authentication Uses the Service Principal to authenticate. +* `username` - (Required for authentication-method: user-authentication) An Azure Active Directory user Format @. Required for authentication-method: user-authentication. +* `password` - (Optional) Password of the Azure account. Required for authentication-method: user-authentication. +* `password_base64` - (Optional) Password of the Azure account encoded in Base64. Required for authentication-method: user-authentication. +* `application_id` - (Required for authentication-method: service-principal-authentication) The Application ID of the Service Principal, in UUID format. Required for authentication-method: service-principal-authentication. +* `application_key` - (Required for authentication-method: service-principal-authentication) The key created for the Service Principal. Required for authentication-method: service-principal-authentication. +* `directory_id` - (Required for authentication-method: service-principal-authentication) The Directory ID of the Azure AD, in UUID format. Required for authentication-method: service-principal-authentication. +* `environment` - (Optional) Select the Azure Cloud Environment. +* `tags` - (Optional) Collection of tag identifiers. tags blocks are documented below. +* `color` - (Optional) Color of the object. Should be one of existing colors. +* `comments` - (Optional) Comments string. +* `ignore_warnings` - (Optional) Apply changes ignoring warnings. +* `ignore_errors` - (Optional) Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored. diff --git a/website/docs/r/checkpoint_management_data_center_query.html.markdown b/website/docs/r/checkpoint_management_data_center_query.html.markdown new file mode 100644 index 00000000..e29d96a0 --- /dev/null +++ b/website/docs/r/checkpoint_management_data_center_query.html.markdown @@ -0,0 +1,43 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_data_center_query" +sidebar_current: "docs-checkpoint-resource-checkpoint-management-data-center-query" +description: |- This resource allows you to execute Check Point Data Center Query. +--- + +# checkpoint_management_data_center_query + +This resource allows you to execute Check Point Data Center Query. + +## Example Usage + +```hcl +resource "checkpoint_management_data_center_query" "example" { + name = "myQuery" + data_centers = ["All"] + query_rules { + key_type = "predefined" + key = "name-in-data-center" + values = ["firstVal", "secondVal"] + } +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) Object name. +* `data_centers` - (Optional) Collection of Data Center servers identified by the name or UID. Use "All" to select all data centers.data_centers blocks are documented below. +* `query_rules` - (Optional) Data Center Query Rules.
There is an 'AND' operation between multiple Query Rules.query_rules blocks are documented below. +* `tags` - (Optional) Collection of tag identifiers.tags blocks are documented below. +* `color` - (Optional) Color of the object. Should be one of existing colors. +* `comments` - (Optional) Comments string. +* `ignore_warnings` - (Optional) Apply changes ignoring warnings. +* `ignore_errors` - (Optional) Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored. + +`query_rules` supports the following: + +* `key_type` - (Optional) The type of the "key" parameter.
Use "predefined" for these keys: type-in-data-center, name-in-data-center, and ip-address.
Use "tag" to query the Data Center tag�s property. +* `key` - (Optional) Defines in which Data Center property to query.
For key-type "predefined", use these keys:type-in-data-center, name-in-data-center, and ip-address.
For key-type "tag", use the Data Center tag key to query.
Keys are case-insensitive. +* `values` - (Optional) The value(s) of the Data Center property to match the Query Rule.
Values are case-insensitive.
There is an 'OR' operation between multiple values.
For key-type "predefined" and key 'ip-address', the values must be an IPv4 or IPv6 address.
For key-type "tag", the values must be the Data Center tag values.values blocks are documented below. diff --git a/website/docs/r/checkpoint_management_gcp_data_center_server.html.markdown b/website/docs/r/checkpoint_management_gcp_data_center_server.html.markdown new file mode 100644 index 00000000..e75fdfd0 --- /dev/null +++ b/website/docs/r/checkpoint_management_gcp_data_center_server.html.markdown @@ -0,0 +1,34 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_gcp_data_center_server" +sidebar_current: "docs-checkpoint-Resource-checkpoint-management-gcp-data-center-server" +description: |- This resource allows you to execute Check Point gcp data center server. +--- + +# Resource: checkpoint_management_gcp_data_center_server + +This resource allows you to execute Check Point Google Cloud Platform Data Center Server. + +## Example Usage + +```hcl +resource "checkpoint_management_gcp_data_center_server" "testGcp" { + name = "myGcp" + authentication_method = "key-authentication" + private_key = "MYKEY.json" + ignore_warnings = true +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) Object name. +* `authentication_method` - (Required) key-authentication Uses the Service Account private key file to authenticate. vm-instance-authentication Uses the Service Account VM Instance to authenticate. This option requires the Security Management Server deployed in a GCP, and runs as a Service Account with the required permissions. +* `private_key` - (Required for authentication-method: key-authentication) A Service Account Key JSON file, encoded in base64. Required for authentication-method:key-authentication. +* `tags` - (Optional) Collection of tag identifiers. tags blocks are documented below. +* `color` - (Optional) Color of the object. Should be one of existing colors. +* `comments` - (Optional) Comments string. +* `ignore_warnings` - (Optional) Apply changes ignoring warnings. +* `ignore_errors` - (Optional) Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored. diff --git a/website/docs/r/checkpoint_management_ise_data_center_server.html.markdown b/website/docs/r/checkpoint_management_ise_data_center_server.html.markdown new file mode 100644 index 00000000..5b756582 --- /dev/null +++ b/website/docs/r/checkpoint_management_ise_data_center_server.html.markdown @@ -0,0 +1,38 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_ise_data_center_server" +sidebar_current: "docs-checkpoint-Resource-checkpoint-management-ise-data-center-server" +description: |- This resource allows you to execute Check Point Cisco ISE data center server. +--- + +# Resource: checkpoint_management_ise_data_center_server + +This resource allows you to execute Check Point Cisco ISE Data Center Server. + +## Example Usage + +```hcl +resource "checkpoint_management_ise_data_center_server" "testIse" { + name = "MyIse" + username = "USERNAME" + password = "PASSWORD" + hostnames = ["host1", "host2"] +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) Object name. +* `hostnames` - (Required) IP address or hostname of the Cisco ISE administration Node(s). +* `username` - (Required) Username of the ISE administrator. +* `password` - (Optional) Password of the ISE administrator. +* `password_base64` - (Optional) Password of the ISE administrator encoded in Base64. +* `certificate_fingerprint` - (Optional) Specify the SHA-1 or SHA-256 fingerprint of the Data Center Server's certificate. +* `unsafe_auto_accept` - (Optional) When set to false, the current Data Center Server's certificate should be trusted, either by providing the certificate-fingerprint argument or by relying on a previously trusted certificate of this hostname. When set to true, trust the current Data Center Server's certificate as-is. +* `tags` - (Optional) Collection of tag identifiers. tags blocks are documented below. +* `color` - (Optional) Color of the object. Should be one of existing colors. +* `comments` - (Optional) Comments string. +* `ignore_warnings` - (Optional) Apply changes ignoring warnings. +* `ignore_errors` - (Optional) Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored. diff --git a/website/docs/r/checkpoint_management_kubernetes_data_center_server.html.markdown b/website/docs/r/checkpoint_management_kubernetes_data_center_server.html.markdown new file mode 100644 index 00000000..8b93d506 --- /dev/null +++ b/website/docs/r/checkpoint_management_kubernetes_data_center_server.html.markdown @@ -0,0 +1,35 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_kubernetes_data_center_server" +sidebar_current: "docs-checkpoint-Resource-checkpoint-management-kubernetes-data-center-server" +description: |- This resource allows you to execute Check Point kubernetes data center server. +--- + +# Resource: checkpoint_management_kubernetes_data_center_server + +This resource allows you to execute Check Point Kubernetes Data Center Server. + +## Example Usage + +```hcl +resource "checkpoint_management_kubernetes_data_center_server" "testKubernetes" { + name = "MyKubernetes" + hostname = "MY_HOSTNAME" + token_file = "MY_TOKEN" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) Object name. +* `hostname` - (Required) IP address or hostname of the Kubernetes server. +* `token_file` - (Required) Kubernetes access token encoded in base64. +* `ca_certificate` - (Optional) The Kubernetes public certificate key encoded in base64. +* `unsafe_auto_accept` - (Optional) When set to false, the current Data Center Server's certificate should be trusted, either by providing the certificate-fingerprint argument or by relying on a previously trusted certificate of this hostname. When set to true, trust the current Data Center Server's certificate as-is. +* `tags` - (Optional) Collection of tag identifiers. tags blocks are documented below. +* `color` - (Optional) Color of the object. Should be one of existing colors. +* `comments` - (Optional) Comments string. +* `ignore_warnings` - (Optional) Apply changes ignoring warnings. +* `ignore_errors` - (Optional) Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored. diff --git a/website/docs/r/checkpoint_management_nat_rule.html.markdown b/website/docs/r/checkpoint_management_nat_rule.html.markdown index 3b6db66a..0b9f8e9f 100644 --- a/website/docs/r/checkpoint_management_nat_rule.html.markdown +++ b/website/docs/r/checkpoint_management_nat_rule.html.markdown @@ -66,5 +66,5 @@ The following arguments are supported: `checkpoint_management_nat_rule` can be imported by using the following format: PACKAGE_NAME;RULE_UID ``` -$ terraform import checkpoint_management_nat_rule.example Standard;9423d36f-2d66-4754-b9e2-e9f4493751d3 +$ terraform import checkpoint_management_nat_rule.example "Standard;9423d36f-2d66-4754-b9e2-e9f4493751d3" ``` \ No newline at end of file diff --git a/website/docs/r/checkpoint_management_nuage_data_center_server.html.markdown b/website/docs/r/checkpoint_management_nuage_data_center_server.html.markdown new file mode 100644 index 00000000..34492dc9 --- /dev/null +++ b/website/docs/r/checkpoint_management_nuage_data_center_server.html.markdown @@ -0,0 +1,40 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_nuage_data_center_server" +sidebar_current: "docs-checkpoint-Resource-checkpoint-management-nuage-data-center-server" +description: |- This resource allows you to execute Check Point nuage data center server. +--- + +# Resource: checkpoint_management_nuage_data_center_server + +This resource allows you to execute Check Point Nuage Data Center Server. + +## Example Usage + +```hcl +resource "checkpoint_management_nuage_data_center_server" "testNuage" { + name = "MyNuage" + organization = "MY_ORG" + username = "USERNAME" + password = "PASSWORD" + hostname = "HOSTNAME" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) Object name. +* `hostname` - (Required) IP address or hostname of the Nuage server. +* `username` - (Required) Username of the Nuage administrator. +* `organization` - (Required) Organization name or enterprise. +* `password` - (Optional) Password of the Nuage administrator. +* `password_base64` - (Optional) Password of the Nuage administrator encoded in Base64. +* `certificate_fingerprint` - (Optional) Specify the SHA-1 or SHA-256 fingerprint of the Data Center Server's certificate. +* `unsafe_auto_accept` - (Optional) When set to false, the current Data Center Server's certificate should be trusted, either by providing the certificate-fingerprint argument or by relying on a previously trusted certificate of this hostname. When set to true, trust the current Data Center Server's certificate as-is. +* `tags` - (Optional) Collection of tag identifiers. tags blocks are documented below. +* `color` - (Optional) Color of the object. Should be one of existing colors. +* `comments` - (Optional) Comments string. +* `ignore_warnings` - (Optional) Apply changes ignoring warnings. +* `ignore_errors` - (Optional) Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored. diff --git a/website/docs/r/checkpoint_management_openstack_data_center_server.html.markdown b/website/docs/r/checkpoint_management_openstack_data_center_server.html.markdown new file mode 100644 index 00000000..c9fd4d9c --- /dev/null +++ b/website/docs/r/checkpoint_management_openstack_data_center_server.html.markdown @@ -0,0 +1,38 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_openstack_data_center_server" +sidebar_current: "docs-checkpoint-Resource-checkpoint-management-openstack-data-center-server" +description: |- This resource allows you to execute Check Point openstack data center server. +--- + +# Resource: checkpoint_management_openstack_data_center_server + +This resource allows you to execute Check Point OpenStack Data Center Server. + +## Example Usage + +```hcl +resource "checkpoint_management_openstack_data_center_server" "testOpenStack" { + name = "MyOpenStack" + username = "USERNAME" + password = "PASSWORD" + hostname = "HOSTNAME" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) Object name. +* `hostname` - (Required) URL of the OpenStack server. http(s)://:/Example: https://1.2.3.4:5000/v2.0 +* `username` - (Required) Username of the OpenStack server. To login to specific domain insert domain name before username. Example: / +* `password` - (Optional) Password of the OpenStack server. +* `password_base64` - (Optional) Password of the OpenStack server encoded in Base64. +* `certificate_fingerprint` - (Optional) Specify the SHA-1 or SHA-256 fingerprint of the Data Center Server's certificate. +* `unsafe_auto_accept` - (Optional) When set to false, the current Data Center Server's certificate should be trusted, either by providing the certificate-fingerprint argument or by relying on a previously trusted certificate of this hostname. When set to true, trust the current Data Center Server's certificate as-is. +* `tags` - (Optional) Collection of tag identifiers. tags blocks are documented below. +* `color` - (Optional) Color of the object. Should be one of existing colors. +* `comments` - (Optional) Comments string. +* `ignore_warnings` - (Optional) Apply changes ignoring warnings. +* `ignore_errors` - (Optional) Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored. diff --git a/website/docs/r/checkpoint_management_threat_rule.html.markdown b/website/docs/r/checkpoint_management_threat_rule.html.markdown index 7d106658..895ac702 100644 --- a/website/docs/r/checkpoint_management_threat_rule.html.markdown +++ b/website/docs/r/checkpoint_management_threat_rule.html.markdown @@ -64,5 +64,5 @@ The following arguments are supported: `checkpoint_management_threat_rule` can be imported by using the following format: LAYER_NAME;RULE_UID ``` -$ terraform import checkpoint_management_threat_rule.example Layer_Name;9423d36f-2d66-4754-b9e2-e9f4493751d3 +$ terraform import checkpoint_management_threat_rule.example "Layer_Name;9423d36f-2d66-4754-b9e2-e9f4493751d3" ``` \ No newline at end of file diff --git a/website/docs/r/checkpoint_management_vmware_data_center_server.html.markdown b/website/docs/r/checkpoint_management_vmware_data_center_server.html.markdown new file mode 100644 index 00000000..5898b18d --- /dev/null +++ b/website/docs/r/checkpoint_management_vmware_data_center_server.html.markdown @@ -0,0 +1,40 @@ +--- +layout: "checkpoint" +page_title: "checkpoint_management_vmware_data_center_server" +sidebar_current: "docs-checkpoint-Resource-checkpoint-management-vmware-data-center-server" +description: |- This resource allows you to execute Check Point vmware data center server. +--- + +# Resource: checkpoint_management_vmware_data_center_server + +This resource allows you to execute Check Point VMware Data Center Server. + +## Example Usage + +```hcl +resource "checkpoint_management_vmware_data_center_server" "testVMware" { + name = "MyVMware" + type = "vcenter" + username = "USERNAME" + password = "PASSWORD" + hostname = "HOSTNAME" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) Object name. +* `type` - (Required) Object type. nsx or nsxt or vcenter. +* `hostname` - (Required) IP Address or hostname of the VMware server. +* `username` - (Required) Username of the VMware server. +* `password` - (Optional) Password of the VMware server. +* `password_base64` - (Optional) Password of the VMware server encoded in Base64. +* `certificate_fingerprint` - (Optional) Specify the SHA-1 or SHA-256 fingerprint of the Data Center Server's certificate. +* `unsafe_auto_accept` - (Optional) When set to false, the current Data Center Server's certificate should be trusted, either by providing the certificate-fingerprint argument or by relying on a previously trusted certificate of this hostname. When set to true, trust the current Data Center Server's certificate as-is. +* `tags` - (Optional) Collection of tag identifiers. tags blocks are documented below. +* `color` - (Optional) Color of the object. Should be one of existing colors. +* `comments` - (Optional) Comments string. +* `ignore_warnings` - (Optional) Apply changes ignoring warnings. +* `ignore_errors` - (Optional) Apply changes ignoring errors. You won't be able to publish such a changes. If ignore-warnings flag was omitted - warnings will also be ignored.