Skip to content

Commit

Permalink
add request string logging to be able to get more information (#155)
Browse files Browse the repository at this point in the history
* add request string logging to be able to get more information

* add ability to import accesstier by name
  • Loading branch information
nareshkakubal authored Feb 21, 2024
1 parent d258936 commit 2c21015
Show file tree
Hide file tree
Showing 8 changed files with 93 additions and 22 deletions.
26 changes: 25 additions & 1 deletion banyan/resource_accesstier.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"reflect"
"strings"
"time"

"github.com/banyansecurity/terraform-banyan-provider/client"
Expand All @@ -23,11 +24,34 @@ func resourceAccessTier() *schema.Resource {
DeleteContext: resourceAccessTierDelete,
Schema: AccessTierSchema(),
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
StateContext: resourceImporter,
},
}
}

func resourceImporter(ctx context.Context, data *schema.ResourceData, i interface{}) ([]*schema.ResourceData, error) {
inID := data.Id()
parts := strings.Split(inID, ":")
if len(parts) == 1 {
data.SetId(inID)
return []*schema.ResourceData{data}, nil
}
if len(parts) != 2 || strings.ToLower(parts[0]) != "name" {
return nil, fmt.Errorf("invalid ID (%s), expected name:<name of access tier to import>", parts)
}
name := parts[1]
accessTierClient, ok := i.(*client.Holder)
if !ok {
return nil, fmt.Errorf("error occured during import %s", inID)
}
accessTierInfo, err := accessTierClient.AccessTier.GetName(name)
if err != nil {
return nil, err
}
data.SetId(accessTierInfo.ID)
return []*schema.ResourceData{data}, nil
}

