Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
…into feat_cloud_cost_credentials-#218
  • Loading branch information
samuel-br committed Apr 13, 2022
2 parents db4b8ea + bc8b0c4 commit bd47d76
Show file tree
Hide file tree
Showing 13 changed files with 308 additions and 7 deletions.
19 changes: 16 additions & 3 deletions .goreleaser.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ checksum:
signs:
- artifacts: checksum
args:
# if you are using this in a GitHub action or some other automated pipeline, you
# if you are using this in a GitHub action or some other automated pipeline, you
# need to pass the batch flag to indicate its not interactive.
- "--batch"
- "--local-user"
Expand All @@ -47,8 +47,21 @@ signs:
- "${signature}"
- "--detach-sign"
- "${artifact}"
changelog:
skip: false
use: github
groups:
- title: Features
order: 0
regexp: "^.*[Ff]eat.*$"
- title: Bug Fixes
order: 1
regexp: "^.*[Ff]ix.*$"
- title: Others
order: 999
filters:
exclude:
- "^.*Update docs.*$"
release:
# If you want to manually examine the release before its live, uncomment this line:
# draft: true
changelog:
skip: true
19 changes: 17 additions & 2 deletions client/agent_project_assignment.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ type ProjectsAgentsAssignments struct {
ProjectsAgents map[string]interface{} `json:"ProjectsAgents"`
}

type Agent struct {
AgentKey string `json:"agentKey"`
}

