Skip to content

Commit a859289

Browse files
Use the ServerVersion() instead of creating a whole new request
1 parent 0c2e812 commit a859289

File tree

1 file changed

+11
-30
lines changed

1 file changed

+11
-30
lines changed

internal/elasticsearch/security/api_key.go

Lines changed: 11 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package security
33
import (
44
"context"
55
"encoding/json"
6-
"github.com/elastic/go-elasticsearch/v7/esapi"
76
"regexp"
87
"strings"
98

@@ -136,10 +135,12 @@ func resourceSecurityApiKeyCreate(ctx context.Context, d *schema.ResourceData, m
136135
}
137136

138137
if hasRestriction {
139-
isSupported, err := doesCurrentVersionSupportRestrictionOnApiKey(ctx, client, keysWithRestrictions)
140-
if err != nil {
141-
return diag.FromErr(err)
138+
isSupported, diags := doesCurrentVersionSupportRestrictionOnApiKey(ctx, client)
139+
140+
if diags.HasError() {
141+
return diags
142142
}
143+
143144
if !isSupported {
144145
return diag.Errorf("Specifying `restriction` on an API key role description is not supported in this version of Elasticsearch. Role descriptor(s) %s", strings.Join(keysWithRestrictions, ", "))
145146
}
@@ -187,34 +188,14 @@ func resourceSecurityApiKeyCreate(ctx context.Context, d *schema.ResourceData, m
187188
return resourceSecurityApiKeyRead(ctx, d, meta)
188189
}
189190

190-
func doesCurrentVersionSupportRestrictionOnApiKey(ctx context.Context, client *clients.ApiClient, keysWithRestrictions []string) (isSupported bool, err error) {
191-
if esClient, err := client.GetESClient(); err == nil {
192-
req := esapi.InfoRequest{}
193-
res, err := req.Do(ctx, esClient.Transport)
194-
if err != nil {
195-
return false, err
196-
}
197-
198-
defer res.Body.Close()
199-
200-
var info info
201-
err = json.NewDecoder(res.Body).Decode(&info)
202-
if err != nil {
203-
return false, err
204-
}
191+
func doesCurrentVersionSupportRestrictionOnApiKey(ctx context.Context, client *clients.ApiClient) (bool, diag.Diagnostics) {
192+
currentVersion, diags := client.ServerVersion(ctx)
205193

206-
currentVersion, err := version.NewVersion(info.Version.Number)
207-
if err != nil {
208-
return false, err
209-
}
210-
211-
supportedVersion, _ := version.NewVersion("8.9.0") // restriction is supported since 8.9.x
212-
213-
if currentVersion.LessThan(supportedVersion) {
214-
return false, err
215-
}
194+
if diags.HasError() {
195+
return false, diags
216196
}
217-
return true, nil
197+
198+
return currentVersion.GreaterThanOrEqual(APIKeyWithRestrictionMinVersion), nil
218199
}
219200

220201
func resourceSecurityApiKeyUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {

0 commit comments

Comments
 (0)