func AccessTierSchema() map[string]*schema.Schema {
s := map[string]*schema.Schema{
"name": {
Expand Down
1 change: 1 addition & 0 deletions banyan/resource_accesstier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ func TestAccAccessTier_required(t *testing.T) {
},
{
ResourceName: "banyan_accesstier.example",
ImportStateId: fmt.Sprintf("name:%s", rName),
ImportState: true,
ImportStateVerify: true,
},
Expand Down
24 changes: 21 additions & 3 deletions client/accesstier/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,34 @@ func (a *AccessTier) GetName(name string) (spec AccessTierInfo, err error) {
if err != nil {
return
}
var j ATResponse
type ats struct {
AccessTiers []AccessTierInfo `json:"access_tiers,omitempty"`
Count int `json:"count"`
}
j := struct {
RequestId string `json:"request_id"`
ErrorCode int `json:"error_code"`
ErrorDescription string `json:"error_description"`
Data ats `json:"data"`
}{}
err = json.Unmarshal(resp, &j)
if err != nil {
return
}
if j.Count == 0 {
if j.Data.Count == 0 {
err = fmt.Errorf("access tier with name %s not found", name)
return
}
return j.Data, nil
for _, accessTier := range j.Data.AccessTiers {
if accessTier.Name == name {
spec = accessTier
break
}
}
if spec.Name == "" {
err = fmt.Errorf("access tier with name %s not found in results %+v", name, j.Data.AccessTiers)
}
return
}

func (a *AccessTier) Create(spec AccessTierPost) (created AccessTierInfo, err error) {
Expand Down
4 changes: 1 addition & 3 deletions client/policyattachment/policyattachment.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@ func NewClient(restClient *restclient.Client) Client {
return &PolicyAttachmentClient
}

const component = "policyattachment"

// Client is used to perform CRUD operations against the policy attachment resource
type Client interface {
Get(attachedToID string, attachedToType string) (attachment GetBody, err error)
Expand Down Expand Up @@ -136,7 +134,7 @@ func (p *PolicyAttachment) Create(policyID string, PolicyAttachment CreateBody)
if err != nil {
return
}
data, err := restclient.HandleResponse(response, component)
data, err := restclient.HandleResponse(response)
if err != nil {
return
}
Expand Down
34 changes: 20 additions & 14 deletions client/restclient/restclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,22 +128,24 @@ func (c *Client) Read(api string, component string, id string, path string) (res
}
response, err := c.DoGet(myUrl.String())
if err != nil {
err = fmt.Errorf("request to %s %s failed %w", response.Request.Method, response.Request.URL.String(), err)
return
}
return HandleResponse(response, myUrl.String())
return HandleResponse(response)
}

func (c *Client) ReadQuery(component string, query url.Values, path string) (r []byte, err error) {
func (c *Client) ReadQuery(_ string, query url.Values, path string) (r []byte, err error) {
myUrl, err := url.Parse(path)
if err != nil {
return
}
myUrl.RawQuery = query.Encode()
response, err := c.DoGet(myUrl.String())
if err != nil {
err = fmt.Errorf("request to %s %s failed %w", response.Request.Method, response.Request.URL.String(), err)
return
}
return HandleResponse(response, myUrl.String())
return HandleResponse(response)
}

func (c *Client) Create(api string, component string, body []byte, path string) (r []byte, err error) {
Expand All @@ -152,13 +154,15 @@ func (c *Client) Create(api string, component string, body []byte, path string)
}
request, err := c.NewRequest(http.MethodPost, path, bytes.NewBuffer(body))
if err != nil {
err = fmt.Errorf("request formation failed for %s %s %w", request.Method, request.URL.String(), err)
return
}
response, err := c.Do(request)
if err != nil {
err = fmt.Errorf("request to %s %s failed %w", request.Method, request.URL.String(), err)
return
}
return HandleResponse(response, path)
return HandleResponse(response)
}

func (c *Client) Update(api string, component string, id string, body []byte, path string) (r []byte, err error) {
Expand All @@ -167,14 +171,16 @@ func (c *Client) Update(api string, component string, id string, body []byte, pa
}
request, err := c.NewRequest(http.MethodPut, path, bytes.NewBuffer(body))
if err != nil {
err = fmt.Errorf("request formation failed for %s %s %w", request.Method, request.URL.String(), err)
return
}
response, err := c.Do(request)
if err != nil {
err = fmt.Errorf("request to %s %s failed %w", request.Method, request.URL.String(), err)
return
}

return HandleResponse(response, path)
return HandleResponse(response)
}

func (c *Client) Delete(api string, component string, id string, path string) (err error) {
Expand All @@ -191,10 +197,11 @@ func (c *Client) Delete(api string, component string, id string, path string) (e
}
response, err := c.DoDelete(myUrl.String())
if err != nil {
err = fmt.Errorf("request to %s %s failed %w", response.Request.Method, response.Request.URL.String(), err)
return
}

_, err = HandleResponse(response, myUrl.String())
_, err = HandleResponse(response)
return
}

Expand All @@ -210,14 +217,16 @@ func (c *Client) DeleteQuery(component string, id string, query url.Values, path
myUrl.RawQuery = query.Encode()
response, err := c.DoDelete(myUrl.String())
if err != nil {
err = fmt.Errorf("request to %s %s failed %w", response.Request.Method, response.Request.URL.String(), err)
return
}
_, err = HandleResponse(response, myUrl.String())
_, err = HandleResponse(response)
return
}

func HandleResponse(response *http.Response, requestStr string) (responseData []byte, err error) {
func HandleResponse(response *http.Response) (responseData []byte, err error) {
defer response.Body.Close()
requestStr := fmt.Sprintf("%s %s", response.Request.Method, response.Request.URL.String())
responseData, err = io.ReadAll(response.Body)
if err != nil {
return
Expand All @@ -232,12 +241,9 @@ func HandleResponse(response *http.Response, requestStr string) (responseData []
}
if response.StatusCode != 200 {
var errResp ErrorResponse
if err != nil {
return
}
uerr := json.Unmarshal(responseData, &errResp)
if uerr == nil {
err = fmt.Errorf("recieved error code %d: %s \n response: \n %s", response.StatusCode, requestStr, responseData)
err = json.Unmarshal(responseData, &errResp)
if err == nil {
err = fmt.Errorf("received error code %d: %s \n response: \n %s", response.StatusCode, requestStr, responseData)
}
return
}
Expand Down
2 changes: 1 addition & 1 deletion client/shield/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func (s *Shield) GetAll() (shields []string, err error) {
if err != nil {
return
}
responseData, err := restclient.HandleResponse(response, myUrl.String())
responseData, err := restclient.HandleResponse(response)
if err != nil {
return
}
Expand Down
12 changes: 12 additions & 0 deletions docs/resources/accesstier.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,13 @@ Import is supported using the following syntax:
terraform import banyan_accesstier.myexample 46f3a708-2a9a-4c87-b18e-b11b6c92bf24

terraform show

# or import via accesstier name
terraform import banyan_accesstier.myexample name:myexample

terraform show


# update thw show output configuration into above main.tf file, then resource is managed.
# BE CAUTIOUS before terraform apply, do terraform plan and verify there are no changes to be applied.

Expand All @@ -137,6 +144,11 @@ terraform show
# to = banyan_accesstier.myexample
# id = "46f3a708-2a9a-4c87-b18e-b11b6c92bf24"
# }
# or import via access_tier name
# import {
# to = banyan_accesstier.myexample
# id = "name:myexample"
# }
# Then execute
terraform plan -generate-config-out=generated.tf
# Configurations are imported into generated.tf edit and verify
Expand Down
12 changes: 12 additions & 0 deletions examples/resources/banyan_accesstier/import.sh
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@
terraform import banyan_accesstier.myexample 46f3a708-2a9a-4c87-b18e-b11b6c92bf24

terraform show

# or import via accesstier name
terraform import banyan_accesstier.myexample name:myexample

terraform show


# update thw show output configuration into above main.tf file, then resource is managed.
# BE CAUTIOUS before terraform apply, do terraform plan and verify there are no changes to be applied.

Expand All @@ -20,6 +27,11 @@ terraform show
# to = banyan_accesstier.myexample
# id = "46f3a708-2a9a-4c87-b18e-b11b6c92bf24"
# }
# or import via access_tier name
# import {
# to = banyan_accesstier.myexample
# id = "name:myexample"
# }
# Then execute
terraform plan -generate-config-out=generated.tf
# Configurations are imported into generated.tf edit and verify
Expand Down

0 comments on commit 2c21015

Please sign in to comment.