diff --git a/nsxt/provider.go b/nsxt/provider.go index 67dd99395..050854c66 100644 --- a/nsxt/provider.go +++ b/nsxt/provider.go @@ -281,6 +281,7 @@ func Provider() terraform.ResourceProvider { "nsxt_policy_bgp_config": resourceNsxtPolicyBgpConfig(), "nsxt_policy_dhcp_relay": resourceNsxtPolicyDhcpRelayConfig(), "nsxt_policy_dhcp_server": resourceNsxtPolicyDhcpServer(), + "nsxt_policy_context_profile": resourceNsxtPolicyContextProfile(), }, ConfigureFunc: providerConfigure, diff --git a/nsxt/resource_nsxt_policy_context_profile.go b/nsxt/resource_nsxt_policy_context_profile.go new file mode 100644 index 000000000..abc24dff7 --- /dev/null +++ b/nsxt/resource_nsxt_policy_context_profile.go @@ -0,0 +1,506 @@ +/* Copyright © 2019 VMware, Inc. All Rights Reserved. + SPDX-License-Identifier: MPL-2.0 */ + +package nsxt + +import ( + "fmt" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client" + gm_infra "github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/global_infra" + gm_cont_prof "github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/global_infra/context_profiles" + gm_model "github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/model" + "github.com/vmware/vsphere-automation-sdk-go/services/nsxt/infra" + cont_prof "github.com/vmware/vsphere-automation-sdk-go/services/nsxt/infra/context_profiles" + "github.com/vmware/vsphere-automation-sdk-go/services/nsxt/model" + "log" +) + +var attributeKeyMap = map[string]string{ + "app_id": model.PolicyAttributes_KEY_APP_ID, + "domain_name": model.PolicyAttributes_KEY_DOMAIN_NAME, + "url_category": model.PolicyAttributes_KEY_URL_CATEGORY, +} + +var attributeReverseKeyMap = map[string]string{ + model.PolicyAttributes_KEY_APP_ID: "app_id", + model.PolicyAttributes_KEY_DOMAIN_NAME: "domain_name", + model.PolicyAttributes_KEY_URL_CATEGORY: "url_category", +} + +var subAttributeKeyMap = map[string]string{ + "tls_cipher_suite": model.PolicySubAttributes_KEY_TLS_CIPHER_SUITE, + "tls_version": model.PolicySubAttributes_KEY_TLS_VERSION, + "cifs_smb_version": model.PolicySubAttributes_KEY_CIFS_SMB_VERSION, +} + +var subAttributeReverseKeyMap = map[string]string{ + model.PolicySubAttributes_KEY_TLS_CIPHER_SUITE: "tls_cipher_suite", + model.PolicySubAttributes_KEY_TLS_VERSION: "tls_version", + model.PolicySubAttributes_KEY_CIFS_SMB_VERSION: "cifs_smb_version", +} + +func resourceNsxtPolicyContextProfile() *schema.Resource { + return &schema.Resource{ + Create: resourceNsxtPolicyContextProfileCreate, + Read: resourceNsxtPolicyContextProfileRead, + Update: resourceNsxtPolicyContextProfileUpdate, + Delete: resourceNsxtPolicyContextProfileDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "nsx_id": getNsxIDSchema(), + "path": getPathSchema(), + "display_name": getDisplayNameSchema(), + "description": getDescriptionSchema(), + "revision": getRevisionSchema(), + "tag": getTagsSchema(), + "app_id": getContextProfilePolicyAppIDAttributesSchema(), + "domain_name": getContextProfilePolicyOtherAttributesSchema(), + "url_category": getContextProfilePolicyOtherAttributesSchema(), + }, + } +} + +func getContextProfilePolicyAppIDAttributesSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "description": getDescriptionSchema(), + "is_alg_type": { + Type: schema.TypeBool, + Description: "Whether the app_id value is ALG type or not", + Computed: true, + }, + "value": { + Type: schema.TypeSet, + Description: "Values for attribute key", + Required: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "sub_attribute": getPolicyAttributeSubAttributeSchema(), + }, + }, + } +} + +func getContextProfilePolicyOtherAttributesSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeSet, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "description": getDescriptionSchema(), + "value": { + Type: schema.TypeSet, + Description: "Values for attribute key", + Required: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + }, + } +} + +func getPolicyAttributeSubAttributeSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeSet, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "tls_cipher_suite": getPolicyAttributeSubAttributeValueSchema("tls_cipher_suite"), + "tls_version": getPolicyAttributeSubAttributeValueSchema("tls_version"), + "cifs_smb_version": getPolicyAttributeSubAttributeValueSchema("cifs_smb_version"), + }, + }, + } +} +func getPolicyAttributeSubAttributeValueSchema(subAttributeKey string) *schema.Schema { + description := fmt.Sprintf("Values for sub attribute key %s", subAttributeKey) + return &schema.Schema{ + Type: schema.TypeSet, + Description: description, + Optional: true, + MinItems: 1, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + } +} + +func resourceNsxtPolicyContextProfileExists(id string, connector *client.RestConnector, isGlobalManager bool) bool { + var err error + if isGlobalManager { + client := gm_infra.NewDefaultContextProfilesClient(connector) + _, err = client.Get(id) + } else { + client := infra.NewDefaultContextProfilesClient(connector) + _, err = client.Get(id) + } + + if err == nil { + return true + } + + if isNotFoundError(err) { + return false + } + + logAPIError("Error retrieving ContextProfile", err) + + return false +} + +func resourceNsxtPolicyContextProfileCreate(d *schema.ResourceData, m interface{}) error { + connector := getPolicyConnector(m) + + // Initialize resource Id and verify this ID is not yet used + id, err := getOrGenerateID(d, m, resourceNsxtPolicyContextProfileExists) + if err != nil { + return err + } + + displayName := d.Get("display_name").(string) + description := d.Get("description").(string) + attributesStructList := make([]model.PolicyAttributes, 0, 0) + for key := range attributeKeyMap { + attributes := d.Get(key).(*schema.Set).List() + if len(attributes) > 0 { + err = checkAttributesValid(attributes, m, key) + if err != nil { + return err + } + attributeStructList, err := constructAttributesModelList(attributes, key) + if err != nil { + return err + } + attributesStructList = append(attributesStructList, attributeStructList...) + } + } + if len(attributesStructList) == 0 { + return fmt.Errorf("At least one attribute should be set") + } + + tags := getPolicyTagsFromSchema(d) + + obj := model.PolicyContextProfile{ + DisplayName: &displayName, + Description: &description, + Tags: tags, + Attributes: attributesStructList, + } + + // Create the resource using PATCH + log.Printf("[INFO] Creating ContextProfile with ID %s", id) + if isPolicyGlobalManager(m) { + client := gm_infra.NewDefaultContextProfilesClient(connector) + gmObj, err1 := convertModelBindingType(obj, model.PolicyContextProfileBindingType(), gm_model.PolicyContextProfileBindingType()) + if err1 != nil { + return err1 + } + err = client.Patch(id, gmObj.(gm_model.PolicyContextProfile)) + } else { + client := infra.NewDefaultContextProfilesClient(connector) + err = client.Patch(id, obj) + } + if err != nil { + return handleCreateError("ContextProfile", id, err) + } + + d.SetId(id) + d.Set("nsx_id", id) + + return resourceNsxtPolicyContextProfileRead(d, m) +} + +func resourceNsxtPolicyContextProfileRead(d *schema.ResourceData, m interface{}) error { + connector := getPolicyConnector(m) + id := d.Id() + if id == "" { + return fmt.Errorf("Error obtaining ContextProfile ID") + } + + var obj model.PolicyContextProfile + if isPolicyGlobalManager(m) { + client := gm_infra.NewDefaultContextProfilesClient(connector) + gmObj, err := client.Get(id) + if err != nil { + return handleReadError(d, "ContextProfile", id, err) + } + rawObj, err := convertModelBindingType(gmObj, gm_model.PolicyContextProfileBindingType(), model.PolicyContextProfileBindingType()) + if err != nil { + return err + } + obj = rawObj.(model.PolicyContextProfile) + } else { + var err error + client := infra.NewDefaultContextProfilesClient(connector) + obj, err = client.Get(id) + if err != nil { + return handleReadError(d, "ContextProfile", id, err) + } + } + + d.Set("display_name", obj.DisplayName) + d.Set("description", obj.Description) + setPolicyTagsInSchema(d, obj.Tags) + d.Set("nsx_id", id) + d.Set("path", obj.Path) + d.Set("revision", obj.Revision) + fillAttributesInSchema(d, obj.Attributes) + + return nil +} + +func resourceNsxtPolicyContextProfileUpdate(d *schema.ResourceData, m interface{}) error { + connector := getPolicyConnector(m) + id := d.Id() + if id == "" { + return fmt.Errorf("Error obtaining ContextProfile ID") + } + + // Read the rest of the configured parameters + displayName := d.Get("display_name").(string) + description := d.Get("description").(string) + attributesStructList := make([]model.PolicyAttributes, 0, 0) + var err error + for key := range attributeKeyMap { + attributes := d.Get(key).(*schema.Set).List() + err := checkAttributesValid(attributes, m, key) + if err != nil { + return err + } + attributeStructList, err := constructAttributesModelList(attributes, key) + if err != nil { + return err + } + attributesStructList = append(attributesStructList, attributeStructList...) + } + tags := getPolicyTagsFromSchema(d) + + obj := model.PolicyContextProfile{ + DisplayName: &displayName, + Description: &description, + Tags: tags, + Attributes: attributesStructList, + } + + // Update the resource using PATCH + if isPolicyGlobalManager(m) { + rawObj, err1 := convertModelBindingType(obj, model.PolicyContextProfileBindingType(), gm_model.PolicyContextProfileBindingType()) + if err1 != nil { + return err1 + } + gmObj := rawObj.(gm_model.PolicyContextProfile) + client := gm_infra.NewDefaultContextProfilesClient(connector) + err = client.Patch(id, gmObj) + } else { + client := infra.NewDefaultContextProfilesClient(connector) + err = client.Patch(id, obj) + } + + if err != nil { + return handleUpdateError("ContextProfile", id, err) + } + + return resourceNsxtPolicyContextProfileRead(d, m) +} + +func resourceNsxtPolicyContextProfileDelete(d *schema.ResourceData, m interface{}) error { + id := d.Id() + if id == "" { + return fmt.Errorf("Error obtaining ContextProfile ID") + } + + connector := getPolicyConnector(m) + var err error + force := true + if isPolicyGlobalManager(m) { + client := gm_infra.NewDefaultContextProfilesClient(connector) + err = client.Delete(id, &force) + } else { + client := infra.NewDefaultContextProfilesClient(connector) + err = client.Delete(id, &force) + } + if err != nil { + return handleDeleteError("ContextProfile", id, err) + } + + return nil +} + +func checkAttributesValid(attributes []interface{}, m interface{}, key string) error { + + if key == "app_id" { + err := validateSubAttributes(attributes) + if err != nil { + return err + } + } + var attrClient interface{} + connector := getPolicyConnector(m) + isPolicyGlobalManager := isPolicyGlobalManager(m) + if isPolicyGlobalManager { + attrClient = gm_cont_prof.NewDefaultAttributesClient(connector) + } else { + attrClient = cont_prof.NewDefaultAttributesClient(connector) + } + attributeValues, err := listAttributesWithKey(attributeKeyMap[key], attrClient, isPolicyGlobalManager) + if err != nil { + return err + } + for _, attribute := range attributes { + attributeMap := attribute.(map[string]interface{}) + values := interface2StringList(attributeMap["value"].(*schema.Set).List()) + if !containsElements(values, attributeValues) { + err := fmt.Errorf("Attribute values %s are not valid for attribute type %s", values, key) + return err + } + } + return nil +} + +func validateSubAttributes(attributes []interface{}) error { + // Validates that sub_attribute keys only present in an attribute with one value + for _, attribute := range attributes { + attributeMap := attribute.(map[string]interface{}) + values := attributeMap["value"].(*schema.Set).List() + if len(attributeMap["sub_attribute"].(*schema.Set).List()) > 0 && len(values) > 1 { + err := fmt.Errorf("Multiple values found for attribute. Sub-attributes are only applicable to an attribute with a single value") + return err + } + } + return nil +} + +func listAttributesWithKey(attributeKey string, attributeClient interface{}, isPolicyGlobalManager bool) ([]string, error) { + // returns a list of attribute values + policyAttributes := make([]string, 0) + policyContextProfileListResult, err := listContextProfileWithKey(&attributeKey, attributeClient, isPolicyGlobalManager) + if err != nil { + return policyAttributes, err + } + for _, policyContextProfile := range policyContextProfileListResult.Results { + for _, attribute := range policyContextProfile.Attributes { + policyAttributes = append(policyAttributes, attribute.Value...) + } + } + return policyAttributes, nil +} + +func listContextProfileWithKey(attributeKey *string, attributeClient interface{}, isPolicyGlobalManager bool) (model.PolicyContextProfileListResult, error) { + var policyContextProfileListResult model.PolicyContextProfileListResult + includeMarkForDeleteObjectsParam := false + if isPolicyGlobalManager { + client := attributeClient.(*gm_cont_prof.DefaultAttributesClient) + gmPolicyContextProfileListResult, err := client.List(attributeKey, nil, &includeMarkForDeleteObjectsParam, nil, nil, nil, nil) + if err != nil { + logAPIError("Error listing Policy Attributes", err) + return policyContextProfileListResult, err + } + lmPolicyContextProfileListResult, err := convertModelBindingType(gmPolicyContextProfileListResult, gm_model.PolicyContextProfileListResultBindingType(), model.PolicyContextProfileListResultBindingType()) + if err != nil { + return policyContextProfileListResult, err + } + policyContextProfileListResult = lmPolicyContextProfileListResult.(model.PolicyContextProfileListResult) + return policyContextProfileListResult, err + } + var err error + client := attributeClient.(*cont_prof.DefaultAttributesClient) + policyContextProfileListResult, err = client.List(attributeKey, nil, &includeMarkForDeleteObjectsParam, nil, nil, nil, nil) + return policyContextProfileListResult, err +} + +func constructAttributesModelList(rawAttributes []interface{}, key string) ([]model.PolicyAttributes, error) { + res := make([]model.PolicyAttributes, 0, len(rawAttributes)) + for _, rawAttribute := range rawAttributes { + attributeMap := rawAttribute.(map[string]interface{}) + dataType := model.PolicyAttributes_DATATYPE_STRING + description := attributeMap["description"].(string) + attrKey := attributeKeyMap[key] + values := interface2StringList(attributeMap["value"].(*schema.Set).List()) + subAttributesList := make([]model.PolicySubAttributes, 0, 0) + if key == "app_id" { + var err error + subAttributes := attributeMap["sub_attribute"].(*schema.Set).List() + subAttributesList, err = constructSubAttributeModelList(subAttributes) + if err != nil { + return nil, err + } + } + attributeStruct := model.PolicyAttributes{ + Datatype: &dataType, + Description: &description, + Key: &attrKey, + Value: values, + SubAttributes: subAttributesList, + } + res = append(res, attributeStruct) + } + return res, nil +} + +func constructSubAttributeModelList(rawSubAttributes []interface{}) ([]model.PolicySubAttributes, error) { + res := make([]model.PolicySubAttributes, 0, 0) + dataType := model.PolicySubAttributes_DATATYPE_STRING + for _, rawSubAttribute := range rawSubAttributes { + rawSubAttributeMap := rawSubAttribute.(map[string]interface{}) + for key, subAttrKey := range subAttributeKeyMap { + vals := rawSubAttributeMap[key] + if vals != nil { + values := interface2StringList(vals.(*schema.Set).List()) + if len(values) > 0 { + tmp := subAttrKey + subAttributeStruct := model.PolicySubAttributes{ + Datatype: &dataType, + Key: &tmp, + Value: values, + } + res = append(res, subAttributeStruct) + } + } + } + } + return res, nil +} + +func fillAttributesInSchema(d *schema.ResourceData, policyAttributes []model.PolicyAttributes) { + attributes := make(map[string][]interface{}) + for _, policyAttribute := range policyAttributes { + elem := make(map[string]interface{}) + key := attributeReverseKeyMap[*policyAttribute.Key] + elem["description"] = policyAttribute.Description + elem["value"] = policyAttribute.Value + if *policyAttribute.Key == model.PolicyAttributes_KEY_APP_ID { + if len(policyAttribute.SubAttributes) > 0 { + elem["sub_attribute"] = fillSubAttributesInSchema(policyAttribute.SubAttributes) + } + elem["is_alg_type"] = policyAttribute.IsALGType + } + attributes[key] = append(attributes[key], elem) + } + for key, attributeList := range attributes { + d.Set(key, attributeList) + } +} + +func fillSubAttributesInSchema(policySubAttributes []model.PolicySubAttributes) []interface{} { + subAttributes := make(map[string]interface{}) + for _, policySubAttribute := range policySubAttributes { + key := subAttributeReverseKeyMap[*policySubAttribute.Key] + subAttributes[key] = policySubAttribute.Value + } + res := make([]interface{}, 0, 1) + res = append(res, subAttributes) + return res +} diff --git a/nsxt/resource_nsxt_policy_context_profile_test.go b/nsxt/resource_nsxt_policy_context_profile_test.go new file mode 100644 index 000000000..8d9a12406 --- /dev/null +++ b/nsxt/resource_nsxt_policy_context_profile_test.go @@ -0,0 +1,362 @@ +/* Copyright © 2019 VMware, Inc. All Rights Reserved. + SPDX-License-Identifier: MPL-2.0 */ + +package nsxt + +import ( + "fmt" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + gm_infra "github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/global_infra" + "github.com/vmware/vsphere-automation-sdk-go/services/nsxt/infra" + "testing" +) + +func TestAccResourceNsxtPolicyContextProfile_basic(t *testing.T) { + name := "terraform-test" + updatedName := fmt.Sprintf("%s-update", name) + testResourceName := "nsxt_policy_context_profile.test" + attributes := testAccNsxtPolicyContextProfileAttributeDomainNameTemplate() + updatedAttributes := testAccNsxtPolicyContextProfileAttributeURLCategoryTemplate() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: func(state *terraform.State) error { + return testAccNsxtPolicyContextProfileCheckDestroy(state, testResourceName) + }, + Steps: []resource.TestStep{ + { + Config: testAccNsxtPolicyContextProfileTemplate(name, attributes), + Check: resource.ComposeTestCheckFunc( + testAccNsxtPolicyContextProfileExists(testResourceName), + resource.TestCheckResourceAttr(testResourceName, "display_name", name), + resource.TestCheckResourceAttr(testResourceName, "description", "Acceptance Test"), + resource.TestCheckResourceAttrSet(testResourceName, "nsx_id"), + resource.TestCheckResourceAttrSet(testResourceName, "path"), + resource.TestCheckResourceAttrSet(testResourceName, "revision"), + resource.TestCheckResourceAttr(testResourceName, "tag.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "app_id.#", "0"), + resource.TestCheckResourceAttr(testResourceName, "domain_name.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "url_category.#", "0"), + resource.TestCheckResourceAttr(testResourceName, "domain_name.238902231.value.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "domain_name.238902231.value.608540107", "*-myfiles.sharepoint.com"), + ), + }, + { + Config: testAccNsxtPolicyContextProfileTemplate(updatedName, updatedAttributes), + Check: resource.ComposeTestCheckFunc( + testAccNsxtPolicyContextProfileExists(testResourceName), + resource.TestCheckResourceAttr(testResourceName, "display_name", updatedName), + resource.TestCheckResourceAttr(testResourceName, "description", "Acceptance Test"), + resource.TestCheckResourceAttrSet(testResourceName, "nsx_id"), + resource.TestCheckResourceAttrSet(testResourceName, "path"), + resource.TestCheckResourceAttrSet(testResourceName, "revision"), + resource.TestCheckResourceAttr(testResourceName, "tag.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "app_id.#", "0"), + resource.TestCheckResourceAttr(testResourceName, "domain_name.#", "0"), + resource.TestCheckResourceAttr(testResourceName, "url_category.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "url_category.1857560543.value.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "url_category.1857560543.value.3317229948", "Abortion"), + ), + }, + }, + }) +} + +func TestAccResourceNsxtPolicyContextProfile_importBasic(t *testing.T) { + name := "terra-test-import" + testResourceName := "nsxt_policy_context_profile.test" + attributes := testAccNsxtPolicyContextProfileAttributeDomainNameTemplate() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: func(state *terraform.State) error { + return testAccNsxtPolicyContextProfileCheckDestroy(state, name) + }, + Steps: []resource.TestStep{ + { + Config: testAccNsxtPolicyContextProfileTemplate(name, attributes), + }, + { + ResourceName: testResourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccResourceNsxtPolicyContextProfile_multipleAttributes(t *testing.T) { + name := "terraform-test" + updatedName := fmt.Sprintf("%s-update", name) + testResourceName := "nsxt_policy_context_profile.test" + attributes := testAccNsxtPolicyContextProfileAttributeDomainNameTemplate() + updatedAttributes := testAccNsxtPolicyContextProfileAttributeDomainNameTemplate() + testAccNsxtPolicyContextProfileAttributeAppIDTemplate() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: func(state *terraform.State) error { + return testAccNsxtPolicyContextProfileCheckDestroy(state, testResourceName) + }, + Steps: []resource.TestStep{ + { + Config: testAccNsxtPolicyContextProfileTemplate(name, attributes), + Check: resource.ComposeTestCheckFunc( + testAccNsxtPolicyContextProfileExists(testResourceName), + resource.TestCheckResourceAttr(testResourceName, "display_name", name), + resource.TestCheckResourceAttr(testResourceName, "description", "Acceptance Test"), + resource.TestCheckResourceAttrSet(testResourceName, "nsx_id"), + resource.TestCheckResourceAttrSet(testResourceName, "path"), + resource.TestCheckResourceAttrSet(testResourceName, "revision"), + resource.TestCheckResourceAttr(testResourceName, "tag.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "app_id.#", "0"), + resource.TestCheckResourceAttr(testResourceName, "domain_name.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "url_category.#", "0"), + resource.TestCheckResourceAttr(testResourceName, "domain_name.238902231.value.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "domain_name.238902231.value.608540107", "*-myfiles.sharepoint.com"), + ), + }, + { + Config: testAccNsxtPolicyContextProfileTemplate(updatedName, updatedAttributes), + Check: resource.ComposeTestCheckFunc( + testAccNsxtPolicyContextProfileExists(testResourceName), + resource.TestCheckResourceAttr(testResourceName, "display_name", updatedName), + resource.TestCheckResourceAttr(testResourceName, "description", "Acceptance Test"), + resource.TestCheckResourceAttrSet(testResourceName, "nsx_id"), + resource.TestCheckResourceAttrSet(testResourceName, "path"), + resource.TestCheckResourceAttrSet(testResourceName, "revision"), + resource.TestCheckResourceAttr(testResourceName, "tag.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "app_id.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "domain_name.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "url_category.#", "0"), + resource.TestCheckResourceAttrSet(testResourceName, "app_id.124112814.is_alg_type"), + resource.TestCheckResourceAttr(testResourceName, "app_id.124112814.value.#", "3"), + resource.TestCheckResourceAttr(testResourceName, "app_id.124112814.value.2076247700", "SSL"), + resource.TestCheckResourceAttr(testResourceName, "app_id.124112814.value.2328579708", "HTTP"), + resource.TestCheckResourceAttr(testResourceName, "app_id.124112814.value.531481488", "SSH"), + resource.TestCheckResourceAttr(testResourceName, "domain_name.238902231.value.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "domain_name.238902231.value.608540107", "*-myfiles.sharepoint.com"), + ), + }, + }, + }) +} + +func TestAccResourceNsxtPolicyContextProfile_subAttributes(t *testing.T) { + name := "terraform-test" + updatedName := fmt.Sprintf("%s-update", name) + testResourceName := "nsxt_policy_context_profile.test" + attributes := testAccNsxtPolicyContextProfileAttributeAppIDSubAttributesTemplate() + updatedAttributes := testAccNsxtPolicyContextProfileAttributeAppIDSubAttributesUpdatedTemplate() + attributesNoSub := testAccNsxtPolicyContextProfileAttributeAppIDSslTemplate() + attributesDomainName := testAccNsxtPolicyContextProfileAttributeDomainNameTemplate() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: func(state *terraform.State) error { + return testAccNsxtPolicyContextProfileCheckDestroy(state, testResourceName) + }, + Steps: []resource.TestStep{ + { + Config: testAccNsxtPolicyContextProfileTemplate(name, attributes), + Check: resource.ComposeTestCheckFunc( + testAccNsxtPolicyContextProfileExists(testResourceName), + resource.TestCheckResourceAttr(testResourceName, "display_name", name), + resource.TestCheckResourceAttr(testResourceName, "description", "Acceptance Test"), + resource.TestCheckResourceAttrSet(testResourceName, "nsx_id"), + resource.TestCheckResourceAttrSet(testResourceName, "path"), + resource.TestCheckResourceAttrSet(testResourceName, "revision"), + resource.TestCheckResourceAttr(testResourceName, "tag.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "app_id.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "domain_name.#", "0"), + resource.TestCheckResourceAttr(testResourceName, "url_category.#", "0"), + resource.TestCheckResourceAttrSet(testResourceName, "app_id.2652970086.is_alg_type"), + resource.TestCheckResourceAttr(testResourceName, "app_id.2652970086.value.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "app_id.2652970086.value.2076247700", "SSL"), + resource.TestCheckResourceAttr(testResourceName, "app_id.2652970086.sub_attribute.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "app_id.2652970086.sub_attribute.250747496.cifs_smb_version.#", "0"), + resource.TestCheckResourceAttr(testResourceName, "app_id.2652970086.sub_attribute.250747496.tls_cipher_suite.#", "0"), + resource.TestCheckResourceAttr(testResourceName, "app_id.2652970086.sub_attribute.250747496.tls_version.#", "3"), + resource.TestCheckResourceAttr(testResourceName, "app_id.2652970086.sub_attribute.250747496.tls_version.2416475543", "TLS_V12"), + resource.TestCheckResourceAttr(testResourceName, "app_id.2652970086.sub_attribute.250747496.tls_version.2721980181", "TLS_V10"), + resource.TestCheckResourceAttr(testResourceName, "app_id.2652970086.sub_attribute.250747496.tls_version.645341863", "SSL_V3"), + ), + }, + { + Config: testAccNsxtPolicyContextProfileTemplate(updatedName, updatedAttributes), + Check: resource.ComposeTestCheckFunc( + testAccNsxtPolicyContextProfileExists(testResourceName), + resource.TestCheckResourceAttr(testResourceName, "display_name", updatedName), + resource.TestCheckResourceAttr(testResourceName, "description", "Acceptance Test"), + resource.TestCheckResourceAttrSet(testResourceName, "nsx_id"), + resource.TestCheckResourceAttrSet(testResourceName, "path"), + resource.TestCheckResourceAttrSet(testResourceName, "revision"), + resource.TestCheckResourceAttr(testResourceName, "tag.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "app_id.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "domain_name.#", "0"), + resource.TestCheckResourceAttr(testResourceName, "url_category.#", "0"), + resource.TestCheckResourceAttrSet(testResourceName, "app_id.832058275.is_alg_type"), + resource.TestCheckResourceAttr(testResourceName, "app_id.832058275.value.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "app_id.832058275.value.1810355442", "CIFS"), + resource.TestCheckResourceAttr(testResourceName, "app_id.832058275.sub_attribute.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "app_id.832058275.sub_attribute.2393957168.cifs_smb_version.#", "2"), + resource.TestCheckResourceAttr(testResourceName, "app_id.832058275.sub_attribute.2393957168.tls_cipher_suite.#", "0"), + resource.TestCheckResourceAttr(testResourceName, "app_id.832058275.sub_attribute.2393957168.tls_version.#", "0"), + resource.TestCheckResourceAttr(testResourceName, "app_id.832058275.sub_attribute.2393957168.cifs_smb_version.3398512106", "CIFS_SMB_V1"), + resource.TestCheckResourceAttr(testResourceName, "app_id.832058275.sub_attribute.2393957168.cifs_smb_version.3787226665", "CIFS_SMB_V2"), + ), + }, + { + Config: testAccNsxtPolicyContextProfileTemplate(updatedName, attributesNoSub), + Check: resource.ComposeTestCheckFunc( + testAccNsxtPolicyContextProfileExists(testResourceName), + resource.TestCheckResourceAttr(testResourceName, "display_name", updatedName), + resource.TestCheckResourceAttr(testResourceName, "description", "Acceptance Test"), + resource.TestCheckResourceAttrSet(testResourceName, "nsx_id"), + resource.TestCheckResourceAttrSet(testResourceName, "path"), + resource.TestCheckResourceAttrSet(testResourceName, "revision"), + resource.TestCheckResourceAttr(testResourceName, "tag.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "app_id.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "domain_name.#", "0"), + resource.TestCheckResourceAttr(testResourceName, "url_category.#", "0"), + resource.TestCheckResourceAttr(testResourceName, "app_id.4162008338.value.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "app_id.4162008338.value.2076247700", "SSL"), + resource.TestCheckResourceAttrSet(testResourceName, "app_id.4162008338.is_alg_type"), + resource.TestCheckResourceAttr(testResourceName, "app_id.4162008338.sub_attribute.#", "0"), + ), + }, + { + Config: testAccNsxtPolicyContextProfileTemplate(updatedName, attributesDomainName), + Check: resource.ComposeTestCheckFunc( + testAccNsxtPolicyContextProfileExists(testResourceName), + resource.TestCheckResourceAttr(testResourceName, "display_name", updatedName), + resource.TestCheckResourceAttr(testResourceName, "description", "Acceptance Test"), + resource.TestCheckResourceAttrSet(testResourceName, "nsx_id"), + resource.TestCheckResourceAttrSet(testResourceName, "path"), + resource.TestCheckResourceAttrSet(testResourceName, "revision"), + resource.TestCheckResourceAttr(testResourceName, "tag.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "app_id.#", "0"), + resource.TestCheckResourceAttr(testResourceName, "domain_name.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "url_category.#", "0"), + resource.TestCheckResourceAttr(testResourceName, "domain_name.238902231.value.#", "1"), + resource.TestCheckResourceAttr(testResourceName, "domain_name.238902231.value.608540107", "*-myfiles.sharepoint.com"), + ), + }, + }, + }) +} + +func testAccNsxtPolicyContextProfileExists(resourceName string) resource.TestCheckFunc { + return func(state *terraform.State) error { + rs, ok := state.RootModule().Resources[resourceName] + if !ok { + return fmt.Errorf("Policy ContextProfile resource %s not found in resources", resourceName) + } + resourceID := rs.Primary.ID + if resourceID == "" { + return fmt.Errorf("Policy ContextProfile resource ID not set in resources") + } + + err := nsxtPolicyContextProfileExists(resourceID) + + if err != nil { + return fmt.Errorf("Error while retrieving policy ContextProfile ID %s. Error: %v", resourceID, err) + } + + return nil + } +} + +func nsxtPolicyContextProfileExists(resourceID string) error { + connector := getPolicyConnector(testAccProvider.Meta().(nsxtClients)) + var err error + if testAccIsGlobalManager() { + nsxClient := gm_infra.NewDefaultContextProfilesClient(connector) + _, err = nsxClient.Get(resourceID) + } else { + nsxClient := infra.NewDefaultContextProfilesClient(connector) + _, err = nsxClient.Get(resourceID) + } + return err +} + +func testAccNsxtPolicyContextProfileCheckDestroy(state *terraform.State, displayName string) error { + for _, rs := range state.RootModule().Resources { + + if rs.Type != "nsxt_policy_context_profile" { + continue + } + + resourceID := rs.Primary.Attributes["id"] + err := nsxtPolicyContextProfileExists(resourceID) + if err == nil { + return fmt.Errorf("Policy ContextProfile %s still exists", displayName) + } + } + return nil +} + +func testAccNsxtPolicyContextProfileTemplate(name string, attributes string) string { + return fmt.Sprintf(` +resource "nsxt_policy_context_profile" "test" { + display_name = "%s" + description = "Acceptance Test" + tag { + scope = "color" + tag = "orange" + } +%s +}`, name, attributes) +} + +func testAccNsxtPolicyContextProfileAttributeDomainNameTemplate() string { + return ` +domain_name { + value = ["*-myfiles.sharepoint.com"] +}` +} + +func testAccNsxtPolicyContextProfileAttributeAppIDTemplate() string { + return ` +app_id { + value = ["SSL", "SSH", "HTTP"] +}` +} + +func testAccNsxtPolicyContextProfileAttributeURLCategoryTemplate() string { + return ` +url_category { + value = ["Abortion"] +}` +} + +func testAccNsxtPolicyContextProfileAttributeAppIDSubAttributesTemplate() string { + return ` +app_id { + value = ["SSL"] + sub_attribute { + tls_version = ["SSL_V3", "TLS_V10", "TLS_V12"] + } +}` +} + +func testAccNsxtPolicyContextProfileAttributeAppIDSubAttributesUpdatedTemplate() string { + return ` +app_id { + value = ["CIFS"] + sub_attribute { + cifs_smb_version = ["CIFS_SMB_V1", "CIFS_SMB_V2"] + } +}` +} + +func testAccNsxtPolicyContextProfileAttributeAppIDSslTemplate() string { + return ` +app_id { + value = ["SSL"] +}` +} diff --git a/nsxt/utils.go b/nsxt/utils.go index a5e7c96d1..4fe63053b 100644 --- a/nsxt/utils.go +++ b/nsxt/utils.go @@ -553,3 +553,23 @@ func resourceNotSupportedError() error { func dataSourceNotSupportedError() error { return fmt.Errorf("This data source is not supported with given provider settings") } + +func stringInList(target string, list []string) bool { + // util to check if target string is in list + for _, value := range list { + if target == value { + return true + } + } + return false +} + +func containsElements(target []string, list []string) bool { + // util to check if all strings in target []string is in list. NOT ordered + for _, value := range target { + if !stringInList(value, list) { + return false + } + } + return true +} diff --git a/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/global_infra/context_profiles/AttributesClient.go b/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/global_infra/context_profiles/AttributesClient.go new file mode 100644 index 000000000..62f87db8d --- /dev/null +++ b/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/global_infra/context_profiles/AttributesClient.go @@ -0,0 +1,35 @@ +/* Copyright © 2019 VMware, Inc. All Rights Reserved. + SPDX-License-Identifier: BSD-2-Clause */ + +// Code generated. DO NOT EDIT. + +/* + * Interface file for service: Attributes + * Used by client-side stubs. + */ + +package context_profiles + +import ( + "github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/model" +) + +type AttributesClient interface { + + // Returns supported attribute and sub-attributes for specified attribute key with their supported values, if provided in query/request parameter, else will fetch all supported attributes and sub-attributes for all supported attribute keys. Alternatively, to get a list of supported attributes and sub-attributes fire the following REST API GET https:///policy/api/v1/infra/context-profiles/attributes + // + // @param attributeKeyParam Fetch attributes and sub-attributes for the given attribute key (optional) + // @param cursorParam Opaque cursor to be used for getting next page of records (supplied by current result page) (optional) + // @param includeMarkForDeleteObjectsParam Include objects that are marked for deletion in results (optional, default to false) + // @param includedFieldsParam Comma separated list of fields that should be included in query result (optional) + // @param pageSizeParam Maximum number of results to return in this page (server may return fewer) (optional, default to 1000) + // @param sortAscendingParam (optional) + // @param sortByParam Field by which records are sorted (optional) + // @return com.vmware.nsx_global_policy.model.PolicyContextProfileListResult + // @throws InvalidRequest Bad Request, Precondition Failed + // @throws Unauthorized Forbidden + // @throws ServiceUnavailable Service Unavailable + // @throws InternalServerError Internal Server Error + // @throws NotFound Not Found + List(attributeKeyParam *string, cursorParam *string, includeMarkForDeleteObjectsParam *bool, includedFieldsParam *string, pageSizeParam *int64, sortAscendingParam *bool, sortByParam *string) (model.PolicyContextProfileListResult, error) +} diff --git a/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/global_infra/context_profiles/AttributesTypes.go b/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/global_infra/context_profiles/AttributesTypes.go new file mode 100644 index 000000000..17a3bdeae --- /dev/null +++ b/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/global_infra/context_profiles/AttributesTypes.go @@ -0,0 +1,112 @@ +/* Copyright © 2019 VMware, Inc. All Rights Reserved. + SPDX-License-Identifier: BSD-2-Clause */ + +// Code generated. DO NOT EDIT. + +/* + * Data type definitions file for service: Attributes. + * Includes binding types of a structures and enumerations defined in the service. + * Shared by client-side stubs and server-side skeletons to ensure type + * compatibility. + */ + +package context_profiles + +import ( + "reflect" + "github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/model" + "github.com/vmware/vsphere-automation-sdk-go/runtime/bindings" + "github.com/vmware/vsphere-automation-sdk-go/runtime/data" + "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol" +) + + + + + +func attributesListInputType() bindings.StructType { + fields := make(map[string]bindings.BindingType) + fieldNameMap := make(map[string]string) + fields["attribute_key"] = bindings.NewOptionalType(bindings.NewStringType()) + fields["cursor"] = bindings.NewOptionalType(bindings.NewStringType()) + fields["include_mark_for_delete_objects"] = bindings.NewOptionalType(bindings.NewBooleanType()) + fields["included_fields"] = bindings.NewOptionalType(bindings.NewStringType()) + fields["page_size"] = bindings.NewOptionalType(bindings.NewIntegerType()) + fields["sort_ascending"] = bindings.NewOptionalType(bindings.NewBooleanType()) + fields["sort_by"] = bindings.NewOptionalType(bindings.NewStringType()) + fieldNameMap["attribute_key"] = "AttributeKey" + fieldNameMap["cursor"] = "Cursor" + fieldNameMap["include_mark_for_delete_objects"] = "IncludeMarkForDeleteObjects" + fieldNameMap["included_fields"] = "IncludedFields" + fieldNameMap["page_size"] = "PageSize" + fieldNameMap["sort_ascending"] = "SortAscending" + fieldNameMap["sort_by"] = "SortBy" + var validators = []bindings.Validator{} + return bindings.NewStructType("operation-input", fields, reflect.TypeOf(data.StructValue{}), fieldNameMap, validators) +} + +func attributesListOutputType() bindings.BindingType { + return bindings.NewReferenceType(model.PolicyContextProfileListResultBindingType) +} + +func attributesListRestMetadata() protocol.OperationRestMetadata { + fields := map[string]bindings.BindingType{} + fieldNameMap := map[string]string{} + paramsTypeMap := map[string]bindings.BindingType{} + pathParams := map[string]string{} + queryParams := map[string]string{} + headerParams := map[string]string{} + dispatchHeaderParams := map[string]string{} + bodyFieldsMap := map[string]string{} + fields["attribute_key"] = bindings.NewOptionalType(bindings.NewStringType()) + fields["cursor"] = bindings.NewOptionalType(bindings.NewStringType()) + fields["include_mark_for_delete_objects"] = bindings.NewOptionalType(bindings.NewBooleanType()) + fields["included_fields"] = bindings.NewOptionalType(bindings.NewStringType()) + fields["page_size"] = bindings.NewOptionalType(bindings.NewIntegerType()) + fields["sort_ascending"] = bindings.NewOptionalType(bindings.NewBooleanType()) + fields["sort_by"] = bindings.NewOptionalType(bindings.NewStringType()) + fieldNameMap["attribute_key"] = "AttributeKey" + fieldNameMap["cursor"] = "Cursor" + fieldNameMap["include_mark_for_delete_objects"] = "IncludeMarkForDeleteObjects" + fieldNameMap["included_fields"] = "IncludedFields" + fieldNameMap["page_size"] = "PageSize" + fieldNameMap["sort_ascending"] = "SortAscending" + fieldNameMap["sort_by"] = "SortBy" + paramsTypeMap["attribute_key"] = bindings.NewOptionalType(bindings.NewStringType()) + paramsTypeMap["included_fields"] = bindings.NewOptionalType(bindings.NewStringType()) + paramsTypeMap["page_size"] = bindings.NewOptionalType(bindings.NewIntegerType()) + paramsTypeMap["include_mark_for_delete_objects"] = bindings.NewOptionalType(bindings.NewBooleanType()) + paramsTypeMap["cursor"] = bindings.NewOptionalType(bindings.NewStringType()) + paramsTypeMap["sort_by"] = bindings.NewOptionalType(bindings.NewStringType()) + paramsTypeMap["sort_ascending"] = bindings.NewOptionalType(bindings.NewBooleanType()) + queryParams["cursor"] = "cursor" + queryParams["sort_ascending"] = "sort_ascending" + queryParams["included_fields"] = "included_fields" + queryParams["attribute_key"] = "attribute_key" + queryParams["sort_by"] = "sort_by" + queryParams["include_mark_for_delete_objects"] = "include_mark_for_delete_objects" + queryParams["page_size"] = "page_size" + resultHeaders := map[string]string{} + errorHeaders := map[string]map[string]string{} + return protocol.NewOperationRestMetadata( + fields, + fieldNameMap, + paramsTypeMap, + pathParams, + queryParams, + headerParams, + dispatchHeaderParams, + bodyFieldsMap, + "", + "", + "GET", + "/global-manager/api/v1/global-infra/context-profiles/attributes", + "", + resultHeaders, + 200, + "", + errorHeaders, + map[string]int{"com.vmware.vapi.std.errors.invalid_request": 400,"com.vmware.vapi.std.errors.unauthorized": 403,"com.vmware.vapi.std.errors.service_unavailable": 503,"com.vmware.vapi.std.errors.internal_server_error": 500,"com.vmware.vapi.std.errors.not_found": 404}) +} + + diff --git a/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/global_infra/context_profiles/ContextProfilesPackageTypes.go b/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/global_infra/context_profiles/ContextProfilesPackageTypes.go new file mode 100644 index 000000000..140c724cc --- /dev/null +++ b/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/global_infra/context_profiles/ContextProfilesPackageTypes.go @@ -0,0 +1,19 @@ +/* Copyright © 2019 VMware, Inc. All Rights Reserved. + SPDX-License-Identifier: BSD-2-Clause */ + +// Code generated. DO NOT EDIT. + +/* + * Data type definitions file for package: com.vmware.nsx_global_policy.global_infra.context_profiles. + * Includes binding types of a top level structures and enumerations. + * Shared by client-side stubs and server-side skeletons to ensure type + * compatibility. + */ + +package context_profiles + + + + + + diff --git a/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/global_infra/context_profiles/DefaultAttributesClient.go b/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/global_infra/context_profiles/DefaultAttributesClient.go new file mode 100644 index 000000000..bcaab51d7 --- /dev/null +++ b/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/global_infra/context_profiles/DefaultAttributesClient.go @@ -0,0 +1,183 @@ + +/* Copyright © 2019 VMware, Inc. All Rights Reserved. + SPDX-License-Identifier: BSD-2-Clause */ + +// Code generated. DO NOT EDIT. + +/* + * Client stubs for service: Attributes + * Functions that implement the generated AttributesClient interface + */ + + +package context_profiles + +import ( + "github.com/vmware/vsphere-automation-sdk-go/services/nsxt-gm/model" + "github.com/vmware/vsphere-automation-sdk-go/lib/vapi/std/errors" + "github.com/vmware/vsphere-automation-sdk-go/runtime/bindings" + "github.com/vmware/vsphere-automation-sdk-go/runtime/core" + "github.com/vmware/vsphere-automation-sdk-go/runtime/data" + "github.com/vmware/vsphere-automation-sdk-go/runtime/lib" + "github.com/vmware/vsphere-automation-sdk-go/runtime/log" + "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client" +) + +type DefaultAttributesClient struct { + interfaceName string + interfaceDefinition core.InterfaceDefinition + methodIdentifiers []core.MethodIdentifier + methodNameToDefMap map[string]*core.MethodDefinition + errorBindingMap map[string]bindings.BindingType + interfaceIdentifier core.InterfaceIdentifier + connector client.Connector +} + +func NewDefaultAttributesClient(connector client.Connector) *DefaultAttributesClient { + interfaceName := "com.vmware.nsx_global_policy.global_infra.context_profiles.attributes" + interfaceIdentifier := core.NewInterfaceIdentifier(interfaceName) + methodIdentifiers := []core.MethodIdentifier{ + core.NewMethodIdentifier(interfaceIdentifier, "list"), + } + interfaceDefinition := core.NewInterfaceDefinition(interfaceIdentifier, methodIdentifiers) + errorBindingMap := make(map[string]bindings.BindingType) + errorBindingMap[errors.AlreadyExists{}.Error()] = errors.AlreadyExistsBindingType() + errorBindingMap[errors.AlreadyInDesiredState{}.Error()] = errors.AlreadyInDesiredStateBindingType() + errorBindingMap[errors.Canceled{}.Error()] = errors.CanceledBindingType() + errorBindingMap[errors.ConcurrentChange{}.Error()] = errors.ConcurrentChangeBindingType() + errorBindingMap[errors.Error{}.Error()] = errors.ErrorBindingType() + errorBindingMap[errors.FeatureInUse{}.Error()] = errors.FeatureInUseBindingType() + errorBindingMap[errors.InternalServerError{}.Error()] = errors.InternalServerErrorBindingType() + errorBindingMap[errors.InvalidArgument{}.Error()] = errors.InvalidArgumentBindingType() + errorBindingMap[errors.InvalidElementConfiguration{}.Error()] = errors.InvalidElementConfigurationBindingType() + errorBindingMap[errors.InvalidElementType{}.Error()] = errors.InvalidElementTypeBindingType() + errorBindingMap[errors.InvalidRequest{}.Error()] = errors.InvalidRequestBindingType() + errorBindingMap[errors.NotFound{}.Error()] = errors.NotFoundBindingType() + errorBindingMap[errors.NotAllowedInCurrentState{}.Error()] = errors.NotAllowedInCurrentStateBindingType() + errorBindingMap[errors.OperationNotFound{}.Error()] = errors.OperationNotFoundBindingType() + errorBindingMap[errors.ResourceBusy{}.Error()] = errors.ResourceBusyBindingType() + errorBindingMap[errors.ResourceInUse{}.Error()] = errors.ResourceInUseBindingType() + errorBindingMap[errors.ResourceInaccessible{}.Error()] = errors.ResourceInaccessibleBindingType() + errorBindingMap[errors.ServiceUnavailable{}.Error()] = errors.ServiceUnavailableBindingType() + errorBindingMap[errors.TimedOut{}.Error()] = errors.TimedOutBindingType() + errorBindingMap[errors.UnableToAllocateResource{}.Error()] = errors.UnableToAllocateResourceBindingType() + errorBindingMap[errors.Unauthenticated{}.Error()] = errors.UnauthenticatedBindingType() + errorBindingMap[errors.Unauthorized{}.Error()] = errors.UnauthorizedBindingType() + errorBindingMap[errors.UnexpectedInput{}.Error()] = errors.UnexpectedInputBindingType() + errorBindingMap[errors.Unsupported{}.Error()] = errors.UnsupportedBindingType() + errorBindingMap[errors.UnverifiedPeer{}.Error()] = errors.UnverifiedPeerBindingType() + + + aIface := DefaultAttributesClient{interfaceName: interfaceName, methodIdentifiers: methodIdentifiers, interfaceDefinition: interfaceDefinition, errorBindingMap: errorBindingMap, interfaceIdentifier: interfaceIdentifier, connector: connector} + aIface.methodNameToDefMap = make(map[string]*core.MethodDefinition) + aIface.methodNameToDefMap["list"] = aIface.listMethodDefinition() + return &aIface +} + +func (aIface *DefaultAttributesClient) List(attributeKeyParam *string, cursorParam *string, includeMarkForDeleteObjectsParam *bool, includedFieldsParam *string, pageSizeParam *int64, sortAscendingParam *bool, sortByParam *string) (model.PolicyContextProfileListResult, error) { + typeConverter := aIface.connector.TypeConverter() + methodIdentifier := core.NewMethodIdentifier(aIface.interfaceIdentifier, "list") + sv := bindings.NewStructValueBuilder(attributesListInputType(), typeConverter) + sv.AddStructField("AttributeKey", attributeKeyParam) + sv.AddStructField("Cursor", cursorParam) + sv.AddStructField("IncludeMarkForDeleteObjects", includeMarkForDeleteObjectsParam) + sv.AddStructField("IncludedFields", includedFieldsParam) + sv.AddStructField("PageSize", pageSizeParam) + sv.AddStructField("SortAscending", sortAscendingParam) + sv.AddStructField("SortBy", sortByParam) + inputDataValue, inputError := sv.GetStructValue() + if inputError != nil { + var emptyOutput model.PolicyContextProfileListResult + return emptyOutput, bindings.VAPIerrorsToError(inputError) + } + operationRestMetaData := attributesListRestMetadata() + connectionMetadata := map[string]interface{}{lib.REST_METADATA: operationRestMetaData} + connectionMetadata["isStreamingResponse"] = false + aIface.connector.SetConnectionMetadata(connectionMetadata) + executionContext := aIface.connector.NewExecutionContext() + methodResult := aIface.Invoke(executionContext, methodIdentifier, inputDataValue) + var emptyOutput model.PolicyContextProfileListResult + if methodResult.IsSuccess() { + output, errorInOutput := typeConverter.ConvertToGolang(methodResult.Output(), attributesListOutputType()) + if errorInOutput != nil { + return emptyOutput, bindings.VAPIerrorsToError(errorInOutput) + } + return output.(model.PolicyContextProfileListResult), nil + } else { + methodError, errorInError := typeConverter.ConvertToGolang(methodResult.Error(), aIface.errorBindingMap[methodResult.Error().Name()]) + if errorInError != nil { + return emptyOutput, bindings.VAPIerrorsToError(errorInError) + } + return emptyOutput, methodError.(error) + } +} + + +func (aIface *DefaultAttributesClient) Invoke(ctx *core.ExecutionContext, methodId core.MethodIdentifier, inputDataValue data.DataValue) core.MethodResult { + methodResult := aIface.connector.GetApiProvider().Invoke(aIface.interfaceName, methodId.Name(), inputDataValue, ctx) + return methodResult +} + + +func (aIface *DefaultAttributesClient) listMethodDefinition() *core.MethodDefinition { + interfaceIdentifier := core.NewInterfaceIdentifier(aIface.interfaceName) + typeConverter := aIface.connector.TypeConverter() + + input, inputError := typeConverter.ConvertToDataDefinition(attributesListInputType()) + output, outputError := typeConverter.ConvertToDataDefinition(attributesListOutputType()) + if inputError != nil { + log.Errorf("Error in ConvertToDataDefinition for DefaultAttributesClient.list method's input - %s", + bindings.VAPIerrorsToError(inputError).Error()) + return nil + } + if outputError != nil { + log.Errorf("Error in ConvertToDataDefinition for DefaultAttributesClient.list method's output - %s", + bindings.VAPIerrorsToError(outputError).Error()) + return nil + } + methodIdentifier := core.NewMethodIdentifier(interfaceIdentifier, "list") + errorDefinitions := make([]data.ErrorDefinition, 0) + aIface.errorBindingMap[errors.InvalidRequest{}.Error()] = errors.InvalidRequestBindingType() + errDef1, errError1 := typeConverter.ConvertToDataDefinition(errors.InvalidRequestBindingType()) + if errError1 != nil { + log.Errorf("Error in ConvertToDataDefinition for DefaultAttributesClient.list method's errors.InvalidRequest error - %s", + bindings.VAPIerrorsToError(errError1).Error()) + return nil + } + errorDefinitions = append(errorDefinitions, errDef1.(data.ErrorDefinition)) + aIface.errorBindingMap[errors.Unauthorized{}.Error()] = errors.UnauthorizedBindingType() + errDef2, errError2 := typeConverter.ConvertToDataDefinition(errors.UnauthorizedBindingType()) + if errError2 != nil { + log.Errorf("Error in ConvertToDataDefinition for DefaultAttributesClient.list method's errors.Unauthorized error - %s", + bindings.VAPIerrorsToError(errError2).Error()) + return nil + } + errorDefinitions = append(errorDefinitions, errDef2.(data.ErrorDefinition)) + aIface.errorBindingMap[errors.ServiceUnavailable{}.Error()] = errors.ServiceUnavailableBindingType() + errDef3, errError3 := typeConverter.ConvertToDataDefinition(errors.ServiceUnavailableBindingType()) + if errError3 != nil { + log.Errorf("Error in ConvertToDataDefinition for DefaultAttributesClient.list method's errors.ServiceUnavailable error - %s", + bindings.VAPIerrorsToError(errError3).Error()) + return nil + } + errorDefinitions = append(errorDefinitions, errDef3.(data.ErrorDefinition)) + aIface.errorBindingMap[errors.InternalServerError{}.Error()] = errors.InternalServerErrorBindingType() + errDef4, errError4 := typeConverter.ConvertToDataDefinition(errors.InternalServerErrorBindingType()) + if errError4 != nil { + log.Errorf("Error in ConvertToDataDefinition for DefaultAttributesClient.list method's errors.InternalServerError error - %s", + bindings.VAPIerrorsToError(errError4).Error()) + return nil + } + errorDefinitions = append(errorDefinitions, errDef4.(data.ErrorDefinition)) + aIface.errorBindingMap[errors.NotFound{}.Error()] = errors.NotFoundBindingType() + errDef5, errError5 := typeConverter.ConvertToDataDefinition(errors.NotFoundBindingType()) + if errError5 != nil { + log.Errorf("Error in ConvertToDataDefinition for DefaultAttributesClient.list method's errors.NotFound error - %s", + bindings.VAPIerrorsToError(errError5).Error()) + return nil + } + errorDefinitions = append(errorDefinitions, errDef5.(data.ErrorDefinition)) + + methodDefinition := core.NewMethodDefinition(methodIdentifier, input, output, errorDefinitions) + return &methodDefinition +} diff --git a/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt/infra/context_profiles/AttributesClient.go b/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt/infra/context_profiles/AttributesClient.go new file mode 100644 index 000000000..f03e4d32f --- /dev/null +++ b/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt/infra/context_profiles/AttributesClient.go @@ -0,0 +1,35 @@ +/* Copyright © 2019 VMware, Inc. All Rights Reserved. + SPDX-License-Identifier: BSD-2-Clause */ + +// Code generated. DO NOT EDIT. + +/* + * Interface file for service: Attributes + * Used by client-side stubs. + */ + +package context_profiles + +import ( + "github.com/vmware/vsphere-automation-sdk-go/services/nsxt/model" +) + +type AttributesClient interface { + + // Returns supported attribute and sub-attributes for specified attribute key with their supported values, if provided in query/request parameter, else will fetch all supported attributes and sub-attributes for all supported attribute keys. Alternatively, to get a list of supported attributes and sub-attributes fire the following REST API GET https:///policy/api/v1/infra/context-profiles/attributes + // + // @param attributeKeyParam Fetch attributes and sub-attributes for the given attribute key (optional) + // @param cursorParam Opaque cursor to be used for getting next page of records (supplied by current result page) (optional) + // @param includeMarkForDeleteObjectsParam Include objects that are marked for deletion in results (optional, default to false) + // @param includedFieldsParam Comma separated list of fields that should be included in query result (optional) + // @param pageSizeParam Maximum number of results to return in this page (server may return fewer) (optional, default to 1000) + // @param sortAscendingParam (optional) + // @param sortByParam Field by which records are sorted (optional) + // @return com.vmware.nsx_policy.model.PolicyContextProfileListResult + // @throws InvalidRequest Bad Request, Precondition Failed + // @throws Unauthorized Forbidden + // @throws ServiceUnavailable Service Unavailable + // @throws InternalServerError Internal Server Error + // @throws NotFound Not Found + List(attributeKeyParam *string, cursorParam *string, includeMarkForDeleteObjectsParam *bool, includedFieldsParam *string, pageSizeParam *int64, sortAscendingParam *bool, sortByParam *string) (model.PolicyContextProfileListResult, error) +} diff --git a/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt/infra/context_profiles/AttributesTypes.go b/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt/infra/context_profiles/AttributesTypes.go new file mode 100644 index 000000000..a6aaaa9c1 --- /dev/null +++ b/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt/infra/context_profiles/AttributesTypes.go @@ -0,0 +1,112 @@ +/* Copyright © 2019 VMware, Inc. All Rights Reserved. + SPDX-License-Identifier: BSD-2-Clause */ + +// Code generated. DO NOT EDIT. + +/* + * Data type definitions file for service: Attributes. + * Includes binding types of a structures and enumerations defined in the service. + * Shared by client-side stubs and server-side skeletons to ensure type + * compatibility. + */ + +package context_profiles + +import ( + "reflect" + "github.com/vmware/vsphere-automation-sdk-go/services/nsxt/model" + "github.com/vmware/vsphere-automation-sdk-go/runtime/bindings" + "github.com/vmware/vsphere-automation-sdk-go/runtime/data" + "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol" +) + + + + + +func attributesListInputType() bindings.StructType { + fields := make(map[string]bindings.BindingType) + fieldNameMap := make(map[string]string) + fields["attribute_key"] = bindings.NewOptionalType(bindings.NewStringType()) + fields["cursor"] = bindings.NewOptionalType(bindings.NewStringType()) + fields["include_mark_for_delete_objects"] = bindings.NewOptionalType(bindings.NewBooleanType()) + fields["included_fields"] = bindings.NewOptionalType(bindings.NewStringType()) + fields["page_size"] = bindings.NewOptionalType(bindings.NewIntegerType()) + fields["sort_ascending"] = bindings.NewOptionalType(bindings.NewBooleanType()) + fields["sort_by"] = bindings.NewOptionalType(bindings.NewStringType()) + fieldNameMap["attribute_key"] = "AttributeKey" + fieldNameMap["cursor"] = "Cursor" + fieldNameMap["include_mark_for_delete_objects"] = "IncludeMarkForDeleteObjects" + fieldNameMap["included_fields"] = "IncludedFields" + fieldNameMap["page_size"] = "PageSize" + fieldNameMap["sort_ascending"] = "SortAscending" + fieldNameMap["sort_by"] = "SortBy" + var validators = []bindings.Validator{} + return bindings.NewStructType("operation-input", fields, reflect.TypeOf(data.StructValue{}), fieldNameMap, validators) +} + +func attributesListOutputType() bindings.BindingType { + return bindings.NewReferenceType(model.PolicyContextProfileListResultBindingType) +} + +func attributesListRestMetadata() protocol.OperationRestMetadata { + fields := map[string]bindings.BindingType{} + fieldNameMap := map[string]string{} + paramsTypeMap := map[string]bindings.BindingType{} + pathParams := map[string]string{} + queryParams := map[string]string{} + headerParams := map[string]string{} + dispatchHeaderParams := map[string]string{} + bodyFieldsMap := map[string]string{} + fields["attribute_key"] = bindings.NewOptionalType(bindings.NewStringType()) + fields["cursor"] = bindings.NewOptionalType(bindings.NewStringType()) + fields["include_mark_for_delete_objects"] = bindings.NewOptionalType(bindings.NewBooleanType()) + fields["included_fields"] = bindings.NewOptionalType(bindings.NewStringType()) + fields["page_size"] = bindings.NewOptionalType(bindings.NewIntegerType()) + fields["sort_ascending"] = bindings.NewOptionalType(bindings.NewBooleanType()) + fields["sort_by"] = bindings.NewOptionalType(bindings.NewStringType()) + fieldNameMap["attribute_key"] = "AttributeKey" + fieldNameMap["cursor"] = "Cursor" + fieldNameMap["include_mark_for_delete_objects"] = "IncludeMarkForDeleteObjects" + fieldNameMap["included_fields"] = "IncludedFields" + fieldNameMap["page_size"] = "PageSize" + fieldNameMap["sort_ascending"] = "SortAscending" + fieldNameMap["sort_by"] = "SortBy" + paramsTypeMap["attribute_key"] = bindings.NewOptionalType(bindings.NewStringType()) + paramsTypeMap["included_fields"] = bindings.NewOptionalType(bindings.NewStringType()) + paramsTypeMap["page_size"] = bindings.NewOptionalType(bindings.NewIntegerType()) + paramsTypeMap["include_mark_for_delete_objects"] = bindings.NewOptionalType(bindings.NewBooleanType()) + paramsTypeMap["cursor"] = bindings.NewOptionalType(bindings.NewStringType()) + paramsTypeMap["sort_by"] = bindings.NewOptionalType(bindings.NewStringType()) + paramsTypeMap["sort_ascending"] = bindings.NewOptionalType(bindings.NewBooleanType()) + queryParams["cursor"] = "cursor" + queryParams["sort_ascending"] = "sort_ascending" + queryParams["included_fields"] = "included_fields" + queryParams["attribute_key"] = "attribute_key" + queryParams["sort_by"] = "sort_by" + queryParams["include_mark_for_delete_objects"] = "include_mark_for_delete_objects" + queryParams["page_size"] = "page_size" + resultHeaders := map[string]string{} + errorHeaders := map[string]map[string]string{} + return protocol.NewOperationRestMetadata( + fields, + fieldNameMap, + paramsTypeMap, + pathParams, + queryParams, + headerParams, + dispatchHeaderParams, + bodyFieldsMap, + "", + "", + "GET", + "/policy/api/v1/infra/context-profiles/attributes", + "", + resultHeaders, + 200, + "", + errorHeaders, + map[string]int{"com.vmware.vapi.std.errors.invalid_request": 400,"com.vmware.vapi.std.errors.unauthorized": 403,"com.vmware.vapi.std.errors.service_unavailable": 503,"com.vmware.vapi.std.errors.internal_server_error": 500,"com.vmware.vapi.std.errors.not_found": 404}) +} + + diff --git a/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt/infra/context_profiles/ContextProfilesPackageTypes.go b/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt/infra/context_profiles/ContextProfilesPackageTypes.go new file mode 100644 index 000000000..649b71660 --- /dev/null +++ b/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt/infra/context_profiles/ContextProfilesPackageTypes.go @@ -0,0 +1,19 @@ +/* Copyright © 2019 VMware, Inc. All Rights Reserved. + SPDX-License-Identifier: BSD-2-Clause */ + +// Code generated. DO NOT EDIT. + +/* + * Data type definitions file for package: com.vmware.nsx_policy.infra.context_profiles. + * Includes binding types of a top level structures and enumerations. + * Shared by client-side stubs and server-side skeletons to ensure type + * compatibility. + */ + +package context_profiles + + + + + + diff --git a/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt/infra/context_profiles/DefaultAttributesClient.go b/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt/infra/context_profiles/DefaultAttributesClient.go new file mode 100644 index 000000000..d34877d40 --- /dev/null +++ b/vendor/github.com/vmware/vsphere-automation-sdk-go/services/nsxt/infra/context_profiles/DefaultAttributesClient.go @@ -0,0 +1,183 @@ + +/* Copyright © 2019 VMware, Inc. All Rights Reserved. + SPDX-License-Identifier: BSD-2-Clause */ + +// Code generated. DO NOT EDIT. + +/* + * Client stubs for service: Attributes + * Functions that implement the generated AttributesClient interface + */ + + +package context_profiles + +import ( + "github.com/vmware/vsphere-automation-sdk-go/services/nsxt/model" + "github.com/vmware/vsphere-automation-sdk-go/lib/vapi/std/errors" + "github.com/vmware/vsphere-automation-sdk-go/runtime/bindings" + "github.com/vmware/vsphere-automation-sdk-go/runtime/core" + "github.com/vmware/vsphere-automation-sdk-go/runtime/data" + "github.com/vmware/vsphere-automation-sdk-go/runtime/lib" + "github.com/vmware/vsphere-automation-sdk-go/runtime/log" + "github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client" +) + +type DefaultAttributesClient struct { + interfaceName string + interfaceDefinition core.InterfaceDefinition + methodIdentifiers []core.MethodIdentifier + methodNameToDefMap map[string]*core.MethodDefinition + errorBindingMap map[string]bindings.BindingType + interfaceIdentifier core.InterfaceIdentifier + connector client.Connector +} + +func NewDefaultAttributesClient(connector client.Connector) *DefaultAttributesClient { + interfaceName := "com.vmware.nsx_policy.infra.context_profiles.attributes" + interfaceIdentifier := core.NewInterfaceIdentifier(interfaceName) + methodIdentifiers := []core.MethodIdentifier{ + core.NewMethodIdentifier(interfaceIdentifier, "list"), + } + interfaceDefinition := core.NewInterfaceDefinition(interfaceIdentifier, methodIdentifiers) + errorBindingMap := make(map[string]bindings.BindingType) + errorBindingMap[errors.AlreadyExists{}.Error()] = errors.AlreadyExistsBindingType() + errorBindingMap[errors.AlreadyInDesiredState{}.Error()] = errors.AlreadyInDesiredStateBindingType() + errorBindingMap[errors.Canceled{}.Error()] = errors.CanceledBindingType() + errorBindingMap[errors.ConcurrentChange{}.Error()] = errors.ConcurrentChangeBindingType() + errorBindingMap[errors.Error{}.Error()] = errors.ErrorBindingType() + errorBindingMap[errors.FeatureInUse{}.Error()] = errors.FeatureInUseBindingType() + errorBindingMap[errors.InternalServerError{}.Error()] = errors.InternalServerErrorBindingType() + errorBindingMap[errors.InvalidArgument{}.Error()] = errors.InvalidArgumentBindingType() + errorBindingMap[errors.InvalidElementConfiguration{}.Error()] = errors.InvalidElementConfigurationBindingType() + errorBindingMap[errors.InvalidElementType{}.Error()] = errors.InvalidElementTypeBindingType() + errorBindingMap[errors.InvalidRequest{}.Error()] = errors.InvalidRequestBindingType() + errorBindingMap[errors.NotFound{}.Error()] = errors.NotFoundBindingType() + errorBindingMap[errors.NotAllowedInCurrentState{}.Error()] = errors.NotAllowedInCurrentStateBindingType() + errorBindingMap[errors.OperationNotFound{}.Error()] = errors.OperationNotFoundBindingType() + errorBindingMap[errors.ResourceBusy{}.Error()] = errors.ResourceBusyBindingType() + errorBindingMap[errors.ResourceInUse{}.Error()] = errors.ResourceInUseBindingType() + errorBindingMap[errors.ResourceInaccessible{}.Error()] = errors.ResourceInaccessibleBindingType() + errorBindingMap[errors.ServiceUnavailable{}.Error()] = errors.ServiceUnavailableBindingType() + errorBindingMap[errors.TimedOut{}.Error()] = errors.TimedOutBindingType() + errorBindingMap[errors.UnableToAllocateResource{}.Error()] = errors.UnableToAllocateResourceBindingType() + errorBindingMap[errors.Unauthenticated{}.Error()] = errors.UnauthenticatedBindingType() + errorBindingMap[errors.Unauthorized{}.Error()] = errors.UnauthorizedBindingType() + errorBindingMap[errors.UnexpectedInput{}.Error()] = errors.UnexpectedInputBindingType() + errorBindingMap[errors.Unsupported{}.Error()] = errors.UnsupportedBindingType() + errorBindingMap[errors.UnverifiedPeer{}.Error()] = errors.UnverifiedPeerBindingType() + + + aIface := DefaultAttributesClient{interfaceName: interfaceName, methodIdentifiers: methodIdentifiers, interfaceDefinition: interfaceDefinition, errorBindingMap: errorBindingMap, interfaceIdentifier: interfaceIdentifier, connector: connector} + aIface.methodNameToDefMap = make(map[string]*core.MethodDefinition) + aIface.methodNameToDefMap["list"] = aIface.listMethodDefinition() + return &aIface +} + +func (aIface *DefaultAttributesClient) List(attributeKeyParam *string, cursorParam *string, includeMarkForDeleteObjectsParam *bool, includedFieldsParam *string, pageSizeParam *int64, sortAscendingParam *bool, sortByParam *string) (model.PolicyContextProfileListResult, error) { + typeConverter := aIface.connector.TypeConverter() + methodIdentifier := core.NewMethodIdentifier(aIface.interfaceIdentifier, "list") + sv := bindings.NewStructValueBuilder(attributesListInputType(), typeConverter) + sv.AddStructField("AttributeKey", attributeKeyParam) + sv.AddStructField("Cursor", cursorParam) + sv.AddStructField("IncludeMarkForDeleteObjects", includeMarkForDeleteObjectsParam) + sv.AddStructField("IncludedFields", includedFieldsParam) + sv.AddStructField("PageSize", pageSizeParam) + sv.AddStructField("SortAscending", sortAscendingParam) + sv.AddStructField("SortBy", sortByParam) + inputDataValue, inputError := sv.GetStructValue() + if inputError != nil { + var emptyOutput model.PolicyContextProfileListResult + return emptyOutput, bindings.VAPIerrorsToError(inputError) + } + operationRestMetaData := attributesListRestMetadata() + connectionMetadata := map[string]interface{}{lib.REST_METADATA: operationRestMetaData} + connectionMetadata["isStreamingResponse"] = false + aIface.connector.SetConnectionMetadata(connectionMetadata) + executionContext := aIface.connector.NewExecutionContext() + methodResult := aIface.Invoke(executionContext, methodIdentifier, inputDataValue) + var emptyOutput model.PolicyContextProfileListResult + if methodResult.IsSuccess() { + output, errorInOutput := typeConverter.ConvertToGolang(methodResult.Output(), attributesListOutputType()) + if errorInOutput != nil { + return emptyOutput, bindings.VAPIerrorsToError(errorInOutput) + } + return output.(model.PolicyContextProfileListResult), nil + } else { + methodError, errorInError := typeConverter.ConvertToGolang(methodResult.Error(), aIface.errorBindingMap[methodResult.Error().Name()]) + if errorInError != nil { + return emptyOutput, bindings.VAPIerrorsToError(errorInError) + } + return emptyOutput, methodError.(error) + } +} + + +func (aIface *DefaultAttributesClient) Invoke(ctx *core.ExecutionContext, methodId core.MethodIdentifier, inputDataValue data.DataValue) core.MethodResult { + methodResult := aIface.connector.GetApiProvider().Invoke(aIface.interfaceName, methodId.Name(), inputDataValue, ctx) + return methodResult +} + + +func (aIface *DefaultAttributesClient) listMethodDefinition() *core.MethodDefinition { + interfaceIdentifier := core.NewInterfaceIdentifier(aIface.interfaceName) + typeConverter := aIface.connector.TypeConverter() + + input, inputError := typeConverter.ConvertToDataDefinition(attributesListInputType()) + output, outputError := typeConverter.ConvertToDataDefinition(attributesListOutputType()) + if inputError != nil { + log.Errorf("Error in ConvertToDataDefinition for DefaultAttributesClient.list method's input - %s", + bindings.VAPIerrorsToError(inputError).Error()) + return nil + } + if outputError != nil { + log.Errorf("Error in ConvertToDataDefinition for DefaultAttributesClient.list method's output - %s", + bindings.VAPIerrorsToError(outputError).Error()) + return nil + } + methodIdentifier := core.NewMethodIdentifier(interfaceIdentifier, "list") + errorDefinitions := make([]data.ErrorDefinition, 0) + aIface.errorBindingMap[errors.InvalidRequest{}.Error()] = errors.InvalidRequestBindingType() + errDef1, errError1 := typeConverter.ConvertToDataDefinition(errors.InvalidRequestBindingType()) + if errError1 != nil { + log.Errorf("Error in ConvertToDataDefinition for DefaultAttributesClient.list method's errors.InvalidRequest error - %s", + bindings.VAPIerrorsToError(errError1).Error()) + return nil + } + errorDefinitions = append(errorDefinitions, errDef1.(data.ErrorDefinition)) + aIface.errorBindingMap[errors.Unauthorized{}.Error()] = errors.UnauthorizedBindingType() + errDef2, errError2 := typeConverter.ConvertToDataDefinition(errors.UnauthorizedBindingType()) + if errError2 != nil { + log.Errorf("Error in ConvertToDataDefinition for DefaultAttributesClient.list method's errors.Unauthorized error - %s", + bindings.VAPIerrorsToError(errError2).Error()) + return nil + } + errorDefinitions = append(errorDefinitions, errDef2.(data.ErrorDefinition)) + aIface.errorBindingMap[errors.ServiceUnavailable{}.Error()] = errors.ServiceUnavailableBindingType() + errDef3, errError3 := typeConverter.ConvertToDataDefinition(errors.ServiceUnavailableBindingType()) + if errError3 != nil { + log.Errorf("Error in ConvertToDataDefinition for DefaultAttributesClient.list method's errors.ServiceUnavailable error - %s", + bindings.VAPIerrorsToError(errError3).Error()) + return nil + } + errorDefinitions = append(errorDefinitions, errDef3.(data.ErrorDefinition)) + aIface.errorBindingMap[errors.InternalServerError{}.Error()] = errors.InternalServerErrorBindingType() + errDef4, errError4 := typeConverter.ConvertToDataDefinition(errors.InternalServerErrorBindingType()) + if errError4 != nil { + log.Errorf("Error in ConvertToDataDefinition for DefaultAttributesClient.list method's errors.InternalServerError error - %s", + bindings.VAPIerrorsToError(errError4).Error()) + return nil + } + errorDefinitions = append(errorDefinitions, errDef4.(data.ErrorDefinition)) + aIface.errorBindingMap[errors.NotFound{}.Error()] = errors.NotFoundBindingType() + errDef5, errError5 := typeConverter.ConvertToDataDefinition(errors.NotFoundBindingType()) + if errError5 != nil { + log.Errorf("Error in ConvertToDataDefinition for DefaultAttributesClient.list method's errors.NotFound error - %s", + bindings.VAPIerrorsToError(errError5).Error()) + return nil + } + errorDefinitions = append(errorDefinitions, errDef5.(data.ErrorDefinition)) + + methodDefinition := core.NewMethodDefinition(methodIdentifier, input, output, errorDefinitions) + return &methodDefinition +} diff --git a/website/docs/r/policy_context_profile.html.markdown b/website/docs/r/policy_context_profile.html.markdown new file mode 100644 index 000000000..ce2e88013 --- /dev/null +++ b/website/docs/r/policy_context_profile.html.markdown @@ -0,0 +1,76 @@ +--- +layout: "nsxt" +page_title: "NSXT: nsxt_policy_context_profile" +sidebar_current: "docs-nsxt-resource-policy-context-profile" +description: A resource to configure a Context Profile. +--- + +# nsxt_policy_context_profile + +This resource provides a method for the management of a Context Profile. + +## Example Usage + +```hcl +resource "nsxt_policy_context_profile" "test" { + display_name = "test" + description = "Terraform provisioned ContextProfile" + domain_name { + description = "test-domain-name-attribute" + value = ["*-myfiles.sharepoint.com"] + } + app_id { + description = "test-app-id-attribute" + value = ["SSL"] + sub_attribute { + tls_version = ["SSL_V3"] + } + } +} + +``` + +## Argument Reference + +The following arguments are supported: +Note: At least one of `app_id`, `domain_name`, or `url_category` must present. + +* `display_name` - (Required) Display name of the resource. +* `description` - (Optional) Description of the resource. +* `tag` - (Optional) A list of scope + tag pairs to associate with this resource. +* `nsx_id` - (Optional) The NSX ID of this resource. If set, this ID will be used to create the resource. +* `app_id` - (Optional) A block to specify app id attributes for the context profile. Only one block is allowed. + * `description` - (Optional) Description of the attribute. + * `value` - (Required) A list of string indicating values for the `app_id`. Must be a subset of valid values for `app_id` on NSX. + * `sub_attribute` - (Optional) A block to specify sub attribute for the `app_id`. Only one block is allowed. + * `tls_cipher_suite` - (Optional) A list of string indicating values for `tls_cipher_suite`, only applicable to `SSL`. + * `tls_version` - (Optional) A list of string indicating values for `tls_version`, only applicable to `SSL`. + * `cifs_smb_version` - (Optional) A list of string indicating values for `cifs_smb_version`, only applicable to `CIFS`. +* `domain_name` - (Optional) A block to specify domain name (FQDN) attributes for the context profile. Only one block is allowed. + * `description` - (Optional) Description of the attribute. + * `value` - (Required) A list of string indicating values for the `domain_name`. Must be a subset of valid values for `domain_name` on NSX. +* `url_category` - (Optional) A block to specify url category attributes for the context profile. Only one block is allowed. + * `description` - (Optional) Description of the attribute. + * `value` - (Required) A list of string indicating values for the `url_category`. Must be a subset of valid values for `url_category` on NSX. + +## Attributes Reference + +In addition to arguments listed above, the following attributes are exported: + +* `id` - ID of the resource. +* `revision` - Indicates current revision number of the object as seen by NSX-T API server. This attribute can be useful for debugging. +* `path` - The NSX path of the policy resource. +* `app_id`: + * `is_alg_type` - Describes whether the APP_ID value is ALG type or not. + +## Importing + +An existing Context Profile can be [imported][docs-import] into this resource, via the following command: + +[docs-import]: /docs/import/index.html + +``` +terraform import nsxt_policy_context_profile.test UUID +``` + +The above command imports Context Profile named `test` with the NSX Context Profile ID `UUID`.