Skip to content

Commit 18e6e5a

Browse files
authored
Add LDAP identity source resource (#1010)
Add LDAP identity source resource This change adds policy LDAP identity source resource. Both ActiveDirectoryIdentitySource and OpenLdapIdentitySource type LDAP are supported. The two resources have different resource type on NSX API, but shares the same attributes. Signed-off-by: Shawn Wang <[email protected]>
1 parent 29d383f commit 18e6e5a

6 files changed

+689
-0
lines changed

nsxt/provider.go

+1
Original file line numberDiff line numberDiff line change
@@ -420,6 +420,7 @@ func Provider() *schema.Provider {
420420
"nsxt_policy_transport_zone": resourceNsxtPolicyTransportZone(),
421421
"nsxt_policy_user_management_role": resourceNsxtPolicyUserManagementRole(),
422422
"nsxt_policy_user_management_role_binding": resourceNsxtPolicyUserManagementRoleBinding(),
423+
"nsxt_policy_ldap_identity_source": resourceNsxtPolicyLdapIdentitySource(),
423424
"nsxt_edge_cluster": resourceNsxtEdgeCluster(),
424425
"nsxt_compute_manager": resourceNsxtComputeManager(),
425426
"nsxt_manager_cluster": resourceNsxtManagerCluster(),
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,356 @@
1+
/* Copyright © 2023 VMware, Inc. All Rights Reserved.
2+
SPDX-License-Identifier: MPL-2.0 */
3+
4+
package nsxt
5+
6+
import (
7+
"fmt"
8+
"log"
9+
"strings"
10+
11+
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
12+
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
13+
"github.com/vmware/vsphere-automation-sdk-go/runtime/bindings"
14+
"github.com/vmware/vsphere-automation-sdk-go/runtime/data"
15+
"github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client"
16+
"github.com/vmware/vsphere-automation-sdk-go/services/nsxt/aaa"
17+
nsxModel "github.com/vmware/vsphere-automation-sdk-go/services/nsxt/model"
18+
)
19+
20+
const (
21+
activeDirectoryType = "ActiveDirectory"
22+
openLdapType = "OpenLdap"
23+
)
24+
25+
var ldapServerTypes = []string{activeDirectoryType, openLdapType}
26+
27+
func resourceNsxtPolicyLdapIdentitySource() *schema.Resource {
28+
return &schema.Resource{
29+
Create: resourceNsxtPolicyLdapIdentitySourceCreate,
30+
Read: resourceNsxtPolicyLdapIdentitySourceRead,
31+
Update: resourceNsxtPolicyLdapIdentitySourceUpdate,
32+
Delete: resourceNsxtPolicyLdapIdentitySourceDelete,
33+
Importer: &schema.ResourceImporter{
34+
State: schema.ImportStatePassthrough,
35+
},
36+
37+
Schema: map[string]*schema.Schema{
38+
"nsx_id": getNsxIDSchema(),
39+
"display_name": getDataSourceDisplayNameSchema(),
40+
"description": getDataSourceDescriptionSchema(),
41+
"revision": getRevisionSchema(),
42+
"tag": getTagsSchema(),
43+
"type": {
44+
Type: schema.TypeString,
45+
Description: "Indicates the type of LDAP server",
46+
Required: true,
47+
ValidateFunc: validation.StringInSlice(ldapServerTypes, false),
48+
ForceNew: true,
49+
},
50+
"domain_name": {
51+
Type: schema.TypeString,
52+
Description: "Authentication domain name",
53+
Required: true,
54+
},
55+
"base_dn": {
56+
Type: schema.TypeString,
57+
Description: "DN of subtree for user and group searches",
58+
Required: true,
59+
},
60+
"alternative_domain_names": {
61+
Type: schema.TypeList,
62+
Description: "Additional domains to be directed to this identity source",
63+
Optional: true,
64+
Elem: &schema.Schema{
65+
Type: schema.TypeString,
66+
},
67+
},
68+
"ldap_server": {
69+
Type: schema.TypeList,
70+
Description: "LDAP servers for this identity source",
71+
Required: true,
72+
MaxItems: 1,
73+
Elem: &schema.Resource{
74+
Schema: map[string]*schema.Schema{
75+
"bind_identity": {
76+
Type: schema.TypeString,
77+
Description: "Username or DN for LDAP authentication",
78+
Optional: true,
79+
},
80+
"certificates": {
81+
Type: schema.TypeList,
82+
Description: "TLS certificate(s) for LDAP server(s)",
83+
Optional: true,
84+
Elem: &schema.Schema{
85+
Type: schema.TypeString,
86+
},
87+
},
88+
"enabled": {
89+
Type: schema.TypeBool,
90+
Description: "If true, this LDAP server is enabled",
91+
Optional: true,
92+
Default: true,
93+
},
94+
"password": {
95+
Type: schema.TypeString,
96+
Description: "The authentication password for login",
97+
Optional: true,
98+
Sensitive: true,
99+
},
100+
"url": {
101+
Type: schema.TypeString,
102+
Description: "The URL for the LDAP server",
103+
Required: true,
104+
ValidateFunc: validateLdapOrLdapsURL(),
105+
},
106+
"use_starttls": {
107+
Type: schema.TypeBool,
108+
Description: "Enable/disable StartTLS",
109+
Optional: true,
110+
Default: false,
111+
},
112+
},
113+
},
114+
},
115+
},
116+
}
117+
}
118+
119+
func getLdapServersFromSchema(d *schema.ResourceData) []nsxModel.IdentitySourceLdapServer {
120+
servers := d.Get("ldap_server").([]interface{})
121+
serverList := make([]nsxModel.IdentitySourceLdapServer, 0)
122+
for _, server := range servers {
123+
data := server.(map[string]interface{})
124+
bindIdentity := data["bind_identity"].(string)
125+
certificates := interface2StringList(data["certificates"].([]interface{}))
126+
enabled := data["enabled"].(bool)
127+
password := data["password"].(string)
128+
url := data["url"].(string)
129+
useStarttls := data["use_starttls"].(bool)
130+
elem := nsxModel.IdentitySourceLdapServer{
131+
BindIdentity: &bindIdentity,
132+
Certificates: certificates,
133+
Enabled: &enabled,
134+
Password: &password,
135+
Url: &url,
136+
UseStarttls: &useStarttls,
137+
}
138+
139+
serverList = append(serverList, elem)
140+
}
141+
return serverList
142+
}
143+
144+
// getLdapServerPasswordMap caches password of ldap servers for setting back to schema after read
145+
func getLdapServerPasswordMap(d *schema.ResourceData) map[string]string {
146+
passwordMap := make(map[string]string)
147+
servers := d.Get("ldap_server").([]interface{})
148+
for _, server := range servers {
149+
data := server.(map[string]interface{})
150+
password := data["password"].(string)
151+
url := data["url"].(string)
152+
passwordMap[url] = password
153+
}
154+
155+
return passwordMap
156+
}
157+
158+
func setLdapServersInSchema(d *schema.ResourceData, nsxLdapServerList []nsxModel.IdentitySourceLdapServer, passwordMap map[string]string) {
159+
var ldapServerList []map[string]interface{}
160+
for _, ldapServer := range nsxLdapServerList {
161+
elem := make(map[string]interface{})
162+
elem["bind_identity"] = ldapServer.BindIdentity
163+
elem["certificates"] = ldapServer.Certificates
164+
elem["enabled"] = ldapServer.Enabled
165+
elem["url"] = ldapServer.Url
166+
elem["use_starttls"] = ldapServer.UseStarttls
167+
if val, ok := passwordMap[*ldapServer.Url]; ok {
168+
elem["password"] = val
169+
}
170+
ldapServerList = append(ldapServerList, elem)
171+
}
172+
err := d.Set("ldap_server", ldapServerList)
173+
if err != nil {
174+
log.Printf("[WARNING] Failed to set ldap_server in schema: %v", err)
175+
}
176+
}
177+
178+
func resourceNsxtPolicyLdapIdentitySourceExists(id string, connector client.Connector, isGlobalManager bool) (bool, error) {
179+
var err error
180+
181+
ldapClient := aaa.NewLdapIdentitySourcesClient(connector)
182+
_, err = ldapClient.Get(id)
183+
if err == nil {
184+
return true, nil
185+
}
186+
if isNotFoundError(err) {
187+
return false, nil
188+
}
189+
190+
return false, logAPIError("Error retrieving resource", err)
191+
}
192+
193+
func resourceNsxtPolicyLdapIdentitySourceProbeAndUpdate(d *schema.ResourceData, m interface{}, id string) error {
194+
connector := getPolicyConnector(m)
195+
ldapClient := aaa.NewLdapIdentitySourcesClient(connector)
196+
converter := bindings.NewTypeConverter()
197+
serverType := d.Get("type").(string)
198+
199+
displayName := d.Get("display_name").(string)
200+
description := d.Get("description").(string)
201+
revision := int64(d.Get("revision").(int))
202+
tags := getPolicyTagsFromSchema(d)
203+
domainName := d.Get("domain_name").(string)
204+
baseDn := d.Get("base_dn").(string)
205+
altDomainNames := getStringListFromSchemaList(d, "alternative_domain_names")
206+
ldapServers := getLdapServersFromSchema(d)
207+
208+
var dataValue data.DataValue
209+
var errs []error
210+
if serverType == activeDirectoryType {
211+
obj := nsxModel.ActiveDirectoryIdentitySource{
212+
DisplayName: &displayName,
213+
Description: &description,
214+
Revision: &revision,
215+
Tags: tags,
216+
DomainName: &domainName,
217+
BaseDn: &baseDn,
218+
AlternativeDomainNames: altDomainNames,
219+
LdapServers: ldapServers,
220+
ResourceType: nsxModel.LdapIdentitySource_RESOURCE_TYPE_ACTIVEDIRECTORYIDENTITYSOURCE,
221+
}
222+
dataValue, errs = converter.ConvertToVapi(obj, nsxModel.ActiveDirectoryIdentitySourceBindingType())
223+
} else if serverType == openLdapType {
224+
obj := nsxModel.OpenLdapIdentitySource{
225+
DisplayName: &displayName,
226+
Description: &description,
227+
Revision: &revision,
228+
Tags: tags,
229+
DomainName: &domainName,
230+
BaseDn: &baseDn,
231+
AlternativeDomainNames: altDomainNames,
232+
LdapServers: ldapServers,
233+
ResourceType: nsxModel.LdapIdentitySource_RESOURCE_TYPE_OPENLDAPIDENTITYSOURCE,
234+
}
235+
dataValue, errs = converter.ConvertToVapi(obj, nsxModel.OpenLdapIdentitySourceBindingType())
236+
}
237+
if errs != nil {
238+
return errs[0]
239+
}
240+
structValue := dataValue.(*data.StructValue)
241+
242+
log.Printf("[INFO] Probing LDAP Identity Source with ID %s", id)
243+
probeResult, err := ldapClient.Probeidentitysource(structValue)
244+
if err != nil {
245+
return logAPIError("Error probing LDAP Identity Source", err)
246+
}
247+
for _, result := range probeResult.Results {
248+
if result.Result != nil && *result.Result != nsxModel.IdentitySourceLdapServerProbeResult_RESULT_SUCCESS {
249+
probeErrs := make([]string, 0)
250+
for _, probeErr := range result.Errors {
251+
if probeErr.ErrorType != nil {
252+
probeErrs = append(probeErrs, *probeErr.ErrorType)
253+
}
254+
}
255+
return fmt.Errorf("LDAP Identity Source server %s probe failed with errors: %s",
256+
*result.Url, strings.Join(probeErrs, ","))
257+
}
258+
}
259+
260+
log.Printf("[INFO] PUT LDAP Identity Source with ID %s", id)
261+
if _, err = ldapClient.Update(id, structValue); err != nil {
262+
return handleUpdateError(serverType, id, err)
263+
}
264+
265+
return nil
266+
}
267+
268+
func resourceNsxtPolicyLdapIdentitySourceCreate(d *schema.ResourceData, m interface{}) error {
269+
// Initialize resource Id and verify this ID is not yet used
270+
id, err := getOrGenerateID(d, m, resourceNsxtPolicyLdapIdentitySourceExists)
271+
if err != nil {
272+
return err
273+
}
274+
275+
if err := resourceNsxtPolicyLdapIdentitySourceProbeAndUpdate(d, m, id); err != nil {
276+
return err
277+
}
278+
d.SetId(id)
279+
d.Set("nsx_id", id)
280+
281+
return resourceNsxtPolicyLdapIdentitySourceRead(d, m)
282+
}
283+
284+
func resourceNsxtPolicyLdapIdentitySourceRead(d *schema.ResourceData, m interface{}) error {
285+
connector := getPolicyConnector(m)
286+
converter := bindings.NewTypeConverter()
287+
288+
id := d.Id()
289+
if id == "" {
290+
return fmt.Errorf("error obtaining LDAPIdentitySource ID")
291+
}
292+
293+
ldapClient := aaa.NewLdapIdentitySourcesClient(connector)
294+
structObj, err := ldapClient.Get(id)
295+
if err != nil {
296+
return handleReadError(d, "LDAPIdentitySource", id, err)
297+
}
298+
299+
obj, errs := converter.ConvertToGolang(structObj, nsxModel.LdapIdentitySourceBindingType())
300+
if errs != nil {
301+
return errs[0]
302+
}
303+
304+
ldapObj := obj.(nsxModel.LdapIdentitySource)
305+
resourceType := ldapObj.ResourceType
306+
var dServerType string
307+
if resourceType == nsxModel.LdapIdentitySource_RESOURCE_TYPE_ACTIVEDIRECTORYIDENTITYSOURCE {
308+
dServerType = activeDirectoryType
309+
} else if resourceType == nsxModel.LdapIdentitySource_RESOURCE_TYPE_OPENLDAPIDENTITYSOURCE {
310+
dServerType = openLdapType
311+
} else {
312+
return fmt.Errorf("unrecognized LdapIdentitySource Resource Type %s", resourceType)
313+
}
314+
315+
passwordMap := getLdapServerPasswordMap(d)
316+
317+
d.Set("nsx_id", id)
318+
d.Set("display_name", ldapObj.DisplayName)
319+
d.Set("description", ldapObj.Description)
320+
d.Set("revision", ldapObj.Revision)
321+
setPolicyTagsInSchema(d, ldapObj.Tags)
322+
d.Set("type", dServerType)
323+
d.Set("domain_name", ldapObj.DomainName)
324+
d.Set("base_dn", ldapObj.BaseDn)
325+
d.Set("alternative_domain_names", ldapObj.AlternativeDomainNames)
326+
setLdapServersInSchema(d, ldapObj.LdapServers, passwordMap)
327+
return nil
328+
}
329+
330+
func resourceNsxtPolicyLdapIdentitySourceUpdate(d *schema.ResourceData, m interface{}) error {
331+
id := d.Id()
332+
if id == "" {
333+
return fmt.Errorf("rrror obtaining LDAPIdentitySource ID")
334+
}
335+
336+
if err := resourceNsxtPolicyLdapIdentitySourceProbeAndUpdate(d, m, id); err != nil {
337+
return handleUpdateError("LDAPIdentitySource", id, err)
338+
}
339+
340+
return resourceNsxtPolicyLdapIdentitySourceRead(d, m)
341+
}
342+
343+
func resourceNsxtPolicyLdapIdentitySourceDelete(d *schema.ResourceData, m interface{}) error {
344+
id := d.Id()
345+
if id == "" {
346+
return fmt.Errorf("error obtaining LDAPIdentitySource ID")
347+
}
348+
349+
connector := getPolicyConnector(m)
350+
ldapClient := aaa.NewLdapIdentitySourcesClient(connector)
351+
if err := ldapClient.Delete(id); err != nil {
352+
return handleDeleteError("LDAPIdentitySource", id, err)
353+
}
354+
355+
return nil
356+
}

0 commit comments

Comments
 (0)