Skip to content

Commit

Permalink
Feat: add support for agent settings (#323)
Browse files Browse the repository at this point in the history
  • Loading branch information
TomerHeber committed Apr 10, 2022
1 parent a5b9ad5 commit 6209d6a
Show file tree
Hide file tree
Showing 7 changed files with 248 additions and 6 deletions.
43 changes: 43 additions & 0 deletions client/agent_project_assignment.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package client

// Key is project id.
// Value is agent id.
type AssignProjectsAgentsAssignmentsPayload map[string]interface{}

type ProjectsAgentsAssignments struct {
DefaultAgent string `json:"defaultAgent"`
ProjectsAgents map[string]interface{} `json:"ProjectsAgents"`
}

func (client *ApiClient) AssignAgentsToProjects(payload AssignProjectsAgentsAssignmentsPayload) (*ProjectsAgentsAssignments, error) {
organizationId, err := client.organizationId()
if err != nil {
return nil, err
}

var result ProjectsAgentsAssignments
if err := client.http.Post("/agents/projects-assignments?organizationId="+organizationId, payload, &result); err != nil {
return nil, err
}

return &result, nil
}

func (client *ApiClient) ProjectsAgentsAssignments() (*ProjectsAgentsAssignments, error) {
organizationId, err := client.organizationId()
if err != nil {
return nil, err
}

var result ProjectsAgentsAssignments
err = client.http.Get("/agents/projects-assignments", map[string]string{"organizationId": organizationId}, &result)
if err != nil {
return nil, err
}

return &result, nil
}

/*
*/
141 changes: 141 additions & 0 deletions client/agent_project_assignment_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
package client_test

import (
"errors"

. "github.com/env0/terraform-provider-env0/client"
"github.com/golang/mock/gomock"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)

// mockOrganizationIdCall(organizationId)

var _ = Describe("Agent Project Assignment", func() {
psas := map[string]interface{}{
"pid1": "aid1",
"pid2": "aid2",
}

expectedResponse := ProjectsAgentsAssignments{
ProjectsAgents: psas,
}

errorMock := errors.New("error")

Describe("AssignAgentsToProjects", func() {

Describe("Successful", func() {
var actualResult *ProjectsAgentsAssignments
var err error

BeforeEach(func() {
mockOrganizationIdCall(organizationId)

httpCall = mockHttpClient.EXPECT().
Post("/agents/projects-assignments?organizationId="+organizationId, gomock.Any(), gomock.Any()).
Do(func(path string, request interface{}, response *ProjectsAgentsAssignments) {
*response = expectedResponse
}).Times(1)
actualResult, err = apiClient.AssignAgentsToProjects(psas)

})

It("Should get organization id", func() {
organizationIdCall.Times(1)
})

It("Should send POST request with params", func() {
httpCall.Times(1)
})

It("should return the POST result", func() {
Expect(*actualResult).To(Equal(expectedResponse))
})

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

Describe("Failure", func() {
var actualResult *ProjectsAgentsAssignments
var err error

BeforeEach(func() {
mockOrganizationIdCall(organizationId)

httpCall = mockHttpClient.EXPECT().
Post("/agents/projects-assignments?organizationId="+organizationId, gomock.Any(), gomock.Any()).
Return(errorMock)

actualResult, err = apiClient.AssignAgentsToProjects(psas)
})

It("Should fail if API call fails", func() {
Expect(err).To(Equal(errorMock))
})

It("Should not return results", func() {
Expect(actualResult).To(BeNil())
})
})
})

Describe("ProjectsAgentsAssignments", func() {
Describe("Successful", func() {
var actualResult *ProjectsAgentsAssignments
var err error

BeforeEach(func() {
mockOrganizationIdCall(organizationId)

httpCall = mockHttpClient.EXPECT().
Get("/agents/projects-assignments", gomock.Any(), gomock.Any()).
Do(func(path string, request interface{}, response *ProjectsAgentsAssignments) {
*response = expectedResponse
})
actualResult, err = apiClient.ProjectsAgentsAssignments()
})

It("Should get organization id", func() {
organizationIdCall.Times(1)
})

It("Should send GET request with params", func() {
httpCall.Times(1)
})

It("Should return the GET result", func() {
Expect(*actualResult).To(Equal(expectedResponse))
})

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

Describe("Failure", func() {
var actualResult *ProjectsAgentsAssignments
var err error

BeforeEach(func() {
mockOrganizationIdCall(organizationId)

httpCall = mockHttpClient.EXPECT().
Get("/agents/projects-assignments", gomock.Any(), gomock.Any()).
Return(errorMock)

actualResult, err = apiClient.ProjectsAgentsAssignments()
})

It("Should fail if API call fails", func() {
Expect(err).To(Equal(errorMock))
})

It("Should not return results", func() {
Expect(actualResult).To(BeNil())
})
})
})
})
2 changes: 2 additions & 0 deletions client/api_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ type ApiClientInterface interface {
ApiKeyCreate(payload ApiKeyCreatePayload) (*ApiKey, error)
ApiKeyDelete(id string) error
ApiKeys() ([]ApiKey, error)
AssignAgentsToProjects(payload AssignProjectsAgentsAssignmentsPayload) (*ProjectsAgentsAssignments, error)
ProjectsAgentsAssignments() (*ProjectsAgentsAssignments, error)
}

func NewApiClient(client http.HttpClientInterface) ApiClientInterface {
Expand Down
30 changes: 30 additions & 0 deletions client/api_client_mock.go

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

1 change: 1 addition & 0 deletions client/configuration_variable.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ func (client *ApiClient) ConfigurationVariablesByScope(scope Scope, scopeId stri
if err != nil {
return []ConfigurationVariable{}, err
}

return result, nil
}

Expand Down
18 changes: 15 additions & 3 deletions env0/resource_environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,14 @@ import (
"fmt"
"log"
"regexp"
"time"

"github.com/env0/terraform-provider-env0/client"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

const deploymentStatusWaitPollInterval = 10 // In seconds
//const deploymentStatusWaitPollInterval = 10 // In seconds

func resourceEnvironment() *schema.Resource {
return &schema.Resource{
Expand Down Expand Up @@ -299,6 +298,7 @@ func resourceEnvironmentRead(ctx context.Context, d *schema.ResourceData, meta i
if err != nil {
return diag.Errorf("could not get environment configuration variables: %v", err)
}
environmentConfigurationVariables = filterOutGlobalScope(environmentConfigurationVariables)
setEnvironmentSchema(d, environment, environmentConfigurationVariables)

return nil
Expand Down Expand Up @@ -555,6 +555,7 @@ func getUpdateConfigurationVariables(configurationChanges client.ConfigurationCh
if err != nil {
diag.Errorf("could not get environment configuration variables: %v", err)
}
existVariables = filterOutGlobalScope(existVariables)
configurationChanges = linkToExistConfigurationVariables(configurationChanges, existVariables)
configurationChanges = deleteUnusedConfigurationVariables(configurationChanges, existVariables)
return configurationChanges
Expand Down Expand Up @@ -704,6 +705,7 @@ func resourceEnvironmentImport(ctx context.Context, d *schema.ResourceData, meta
if err != nil {
return nil, fmt.Errorf("could not get environment configuration variables: %v", err)
}
environmentConfigurationVariables = filterOutGlobalScope(environmentConfigurationVariables)
d.Set("deployment_id", environment.LatestDeploymentLogId)
setEnvironmentSchema(d, environment, environmentConfigurationVariables)

Expand All @@ -730,7 +732,7 @@ func waitForDeployment(deploymentLogId string, apiClient client.ApiClientInterfa
"QUEUED",
"WAITING_FOR_USER":
log.Println("[INFO] Deployment not yet done deploying. Got status ", deployment.Status)
time.Sleep(deploymentStatusWaitPollInterval * time.Second)
//time.Sleep(deploymentStatusWaitPollInterval * time.Second)
case "SUCCESS",
"SKIPPED":
log.Println("[INFO] Deployment done deploying! Got status ", deployment.Status)
Expand All @@ -740,3 +742,13 @@ func waitForDeployment(deploymentLogId string, apiClient client.ApiClientInterfa
}
}
}

func filterOutGlobalScope(variables []client.ConfigurationVariable) []client.ConfigurationVariable {
filteredVariables := []client.ConfigurationVariable{}
for _, variable := range variables {
if variable.Scope != client.ScopeGlobal {
filteredVariables = append(filteredVariables, variable)
}
}
return filteredVariables
}
19 changes: 16 additions & 3 deletions env0/resource_environment_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,14 @@ func TestUnitEnvironmentResource(t *testing.T) {
Name: "my env var",
Type: &varType,
Schema: &varSchema,
Scope: client.ScopeEnvironment,
}
formatVariables := func(variables []client.ConfigurationVariable) string {
format := ""
for _, variable := range variables {
if variable.Scope == client.ScopeGlobal {
continue
}
schemaFormat := ""
if variable.Schema != nil {
if variable.Schema.Enum != nil {
Expand Down Expand Up @@ -203,6 +207,13 @@ func TestUnitEnvironmentResource(t *testing.T) {

environmentResource := formatResourceWithConfiguration(environment, client.ConfigurationChanges{configurationVariables})
newVarType := client.ConfigurationVariableTypeTerraform
globalConfigurationVariables := client.ConfigurationVariable{
Value: "1111",
Name: "2222",
Type: &varType,
Schema: &varSchema,
Scope: client.ScopeGlobal,
}
redeployConfigurationVariables := client.ConfigurationChanges{client.ConfigurationVariable{
Value: "configurationVariables.Value",
Name: configurationVariables.Name,
Expand All @@ -211,7 +222,9 @@ func TestUnitEnvironmentResource(t *testing.T) {
Type: "string",
Format: client.Text,
},
}}
Scope: client.ScopeEnvironment,
}, globalConfigurationVariables}

updatedEnvironmentResource := formatResourceWithConfiguration(updatedEnvironment, redeployConfigurationVariables)
testCase := resource.TestCase{
Steps: []resource.TestStep{
Expand Down Expand Up @@ -269,8 +282,8 @@ func TestUnitEnvironmentResource(t *testing.T) {
varTrue := true
configurationVariables.ToDelete = &varTrue
gomock.InOrder(
mock.EXPECT().ConfigurationVariablesByScope(client.ScopeEnvironment, updatedEnvironment.Id).Times(3).Return(client.ConfigurationChanges{configurationVariables}, nil), // read after create -> on update
mock.EXPECT().ConfigurationVariablesByScope(client.ScopeEnvironment, updatedEnvironment.Id).Times(1).Return(redeployConfigurationVariables, nil), // read after create -> on update -> read after update
mock.EXPECT().ConfigurationVariablesByScope(client.ScopeEnvironment, updatedEnvironment.Id).Times(3).Return(client.ConfigurationChanges{configurationVariables, globalConfigurationVariables}, nil), // read after create -> on update
mock.EXPECT().ConfigurationVariablesByScope(client.ScopeEnvironment, updatedEnvironment.Id).Times(1).Return(redeployConfigurationVariables, nil), // read after create -> on update -> read after update
)
redeployConfigurationVariables[0].Scope = client.ScopeDeployment
redeployConfigurationVariables[0].IsSensitive = &isSensitive
Expand Down

0 comments on commit 6209d6a

Please sign in to comment.