From feec86e44c23df68e129d70b9d128474e4ccbc54 Mon Sep 17 00:00:00 2001 From: Harness CI Date: Tue, 7 Jan 2025 10:45:58 +0000 Subject: [PATCH 1/8] Update Changelog --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f23bccf18..c50b643c1 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,5 @@ +# 0.34.7 (January 07,2025) + # 0.34.6 (December 26,2024) # 0.34.5 (December 09,2024) From 4949d29d3f9516a73b96605b5351604be4914c44 Mon Sep 17 00:00:00 2001 From: Manish Singh <142880974+mani5h-harness@users.noreply.github.com> Date: Tue, 7 Jan 2025 17:01:54 +0530 Subject: [PATCH 2/8] fix: [CDS-105417]: Update GitOps app resource test as identifier for app is deprecated (#1144) --- .../gitops/applications/resource_gitops_applications_test.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/internal/service/platform/gitops/applications/resource_gitops_applications_test.go b/internal/service/platform/gitops/applications/resource_gitops_applications_test.go index ea58ad3bb..8eb8b28e8 100644 --- a/internal/service/platform/gitops/applications/resource_gitops_applications_test.go +++ b/internal/service/platform/gitops/applications/resource_gitops_applications_test.go @@ -38,14 +38,12 @@ func TestAccResourceGitopsApplication_HelmApp(t *testing.T) { Config: testAccResourceGitopsApplicationHelm(id, accountId, name, agentId, clusterName, namespace, clusterServer, clusterId, repo, repoId), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "id", id), - resource.TestCheckResourceAttr(resourceName, "identifier", id), ), }, { Config: testAccResourceGitopsApplicationHelm(id, accountId, name, agentId, clusterName, namespaceUpdated, clusterServer, clusterId, repo, repoId), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "id", id), - resource.TestCheckResourceAttr(resourceName, "identifier", id), resource.TestCheckResourceAttr(resourceName, "application.0.spec.0.destination.0.namespace", namespaceUpdated), ), }, From bd90a55068b0b4e1d67b5b8a27c88dfd65ed4766 Mon Sep 17 00:00:00 2001 From: Fernando Dourado Date: Tue, 7 Jan 2025 17:19:31 -0300 Subject: [PATCH 3/8] feat: [CDS-105076]: Add support for azure artifacts connector (#1141) * feat: [CDS-105076]: Add support for azure artifacts connector * feat: [CDS-105076]: Dependency update --- .gitignore | 1 + go.mod | 2 +- go.sum | 4 +- internal/provider/provider.go | 6 +- .../artifactRepositories/azure_artifacts.go | 138 ++++++++++++++++++ .../azure_artifacts_test.go | 136 +++++++++++++++++ 6 files changed, 282 insertions(+), 5 deletions(-) create mode 100644 internal/service/cd_nextgen/connector/artifactRepositories/azure_artifacts.go create mode 100644 internal/service/cd_nextgen/connector/artifactRepositories/azure_artifacts_test.go diff --git a/.gitignore b/.gitignore index 4d63a98f8..8bd5929eb 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,4 @@ test-report.xml terraform-provider-harness .terraform.lock.hcl +local.sh diff --git a/go.mod b/go.mod index df4c1da91..2c8e98d2e 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,7 @@ require ( github.com/antihax/optional v1.0.0 github.com/aws/aws-sdk-go v1.46.4 github.com/docker/docker v24.0.5+incompatible - github.com/harness/harness-go-sdk v0.4.23 + github.com/harness/harness-go-sdk v0.4.24 github.com/harness/harness-openapi-go-client v0.0.21 github.com/hashicorp/go-cleanhttp v0.5.2 github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 diff --git a/go.sum b/go.sum index 6fe6cb557..918fd5327 100644 --- a/go.sum +++ b/go.sum @@ -54,8 +54,8 @@ github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/harness/harness-go-sdk v0.4.23 h1:iPh1v1sdZ1So1CdtqRkX+YY2hXTApaJsDt0XZWwa+hs= -github.com/harness/harness-go-sdk v0.4.23/go.mod h1:CPXydorp4zd5Dz2u2FXiHyWL4yd5PQafOMN69cgPSvk= +github.com/harness/harness-go-sdk v0.4.24 h1:pfN0JdnrwzWgt1OB4SinOGTJp1yy4RCiJr1xpPYOGd0= +github.com/harness/harness-go-sdk v0.4.24/go.mod h1:CPXydorp4zd5Dz2u2FXiHyWL4yd5PQafOMN69cgPSvk= github.com/harness/harness-openapi-go-client v0.0.21 h1:VtJnpQKZvCAlaCmUPbNR69OT3c5WRdhNN5TOgUwtwZ4= github.com/harness/harness-openapi-go-client v0.0.21/go.mod h1:u0vqYb994BJGotmEwJevF4L3BNAdU9i8ui2d22gmLPA= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= diff --git a/internal/provider/provider.go b/internal/provider/provider.go index a2908e3fe..18115b80a 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -3,10 +3,11 @@ package provider import ( "context" "fmt" - "github.com/harness/terraform-provider-harness/internal/service/platform/module_registry" + "log" + cdng_service "github.com/harness/terraform-provider-harness/internal/service/cd_nextgen/service" + "github.com/harness/terraform-provider-harness/internal/service/platform/module_registry" "github.com/harness/terraform-provider-harness/internal/service/platform/service_account" - "log" pipeline_gitx "github.com/harness/terraform-provider-harness/internal/service/pipeline/gitx/webhook" "github.com/harness/terraform-provider-harness/internal/service/platform/cluster_orchestrator" @@ -306,6 +307,7 @@ func Provider(version string) func() *schema.Provider { "harness_platform_connector_appdynamics": connector.ResourceConnectorAppDynamics(), "harness_platform_connector_elasticsearch": connector.ResourceConnectorElasticSearch(), "harness_platform_connector_artifactory": cdng_connector_artifactRepositories.ResourceConnectorArtifactory(), + "harness_platform_connector_azure_artifacts": cdng_connector_artifactRepositories.ResourceConnectorAzureArtifacts(), "harness_platform_connector_aws_secret_manager": pl_secretManagers.ResourceConnectorAwsSM(), "harness_platform_connector_aws": cdng_connector_cloudProviders.ResourceConnectorAws(), "harness_platform_connector_awscc": connector.ResourceConnectorAwsCC(), diff --git a/internal/service/cd_nextgen/connector/artifactRepositories/azure_artifacts.go b/internal/service/cd_nextgen/connector/artifactRepositories/azure_artifacts.go new file mode 100644 index 000000000..3361383d0 --- /dev/null +++ b/internal/service/cd_nextgen/connector/artifactRepositories/azure_artifacts.go @@ -0,0 +1,138 @@ +package artifactRepositories + +import ( + "context" + "fmt" + + "github.com/harness/harness-go-sdk/harness/nextgen" + "github.com/harness/terraform-provider-harness/helpers" + "github.com/harness/terraform-provider-harness/internal/utils" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func ResourceConnectorAzureArtifacts() *schema.Resource { + resource := &schema.Resource{ + Description: "Resource for creating an Azure Artifacts connector.", + ReadContext: resourceConnectorAzureArtifactsRead, + CreateContext: resourceConnectorAzureArtifactsCreateOrUpdate, + UpdateContext: resourceConnectorAzureArtifactsCreateOrUpdate, + DeleteContext: resourceConnectorDelete, + Importer: helpers.MultiLevelResourceImporter, + Schema: map[string]*schema.Schema{ + "url": { + Description: "URL of the Azure Artifacts server.", + Type: schema.TypeString, + Required: true, + }, + "delegate_selectors": { + Description: "Tags to filter delegates for connection.", + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "credentials": { + Description: "Credentials to use for authentication.", + Type: schema.TypeList, + MaxItems: 1, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "token_ref": { + Description: "Reference to a secret containing the token to use for authentication." + secret_ref_text, + Type: schema.TypeString, + Required: true, + }, + }, + }, + }, + }, + } + + helpers.SetMultiLevelResourceSchema(resource.Schema) + + return resource +} + +func resourceConnectorAzureArtifactsRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn, err := resourceConnectorReadBase(ctx, d, meta, nextgen.ConnectorTypes.AzureArtifacts) + if err != nil { + return err + } + + if conn == nil { + return nil + } + + if err := readConnectorAzureArtifacts(d, conn); err != nil { + return diag.FromErr(err) + } + + return nil +} + +func readConnectorAzureArtifacts(d *schema.ResourceData, connector *nextgen.ConnectorInfo) error { + + d.Set("url", connector.AzureArtifacts.Url) + d.Set("delegate_selectors", connector.AzureArtifacts.DelegateSelectors) + + switch connector.AzureArtifacts.Auth.Creds.Type_ { + case nextgen.AzureArtifactsAuthTypes.PersonalAccessToken: + d.Set("credentials", []map[string]interface{}{ + { + "token_ref": connector.AzureArtifacts.Auth.Creds.UserToken.TokenRef, + }, + }) + default: + return fmt.Errorf("unsupported auth type: %s", connector.AzureArtifacts.Auth.Creds.Type_) + } + + return nil +} + +func resourceConnectorAzureArtifactsCreateOrUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + conn := buildConnectorAzureArtifacts(d) + + newConn, err := resourceConnectorCreateOrUpdateBase(ctx, d, meta, conn) + if err != nil { + return err + } + + if err := readConnectorAzureArtifacts(d, newConn); err != nil { + return diag.FromErr(err) + } + + return nil +} + +func buildConnectorAzureArtifacts(d *schema.ResourceData) *nextgen.ConnectorInfo { + connector := &nextgen.ConnectorInfo{ + Type_: nextgen.ConnectorTypes.AzureArtifacts, + AzureArtifacts: &nextgen.AzureArtifactsConnector{ + Auth: &nextgen.AzureArtifactsAuthentication{ + Creds: &nextgen.AzureArtifactsHttpCredentials{}, + }, + }, + } + + if attr, ok := d.GetOk("url"); ok { + connector.AzureArtifacts.Url = attr.(string) + } + + if attr, ok := d.GetOk("delegate_selectors"); ok { + connector.AzureArtifacts.DelegateSelectors = utils.InterfaceSliceToStringSlice(attr.(*schema.Set).List()) + } + + if attr, ok := d.GetOk("credentials"); ok { + config := attr.([]interface{})[0].(map[string]interface{}) + + connector.AzureArtifacts.Auth.Creds.Type_ = nextgen.AzureArtifactsAuthTypes.PersonalAccessToken + connector.AzureArtifacts.Auth.Creds.UserToken = &nextgen.AzureArtifactsUsernameToken{} + + if attr, ok := config["token_ref"]; ok { + connector.AzureArtifacts.Auth.Creds.UserToken.TokenRef = attr.(string) + } + } + + return connector +} diff --git a/internal/service/cd_nextgen/connector/artifactRepositories/azure_artifacts_test.go b/internal/service/cd_nextgen/connector/artifactRepositories/azure_artifacts_test.go new file mode 100644 index 000000000..b8c122724 --- /dev/null +++ b/internal/service/cd_nextgen/connector/artifactRepositories/azure_artifacts_test.go @@ -0,0 +1,136 @@ +package artifactRepositories_test + +import ( + "fmt" + "testing" + + "github.com/harness/harness-go-sdk/harness/utils" + "github.com/harness/terraform-provider-harness/internal/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func TestAccResourceConnectorAzureArtifacts(t *testing.T) { + + id := fmt.Sprintf("%s_%s", t.Name(), utils.RandStringBytes(5)) + name := id + resourceName := "harness_platform_connector_azure_artifacts.test" + + resource.UnitTest(t, resource.TestCase{ + PreCheck: func() { acctest.TestAccPreCheck(t) }, + ProviderFactories: acctest.ProviderFactories, + ExternalProviders: map[string]resource.ExternalProvider{ + "time": {}, + }, + CheckDestroy: testAccConnectorDestroy(resourceName), + Steps: []resource.TestStep{ + { + Config: testAccResourceConnectorAzureArtifacts(id, name), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr(resourceName, "id", id), + resource.TestCheckResourceAttr(resourceName, "identifier", id), + resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "url", "https://az-artifacts.example.com"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccResourceConnectorAzureArtifactsWithDelegateSelectors(t *testing.T) { + + id := fmt.Sprintf("%s_%s", t.Name(), utils.RandStringBytes(5)) + name := id + resourceName := "harness_platform_connector_azure_artifacts.test" + + resource.UnitTest(t, resource.TestCase{ + PreCheck: func() { acctest.TestAccPreCheck(t) }, + ProviderFactories: acctest.ProviderFactories, + ExternalProviders: map[string]resource.ExternalProvider{ + "time": {}, + }, + CheckDestroy: testAccConnectorDestroy(resourceName), + Steps: []resource.TestStep{ + { + Config: testAccResourceConnectorAzureArtifactsWithDelegateSelectors(id, name), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr(resourceName, "id", id), + resource.TestCheckResourceAttr(resourceName, "identifier", id), + resource.TestCheckResourceAttr(resourceName, "name", name), + resource.TestCheckResourceAttr(resourceName, "url", "https://az-artifacts.example.com"), + resource.TestCheckResourceAttr(resourceName, "delegate_selectors.#", "1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccResourceConnectorAzureArtifacts(id, name string) string { + return fmt.Sprintf(` + resource "harness_platform_secret_text" "test" { + identifier = "%[1]s" + name = "%[2]s" + description = "test" + + secret_manager_identifier = "harnessSecretManager" + value_type = "Inline" + value = "secret" + } + + resource "harness_platform_connector_azure_artifacts" "test" { + identifier = "%[1]s" + name = "%[2]s" + description = "test" + url = "https://az-artifacts.example.com" + credentials { + token_ref = "account.${harness_platform_secret_text.test.id}" + } + depends_on = [time_sleep.wait_4_seconds] + } + + resource "time_sleep" "wait_4_seconds" { + depends_on = [harness_platform_secret_text.test] + destroy_duration = "4s" + } +`, id, name) +} + +func testAccResourceConnectorAzureArtifactsWithDelegateSelectors(id, name string) string { + return fmt.Sprintf(` + resource "harness_platform_secret_text" "test" { + identifier = "%[1]s" + name = "%[2]s" + description = "test" + + secret_manager_identifier = "harnessSecretManager" + value_type = "Inline" + value = "secret" + } + + resource "harness_platform_connector_azure_artifacts" "test" { + identifier = "%[1]s" + name = "%[2]s" + description = "test" + url = "https://az-artifacts.example.com" + credentials { + token_ref = "account.${harness_platform_secret_text.test.id}" + } + delegate_selectors = ["harness-delegate"] + depends_on = [time_sleep.wait_4_seconds] + } + + resource "time_sleep" "wait_4_seconds" { + depends_on = [harness_platform_secret_text.test] + destroy_duration = "4s" + } +`, id, name) +} From c3dee404891b5b658d2f8cbedf716d0d7f389e3a Mon Sep 17 00:00:00 2001 From: Harness CI Date: Wed, 8 Jan 2025 12:35:25 +0000 Subject: [PATCH 4/8] Update Changelog --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c50b643c1..0e5a76b4c 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,5 @@ +# 0.34.8 (January 08,2025) + # 0.34.7 (January 07,2025) # 0.34.6 (December 26,2024) From e50d8c881510b7d1d58d802b54a60fde1645f1e9 Mon Sep 17 00:00:00 2001 From: Fernando Dourado Date: Thu, 9 Jan 2025 03:03:02 -0300 Subject: [PATCH 5/8] feat: [CDS-105527] Add page and size for service list datasource (#1145) --- helpers/schema.go | 7 +++ helpers/schema_test.go | 46 +++++++++++++++++++ .../service/data_source_service_list.go | 12 +++++ 3 files changed, 65 insertions(+) create mode 100644 helpers/schema_test.go diff --git a/helpers/schema.go b/helpers/schema.go index 08fe16977..e88d5ff76 100644 --- a/helpers/schema.go +++ b/helpers/schema.go @@ -200,6 +200,13 @@ func BuildField(d *schema.ResourceData, field string) optional.String { return optional.EmptyString() } +func BuildFieldInt32(d *schema.ResourceData, field string) optional.Int32 { + if arr, ok := d.GetOk(field); ok { + return optional.NewInt32(int32(arr.(int))) + } + return optional.EmptyInt32() +} + func BuildFieldForBoolean(d *schema.ResourceData, field string) optional.Bool { if arr, ok := d.GetOk(field); ok { diff --git a/helpers/schema_test.go b/helpers/schema_test.go new file mode 100644 index 000000000..9b1270b6f --- /dev/null +++ b/helpers/schema_test.go @@ -0,0 +1,46 @@ +package helpers + +import ( + "testing" + + "github.com/antihax/optional" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/stretchr/testify/assert" +) + +func TestBuildFieldForInt32_Int(t *testing.T) { + + var value = 14 + expected := optional.NewInt32(int32(value)) + + resource := createTestResourceForBuildField() + data := map[string]interface{}{ + "field_int": value, + } + + d := schema.TestResourceDataRaw(t, resource.Schema, data) + + assert.Equal(t, expected, BuildFieldInt32(d, "field_int")) +} + +func TestBuildFieldForInt32_Missing(t *testing.T) { + + expected := optional.EmptyInt32() + + resource := createTestResourceForBuildField() + data := map[string]interface{}{} + + d := schema.TestResourceDataRaw(t, resource.Schema, data) + + assert.Equal(t, expected, BuildFieldInt32(d, "field_int")) +} + +func createTestResourceForBuildField() *schema.Resource { + return &schema.Resource{ + Schema: map[string]*schema.Schema{ + "field_int": { + Type: schema.TypeInt, + }, + }, + } +} diff --git a/internal/service/cd_nextgen/service/data_source_service_list.go b/internal/service/cd_nextgen/service/data_source_service_list.go index cd5b502b5..4fdecb8bd 100644 --- a/internal/service/cd_nextgen/service/data_source_service_list.go +++ b/internal/service/cd_nextgen/service/data_source_service_list.go @@ -34,6 +34,16 @@ func DataSourceServiceList() *schema.Resource { }, }, }, + "page": { + Description: "Page index of the results to fetch. Default: 0", + Type: schema.TypeInt, + Optional: true, + }, + "size": { + Description: "Results per page. Default: 100; Max: 1000", + Type: schema.TypeInt, + Optional: true, + }, }, } @@ -52,6 +62,8 @@ func dataSourceServiceListRead(ctx context.Context, d *schema.ResourceData, meta resp, httpResp, err = c.ServicesApi.GetServiceList(ctx, c.AccountId, &nextgen.ServicesApiGetServiceListOpts{ OrgIdentifier: helpers.BuildField(d, "org_id"), ProjectIdentifier: helpers.BuildField(d, "project_id"), + Page: helpers.BuildFieldInt32(d, "page"), + Size: helpers.BuildFieldInt32(d, "size"), }) var output []nextgen.ServiceResponse = resp.Data.Content var services []map[string]interface{} From 437a79a35be162db9a3e7384dca7c07ea690aa43 Mon Sep 17 00:00:00 2001 From: Sameed Ul Haq <145802784+sameed-haq@users.noreply.github.com> Date: Thu, 9 Jan 2025 16:14:45 +0530 Subject: [PATCH 6/8] Fix:[IMPENG-324]: added execute_on_delagte param support. (#1147) * Fix:[IMPENG-324]: added execute_on_delagte param support. * Fix:[IMPENG-324]: aws data source fix * Doc updates * ChangeLog Updataion --- .changelog/1032.txt | 4 ++ docs/data-sources/platform_connector_aws.md | 52 +++++++++---------- .../connector/cloudProviders/aws.go | 25 ++++++--- .../cloudProviders/aws_data_source.go | 15 ++++-- .../cloudProviders/azure_cloud_provider.go | 4 ++ 5 files changed, 61 insertions(+), 39 deletions(-) create mode 100644 .changelog/1032.txt diff --git a/.changelog/1032.txt b/.changelog/1032.txt new file mode 100644 index 000000000..4dbad51b4 --- /dev/null +++ b/.changelog/1032.txt @@ -0,0 +1,4 @@ +```relese-note:fix +harness_platform_connector_aws: Added Support for execute_on_delegate param. +harness_platform_connector_azure_cloud_provider: Added Support for execute_on_delegate param. +``` diff --git a/docs/data-sources/platform_connector_aws.md b/docs/data-sources/platform_connector_aws.md index da01ba9f3..2307531b9 100644 --- a/docs/data-sources/platform_connector_aws.md +++ b/docs/data-sources/platform_connector_aws.md @@ -36,6 +36,7 @@ data "harness_platform_connector_aws" "example" { - `cross_account_access` (List of Object) Select this option if you want to use one AWS account for the connection, but you want to deploy or build in a different AWS account. In this scenario, the AWS account used for AWS access in Credentials will assume the IAM role you specify in Cross-account role ARN setting. This option uses the AWS Security Token Service (STS) feature. (see [below for nested schema](#nestedatt--cross_account_access)) - `description` (String) Description of the resource. - `equal_jitter_backoff_strategy` (List of Object) Equal Jitter BackOff Strategy. (see [below for nested schema](#nestedatt--equal_jitter_backoff_strategy)) +- `execute_on_delegate` (Boolean) Execute on delegate or not. - `fixed_delay_backoff_strategy` (List of Object) Fixed Delay BackOff Strategy. (see [below for nested schema](#nestedatt--fixed_delay_backoff_strategy)) - `full_jitter_backoff_strategy` (List of Object) Full Jitter BackOff Strategy. (see [below for nested schema](#nestedatt--full_jitter_backoff_strategy)) - `id` (String) The ID of this resource. @@ -43,7 +44,6 @@ data "harness_platform_connector_aws" "example" { - `irsa` (List of Object) Use IAM role for service accounts. (see [below for nested schema](#nestedatt--irsa)) - `manual` (List of Object) Use IAM role for service accounts. (see [below for nested schema](#nestedatt--manual)) - `oidc_authentication` (List of Object) Authentication using harness oidc. (see [below for nested schema](#nestedatt--oidc_authentication)) -- `region` AWS Region to perform Connection test of Connector. - `tags` (Set of String) Tags to associate with the resource. @@ -51,8 +51,8 @@ data "harness_platform_connector_aws" "example" { Read-Only: -- `external_id` (String) If the administrator of the account to which the role belongs provided you with an external ID, then enter that value. -- `role_arn` (String) The Amazon Resource Name (ARN) of the role that you want to assume. This is an IAM role in the target AWS account. +- `external_id` (String) +- `role_arn` (String) @@ -60,9 +60,9 @@ Read-Only: Read-Only: -- `base_delay` (Number) Base delay. -- `max_backoff_time` (Number) Max BackOff Time. -- `retry_count` (Number) Retry Count. +- `base_delay` (Number) +- `max_backoff_time` (Number) +- `retry_count` (Number) @@ -70,8 +70,8 @@ Read-Only: Read-Only: -- `fixed_backoff` (Number) Fixed Backoff. -- `retry_count` (Number) Retry Count. +- `fixed_backoff` (Number) +- `retry_count` (Number) @@ -79,9 +79,9 @@ Read-Only: Read-Only: -- `base_delay` (Number) Base delay. -- `max_backoff_time` (Number) Max BackOff Time. -- `retry_count` (Number) Retry Count. +- `base_delay` (Number) +- `max_backoff_time` (Number) +- `retry_count` (Number) @@ -89,8 +89,8 @@ Read-Only: Read-Only: -- `delegate_selectors` (Set of String) The delegates to inherit the credentials from. -- `region` AWS Region to perform Connection test of Connector. +- `delegate_selectors` (Set of String) +- `region` (String) @@ -98,8 +98,8 @@ Read-Only: Read-Only: -- `delegate_selectors` (Set of String) The delegates to inherit the credentials from. -- `region` AWS Region to perform Connection test of Connector. +- `delegate_selectors` (Set of String) +- `region` (String) @@ -107,20 +107,20 @@ Read-Only: Read-Only: -- `access_key` (String) AWS access key. -- `access_key_ref` (String) Reference to the Harness secret containing the aws access key. To reference a secret at the organization scope, prefix 'org' to the expression: org.{identifier}. To reference a secret at the account scope, prefix 'account` to the expression: account.{identifier}. -- `delegate_selectors` (Set of String) Connect only use delegates with these tags. -- `secret_key_ref` (String) Reference to the Harness secret containing the aws secret key. To reference a secret at the organization scope, prefix 'org' to the expression: org.{identifier}. To reference a secret at the account scope, prefix 'account` to the expression: account.{identifier}. -- `session_token_ref` (String) Reference to the Harness secret containing the aws session token. -- `region` AWS Region to perform Connection test of Connector. +- `access_key` (String) +- `access_key_plain_text` (String) +- `access_key_ref` (String) +- `delegate_selectors` (Set of String) +- `region` (String) +- `secret_key_ref` (String) +- `session_token_ref` (String) -### Nested Schema for `oidc authentication` +### Nested Schema for `oidc_authentication` Read-Only: -- `iam_role_arn` (String) The IAM Role to assume the credentials from. -- `delegate_selectors` (Set of String) The delegates to inherit the credentials from. -- `region` AWS Region to perform Connection test of Connector. - +- `delegate_selectors` (Set of String) +- `iam_role_arn` (String) +- `region` (String) diff --git a/internal/service/cd_nextgen/connector/cloudProviders/aws.go b/internal/service/cd_nextgen/connector/cloudProviders/aws.go index 819898c1b..8e89508d1 100644 --- a/internal/service/cd_nextgen/connector/cloudProviders/aws.go +++ b/internal/service/cd_nextgen/connector/cloudProviders/aws.go @@ -58,11 +58,11 @@ func ResourceConnectorAws() *schema.Resource { Type: schema.TypeString, Required: true, }, - "session_token_ref": { - Description: "Reference to the Harness secret containing the aws session token." + secret_ref_text, - Type: schema.TypeString, - Optional: true, - }, + "session_token_ref": { + Description: "Reference to the Harness secret containing the aws session token." + secret_ref_text, + Type: schema.TypeString, + Optional: true, + }, "delegate_selectors": { Description: "Connect only use delegates with these tags.", Type: schema.TypeSet, @@ -286,6 +286,11 @@ func ResourceConnectorAws() *schema.Resource { Optional: true, Computed: true, }, + "execute_on_delegate": { + Description: "Enable this flag to execute on Delegate", + Type: schema.TypeBool, + Optional: true, + }, }, } @@ -351,9 +356,9 @@ func buildConnectorAws(d *schema.ResourceData) *nextgen.ConnectorInfo { connector.Aws.Credential.ManualConfig.SecretKeyRef = attr } - if attr := config["session_token_ref"].(string); attr != "" { - connector.Aws.Credential.ManualConfig.SessionTokenRef = attr - } + if attr := config["session_token_ref"].(string); attr != "" { + connector.Aws.Credential.ManualConfig.SessionTokenRef = attr + } if attr := config["delegate_selectors"].(*schema.Set).List(); len(attr) > 0 { connector.Aws.DelegateSelectors = utils.InterfaceSliceToStringSlice(attr) @@ -468,6 +473,9 @@ func buildConnectorAws(d *schema.ResourceData) *nextgen.ConnectorInfo { connector.Aws.AwsSdkClientBackOffStrategyOverride.FixedDelay.FixedBackoff = int64(val.(int)) } } + if attr, ok := d.GetOk("execute_on_delegate"); ok { + connector.Aws.ExecuteOnDelegate = attr.(bool) + } return connector } @@ -546,6 +554,7 @@ func readConnectorAws(d *schema.ResourceData, connector *nextgen.ConnectorInfo) default: return fmt.Errorf("unsupported aws credential type: %s", connector.Aws.AwsSdkClientBackOffStrategyOverride.Type_) } + d.Set("execute_on_delegate", connector.Aws.ExecuteOnDelegate) } return nil diff --git a/internal/service/cd_nextgen/connector/cloudProviders/aws_data_source.go b/internal/service/cd_nextgen/connector/cloudProviders/aws_data_source.go index 8a288a11d..bbbe72840 100644 --- a/internal/service/cd_nextgen/connector/cloudProviders/aws_data_source.go +++ b/internal/service/cd_nextgen/connector/cloudProviders/aws_data_source.go @@ -37,11 +37,11 @@ func DatasourceConnectorAws() *schema.Resource { Type: schema.TypeString, Computed: true, }, - "session_token_ref": { - Description: "Reference to the Harness secret containing the aws session token." + secret_ref_text, - Type: schema.TypeString, - Optional: true, - }, + "session_token_ref": { + Description: "Reference to the Harness secret containing the aws session token." + secret_ref_text, + Type: schema.TypeString, + Optional: true, + }, "delegate_selectors": { Description: "Connect only use delegates with these tags.", Type: schema.TypeSet, @@ -207,6 +207,11 @@ func DatasourceConnectorAws() *schema.Resource { }, }, }, + "execute_on_delegate": { + Description: "Execute on delegate or not.", + Type: schema.TypeBool, + Computed: true, + }, }, } diff --git a/internal/service/cd_nextgen/connector/cloudProviders/azure_cloud_provider.go b/internal/service/cd_nextgen/connector/cloudProviders/azure_cloud_provider.go index ef2be0a7a..863bcdc0c 100644 --- a/internal/service/cd_nextgen/connector/cloudProviders/azure_cloud_provider.go +++ b/internal/service/cd_nextgen/connector/cloudProviders/azure_cloud_provider.go @@ -313,6 +313,9 @@ func buildConnectorAzureCloudProvider(d *schema.ResourceData) *nextgen.Connector if attr, ok := d.GetOk("azure_environment_type"); ok { connector.Azure.AzureEnvironmentType = attr.(string) } + if attr, ok := d.GetOk("execute_on_delegate"); ok { + connector.Azure.ExecuteOnDelegate = attr.(bool) + } return connector } @@ -327,6 +330,7 @@ func readConnectorAzureCloudProvider(d *schema.ResourceData, connector *nextgen. }) d.Set("delegate_selectors", connector.Azure.DelegateSelectors) d.Set("azure_environment_type", connector.Azure.AzureEnvironmentType) + d.Set("execute_on_delegate", connector.Azure.ExecuteOnDelegate) return nil } From 43d3f9837bf2db110114b46d7f96e38f25588d58 Mon Sep 17 00:00:00 2001 From: Saranya Jena Date: Thu, 9 Jan 2025 16:56:41 +0530 Subject: [PATCH 7/8] chore: [CHAOS-6992]: Added support of chaos infrastructure (#1138) * chore: [CHAOS-6992]: Added support of chaos infrastructure Signed-off-by: Saranya-jena * chore: [CHAOS-6992]: resolved comments Signed-off-by: Saranya-jena * chore: [CHAOS-6992]: fixed imports Signed-off-by: Saranya-jena --------- Signed-off-by: Saranya-jena --- docs/data-sources/chaos_infrastructure.md | 37 +++ docs/resources/chaos_infrastructure.md | 61 ++++ .../data-source.tf | 6 + .../harness_chaos_infrastructure/import.sh | 2 + .../harness_chaos_infrastructure/resource.tf | 11 + internal/provider/provider.go | 16 ++ .../data_source_infrastructure.go | 74 +++++ .../infrastructure/resource_infrastructure.go | 272 ++++++++++++++++++ internal/session.go | 10 +- 9 files changed, 488 insertions(+), 1 deletion(-) create mode 100644 docs/data-sources/chaos_infrastructure.md create mode 100644 docs/resources/chaos_infrastructure.md create mode 100644 examples/data-sources/harness_chaos_infrastructure/data-source.tf create mode 100644 examples/resources/harness_chaos_infrastructure/import.sh create mode 100644 examples/resources/harness_chaos_infrastructure/resource.tf create mode 100644 internal/service/chaos/infrastructure/data_source_infrastructure.go create mode 100644 internal/service/chaos/infrastructure/resource_infrastructure.go diff --git a/docs/data-sources/chaos_infrastructure.md b/docs/data-sources/chaos_infrastructure.md new file mode 100644 index 000000000..07a45a737 --- /dev/null +++ b/docs/data-sources/chaos_infrastructure.md @@ -0,0 +1,37 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "harness_chaos_infrastructure Data Source - terraform-provider-harness" +subcategory: "Next Gen" +description: |- + Data source for retrieving a chaos infrastructure. +--- + +# harness_chaos_infrastructure (Data Source) + +Data source for retrieving a chaos infrastructure. + +## Example Usage + +```terraform + data "harness_chaos_infrastructure" "example" { + identifier = "identifier" + org_id = "org_id" + project_id = "project_id" + environment_id = "env_id" + } +``` + + + +## Schema + +### Required + +- `environment_id` (String) Environment identifier of the chaos infrastructure. +- `identifier` (String) Identifier of the chaos infrastructure. +- `org_id` (String) Identifier of the organization in which the chaos infrastructure is configured. +- `project_id` (String) Identifier of the project in which the chaos infrastructure is configured. + +### Read-Only + +- `id` (String) The ID of this resource. diff --git a/docs/resources/chaos_infrastructure.md b/docs/resources/chaos_infrastructure.md new file mode 100644 index 000000000..88ad429ab --- /dev/null +++ b/docs/resources/chaos_infrastructure.md @@ -0,0 +1,61 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "harness_chaos_infrastructure Resource - terraform-provider-harness" +subcategory: "Next Gen" +description: |- + Resource for creating a Chaos Infrastructure. +--- + +# harness_chaos_infrastructure (Resource) + +Resource for creating a Chaos Infrastructure. + +### References: + +- For details on how to onboard with Terraform, please see [Harness Terraform Provider Overview](https://developer.harness.io/docs/platform/automation/terraform/harness-terraform-provider-overview/) + +## Example to create Chaos Infrastructure + +```terraform +resource "harness_chaos_infrastructure" "example" { + identifier = "identifier" + name = "name" + org_id = "org_id" + project_id = "project_id" + environment_id = "env_id" + namespace = "namespace" + service_account = "service_acc_name" +} +``` + + + +## Schema + +### Required + +- `org_id` (String) Unique identifier of the organization. +- `project_id` (String) Unique identifier of the project. +- `environment_id` (String) Environment ID of the chaos infrastructure. +- `identifier` (String) Unique identifier of the resource. +- `name` (String) Name of the resource. +- `namespace` (String) Namespace of the chaos infrastructure. +- `service_account` (String) Service Account of the chaos infrastructure. + +### Optional + +- `description` (String) Description of the resource. +- `tags` (Set of String) Tags to associate with the resource. + +### Read-Only + +- `id` (String) The ID of this resource. + +## Import + +Import is supported using the following syntax: + +```shell +# Import using the Chaos Infra ID. +terraform import harness_chaos_infrastructure.example +``` diff --git a/examples/data-sources/harness_chaos_infrastructure/data-source.tf b/examples/data-sources/harness_chaos_infrastructure/data-source.tf new file mode 100644 index 000000000..e4ee32f47 --- /dev/null +++ b/examples/data-sources/harness_chaos_infrastructure/data-source.tf @@ -0,0 +1,6 @@ + data "harness_chaos_infrastructure" "example" { + identifier = "identifier" + org_id = "org_id" + project_id = "project_id" + environment_id= "env_id" + } \ No newline at end of file diff --git a/examples/resources/harness_chaos_infrastructure/import.sh b/examples/resources/harness_chaos_infrastructure/import.sh new file mode 100644 index 000000000..7db91bcc7 --- /dev/null +++ b/examples/resources/harness_chaos_infrastructure/import.sh @@ -0,0 +1,2 @@ +# Import using the Harness chaos_infra_id. +terraform import harness_chaos_infrastructure.example \ No newline at end of file diff --git a/examples/resources/harness_chaos_infrastructure/resource.tf b/examples/resources/harness_chaos_infrastructure/resource.tf new file mode 100644 index 000000000..f8029d6d3 --- /dev/null +++ b/examples/resources/harness_chaos_infrastructure/resource.tf @@ -0,0 +1,11 @@ + +# Sample resource for chaos infrastructure +resource "harness_chaos_infrastructure" "example" { + identifier = "identifier" + name = "name" + org_id = "org_id" + project_id = "project_id" + environment_id = "env_id" + namespace = "namespace" + service_account = "service_acc_name" +} \ No newline at end of file diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 18115b80a..ad1498d76 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -5,7 +5,9 @@ import ( "fmt" "log" + "github.com/harness/harness-go-sdk/harness/chaos" cdng_service "github.com/harness/terraform-provider-harness/internal/service/cd_nextgen/service" + "github.com/harness/terraform-provider-harness/internal/service/chaos/infrastructure" "github.com/harness/terraform-provider-harness/internal/service/platform/module_registry" "github.com/harness/terraform-provider-harness/internal/service/platform/service_account" @@ -297,6 +299,7 @@ func Provider(version string) func() *schema.Provider { "harness_governance_rule_set": governance_rule_set.DatasourceRuleSet(), "harness_cluster_orchestrator": cluster_orchestrator.DataSourceClusterOrchestrator(), "harness_platform_infra_module": module_registry.DataSourceInfraModule(), + "harness_chaos_infrastructure": infrastructure.DataSourceChaosInfrastructureService(), }, ResourcesMap: map[string]*schema.Resource{ "harness_platform_template": pipeline_template.ResourceTemplate(), @@ -446,6 +449,7 @@ func Provider(version string) func() *schema.Provider { "harness_governance_rule_set": governance_rule_set.ResourceRuleSet(), "harness_cluster_orchestrator": cluster_orchestrator.ResourceClusterOrchestrator(), "harness_platform_infra_module": module_registry.ResourceInfraModule(), + "harness_chaos_infrastructure": infrastructure.ResourceChaosInfrastructure(), }, } @@ -540,6 +544,17 @@ func getCodeClient(d *schema.ResourceData, version string) *code.APIClient { return client } +func getChaosClient(d *schema.ResourceData, version string) *chaos.APIClient { + client := chaos.NewAPIClient(&chaos.Configuration{ + AccountId: d.Get("account_id").(string), + BasePath: d.Get("endpoint").(string) + "/chaos/manager/api", // check if this can be taken from sdk + ApiKey: d.Get("platform_api_key").(string), + UserAgent: fmt.Sprintf("terraform-provider-harness-platform-%s", version), + DefaultHeader: map[string]string{"X-Api-Key": d.Get("platform_api_key").(string)}, + }) + return client +} + // Setup the client for interacting with the Harness API func configure(version string, p *schema.Provider) func(context.Context, *schema.ResourceData) (interface{}, diag.Diagnostics) { return func(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) { @@ -551,6 +566,7 @@ func configure(version string, p *schema.Provider) func(context.Context, *schema Client: getClient(d, version), CodeClient: getCodeClient(d, version), DBOpsClient: getDBOpsClient(d, version), + ChaosClient: getChaosClient(d, version), }, nil } } diff --git a/internal/service/chaos/infrastructure/data_source_infrastructure.go b/internal/service/chaos/infrastructure/data_source_infrastructure.go new file mode 100644 index 000000000..07c289096 --- /dev/null +++ b/internal/service/chaos/infrastructure/data_source_infrastructure.go @@ -0,0 +1,74 @@ +package infrastructure + +import ( + "context" + + "github.com/harness/terraform-provider-harness/helpers" + "github.com/harness/terraform-provider-harness/internal" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func DataSourceChaosInfrastructureService() *schema.Resource { + resource := &schema.Resource{ + Description: "Data source for retrieving a chaos infrastructure.", + + ReadContext: dataSourceChaosInfrastructureRead, + + Schema: map[string]*schema.Schema{ + "org_id": { + Description: "Identifier of the organization in which the chaos infrastructure is configured.", + Type: schema.TypeString, + Required: true, + }, + "project_id": { + Description: "Identifier of the project in which the chaos infrastructure is configured.", + Type: schema.TypeString, + Required: true, + }, + "identifier": { + Description: "Identifier of the chaos infrastructure.", + Type: schema.TypeString, + Required: true, + }, + "environment_id": { + Description: "Environment identifier of the chaos infrastructure.", + Type: schema.TypeString, + Required: true, + }, + }, + } + + return resource +} + +func dataSourceChaosInfrastructureRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + c, ctx := meta.(*internal.Session).GetChaosClientWithContext(ctx) + var accountIdentifier, orgIdentifier, projectIdentifier, identifier, envIdentifier string + accountIdentifier = c.AccountId + if attr, ok := d.GetOk("org_id"); ok { + orgIdentifier = attr.(string) + } + if attr, ok := d.GetOk("project_id"); ok { + projectIdentifier = attr.(string) + } + if attr, ok := d.GetOk("identifier"); ok { + identifier = attr.(string) + } + if attr, ok := d.GetOk("environment_id"); ok { + envIdentifier = attr.(string) + } + resp, httpResp, err := c.ChaosSdkApi.GetInfraV2(ctx, identifier, accountIdentifier, orgIdentifier, projectIdentifier, envIdentifier) + + if err != nil { + if err.Error() == "404 Not Found" { + d.SetId("") + d.MarkNewResource() + return nil + } + return helpers.HandleReadApiError(err, d, httpResp) + } + readChaosInfrastructure(d, resp) + + return nil +} diff --git a/internal/service/chaos/infrastructure/resource_infrastructure.go b/internal/service/chaos/infrastructure/resource_infrastructure.go new file mode 100644 index 000000000..0e8d17a16 --- /dev/null +++ b/internal/service/chaos/infrastructure/resource_infrastructure.go @@ -0,0 +1,272 @@ +package infrastructure + +import ( + "context" + "log" + + "github.com/harness/harness-go-sdk/harness/chaos" + hh "github.com/harness/harness-go-sdk/harness/helpers" + "github.com/harness/terraform-provider-harness/helpers" + "github.com/harness/terraform-provider-harness/internal" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func ResourceChaosInfrastructure() *schema.Resource { + resource := &schema.Resource{ + Description: "Resource for creating a Chaos Infrastructure.", + + ReadContext: resourceChaosInfrastructureRead, + UpdateContext: resourceChaosInfrastructureUpdate, + DeleteContext: resourceChaosInfrastructureDelete, + CreateContext: resourceChaosInfrastructureCreate, + Importer: helpers.MultiLevelResourceImporter, + + Schema: map[string]*schema.Schema{ + "org_id": { + Description: "Identifier of the organization in which the chaos infrastructure is configured.", + Type: schema.TypeString, + Required: true, + }, + "project_id": { + Description: "Identifier of the project in which the chaos infrastructure is configured.", + Type: schema.TypeString, + Required: true, + }, + "identifier": { + Description: "Identifier of the chaos infrastructure.", + Type: schema.TypeString, + Required: true, + }, + "name": { + Description: "Name of the chaos infrastructure.", + Type: schema.TypeString, + Required: true, + }, + "description": { + Description: "Description of the chaos infrastructure.", + Type: schema.TypeString, + Optional: true, + }, + "environment_id": { + Description: "Environment ID of the chaos infrastructure.", + Type: schema.TypeString, + Required: true, + }, + "namespace": { + Description: "Namespace of the chaos infrastructure.", + Type: schema.TypeString, + Required: true, + }, + "service_account": { + Description: "Service Account of the chaos infrastructure.", + Type: schema.TypeString, + Required: true, + }, + "tags": { + Description: "Tags of the chaos infrastructure.", + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + } + + helpers.SetMultiLevelResourceSchema(resource.Schema) + + return resource +} + +func resourceChaosInfrastructureRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + c, ctx := meta.(*internal.Session).GetChaosClientWithContext(ctx) + var accountIdentifier, orgIdentifier, projectIdentifier, identifier, envIdentifier string + accountIdentifier = c.AccountId + if attr, ok := d.GetOk("org_id"); ok { + orgIdentifier = attr.(string) + } + if attr, ok := d.GetOk("project_id"); ok { + projectIdentifier = attr.(string) + } + if attr, ok := d.GetOk("identifier"); ok { + identifier = attr.(string) + } + if attr, ok := d.GetOk("environment_id"); ok { + envIdentifier = attr.(string) + } + resp, httpResp, err := c.ChaosSdkApi.GetInfraV2(ctx, identifier, accountIdentifier, orgIdentifier, projectIdentifier, envIdentifier) + + if err != nil { + if err.Error() == "404 Not Found" { + d.SetId("") + d.MarkNewResource() + return nil + } + return helpers.HandleReadApiError(err, d, httpResp) + } + readChaosInfrastructure(d, resp) + + return nil +} + +func resourceChaosInfrastructureUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + c, ctx := meta.(*internal.Session).GetChaosClientWithContext(ctx) + var accountIdentifier, orgIdentifier, projectIdentifier string + accountIdentifier = c.AccountId + if attr, ok := d.GetOk("org_id"); ok { + orgIdentifier = attr.(string) + } + if attr, ok := d.GetOk("project_id"); ok { + projectIdentifier = attr.(string) + } + + updateInfraRequest := buildUpdateInfraRequest(d) + _, httpRespUpdate, errUpdate := c.ChaosSdkApi.UpdateInfraV2(ctx, *updateInfraRequest, accountIdentifier, orgIdentifier, projectIdentifier, &chaos.ChaosSdkApiUpdateInfraV2Opts{}) + + if errUpdate != nil { + return helpers.HandleApiError(errUpdate, d, httpRespUpdate) + } + readInfraUpdate(d, updateInfraRequest.Identity, updateInfraRequest.EnvironmentID) + return nil +} + +func buildUpdateInfraRequest(d *schema.ResourceData) *chaos.InfraV2UpdateKubernetesInfrastructureV2Request { + infraReq := &chaos.InfraV2UpdateKubernetesInfrastructureV2Request{} + + if attr, ok := d.GetOk("identifier"); ok { + infraReq.Identity = attr.(string) + } + + infraReq.Name = d.Get("name").(string) + infraReq.Description = d.Get("description").(string) + + tags := []string{} + for _, t := range d.Get("tags").(*schema.Set).List() { + tagStr := t.(string) + tags = append(tags, tagStr) + } + infraReq.Tags = tags + infraReq.InfraNamespace = d.Get("namespace").(string) + if attr, ok := d.GetOk("environment_id"); ok { + infraReq.EnvironmentID = attr.(string) + } + if attr, ok := d.GetOk("service_account"); ok { + infraReq.ServiceAccount = attr.(string) + } + + return infraReq +} + +func readInfraUpdate(d *schema.ResourceData, identifier string, envID string) { + + // can we use corr ID or do we need to return identity? + d.SetId(identifier) + d.Set("environment_id", envID) + +} + +func resourceChaosInfrastructureDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + c, ctx := meta.(*internal.Session).GetChaosClientWithContext(ctx) + + var accountIdentifier, orgIdentifier, projectIdentifier, identifier, environmentID string + accountIdentifier = c.AccountId + if attr, ok := d.GetOk("org_id"); ok { + orgIdentifier = attr.(string) + } + if attr, ok := d.GetOk("project_id"); ok { + projectIdentifier = attr.(string) + } + if attr, ok := d.GetOk("identifier"); ok { + identifier = attr.(string) + } + if attr, ok := d.GetOk("environment_id"); ok { + environmentID = attr.(string) + } + _, httpResp, err := c.ChaosSdkApi.DeleteInfraV2(ctx, identifier, environmentID, accountIdentifier, orgIdentifier, projectIdentifier) + + if err != nil { + return helpers.HandleApiError(err, d, httpResp) + } + + return nil +} + +func readInfraCreate(d *schema.ResourceData, infraResponse *chaos.InfraV2RegisterInfrastructureV2Response, envID string) { + d.SetId(infraResponse.Identity) + d.Set("name", infraResponse.Name) + d.Set("environment_id", envID) +} + +func resourceChaosInfrastructureCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + c, ctx := meta.(*internal.Session).GetChaosClientWithContext(ctx) + log.Printf("Debugging message: %v", c) + + ctx = context.WithValue(ctx, chaos.ContextAccessToken, hh.EnvVars.BearerToken.Get()) // do we need it + var accountIdentifier, orgIdentifier, projectIdentifier string + createInfraRequest := buildInfraCreateRequest(d) + identifiers := chaos.InfraV2Identifiers{} + createInfraRequest.Identifier = &identifiers + createInfraRequest.Identifier.AccountIdentifier = c.AccountId + accountIdentifier = c.AccountId + if attr, ok := d.GetOk("org_id"); ok { + orgIdentifier = attr.(string) + createInfraRequest.Identifier.OrgIdentifier = attr.(string) + } + if attr, ok := d.GetOk("project_id"); ok { + projectIdentifier = attr.(string) + createInfraRequest.Identifier.ProjectIdentifier = attr.(string) + } + + resp, httpRespUpdate, errUpdate := c.ChaosSdkApi.RegisterInfraV2(ctx, createInfraRequest, accountIdentifier, orgIdentifier, projectIdentifier, &chaos.ChaosSdkApiRegisterInfraV2Opts{}) + if errUpdate != nil { + return helpers.HandleApiError(errUpdate, d, httpRespUpdate) + } + readInfraCreate(d, &resp, createInfraRequest.EnvironmentID) + defer httpRespUpdate.Body.Close() + return nil +} + +func buildInfraCreateRequest(d *schema.ResourceData) chaos.InfraV2RegisterInfrastructureV2Request { + infraReq := chaos.InfraV2RegisterInfrastructureV2Request{} + + if attr, ok := d.GetOk("identifier"); ok { + infraReq.Identity = attr.(string) + infraReq.InfraID = attr.(string) + } + + infraReq.Name = d.Get("name").(string) + infraReq.Description = d.Get("description").(string) + + tags := []string{} + for _, t := range d.Get("tags").(*schema.Set).List() { + tagStr := t.(string) + tags = append(tags, tagStr) + } + infraReq.Tags = tags + + infraReq.InfraNamespace = d.Get("namespace").(string) + if attr, ok := d.GetOk("environment_id"); ok { + infraReq.EnvironmentID = attr.(string) + } + if attr, ok := d.GetOk("service_account"); ok { + infraReq.ServiceAccount = attr.(string) + } + scope := chaos.CLUSTER_InfraV2InfraScope + infraReq.InfraScope = &scope + infraType := chaos.KUBERNETES_InfraV2InfraType + infraReq.InfraType = &infraType + + return infraReq +} + +func readChaosInfrastructure(d *schema.ResourceData, infra chaos.InfraV2KubernetesInfrastructureV2Details) { + d.SetId(infra.Identity) + d.Set("org_id", infra.Identifier.OrgIdentifier) + d.Set("project_id", infra.Identifier.ProjectIdentifier) + d.Set("identifier", infra.Identity) + d.Set("name", infra.Name) + d.Set("description", infra.Description) + d.Set("infra_id", infra.InfraID) + d.Set("environment_id", infra.EnvironmentID) +} diff --git a/internal/session.go b/internal/session.go index 07b7c50e6..4c61e6aa1 100644 --- a/internal/session.go +++ b/internal/session.go @@ -2,8 +2,8 @@ package internal import ( "context" - "github.com/harness/harness-go-sdk/harness/cd" + "github.com/harness/harness-go-sdk/harness/chaos" "github.com/harness/harness-go-sdk/harness/code" "github.com/harness/harness-go-sdk/harness/dbops" "github.com/harness/harness-go-sdk/harness/nextgen" @@ -19,6 +19,7 @@ type Session struct { DBOpsClient *dbops.APIClient Client *openapi_client_nextgen.APIClient CodeClient *code.APIClient + ChaosClient *chaos.APIClient } func (s *Session) GetPlatformClient() (*nextgen.APIClient, context.Context) { @@ -63,3 +64,10 @@ func (s *Session) GetCodeClientWithContext(ctx context.Context) (*code.APIClient return s.CodeClient.WithAuthContext(ctx) } + +func (s *Session) GetChaosClientWithContext(ctx context.Context) (*chaos.APIClient, context.Context) { + if ctx == nil { + ctx = context.Background() + } + return s.ChaosClient.WithAuthContext(ctx) +} From b3b28e7cd1768cf6996aeb2b032687f4f357e702 Mon Sep 17 00:00:00 2001 From: Harness CI Date: Mon, 13 Jan 2025 05:35:33 +0000 Subject: [PATCH 8/8] Update Changelog --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e5a76b4c..5c0038f86 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,5 @@ +# 0.34.9 (January 13,2025) + # 0.34.8 (January 08,2025) # 0.34.7 (January 07,2025)