Skip to content

Commit

Permalink
changes based on PR comments
Browse files Browse the repository at this point in the history
  • Loading branch information
TomerHeber committed Sep 3, 2024
1 parent cf80383 commit fe03ea6
Show file tree
Hide file tree
Showing 11 changed files with 172 additions and 68 deletions.
3 changes: 2 additions & 1 deletion client/api_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ type ApiClientInterface interface {
Environment(id string) (Environment, error)
EnvironmentCreate(payload EnvironmentCreate) (Environment, error)
EnvironmentCreateWithoutTemplate(payload EnvironmentCreateWithoutTemplate) (Environment, error)
EnvironmentDestroy(id string) (Environment, error)
EnvironmentDestroy(id string) (*EnvironmentDestroyResponse, error)
EnvironmentMarkAsArchived(id string) error
EnvironmentUpdate(id string, payload EnvironmentUpdate) (Environment, error)
EnvironmentDeploy(id string, payload DeployRequest) (EnvironmentDeployResponse, error)
Expand All @@ -75,6 +75,7 @@ type ApiClientInterface interface {
EnvironmentScheduling(environmentId string) (EnvironmentScheduling, error)
EnvironmentSchedulingUpdate(environmentId string, payload EnvironmentScheduling) (EnvironmentScheduling, error)
EnvironmentSchedulingDelete(environmentId string) error
EnvironmentDeployment(id string) (*DeploymentLog, error)
WorkflowTrigger(environmentId string) ([]WorkflowTrigger, error)
WorkflowTriggerUpsert(environmentId string, request WorkflowTriggerUpsertPayload) ([]WorkflowTrigger, error)
EnvironmentDriftDetection(environmentId string) (EnvironmentSchedulingExpression, error)
Expand Down
19 changes: 17 additions & 2 deletions client/api_client_mock.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 21 additions & 5 deletions client/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

const ENVIRONMENT = "environment"

type ConfigurationVariableType int

func (c *ConfigurationVariableType) ReadResourceData(fieldName string, d *schema.ResourceData) error {
Expand All @@ -27,7 +29,7 @@ func (c *ConfigurationVariableType) WriteResourceData(fieldName string, d *schem

switch val := *c; val {
case 0:
valStr = "environment"
valStr = ENVIRONMENT
case 1:
valStr = TERRAFORM
default:
Expand Down Expand Up @@ -91,6 +93,7 @@ type DeploymentLog struct {
Output json.RawMessage `json:"output,omitempty"`
Error json.RawMessage `json:"error,omitempty"`
Type string `json:"type"`
Status string `json:"status"`
WorkflowFile *WorkflowFile `json:"workflowFile,omitempty" tfschema:"-"`
}

Expand Down Expand Up @@ -163,6 +166,10 @@ type EnvironmentMoveRequest struct {
ProjectId string `json:"projectId"`
}

type EnvironmentDestroyResponse struct {
Id string `json:"id"`
}

func GetConfigurationVariableType(variableType string) (ConfigurationVariableType, error) {
switch variableType {
case "terraform":
Expand Down Expand Up @@ -256,6 +263,15 @@ func (client *ApiClient) Environment(id string) (Environment, error) {
return result, nil
}

func (client *ApiClient) EnvironmentDeployment(id string) (*DeploymentLog, error) {
var result DeploymentLog
err := client.http.Get("/environments/deployments/"+id, nil, &result)
if err != nil {
return nil, err
}
return &result, nil
}

func (client *ApiClient) EnvironmentCreate(payload EnvironmentCreate) (Environment, error) {
var result Environment

Expand Down Expand Up @@ -283,13 +299,13 @@ func (client *ApiClient) EnvironmentCreateWithoutTemplate(payload EnvironmentCre
return result, nil
}

func (client *ApiClient) EnvironmentDestroy(id string) (Environment, error) {
var result Environment
func (client *ApiClient) EnvironmentDestroy(id string) (*EnvironmentDestroyResponse, error) {
var result EnvironmentDestroyResponse
err := client.http.Post("/environments/"+id+"/destroy", nil, &result)
if err != nil {
return Environment{}, err
return nil, err
}
return result, nil
return &result, nil
}

func (client *ApiClient) EnvironmentUpdate(id string, payload EnvironmentUpdate) (Environment, error) {
Expand Down
45 changes: 43 additions & 2 deletions client/environment_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"testing"

"github.com/env0/terraform-provider-env0/client"
. "github.com/env0/terraform-provider-env0/client"
"github.com/jinzhu/copier"
. "github.com/onsi/ginkgo"
Expand Down Expand Up @@ -280,15 +281,27 @@ var _ = Describe("Environment Client", func() {

Describe("EnvironmentDelete", func() {
var err error
var res *client.EnvironmentDestroyResponse

mockedRes := client.EnvironmentDestroyResponse{
Id: "id123",
}

BeforeEach(func() {
httpCall = mockHttpClient.EXPECT().Post("/environments/"+mockEnvironment.Id+"/destroy", nil, gomock.Any()).Times(1)
_, err = apiClient.EnvironmentDestroy(mockEnvironment.Id)
httpCall = mockHttpClient.EXPECT().Post("/environments/"+mockEnvironment.Id+"/destroy", nil, gomock.Any()).Times(1).
Do((func(path string, request interface{}, response *EnvironmentDestroyResponse) {
*response = mockedRes
}))
res, err = apiClient.EnvironmentDestroy(mockEnvironment.Id)
})

It("Should not return error", func() {
Expect(err).To(BeNil())
})

It("Should return the expected response", func() {
Expect(*res).To(Equal(mockedRes))
})
})

Describe("EnvironmentMarkAsArchived", func() {
Expand Down Expand Up @@ -438,6 +451,34 @@ var _ = Describe("Environment Client", func() {
Expect(err).To(BeNil())
})
})

Describe("EnvironmentDeployment", func() {
var deployment *DeploymentLog
var err error

mockDeployment := DeploymentLog{
Id: "id12345",
Status: "IN_PROGRESS",
}

BeforeEach(func() {
httpCall = mockHttpClient.EXPECT().
Get("/environments/deployments/"+mockDeployment.Id, nil, gomock.Any()).
Do(func(path string, request interface{}, response *DeploymentLog) {
*response = mockDeployment
}).Times(1)

deployment, err = apiClient.EnvironmentDeployment(mockDeployment.Id)
})

It("Should return deployment", func() {
Expect(*deployment).To(Equal(mockDeployment))
})

It("Should not return an error", func() {
Expect(err).To(BeNil())
})
})
})

func TestMarshalEnvironmentCreateWithoutTemplate(t *testing.T) {
Expand Down
14 changes: 12 additions & 2 deletions env0/data_configuration_variable.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,37 +198,47 @@ func getConfigurationVariable(params ConfigurationVariableParams, meta interface
name, nameOk := params.Name, params.Name != ""
typeString, ok := params.ConfigurationType, params.ConfigurationType != ""
type_ := -1

if ok {
if !nameOk {
return client.ConfigurationVariable{}, diag.Errorf("Specify 'type' only when searching configuration variables by 'name' (not by 'id')")
}

switch typeString {
case "environment":
case client.ENVIRONMENT:
type_ = int(client.ConfigurationVariableTypeEnvironment)
case "terraform":
case client.TERRAFORM:
type_ = int(client.ConfigurationVariableTypeTerraform)
default:
return client.ConfigurationVariable{}, diag.Errorf("Invalid value for 'type': %s. can be either 'environment' or 'terraform'", typeString)
}
}

var variable client.ConfigurationVariable

for _, candidate := range variables {
if idOk && candidate.Id == id {
variable = candidate

break
}

if nameOk && candidate.Name == name {
if type_ != -1 {
if int(*candidate.Type) != type_ {
continue
}
}

variable = candidate

break
}
}

if variable.Id == "" {
return client.ConfigurationVariable{}, diag.Errorf("Could not find variable")
}

return variable, nil
}
1 change: 1 addition & 0 deletions env0/data_git_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ func dataGitToken() *schema.Resource {

func dataGitTokenRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var gitToken *client.GitToken

var err error

id, ok := d.GetOk("id")
Expand Down
1 change: 1 addition & 0 deletions env0/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ func ResourceGetFailure(ctx context.Context, resourceName string, d *schema.Reso
if driftDetected(err) {
tflog.Warn(ctx, "Drift Detected: Terraform will remove id from state", map[string]interface{}{"id": d.Id()})
d.SetId("")

return nil
}

Expand Down
6 changes: 6 additions & 0 deletions env0/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,29 +193,34 @@ func configureProvider(version string, p *schema.Provider) schema.ConfigureConte
if r != nil {
tflog.SubsystemInfo(subCtx, "env0_api_client", "Sending request", map[string]interface{}{"method": r.Method, "url": r.URL})
}

return nil
}).
OnAfterResponse(func(c *resty.Client, r *resty.Response) error {
tflog.SubsystemInfo(subCtx, "env0_api_client", "Received response", map[string]interface{}{"method": r.Request.Method, "url": r.Request.URL, "status": r.Status()})

return nil
}).
AddRetryAfterErrorCondition().
AddRetryCondition(func(r *resty.Response, err error) bool {
if r == nil {
// No response. Possibly a networking issue (E.g. DNS lookup failure).
tflog.SubsystemWarn(subCtx, "env0_api_client", "No response, retrying request")

return true
}

// When running integration tests 404 may occur due to "database eventual consistency".
// Retry when there's a 5xx error. Otherwise do not retry.
if r.StatusCode() >= 500 || (isIntegrationTest && r.StatusCode() == 404) {
tflog.SubsystemWarn(subCtx, "env0_api_client", "Received a failed or not found response, retrying request", map[string]interface{}{"method": r.Request.Method, "url": r.Request.URL, "status code": r.StatusCode()})

return true
}

if r.StatusCode() == 200 && isIntegrationTest && r.String() == "[]" {
tflog.SubsystemWarn(subCtx, "env0_api_client", "Received an empty list , retrying request", map[string]interface{}{"method": r.Request.Method, "url": r.Request.URL})

return true
}

Expand Down Expand Up @@ -249,6 +254,7 @@ func configureProvider(version string, p *schema.Provider) schema.ConfigureConte
if _, err := apiClient.OrganizationId(); err != nil {
return nil, diag.Diagnostics{diag.Diagnostic{Severity: diag.Error, Summary: err.Error()}}
}

return apiClient, nil
}
}
Loading

0 comments on commit fe03ea6

Please sign in to comment.