func (client *ApiClient) AssignAgentsToProjects(payload AssignProjectsAgentsAssignmentsPayload) (*ProjectsAgentsAssignments, error) {
organizationId, err := client.organizationId()
if err != nil {
Expand Down Expand Up @@ -38,6 +42,17 @@ func (client *ApiClient) ProjectsAgentsAssignments() (*ProjectsAgentsAssignments
return &result, nil
}

/*
func (client *ApiClient) Agents() ([]Agent, error) {
organizationId, err := client.organizationId()
if err != nil {
return nil, err
}

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

return result, nil
}
65 changes: 63 additions & 2 deletions client/agent_project_assignment_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import (
. "github.com/onsi/gomega"
)

// mockOrganizationIdCall(organizationId)

var _ = Describe("Agent Project Assignment", func() {
psas := map[string]interface{}{
"pid1": "aid1",
Expand Down Expand Up @@ -138,4 +136,67 @@ var _ = Describe("Agent Project Assignment", func() {
})
})
})

Describe("Agents", func() {
mockAgent := Agent{
AgentKey: "key",
}

expectedResponse := []Agent{mockAgent}

Describe("Successful", func() {
var actualResult []Agent
var err error

BeforeEach(func() {
mockOrganizationIdCall(organizationId)

httpCall = mockHttpClient.EXPECT().
Get("/agents", gomock.Any(), gomock.Any()).
Do(func(path string, request interface{}, response *[]Agent) {
*response = expectedResponse
})
actualResult, err = apiClient.Agents()
})

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 []Agent
var err error

BeforeEach(func() {
mockOrganizationIdCall(organizationId)

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

actualResult, err = apiClient.Agents()
})

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

It("Should not return results", func() {
Expect(actualResult).To(BeNil())
})
})
})
})
1 change: 1 addition & 0 deletions client/api_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ type ApiClientInterface interface {
ApiKeys() ([]ApiKey, error)
AssignAgentsToProjects(payload AssignProjectsAgentsAssignmentsPayload) (*ProjectsAgentsAssignments, error)
ProjectsAgentsAssignments() (*ProjectsAgentsAssignments, error)
Agents() ([]Agent, error)
}

func NewApiClient(client http.HttpClientInterface) ApiClientInterface {
Expand Down
15 changes: 15 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.

33 changes: 33 additions & 0 deletions docs/data-sources/agents.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "env0_agents Data Source - terraform-provider-env0"
subcategory: ""
description: |-
---

# env0_agents (Data Source)





<!-- schema generated by tfplugindocs -->
## Schema

### Optional

- **id** (String) The ID of this resource.

### Read-Only

- **agents** (List of Object) list of organization agents (see [below for nested schema](#nestedatt--agents))

<a id="nestedatt--agents"></a>
### Nested Schema for `agents`

Read-Only:

- **agent_key** (String)


20 changes: 20 additions & 0 deletions docs/resources/agent_project_assignment.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,21 @@ description: |-



## Example Usage

```terraform
resource "env0_project" "example" {
name = "example"
description = "Example project"
}
data "env0_agents" "agents" {}
resource "env0_agent_project_assignment" {
agent_id = data.env0_agents.agents.0.agent_key
project_id = env0_project.example.id
}
```

<!-- schema generated by tfplugindocs -->
## Schema
Expand All @@ -24,4 +38,10 @@ description: |-

- **id** (String) The ID of this resource.

## Import

Import is supported using the following syntax:

```shell
terraform import env0_agent_project_assigment.example agent-id_project-id
```
54 changes: 54 additions & 0 deletions env0/data_agents.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package env0

import (
"context"

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

func dataAgents() *schema.Resource {
return &schema.Resource{
ReadContext: agentsRead,

Schema: map[string]*schema.Schema{
"agents": {
Type: schema.TypeList,
Description: "list of organization agents",
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"agent_key": {
Type: schema.TypeString,
Description: "agent key identifier",
Required: true,
},
},
},
},
},
}
}

func agentsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
apiClient := meta.(client.ApiClientInterface)

agents, err := apiClient.Agents()
if err != nil {
return diag.Errorf("could not read agents: %v", err)
}

data := struct {
Agents []client.Agent
}{agents}

if err := writeResourceData(&data, d); err != nil {
return diag.Errorf("schema resource data serialization failed: %v", err)
}

// Not really needed. But required by Terraform SDK - https://github.com/hashicorp/terraform-plugin-sdk/issues/541
d.SetId("1")

return nil
}
67 changes: 67 additions & 0 deletions env0/data_agents_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package env0

import (
"errors"
"regexp"
"testing"

"github.com/env0/terraform-provider-env0/client"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func TestAgentsDataSource(t *testing.T) {
agent1 := client.Agent{
AgentKey: "akey1",
}

agent2 := client.Agent{
AgentKey: "akey2",
}

resourceType := "env0_agents"
resourceName := "test_agents"
accessor := dataSourceAccessor(resourceType, resourceName)

getTestCase := func() resource.TestCase {
return resource.TestCase{
Steps: []resource.TestStep{
{
Config: dataSourceConfigCreate(resourceType, resourceName, map[string]interface{}{}),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr(accessor, "agents.0.agent_key", agent1.AgentKey),
resource.TestCheckResourceAttr(accessor, "agents.1.agent_key", agent2.AgentKey),
),
},
},
}
}

mockAgents := func(returnValue []client.Agent) func(mockFunc *client.MockApiClientInterface) {
return func(mock *client.MockApiClientInterface) {
mock.EXPECT().Agents().AnyTimes().Return(returnValue, nil)
}
}

t.Run("Success", func(t *testing.T) {
runUnitTest(t,
getTestCase(),
mockAgents([]client.Agent{agent1, agent2}),
)
})

t.Run("API Call Error", func(t *testing.T) {
runUnitTest(t,
resource.TestCase{
Steps: []resource.TestStep{
{
Config: dataSourceConfigCreate(resourceType, resourceName, map[string]interface{}{}),
ExpectError: regexp.MustCompile("error"),
},
},
},
func(mock *client.MockApiClientInterface) {
mock.EXPECT().Agents().AnyTimes().Return(nil, errors.New("error"))
},
)
})
}
1 change: 1 addition & 0 deletions env0/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ func Provider(version string) plugin.ProviderFunc {
"env0_module": dataModule(),
"env0_git_token": dataGitToken(),
"env0_api_key": dataApiKey(),
"env0_agents": dataAgents(),
},
ResourcesMap: map[string]*schema.Resource{
"env0_project": resourceProject(),
Expand Down
9 changes: 9 additions & 0 deletions env0/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,15 @@ func writeResourceData(i interface{}, d *schema.ResourceData) error {
if err := d.Set(fieldNameSC, rawSshKeys); err != nil {
return err
}
case reflect.TypeOf([]client.Agent{}):
var agents []map[string]string
for i := 0; i < field.Len(); i++ {
agent := field.Index(i).Interface().(client.Agent)
agents = append(agents, map[string]string{"agent_key": agent.AgentKey})
}
if err := d.Set(fieldNameSC, agents); err != nil {
return err
}
case reflect.TypeOf([]string{}):
var strs []interface{}
for i := 0; i < field.Len(); i++ {
Expand Down
1 change: 1 addition & 0 deletions examples/resources/env0_agent_project_assignment/import.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
terraform import env0_agent_project_assigment.example agent-id_project-id
11 changes: 11 additions & 0 deletions examples/resources/env0_agent_project_assignment/resource.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
resource "env0_project" "example" {
name = "example"
description = "Example project"
}

data "env0_agents" "agents" {}

resource "env0_agent_project_assignment" {
agent_id = data.env0_agents.agents.0.agent_key
project_id = env0_project.example.id
}

0 comments on commit bd47d76

Please sign in to comment.