Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: add data source for getting a list of Cloud Credentials #375

Merged
merged 2 commits into from
May 16, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions env0/data_cloud_credentials.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package env0

import (
"context"
"fmt"
"strings"

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

var allowedCredentialTypes = []string{
"AWS_ASSUMED_ROLE",
"AWS_ASSUMED_ROLE_FOR_DEPLOYMENT",
"AWS_ACCESS_KEYS_FOR_DEPLOYMENT",
"GCP_CREDENTIALS",
"GCP_SERVICE_ACCOUNT_FOR_DEPLOYMENT",
"AZURE_CREDENTIALS",
"AZURE_SERVICE_PRINCIPAL_FOR_DEPLOYMENT",
}

func dataCloudCredentials() *schema.Resource {
allowedCredentialTypesStr := fmt.Sprintf("(allowed values: %s)", strings.Join(allowedCredentialTypes, ", "))

return &schema.Resource{
ReadContext: dataCloudCredentialsRead,

Schema: map[string]*schema.Schema{
"names": {
Type: schema.TypeList,
Description: "list of all cloud credentials (by name), optionaly filtered by credential_type",
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
Description: "the credential name",
},
},
"credential_type": {
Type: schema.TypeString,
Description: "the type of cloud credential to filter by " + allowedCredentialTypesStr,
Optional: true,
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

setting to optional incases where someone (for some reason) wants to get all the credentials regardless of type.

ValidateDiagFunc: NewStringInValidator(allowedCredentialTypes),
},
},
}
}

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

credentialsList, err := apiClient.CloudCredentialsList()
if err != nil {
return diag.Errorf("Could not get cloud credentials list: %v", err)
}

credential_type, filter := d.GetOk("credential_type")

data := []string{}

for _, credentials := range credentialsList {
if filter && credential_type != credentials.Type {
continue
}
data = append(data, credentials.Name)
}

d.Set("names", data)

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

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

import (
"errors"
"regexp"
"testing"

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

func TestCloudCredentialsDataSource(t *testing.T) {
credentials1 := client.Credentials{
Id: "id0",
Name: "name0",
Type: "AWS_ASSUMED_ROLE",
}

credentials2 := client.Credentials{
Id: "id1",
Name: "name1",
Type: "AZURE_CREDENTIALS",
}

resourceType := "env0_cloud_credentials"
resourceName := "test_cloud_credentials"
accessor := dataSourceAccessor(resourceType, resourceName)

mockCloudCredentials := func(returnValue []client.Credentials) func(mockFunc *client.MockApiClientInterface) {
return func(mock *client.MockApiClientInterface) {
mock.EXPECT().CloudCredentialsList().AnyTimes().Return(returnValue, nil)
}
}

t.Run("Success", func(t *testing.T) {
runUnitTest(t,
resource.TestCase{
Steps: []resource.TestStep{
{
Config: dataSourceConfigCreate(resourceType, resourceName, map[string]interface{}{}),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr(accessor, "names.0", credentials1.Name),
resource.TestCheckResourceAttr(accessor, "names.1", credentials2.Name),
),
},
},
},
mockCloudCredentials([]client.Credentials{credentials1, credentials2}),
)
})

t.Run("Success With Filter", func(t *testing.T) {
runUnitTest(t,
resource.TestCase{
Steps: []resource.TestStep{
{
Config: dataSourceConfigCreate(resourceType, resourceName, map[string]interface{}{"credential_type": credentials2.Type}),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr(accessor, "names.0", credentials2.Name),
),
},
},
},
mockCloudCredentials([]client.Credentials{credentials1, credentials2}),
)
})

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().CloudCredentialsList().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 @@ -71,6 +71,7 @@ func Provider(version string) plugin.ProviderFunc {
"env0_api_key": dataApiKey(),
"env0_agents": dataAgents(),
"env0_user": dataUser(),
"env0_cloud_credentials": dataCloudCredentials(),
},
ResourcesMap: map[string]*schema.Resource{
"env0_project": resourceProject(),
Expand Down
12 changes: 12 additions & 0 deletions examples/data-sources/env0_cloud_credentials/data-source.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
data "env0_cloud_credentials" "aws_credentials" {
credential_type = "AWS_ASSUMED_ROLE_FOR_DEPLOYMENT"
}

data "env0_aws_credentials" "aws_credentials" {
for_each = toset(data.env0_cloud_credentials.aws_credentials.names)
name = each.value
}

output "credentials_name" {
value = var.second_run ? data.env0_aws_credentials.aws_credentials["Test Role arn1"].name : ""
}
15 changes: 15 additions & 0 deletions tests/integration/024_cloud_credentials/conf.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
terraform {
backend "local" {
}
required_providers {
env0 = {
source = "terraform-registry.env0.com/env0/env0"
}
Comment on lines +4 to +7
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this a new thing or am I wrong? I mean, shouldn't the integration tests use the local version and not the version from the public registry?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes. This is my bad.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@yaronya - actually looking at it again. This is not new. All tests are like this.
I guess it's somehow working as expected...

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not the real registry (terraform-registry.env0.com doesn't exist).
This is set up in buildFakeTerraformRegistry in harness.go

}
}

provider "env0" {}

variable "second_run" {
default = false
}
3 changes: 3 additions & 0 deletions tests/integration/024_cloud_credentials/expected_outputs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"credentials_name": "Test Role arn1"
}
24 changes: 24 additions & 0 deletions tests/integration/024_cloud_credentials/main.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
resource "env0_aws_credentials" "cred1" {
name = "Test Role arn1"
arn = "Role ARN1"
external_id = "External id1"
}

resource "env0_gcp_credentials" "cred2" {
name = "name"
service_account_key = "your_account_key"
project_id = "your_project_id"
}

data "env0_cloud_credentials" "aws_credentials" {
credential_type = "AWS_ASSUMED_ROLE_FOR_DEPLOYMENT"
}

data "env0_aws_credentials" "aws_credentials" {
for_each = toset(data.env0_cloud_credentials.aws_credentials.names)
name = each.value
}

output "credentials_name" {
value = var.second_run ? data.env0_aws_credentials.aws_credentials["Test Role arn1"].name : ""
}