Move internal packages into internal folder (#33)
* Move internal packages into internal folder * Fix testutil imports
This commit is contained in:
parent
46be7cfafd
commit
f8c9e4c0af
83 changed files with 148 additions and 148 deletions
353
stackit/internal/services/argus/argus_acc_test.go
Normal file
353
stackit/internal/services/argus/argus_acc_test.go
Normal file
|
|
@ -0,0 +1,353 @@
|
|||
package argus_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-testing/helper/acctest"
|
||||
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
|
||||
"github.com/hashicorp/terraform-plugin-testing/terraform"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/argus"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/testutil"
|
||||
)
|
||||
|
||||
var instanceResource = map[string]string{
|
||||
"project_id": testutil.ProjectId,
|
||||
"name": testutil.ResourceNameWithDateTime("argus"),
|
||||
"plan_name": "Monitoring-Medium-EU01",
|
||||
}
|
||||
|
||||
var scrapeConfigResource = map[string]string{
|
||||
"project_id": testutil.ProjectId,
|
||||
"name": fmt.Sprintf("scrapeconfig-%s", acctest.RandStringFromCharSet(7, acctest.CharSetAlphaNum)),
|
||||
"urls": fmt.Sprintf(`{urls = ["www.%s.de","%s.de"]}`, acctest.RandStringFromCharSet(15, acctest.CharSetAlphaNum), acctest.RandStringFromCharSet(15, acctest.CharSetAlphaNum)),
|
||||
"metrics_path": "/metrics",
|
||||
"scheme": "https",
|
||||
"scrape_interval": "4m", // non-default
|
||||
"saml2_enable_url_parameters": "false",
|
||||
}
|
||||
|
||||
var credentialsResource = map[string]string{
|
||||
"project_id": testutil.ProjectId,
|
||||
}
|
||||
|
||||
func resourceConfig(instanceName, target, saml2EnableUrlParameters string) string {
|
||||
return fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
resource "stackit_argus_instance" "instance" {
|
||||
project_id = "%s"
|
||||
name = "%s"
|
||||
plan_name = "%s"
|
||||
}
|
||||
|
||||
resource "stackit_argus_scrapeconfig" "scrapeconfig" {
|
||||
project_id = stackit_argus_instance.instance.project_id
|
||||
instance_id = stackit_argus_instance.instance.instance_id
|
||||
name = "%s"
|
||||
metrics_path = "%s"
|
||||
targets = [%s]
|
||||
scrape_interval = "%s"
|
||||
saml2 = {
|
||||
enable_url_parameters = %s
|
||||
}
|
||||
}
|
||||
|
||||
resource "stackit_argus_credential" "credential" {
|
||||
project_id = stackit_argus_instance.instance.project_id
|
||||
instance_id = stackit_argus_instance.instance.instance_id
|
||||
}
|
||||
|
||||
`,
|
||||
testutil.ArgusProviderConfig(),
|
||||
instanceResource["project_id"],
|
||||
instanceName,
|
||||
instanceResource["plan_name"],
|
||||
scrapeConfigResource["name"],
|
||||
scrapeConfigResource["metrics_path"],
|
||||
target,
|
||||
scrapeConfigResource["scrape_interval"],
|
||||
saml2EnableUrlParameters,
|
||||
)
|
||||
}
|
||||
|
||||
func TestAccResource(t *testing.T) {
|
||||
resource.Test(t, resource.TestCase{
|
||||
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
|
||||
CheckDestroy: testAccCheckArgusDestroy,
|
||||
Steps: []resource.TestStep{
|
||||
// Creation
|
||||
{
|
||||
Config: resourceConfig(instanceResource["name"], scrapeConfigResource["urls"], scrapeConfigResource["saml2_enable_url_parameters"]),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("stackit_argus_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_argus_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_argus_instance.instance", "plan_name", instanceResource["plan_name"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "dashboard_url"),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "is_updatable"),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "grafana_public_read_access"),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "grafana_url"),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "grafana_initial_admin_user"),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "grafana_initial_admin_password"),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "metrics_retention_days"),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "metrics_retention_days_5m_downsampling"),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "metrics_retention_days_1h_downsampling"),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "metrics_url"),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "metrics_push_url"),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "targets_url"),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "alerting_url"),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "logs_url"),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "logs_push_url"),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "jaeger_traces_url"),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "jaeger_ui_url"),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "otlp_traces_url"),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "zipkin_spans_url"),
|
||||
|
||||
// scrape config data
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_argus_instance.instance", "project_id",
|
||||
"stackit_argus_scrapeconfig.scrapeconfig", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_argus_instance.instance", "instance_id",
|
||||
"stackit_argus_scrapeconfig.scrapeconfig", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "name", scrapeConfigResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "targets.0.urls.#", "2"),
|
||||
resource.TestCheckResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "metrics_path", scrapeConfigResource["metrics_path"]),
|
||||
resource.TestCheckResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "scheme", scrapeConfigResource["scheme"]),
|
||||
resource.TestCheckResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "scrape_interval", scrapeConfigResource["scrape_interval"]),
|
||||
resource.TestCheckResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "scrape_interval", scrapeConfigResource["scrape_interval"]),
|
||||
resource.TestCheckResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "saml2.enable_url_parameters", scrapeConfigResource["saml2_enable_url_parameters"]),
|
||||
|
||||
// credentials
|
||||
resource.TestCheckResourceAttr("stackit_argus_credential.credential", "project_id", credentialsResource["project_id"]),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_argus_instance.instance", "instance_id",
|
||||
"stackit_argus_credential.credential", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_credential.credential", "username"),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_credential.credential", "password"),
|
||||
),
|
||||
}, {
|
||||
// Data source
|
||||
Config: fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
data "stackit_argus_instance" "instance" {
|
||||
project_id = stackit_argus_instance.instance.project_id
|
||||
instance_id = stackit_argus_instance.instance.instance_id
|
||||
}
|
||||
|
||||
data "stackit_argus_scrapeconfig" "scrapeconfig" {
|
||||
project_id = stackit_argus_scrapeconfig.scrapeconfig.project_id
|
||||
instance_id = stackit_argus_scrapeconfig.scrapeconfig.instance_id
|
||||
name = stackit_argus_scrapeconfig.scrapeconfig.name
|
||||
}
|
||||
`,
|
||||
resourceConfig(instanceResource["name"], scrapeConfigResource["urls"], scrapeConfigResource["saml2_enable_url_parameters"]),
|
||||
),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("data.stackit_argus_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_argus_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("data.stackit_argus_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_argus_instance.instance", "plan_name", instanceResource["plan_name"]),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_argus_instance.instance", "project_id",
|
||||
"data.stackit_argus_instance.instance", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_argus_instance.instance", "instance_id",
|
||||
"data.stackit_argus_instance.instance", "instance_id",
|
||||
),
|
||||
// scrape config data
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_argus_scrapeconfig.scrapeconfig", "project_id",
|
||||
"data.stackit_argus_scrapeconfig.scrapeconfig", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_argus_scrapeconfig.scrapeconfig", "instance_id",
|
||||
"data.stackit_argus_scrapeconfig.scrapeconfig", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_argus_scrapeconfig.scrapeconfig", "name",
|
||||
"data.stackit_argus_scrapeconfig.scrapeconfig", "name",
|
||||
),
|
||||
resource.TestCheckResourceAttr("data.stackit_argus_scrapeconfig.scrapeconfig", "name", scrapeConfigResource["name"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_argus_scrapeconfig.scrapeconfig", "targets.0.urls.#", "2"),
|
||||
resource.TestCheckResourceAttr("data.stackit_argus_scrapeconfig.scrapeconfig", "metrics_path", scrapeConfigResource["metrics_path"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_argus_scrapeconfig.scrapeconfig", "scheme", scrapeConfigResource["scheme"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_argus_scrapeconfig.scrapeconfig", "scrape_interval", scrapeConfigResource["scrape_interval"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_argus_scrapeconfig.scrapeconfig", "saml2.enable_url_parameters", scrapeConfigResource["saml2_enable_url_parameters"]),
|
||||
),
|
||||
},
|
||||
|
||||
// Import
|
||||
{
|
||||
ResourceName: "stackit_argus_instance.instance",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_argus_instance.instance"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_argus_instance.instance")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s,%s", testutil.ProjectId, instanceId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
{
|
||||
ResourceName: "stackit_argus_scrapeconfig.scrapeconfig",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_argus_scrapeconfig.scrapeconfig"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_argus_scrapeconfig.scrapeconfig")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
name, ok := r.Primary.Attributes["name"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute name")
|
||||
}
|
||||
return fmt.Sprintf("%s,%s,%s", testutil.ProjectId, instanceId, name), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
// Update
|
||||
{
|
||||
Config: resourceConfig(fmt.Sprintf("%s-new", instanceResource["name"]), "", "true"),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance
|
||||
resource.TestCheckResourceAttr("stackit_argus_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_argus_instance.instance", "name", instanceResource["name"]+"-new"),
|
||||
resource.TestCheckResourceAttr("stackit_argus_instance.instance", "plan_name", instanceResource["plan_name"]),
|
||||
|
||||
// Scrape Config
|
||||
resource.TestCheckResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "name", scrapeConfigResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "targets.#", "0"),
|
||||
resource.TestCheckResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "metrics_path", scrapeConfigResource["metrics_path"]),
|
||||
resource.TestCheckResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "scheme", scrapeConfigResource["scheme"]),
|
||||
resource.TestCheckResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "scrape_interval", scrapeConfigResource["scrape_interval"]),
|
||||
resource.TestCheckResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "saml2.%", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "saml2.enable_url_parameters", "true"),
|
||||
|
||||
// Credentials
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_credential.credential", "username"),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_credential.credential", "password"),
|
||||
),
|
||||
},
|
||||
// Update and remove saml2 attribute
|
||||
{
|
||||
Config: fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
resource "stackit_argus_instance" "instance" {
|
||||
project_id = "%s"
|
||||
name = "%s"
|
||||
plan_name = "%s"
|
||||
}
|
||||
|
||||
resource "stackit_argus_scrapeconfig" "scrapeconfig" {
|
||||
project_id = stackit_argus_instance.instance.project_id
|
||||
instance_id = stackit_argus_instance.instance.instance_id
|
||||
name = "%s"
|
||||
targets = [%s]
|
||||
scrape_interval = "%s"
|
||||
metrics_path = "%s"
|
||||
}
|
||||
`,
|
||||
testutil.ArgusProviderConfig(),
|
||||
instanceResource["project_id"],
|
||||
instanceResource["name"],
|
||||
instanceResource["plan_name"],
|
||||
scrapeConfigResource["name"],
|
||||
scrapeConfigResource["urls"],
|
||||
scrapeConfigResource["scrape_interval"],
|
||||
scrapeConfigResource["metrics_path"],
|
||||
),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance
|
||||
resource.TestCheckResourceAttr("stackit_argus_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_argus_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_argus_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_argus_instance.instance", "plan_name", instanceResource["plan_name"]),
|
||||
|
||||
// Scrape Config
|
||||
resource.TestCheckResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "name", scrapeConfigResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "targets.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "metrics_path", scrapeConfigResource["metrics_path"]),
|
||||
resource.TestCheckResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "scheme", scrapeConfigResource["scheme"]),
|
||||
resource.TestCheckResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "scrape_interval", scrapeConfigResource["scrape_interval"]),
|
||||
resource.TestCheckResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "saml2.%", "0"),
|
||||
resource.TestCheckNoResourceAttr("stackit_argus_scrapeconfig.scrapeconfig", "saml2.enable_url_parameters"),
|
||||
),
|
||||
},
|
||||
|
||||
// Deletion is done by the framework implicitly
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func testAccCheckArgusDestroy(s *terraform.State) error {
|
||||
ctx := context.Background()
|
||||
var client *argus.APIClient
|
||||
var err error
|
||||
if testutil.ArgusCustomEndpoint == "" {
|
||||
client, err = argus.NewAPIClient()
|
||||
} else {
|
||||
client, err = argus.NewAPIClient(
|
||||
config.WithEndpoint(testutil.ArgusCustomEndpoint),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating client: %w", err)
|
||||
}
|
||||
|
||||
instancesToDestroy := []string{}
|
||||
for _, rs := range s.RootModule().Resources {
|
||||
if rs.Type != "stackit_argus_instance" {
|
||||
continue
|
||||
}
|
||||
// instance terraform ID: = "[project_id],[instance_id],[name]"
|
||||
instanceId := strings.Split(rs.Primary.ID, core.Separator)[1]
|
||||
instancesToDestroy = append(instancesToDestroy, instanceId)
|
||||
}
|
||||
|
||||
instancesResp, err := client.GetInstances(ctx, testutil.ProjectId).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting instancesResp: %w", err)
|
||||
}
|
||||
|
||||
instances := *instancesResp.Instances
|
||||
for i := range instances {
|
||||
if utils.Contains(instancesToDestroy, *instances[i].Id) {
|
||||
if *instances[i].Status != argus.DeleteSuccess {
|
||||
_, err := client.DeleteInstanceExecute(ctx, testutil.ProjectId, *instances[i].Id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying instance %s during CheckDestroy: %w", *instances[i].Id, err)
|
||||
}
|
||||
_, err = argus.DeleteInstanceWaitHandler(ctx, client, testutil.ProjectId, *instances[i].Id).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying instance %s during CheckDestroy: waiting for deletion %w", *instances[i].Id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
244
stackit/internal/services/argus/credential/resource.go
Normal file
244
stackit/internal/services/argus/credential/resource.go
Normal file
|
|
@ -0,0 +1,244 @@
|
|||
package argus
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/argus"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &credentialResource{}
|
||||
_ resource.ResourceWithConfigure = &credentialResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
Username types.String `tfsdk:"username"`
|
||||
Password types.String `tfsdk:"password"`
|
||||
}
|
||||
|
||||
// NewCredentialResource is a helper function to simplify the provider implementation.
|
||||
func NewCredentialResource() resource.Resource {
|
||||
return &credentialResource{}
|
||||
}
|
||||
|
||||
// credentialResource is the resource implementation.
|
||||
type credentialResource struct {
|
||||
client *argus.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *credentialResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_argus_credential"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *credentialResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *argus.APIClient
|
||||
var err error
|
||||
if providerData.ArgusCustomEndpoint != "" {
|
||||
apiClient, err = argus.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.ArgusCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = argus.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "Argus credential client configured")
|
||||
}
|
||||
|
||||
func (r *credentialResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`,`username`\".",
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: "STACKIT project ID to which the credential is associated.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
},
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: "The Argus Instance ID the credential belongs to.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
},
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Description: "Credential username",
|
||||
Computed: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
},
|
||||
},
|
||||
"password": schema.StringAttribute{
|
||||
Description: "Credential password",
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
},
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *credentialResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
|
||||
got, err := r.client.CreateCredential(ctx, instanceId, projectId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credential", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
err = mapFields(got.Credentials, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credential", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
diags = resp.State.Set(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Argus credential created")
|
||||
}
|
||||
|
||||
func mapFields(r *argus.Credential, model *Model) error {
|
||||
if r == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
var userName string
|
||||
if model.Username.ValueString() != "" {
|
||||
userName = model.Username.ValueString()
|
||||
} else if r.Username != nil {
|
||||
userName = *r.Username
|
||||
} else {
|
||||
return fmt.Errorf("username id not present")
|
||||
}
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
model.InstanceId.ValueString(),
|
||||
userName,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.Username = types.StringPointerValue(r.Username)
|
||||
model.Password = types.StringPointerValue(r.Password)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *credentialResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
userName := model.Username.ValueString()
|
||||
_, err := r.client.GetCredential(ctx, instanceId, projectId, userName).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credential", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Argus credential read")
|
||||
}
|
||||
|
||||
func (r *credentialResource) Update(ctx context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Update shouldn't be called
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating credential", "Credential can't be updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *credentialResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from state
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
userName := model.Username.ValueString()
|
||||
_, err := r.client.DeleteCredential(ctx, instanceId, projectId, userName).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credential", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Argus credential deleted")
|
||||
}
|
||||
77
stackit/internal/services/argus/credential/resource_test.go
Normal file
77
stackit/internal/services/argus/credential/resource_test.go
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
package argus
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/argus"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *argus.Credential
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"ok",
|
||||
&argus.Credential{
|
||||
Username: utils.Ptr("username"),
|
||||
Password: utils.Ptr("password"),
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,username"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
Username: types.StringValue("username"),
|
||||
Password: types.StringValue("password"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"response_nil_fail",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"response_fields_nil_fail",
|
||||
&argus.Credential{
|
||||
Password: nil,
|
||||
Username: nil,
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&argus.Credential{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
state := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
}
|
||||
err := mapFields(tt.input, state)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
229
stackit/internal/services/argus/instance/datasource.go
Normal file
229
stackit/internal/services/argus/instance/datasource.go
Normal file
|
|
@ -0,0 +1,229 @@
|
|||
package argus
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/argus"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &instanceDataSource{}
|
||||
)
|
||||
|
||||
// NewInstanceDataSource is a helper function to simplify the provider implementation.
|
||||
func NewInstanceDataSource() datasource.DataSource {
|
||||
return &instanceDataSource{}
|
||||
}
|
||||
|
||||
// instanceDataSource is the data source implementation.
|
||||
type instanceDataSource struct {
|
||||
client *argus.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the data source type name.
|
||||
func (d *instanceDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_argus_instance"
|
||||
}
|
||||
|
||||
func (d *instanceDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *argus.APIClient
|
||||
var err error
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
if providerData.ArgusCustomEndpoint != "" {
|
||||
apiClient, err = argus.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.ArgusCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = argus.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
d.client = apiClient
|
||||
tflog.Info(ctx, "Argus instance client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the data source.
|
||||
func (d *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`\".",
|
||||
Computed: true,
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: "STACKIT project ID to which the instance is associated.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: "The Argus instance ID.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: "The name of the Argus instance.",
|
||||
Computed: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
stringvalidator.LengthAtMost(300),
|
||||
},
|
||||
},
|
||||
"plan_name": schema.StringAttribute{
|
||||
Description: "Specifies the Argus plan. E.g. `Monitoring-Medium-EU01`.",
|
||||
Computed: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
stringvalidator.LengthAtMost(200),
|
||||
},
|
||||
},
|
||||
"plan_id": schema.StringAttribute{
|
||||
Description: "The Argus plan ID.",
|
||||
Computed: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
},
|
||||
},
|
||||
"parameters": schema.MapAttribute{
|
||||
Description: "Additional parameters.",
|
||||
Computed: true,
|
||||
ElementType: types.StringType,
|
||||
},
|
||||
"dashboard_url": schema.StringAttribute{
|
||||
Description: "Specifies Argus instance dashboard URL.",
|
||||
Computed: true,
|
||||
},
|
||||
"is_updatable": schema.BoolAttribute{
|
||||
Description: "Specifies if the instance can be updated.",
|
||||
Computed: true,
|
||||
},
|
||||
"grafana_public_read_access": schema.BoolAttribute{
|
||||
Description: "If true, anyone can access Grafana dashboards without logging in.",
|
||||
Computed: true,
|
||||
},
|
||||
"grafana_url": schema.StringAttribute{
|
||||
Description: "Specifies Grafana URL.",
|
||||
Computed: true,
|
||||
},
|
||||
"grafana_initial_admin_user": schema.StringAttribute{
|
||||
Description: "Specifies an initial Grafana admin username.",
|
||||
Computed: true,
|
||||
},
|
||||
"grafana_initial_admin_password": schema.StringAttribute{
|
||||
Description: "Specifies an initial Grafana admin password.",
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"metrics_retention_days": schema.Int64Attribute{
|
||||
Description: "Specifies for how many days the raw metrics are kept.",
|
||||
Computed: true,
|
||||
},
|
||||
"metrics_retention_days_5m_downsampling": schema.Int64Attribute{
|
||||
Description: "Specifies for how many days the 5m downsampled metrics are kept. must be less than the value of the general retention. Default is set to `0` (disabled).",
|
||||
Computed: true,
|
||||
},
|
||||
"metrics_retention_days_1h_downsampling": schema.Int64Attribute{
|
||||
Description: "Specifies for how many days the 1h downsampled metrics are kept. must be less than the value of the 5m downsampling retention. Default is set to `0` (disabled).",
|
||||
Computed: true,
|
||||
},
|
||||
"metrics_url": schema.StringAttribute{
|
||||
Description: "Specifies metrics URL.",
|
||||
Computed: true,
|
||||
},
|
||||
"metrics_push_url": schema.StringAttribute{
|
||||
Description: "Specifies URL for pushing metrics.",
|
||||
Computed: true,
|
||||
},
|
||||
"targets_url": schema.StringAttribute{
|
||||
Description: "Specifies Targets URL.",
|
||||
Computed: true,
|
||||
},
|
||||
"alerting_url": schema.StringAttribute{
|
||||
Description: "Specifies Alerting URL.",
|
||||
Computed: true,
|
||||
},
|
||||
"logs_url": schema.StringAttribute{
|
||||
Description: "Specifies Logs URL.",
|
||||
Computed: true,
|
||||
},
|
||||
"logs_push_url": schema.StringAttribute{
|
||||
Description: "Specifies URL for pushing logs.",
|
||||
Computed: true,
|
||||
},
|
||||
"jaeger_traces_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"jaeger_ui_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"otlp_traces_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"zipkin_spans_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (d *instanceDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
instanceResponse, err := d.client.GetInstance(ctx, instanceId, projectId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
err = mapFields(ctx, instanceResponse, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Argus instance read")
|
||||
}
|
||||
574
stackit/internal/services/argus/instance/resource.go
Normal file
574
stackit/internal/services/argus/instance/resource.go
Normal file
|
|
@ -0,0 +1,574 @@
|
|||
package argus
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/mapplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/argus"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &instanceResource{}
|
||||
_ resource.ResourceWithConfigure = &instanceResource{}
|
||||
_ resource.ResourceWithImportState = &instanceResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
PlanName types.String `tfsdk:"plan_name"`
|
||||
PlanId types.String `tfsdk:"plan_id"`
|
||||
Parameters types.Map `tfsdk:"parameters"`
|
||||
DashboardURL types.String `tfsdk:"dashboard_url"`
|
||||
IsUpdatable types.Bool `tfsdk:"is_updatable"`
|
||||
GrafanaURL types.String `tfsdk:"grafana_url"`
|
||||
GrafanaPublicReadAccess types.Bool `tfsdk:"grafana_public_read_access"`
|
||||
GrafanaInitialAdminPassword types.String `tfsdk:"grafana_initial_admin_password"`
|
||||
GrafanaInitialAdminUser types.String `tfsdk:"grafana_initial_admin_user"`
|
||||
MetricsRetentionDays types.Int64 `tfsdk:"metrics_retention_days"`
|
||||
MetricsRetentionDays5mDownsampling types.Int64 `tfsdk:"metrics_retention_days_5m_downsampling"`
|
||||
MetricsRetentionDays1hDownsampling types.Int64 `tfsdk:"metrics_retention_days_1h_downsampling"`
|
||||
MetricsURL types.String `tfsdk:"metrics_url"`
|
||||
MetricsPushURL types.String `tfsdk:"metrics_push_url"`
|
||||
TargetsURL types.String `tfsdk:"targets_url"`
|
||||
AlertingURL types.String `tfsdk:"alerting_url"`
|
||||
LogsURL types.String `tfsdk:"logs_url"`
|
||||
LogsPushURL types.String `tfsdk:"logs_push_url"`
|
||||
JaegerTracesURL types.String `tfsdk:"jaeger_traces_url"`
|
||||
JaegerUIURL types.String `tfsdk:"jaeger_ui_url"`
|
||||
OtlpTracesURL types.String `tfsdk:"otlp_traces_url"`
|
||||
ZipkinSpansURL types.String `tfsdk:"zipkin_spans_url"`
|
||||
}
|
||||
|
||||
// NewInstanceResource is a helper function to simplify the provider implementation.
|
||||
func NewInstanceResource() resource.Resource {
|
||||
return &instanceResource{}
|
||||
}
|
||||
|
||||
// instanceResource is the resource implementation.
|
||||
type instanceResource struct {
|
||||
client *argus.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *instanceResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_argus_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *instanceResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *argus.APIClient
|
||||
var err error
|
||||
if providerData.ArgusCustomEndpoint != "" {
|
||||
apiClient, err = argus.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.ArgusCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = argus.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "Argus instance client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *instanceResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`\".",
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: "STACKIT project ID to which the instance is associated.",
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: "The Argus instance ID.",
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: "The name of the Argus instance.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
stringvalidator.LengthAtMost(200),
|
||||
},
|
||||
},
|
||||
"plan_name": schema.StringAttribute{
|
||||
Description: "Specifies the Argus plan. E.g. `Monitoring-Medium-EU01`.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
stringvalidator.LengthAtMost(200),
|
||||
},
|
||||
},
|
||||
"plan_id": schema.StringAttribute{
|
||||
Description: "The Argus plan ID.",
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
},
|
||||
},
|
||||
"parameters": schema.MapAttribute{
|
||||
Description: "Additional parameters.",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
ElementType: types.StringType,
|
||||
PlanModifiers: []planmodifier.Map{
|
||||
mapplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"dashboard_url": schema.StringAttribute{
|
||||
Description: "Specifies Argus instance dashboard URL.",
|
||||
Computed: true,
|
||||
},
|
||||
"is_updatable": schema.BoolAttribute{
|
||||
Description: "Specifies if the instance can be updated.",
|
||||
Computed: true,
|
||||
},
|
||||
"grafana_public_read_access": schema.BoolAttribute{
|
||||
Description: "If true, anyone can access Grafana dashboards without logging in.",
|
||||
Computed: true,
|
||||
},
|
||||
"grafana_url": schema.StringAttribute{
|
||||
Description: "Specifies Grafana URL.",
|
||||
Computed: true,
|
||||
},
|
||||
"grafana_initial_admin_user": schema.StringAttribute{
|
||||
Description: "Specifies an initial Grafana admin username.",
|
||||
Computed: true,
|
||||
},
|
||||
"grafana_initial_admin_password": schema.StringAttribute{
|
||||
Description: "Specifies an initial Grafana admin password.",
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"metrics_retention_days": schema.Int64Attribute{
|
||||
Description: "Specifies for how many days the raw metrics are kept.",
|
||||
Computed: true,
|
||||
},
|
||||
"metrics_retention_days_5m_downsampling": schema.Int64Attribute{
|
||||
Description: "Specifies for how many days the 5m downsampled metrics are kept. must be less than the value of the general retention. Default is set to `0` (disabled).",
|
||||
Computed: true,
|
||||
},
|
||||
"metrics_retention_days_1h_downsampling": schema.Int64Attribute{
|
||||
Description: "Specifies for how many days the 1h downsampled metrics are kept. must be less than the value of the 5m downsampling retention. Default is set to `0` (disabled).",
|
||||
Computed: true,
|
||||
},
|
||||
"metrics_url": schema.StringAttribute{
|
||||
Description: "Specifies metrics URL.",
|
||||
Computed: true,
|
||||
},
|
||||
"metrics_push_url": schema.StringAttribute{
|
||||
Description: "Specifies URL for pushing metrics.",
|
||||
Computed: true,
|
||||
},
|
||||
"targets_url": schema.StringAttribute{
|
||||
Description: "Specifies Targets URL.",
|
||||
Computed: true,
|
||||
},
|
||||
"alerting_url": schema.StringAttribute{
|
||||
Description: "Specifies Alerting URL.",
|
||||
Computed: true,
|
||||
},
|
||||
"logs_url": schema.StringAttribute{
|
||||
Description: "Specifies Logs URL.",
|
||||
Computed: true,
|
||||
},
|
||||
"logs_push_url": schema.StringAttribute{
|
||||
Description: "Specifies URL for pushing logs.",
|
||||
Computed: true,
|
||||
},
|
||||
"jaeger_traces_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"jaeger_ui_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"otlp_traces_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"zipkin_spans_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *instanceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
|
||||
err := r.loadPlanId(ctx, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Loading service plan: %v", err))
|
||||
return
|
||||
}
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
createResp, err := r.client.CreateInstance(ctx, projectId).CreateInstancePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
instanceId := createResp.InstanceId
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
wr, err := argus.CreateInstanceWaitHandler(ctx, r.client, *instanceId, projectId).SetTimeout(20 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Instance creation waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*argus.InstanceResponse)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(ctx, got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Argus instance created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
instanceResp, err := r.client.GetInstance(ctx, instanceId, projectId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(ctx, instanceResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Set refreshed model
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Argus instance created")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *instanceResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
|
||||
err := r.loadPlanId(ctx, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Loading service plan: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toUpdatePayload(&model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Update existing instance
|
||||
_, err = r.client.UpdateInstance(ctx, instanceId, projectId).UpdateInstancePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
wr, err := argus.UpdateInstanceWaitHandler(ctx, r.client, instanceId, projectId).SetTimeout(20 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Instance update waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*argus.InstanceResponse)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
err = mapFields(ctx, got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Argus instance updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *instanceResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from state
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
|
||||
// Delete existing instance
|
||||
_, err := r.client.DeleteInstance(ctx, instanceId, projectId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
_, err = argus.DeleteInstanceWaitHandler(ctx, r.client, instanceId, projectId).SetTimeout(10 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
tflog.Info(ctx, "Argus instance deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,instance_id
|
||||
func (r *instanceResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
|
||||
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing instance",
|
||||
fmt.Sprintf("Expected import identifier with format: [project_id],[instance_id] Got: %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[1])...)
|
||||
tflog.Info(ctx, "Argus instance state imported")
|
||||
}
|
||||
|
||||
func mapFields(ctx context.Context, r *argus.InstanceResponse, model *Model) error {
|
||||
if r == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
var instanceId string
|
||||
if model.InstanceId.ValueString() != "" {
|
||||
instanceId = model.InstanceId.ValueString()
|
||||
} else if r.Id != nil {
|
||||
instanceId = *r.Id
|
||||
} else {
|
||||
return fmt.Errorf("instance id not present")
|
||||
}
|
||||
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
instanceId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.InstanceId = types.StringValue(instanceId)
|
||||
model.PlanName = types.StringPointerValue(r.PlanName)
|
||||
model.PlanId = types.StringPointerValue(r.PlanId)
|
||||
model.Name = types.StringPointerValue(r.Name)
|
||||
|
||||
ps := r.Parameters
|
||||
if ps == nil {
|
||||
model.Parameters = types.MapNull(types.StringType)
|
||||
} else {
|
||||
params := make(map[string]attr.Value, len(*ps))
|
||||
for k, v := range *ps {
|
||||
params[k] = types.StringValue(v)
|
||||
}
|
||||
res, diags := types.MapValueFrom(ctx, types.StringType, params)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("parameter mapping %s", diags.Errors())
|
||||
}
|
||||
model.Parameters = res
|
||||
}
|
||||
|
||||
model.IsUpdatable = types.BoolPointerValue(r.IsUpdatable)
|
||||
model.DashboardURL = types.StringPointerValue(r.DashboardUrl)
|
||||
if r.Instance != nil {
|
||||
i := *r.Instance
|
||||
model.GrafanaURL = types.StringPointerValue(i.GrafanaUrl)
|
||||
model.GrafanaPublicReadAccess = types.BoolPointerValue(i.GrafanaPublicReadAccess)
|
||||
model.GrafanaInitialAdminPassword = types.StringPointerValue(i.GrafanaAdminPassword)
|
||||
model.GrafanaInitialAdminUser = types.StringPointerValue(i.GrafanaAdminUser)
|
||||
model.MetricsRetentionDays = types.Int64Value(int64(*i.MetricsRetentionTimeRaw))
|
||||
model.MetricsRetentionDays5mDownsampling = types.Int64Value(int64(*i.MetricsRetentionTime5m))
|
||||
model.MetricsRetentionDays1hDownsampling = types.Int64Value(int64(*i.MetricsRetentionTime1h))
|
||||
model.MetricsURL = types.StringPointerValue(i.MetricsUrl)
|
||||
model.MetricsPushURL = types.StringPointerValue(i.PushMetricsUrl)
|
||||
model.TargetsURL = types.StringPointerValue(i.TargetsUrl)
|
||||
model.AlertingURL = types.StringPointerValue(i.AlertingUrl)
|
||||
model.LogsURL = types.StringPointerValue(i.LogsUrl)
|
||||
model.LogsPushURL = types.StringPointerValue(i.LogsPushUrl)
|
||||
model.JaegerTracesURL = types.StringPointerValue(i.JaegerTracesUrl)
|
||||
model.JaegerUIURL = types.StringPointerValue(i.JaegerUiUrl)
|
||||
model.OtlpTracesURL = types.StringPointerValue(i.OtlpTracesUrl)
|
||||
model.ZipkinSpansURL = types.StringPointerValue(i.ZipkinSpansUrl)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model) (*argus.CreateInstancePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
elements := model.Parameters.Elements()
|
||||
pa := make(map[string]interface{}, len(elements))
|
||||
for k := range elements {
|
||||
pa[k] = elements[k].String()
|
||||
}
|
||||
return &argus.CreateInstancePayload{
|
||||
Name: model.Name.ValueStringPointer(),
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
Parameter: &pa,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toUpdatePayload(model *Model) (*argus.UpdateInstancePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
elements := model.Parameters.Elements()
|
||||
pa := make(map[string]interface{}, len(elements))
|
||||
for k, v := range elements {
|
||||
pa[k] = v.String()
|
||||
}
|
||||
return &argus.UpdateInstancePayload{
|
||||
Name: model.Name.ValueStringPointer(),
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
Parameter: &pa,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *instanceResource) loadPlanId(ctx context.Context, model *Model) error {
|
||||
projectId := model.ProjectId.ValueString()
|
||||
res, err := r.client.GetPlans(ctx, projectId).Execute()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
planName := model.PlanName.ValueString()
|
||||
avl := ""
|
||||
plans := *res.Plans
|
||||
for i := range plans {
|
||||
p := plans[i]
|
||||
if p.Name == nil {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(*p.Name, planName) && p.PlanId != nil {
|
||||
model.PlanId = types.StringPointerValue(p.PlanId)
|
||||
break
|
||||
}
|
||||
avl = fmt.Sprintf("%s\n- %s", avl, *p.Name)
|
||||
}
|
||||
if model.PlanId.ValueString() == "" {
|
||||
return fmt.Errorf("couldn't find plan_name '%s', available names are: %s", planName, avl)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
250
stackit/internal/services/argus/instance/resource_test.go
Normal file
250
stackit/internal/services/argus/instance/resource_test.go
Normal file
|
|
@ -0,0 +1,250 @@
|
|||
package argus
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/argus"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *argus.InstanceResponse
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_ok",
|
||||
&argus.InstanceResponse{
|
||||
Id: utils.Ptr("iid"),
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
PlanId: types.StringNull(),
|
||||
PlanName: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Parameters: types.MapNull(types.StringType),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"values_ok",
|
||||
&argus.InstanceResponse{
|
||||
Id: utils.Ptr("iid"),
|
||||
Name: utils.Ptr("name"),
|
||||
PlanName: utils.Ptr("plan1"),
|
||||
PlanId: utils.Ptr("planId"),
|
||||
Parameters: &map[string]string{"key": "value"},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringValue("name"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
PlanId: types.StringValue("planId"),
|
||||
PlanName: types.StringValue("plan1"),
|
||||
Parameters: toTerraformStringMapMust(context.Background(), map[string]string{"key": "value"}),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nullable_fields_ok",
|
||||
&argus.InstanceResponse{
|
||||
Id: utils.Ptr("iid"),
|
||||
Name: nil,
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
PlanId: types.StringNull(),
|
||||
PlanName: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Parameters: types.MapNull(types.StringType),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"response_nil_fail",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&argus.InstanceResponse{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
state := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
}
|
||||
err := mapFields(context.Background(), tt.input, state)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
expected *argus.CreateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"basic_ok",
|
||||
&Model{
|
||||
PlanId: types.StringValue("planId"),
|
||||
},
|
||||
&argus.CreateInstancePayload{
|
||||
Name: nil,
|
||||
PlanId: utils.Ptr("planId"),
|
||||
Parameter: &map[string]interface{}{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"ok",
|
||||
&Model{
|
||||
Name: types.StringValue("Name"),
|
||||
PlanId: types.StringValue("planId"),
|
||||
Parameters: makeTestMap(t),
|
||||
},
|
||||
&argus.CreateInstancePayload{
|
||||
Name: utils.Ptr("Name"),
|
||||
PlanId: utils.Ptr("planId"),
|
||||
Parameter: &map[string]interface{}{"key": `"value"`},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toCreatePayload(tt.input)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToPayloadUpdate(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
expected *argus.UpdateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"basic_ok",
|
||||
&Model{
|
||||
PlanId: types.StringValue("planId"),
|
||||
},
|
||||
&argus.UpdateInstancePayload{
|
||||
Name: nil,
|
||||
PlanId: utils.Ptr("planId"),
|
||||
Parameter: &map[string]any{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"ok",
|
||||
&Model{
|
||||
Name: types.StringValue("Name"),
|
||||
PlanId: types.StringValue("planId"),
|
||||
Parameters: makeTestMap(t),
|
||||
},
|
||||
&argus.UpdateInstancePayload{
|
||||
Name: utils.Ptr("Name"),
|
||||
PlanId: utils.Ptr("planId"),
|
||||
Parameter: &map[string]any{"key": `"value"`},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toUpdatePayload(tt.input)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func makeTestMap(t *testing.T) basetypes.MapValue {
|
||||
p := make(map[string]attr.Value, 1)
|
||||
p["key"] = types.StringValue("value")
|
||||
params, diag := types.MapValueFrom(context.Background(), types.StringType, p)
|
||||
if diag.HasError() {
|
||||
t.Fail()
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
// ToTerraformStringMapMust Silently ignores the error
|
||||
func toTerraformStringMapMust(ctx context.Context, m map[string]string) basetypes.MapValue {
|
||||
labels := make(map[string]attr.Value, len(m))
|
||||
for l, v := range m {
|
||||
stringValue := types.StringValue(v)
|
||||
labels[l] = stringValue
|
||||
}
|
||||
res, diags := types.MapValueFrom(ctx, types.StringType, m)
|
||||
if diags.HasError() {
|
||||
return types.MapNull(types.StringType)
|
||||
}
|
||||
return res
|
||||
}
|
||||
218
stackit/internal/services/argus/scrapeconfig/datasource.go
Normal file
218
stackit/internal/services/argus/scrapeconfig/datasource.go
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
package argus
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/listvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/mapvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/argus"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &scrapeConfigDataSource{}
|
||||
)
|
||||
|
||||
// NewScrapeConfigDataSource is a helper function to simplify the provider implementation.
|
||||
func NewScrapeConfigDataSource() datasource.DataSource {
|
||||
return &scrapeConfigDataSource{}
|
||||
}
|
||||
|
||||
// scrapeConfigDataSource is the data source implementation.
|
||||
type scrapeConfigDataSource struct {
|
||||
client *argus.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the data source type name.
|
||||
func (d *scrapeConfigDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_argus_scrapeconfig"
|
||||
}
|
||||
|
||||
func (d *scrapeConfigDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *argus.APIClient
|
||||
var err error
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
if providerData.ArgusCustomEndpoint != "" {
|
||||
apiClient, err = argus.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.ArgusCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = argus.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
d.client = apiClient
|
||||
}
|
||||
|
||||
// Schema defines the schema for the data source.
|
||||
func (d *scrapeConfigDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`,`name`\".",
|
||||
Computed: true,
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: "STACKIT project ID to which the scraping job is associated.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: "Argus instance ID to which the scraping job is associated.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: "Specifies the name of the scraping job",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
stringvalidator.LengthBetween(1, 200),
|
||||
},
|
||||
},
|
||||
"metrics_path": schema.StringAttribute{
|
||||
Description: "Specifies the job scraping url path.",
|
||||
Computed: true,
|
||||
},
|
||||
|
||||
"scheme": schema.StringAttribute{
|
||||
Description: "Specifies the http scheme.",
|
||||
Computed: true,
|
||||
},
|
||||
|
||||
"scrape_interval": schema.StringAttribute{
|
||||
Description: "Specifies the scrape interval as duration string.",
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthBetween(2, 8),
|
||||
},
|
||||
Computed: true,
|
||||
},
|
||||
|
||||
"scrape_timeout": schema.StringAttribute{
|
||||
Description: "Specifies the scrape timeout as duration string.",
|
||||
Computed: true,
|
||||
},
|
||||
"saml2": schema.SingleNestedAttribute{
|
||||
Description: "A SAML2 configuration block",
|
||||
Computed: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"enable_url_parameters": schema.BoolAttribute{
|
||||
Description: "Are URL parameters be enabled?",
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
"basic_auth": schema.SingleNestedAttribute{
|
||||
Description: "A basic authentication block.",
|
||||
Computed: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"username": schema.StringAttribute{
|
||||
Description: "Specifies basic auth username.",
|
||||
Computed: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthBetween(1, 200),
|
||||
},
|
||||
},
|
||||
"password": schema.StringAttribute{
|
||||
Description: "Specifies basic auth password.",
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthBetween(1, 200),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"targets": schema.ListNestedAttribute{
|
||||
Description: "The targets list (specified by the static config).",
|
||||
Computed: true,
|
||||
NestedObject: schema.NestedAttributeObject{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"urls": schema.ListAttribute{
|
||||
Description: "Specifies target URLs.",
|
||||
Computed: true,
|
||||
ElementType: types.StringType,
|
||||
Validators: []validator.List{
|
||||
listvalidator.ValueStringsAre(
|
||||
stringvalidator.LengthBetween(1, 500),
|
||||
),
|
||||
},
|
||||
},
|
||||
"labels": schema.MapAttribute{
|
||||
Description: "Specifies labels.",
|
||||
Computed: true,
|
||||
ElementType: types.StringType,
|
||||
Validators: []validator.Map{
|
||||
mapvalidator.SizeAtMost(10),
|
||||
mapvalidator.ValueStringsAre(stringvalidator.LengthBetween(0, 200)),
|
||||
mapvalidator.KeysAre(stringvalidator.LengthBetween(0, 200)),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (d *scrapeConfigDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
scName := model.Name.ValueString()
|
||||
|
||||
scResp, err := d.client.GetScrapeConfig(ctx, instanceId, scName, projectId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Unable to read scrape config", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
err = mapFields(scResp.Data, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Mapping fields", err.Error())
|
||||
return
|
||||
}
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
687
stackit/internal/services/argus/scrapeconfig/resource.go
Normal file
687
stackit/internal/services/argus/scrapeconfig/resource.go
Normal file
|
|
@ -0,0 +1,687 @@
|
|||
package argus
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/listvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/mapvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/argus"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultScheme = "https" // API default is "http"
|
||||
DefaultScrapeInterval = "5m"
|
||||
DefaultScrapeTimeout = "2m"
|
||||
DefaultSAML2EnableURLParameters = true
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &scrapeConfigResource{}
|
||||
_ resource.ResourceWithConfigure = &scrapeConfigResource{}
|
||||
_ resource.ResourceWithImportState = &scrapeConfigResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
MetricsPath types.String `tfsdk:"metrics_path"`
|
||||
Scheme types.String `tfsdk:"scheme"`
|
||||
ScrapeInterval types.String `tfsdk:"scrape_interval"`
|
||||
ScrapeTimeout types.String `tfsdk:"scrape_timeout"`
|
||||
SAML2 *SAML2 `tfsdk:"saml2"`
|
||||
BasicAuth *BasicAuth `tfsdk:"basic_auth"`
|
||||
Targets []Target `tfsdk:"targets"`
|
||||
}
|
||||
|
||||
type SAML2 struct {
|
||||
EnableURLParameters types.Bool `tfsdk:"enable_url_parameters"`
|
||||
}
|
||||
|
||||
type Target struct {
|
||||
URLs []types.String `tfsdk:"urls"`
|
||||
Labels types.Map `tfsdk:"labels"`
|
||||
}
|
||||
|
||||
type BasicAuth struct {
|
||||
Username types.String `tfsdk:"username"`
|
||||
Password types.String `tfsdk:"password"`
|
||||
}
|
||||
|
||||
// NewScrapeConfigResource is a helper function to simplify the provider implementation.
|
||||
func NewScrapeConfigResource() resource.Resource {
|
||||
return &scrapeConfigResource{}
|
||||
}
|
||||
|
||||
// scrapeConfigResource is the resource implementation.
|
||||
type scrapeConfigResource struct {
|
||||
client *argus.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *scrapeConfigResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_argus_scrapeconfig"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *scrapeConfigResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *argus.APIClient
|
||||
var err error
|
||||
if providerData.ArgusCustomEndpoint != "" {
|
||||
apiClient, err = argus.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.ArgusCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = argus.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", err.Error())
|
||||
return
|
||||
}
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "Argus scrape config client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *scrapeConfigResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`,`name`\".",
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: "STACKIT project ID to which the scraping job is associated.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: "Argus instance ID to which the scraping job is associated.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: "Specifies the name of the scraping job.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
stringvalidator.LengthBetween(1, 200),
|
||||
},
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"metrics_path": schema.StringAttribute{
|
||||
Description: "Specifies the job scraping url path. E.g. `/metrics`.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthBetween(1, 200),
|
||||
},
|
||||
},
|
||||
|
||||
"scheme": schema.StringAttribute{
|
||||
Description: "Specifies the http scheme. E.g. `https`.",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Default: stringdefault.StaticString(DefaultScheme),
|
||||
},
|
||||
"scrape_interval": schema.StringAttribute{
|
||||
Description: "Specifies the scrape interval as duration string. E.g. `5m`.",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthBetween(2, 8),
|
||||
},
|
||||
Default: stringdefault.StaticString(DefaultScrapeInterval),
|
||||
},
|
||||
"scrape_timeout": schema.StringAttribute{
|
||||
Description: "Specifies the scrape timeout as duration string. E.g.`2m`.",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthBetween(2, 8),
|
||||
},
|
||||
Default: stringdefault.StaticString(DefaultScrapeTimeout),
|
||||
},
|
||||
"saml2": schema.SingleNestedAttribute{
|
||||
Description: "A SAML2 configuration block.",
|
||||
Optional: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"enable_url_parameters": schema.BoolAttribute{
|
||||
Description: "Are URL parameters be enabled?",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Default: booldefault.StaticBool(DefaultSAML2EnableURLParameters),
|
||||
},
|
||||
},
|
||||
},
|
||||
"basic_auth": schema.SingleNestedAttribute{
|
||||
Description: "A basic authentication block.",
|
||||
Optional: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"username": schema.StringAttribute{
|
||||
Description: "Specifies basic auth username.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthBetween(1, 200),
|
||||
},
|
||||
},
|
||||
"password": schema.StringAttribute{
|
||||
Description: "Specifies basic auth password.",
|
||||
Required: true,
|
||||
Sensitive: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthBetween(1, 200),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"targets": schema.ListNestedAttribute{
|
||||
Description: "The targets list (specified by the static config).",
|
||||
Required: true,
|
||||
NestedObject: schema.NestedAttributeObject{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"urls": schema.ListAttribute{
|
||||
Description: "Specifies target URLs.",
|
||||
Required: true,
|
||||
ElementType: types.StringType,
|
||||
Validators: []validator.List{
|
||||
listvalidator.ValueStringsAre(
|
||||
stringvalidator.LengthBetween(1, 500),
|
||||
),
|
||||
},
|
||||
},
|
||||
"labels": schema.MapAttribute{
|
||||
Description: "Specifies labels.",
|
||||
Optional: true,
|
||||
ElementType: types.StringType,
|
||||
Validators: []validator.Map{
|
||||
mapvalidator.SizeAtMost(10),
|
||||
mapvalidator.ValueStringsAre(stringvalidator.LengthBetween(0, 200)),
|
||||
mapvalidator.KeysAre(stringvalidator.LengthBetween(0, 200)),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *scrapeConfigResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
scName := model.Name.ValueString()
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(ctx, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating scrape config", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
_, err = r.client.CreateScrapeConfig(ctx, instanceId, projectId).CreateScrapeConfigPayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating scrape config", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
_, err = argus.CreateScrapeConfigWaitHandler(ctx, r.client, instanceId, scName, projectId).SetTimeout(3 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating scrape config", fmt.Sprintf("Scrape config creation waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, err := r.client.GetScrapeConfig(ctx, instanceId, scName, projectId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating scrape config", fmt.Sprintf("Calling API for updated data: %v", err))
|
||||
return
|
||||
}
|
||||
err = mapFields(got.Data, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating scrape config", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Argus scrape config created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *scrapeConfigResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
scName := model.Name.ValueString()
|
||||
|
||||
scResp, err := r.client.GetScrapeConfig(ctx, instanceId, scName, projectId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading scrape config", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(scResp.Data, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading scrape config", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Set refreshed model
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Argus scrape config read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *scrapeConfigResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
scName := model.Name.ValueString()
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toUpdatePayload(ctx, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating scrape config", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
_, err = r.client.UpdateScrapeConfig(ctx, instanceId, scName, projectId).UpdateScrapeConfigPayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating scrape config", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
// We do not have an update status provided by the argus scrape config api, so we cannot use a waiter here, hence a simple sleep is used.
|
||||
time.Sleep(15 * time.Second)
|
||||
|
||||
// Fetch updated ScrapeConfig
|
||||
scResp, err := r.client.GetScrapeConfig(ctx, instanceId, scName, projectId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating scrape config", fmt.Sprintf("Calling API for updated data: %v", err))
|
||||
return
|
||||
}
|
||||
err = mapFields(scResp.Data, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating scrape config", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Argus scrape config updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *scrapeConfigResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from state
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
scName := model.Name.ValueString()
|
||||
|
||||
// Delete existing ScrapeConfig
|
||||
_, err := r.client.DeleteScrapeConfig(ctx, instanceId, scName, projectId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting scrape config", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
_, err = argus.DeleteScrapeConfigWaitHandler(ctx, r.client, instanceId, scName, projectId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting scrape config", fmt.Sprintf("Scrape config deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
tflog.Info(ctx, "Argus scrape config deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,instance_id,name
|
||||
func (r *scrapeConfigResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
|
||||
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing scrape config",
|
||||
fmt.Sprintf("Expected import identifier with format: [project_id],[instance_id],[name] Got: %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[1])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("name"), idParts[2])...)
|
||||
tflog.Info(ctx, "Argus scrape config state imported")
|
||||
}
|
||||
|
||||
func mapFields(sc *argus.Job, model *Model) error {
|
||||
if sc == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
|
||||
var scName string
|
||||
if model.Name.ValueString() != "" {
|
||||
scName = model.Name.ValueString()
|
||||
} else if sc.JobName != nil {
|
||||
scName = *sc.JobName
|
||||
} else {
|
||||
return fmt.Errorf("scrape config name not present")
|
||||
}
|
||||
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
model.InstanceId.ValueString(),
|
||||
scName,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.Name = types.StringValue(scName)
|
||||
|
||||
model.MetricsPath = types.StringPointerValue(sc.MetricsPath)
|
||||
model.Scheme = types.StringPointerValue(sc.Scheme)
|
||||
model.ScrapeInterval = types.StringPointerValue(sc.ScrapeInterval)
|
||||
model.ScrapeTimeout = types.StringPointerValue(sc.ScrapeTimeout)
|
||||
handleSAML2(sc, model)
|
||||
handleBasicAuth(sc, model)
|
||||
handleTargets(sc, model)
|
||||
return nil
|
||||
}
|
||||
|
||||
func handleBasicAuth(sc *argus.Job, model *Model) {
|
||||
if sc.BasicAuth == nil {
|
||||
model.BasicAuth = nil
|
||||
return
|
||||
}
|
||||
model.BasicAuth = &BasicAuth{
|
||||
Username: types.StringPointerValue(sc.BasicAuth.Username),
|
||||
Password: types.StringPointerValue(sc.BasicAuth.Password),
|
||||
}
|
||||
}
|
||||
|
||||
func handleSAML2(sc *argus.Job, model *Model) {
|
||||
if (sc.Params == nil || *sc.Params == nil) && model.SAML2 == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if model.SAML2 == nil {
|
||||
model.SAML2 = &SAML2{}
|
||||
}
|
||||
|
||||
flag := true
|
||||
if sc.Params == nil || *sc.Params == nil {
|
||||
return
|
||||
}
|
||||
p := *sc.Params
|
||||
if v, ok := p["saml2"]; ok {
|
||||
if len(v) == 1 && v[0] == "disabled" {
|
||||
flag = false
|
||||
}
|
||||
}
|
||||
|
||||
model.SAML2 = &SAML2{
|
||||
EnableURLParameters: types.BoolValue(flag),
|
||||
}
|
||||
}
|
||||
|
||||
func handleTargets(sc *argus.Job, model *Model) {
|
||||
if sc == nil || sc.StaticConfigs == nil {
|
||||
model.Targets = []Target{}
|
||||
return
|
||||
}
|
||||
newTargets := []Target{}
|
||||
for i, sc := range *sc.StaticConfigs {
|
||||
nt := Target{
|
||||
URLs: []types.String{},
|
||||
}
|
||||
if sc.Targets != nil {
|
||||
for _, v := range *sc.Targets {
|
||||
nt.URLs = append(nt.URLs, types.StringValue(v))
|
||||
}
|
||||
}
|
||||
|
||||
if len(model.Targets) > i && model.Targets[i].Labels.IsNull() || sc.Labels == nil {
|
||||
nt.Labels = types.MapNull(types.StringType)
|
||||
} else {
|
||||
newl := map[string]attr.Value{}
|
||||
for k, v := range *sc.Labels {
|
||||
newl[k] = types.StringValue(v)
|
||||
}
|
||||
nt.Labels = types.MapValueMust(types.StringType, newl)
|
||||
}
|
||||
newTargets = append(newTargets, nt)
|
||||
}
|
||||
model.Targets = newTargets
|
||||
}
|
||||
|
||||
func toCreatePayload(ctx context.Context, model *Model) (*argus.CreateScrapeConfigPayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
sc := argus.CreateScrapeConfigPayload{
|
||||
JobName: model.Name.ValueStringPointer(),
|
||||
MetricsPath: model.MetricsPath.ValueStringPointer(),
|
||||
ScrapeInterval: model.ScrapeInterval.ValueStringPointer(),
|
||||
ScrapeTimeout: model.ScrapeTimeout.ValueStringPointer(),
|
||||
Scheme: model.Scheme.ValueStringPointer(),
|
||||
}
|
||||
setDefaultsCreateScrapeConfig(&sc, model)
|
||||
|
||||
if model.SAML2 != nil && !model.SAML2.EnableURLParameters.ValueBool() {
|
||||
m := make(map[string]interface{})
|
||||
if sc.Params != nil {
|
||||
m = *sc.Params
|
||||
}
|
||||
m["saml2"] = []string{"disabled"}
|
||||
sc.Params = &m
|
||||
}
|
||||
|
||||
if model.BasicAuth != nil {
|
||||
if sc.BasicAuth == nil {
|
||||
sc.BasicAuth = &argus.UpdateScrapeConfigPayloadBasicAuth{
|
||||
Username: model.BasicAuth.Username.ValueStringPointer(),
|
||||
Password: model.BasicAuth.Password.ValueStringPointer(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
t := make([]argus.CreateScrapeConfigPayloadStaticConfigsInner, len(model.Targets))
|
||||
for i, target := range model.Targets {
|
||||
ti := argus.CreateScrapeConfigPayloadStaticConfigsInner{}
|
||||
tgts := []string{}
|
||||
for _, v := range target.URLs {
|
||||
tgts = append(tgts, v.ValueString())
|
||||
}
|
||||
ti.Targets = &tgts
|
||||
|
||||
ls := map[string]interface{}{}
|
||||
for k, v := range target.Labels.Elements() {
|
||||
ls[k], _ = conversion.ToString(ctx, v)
|
||||
}
|
||||
ti.Labels = &ls
|
||||
t[i] = ti
|
||||
}
|
||||
sc.StaticConfigs = &t
|
||||
return &sc, nil
|
||||
}
|
||||
|
||||
func setDefaultsCreateScrapeConfig(sc *argus.CreateScrapeConfigPayload, model *Model) {
|
||||
if sc == nil {
|
||||
return
|
||||
}
|
||||
if model.Scheme.IsNull() || model.Scheme.IsUnknown() {
|
||||
sc.Scheme = utils.Ptr(DefaultScheme)
|
||||
}
|
||||
if model.ScrapeInterval.IsNull() || model.ScrapeInterval.IsUnknown() {
|
||||
sc.ScrapeInterval = utils.Ptr(DefaultScrapeInterval)
|
||||
}
|
||||
if model.ScrapeTimeout.IsNull() || model.ScrapeTimeout.IsUnknown() {
|
||||
sc.ScrapeTimeout = utils.Ptr(DefaultScrapeTimeout)
|
||||
}
|
||||
// Make the API default more explicit by setting the field.
|
||||
if model.SAML2 == nil || model.SAML2.EnableURLParameters.IsNull() || model.SAML2.EnableURLParameters.IsUnknown() {
|
||||
m := map[string]interface{}{}
|
||||
if sc.Params != nil {
|
||||
m = *sc.Params
|
||||
}
|
||||
if DefaultSAML2EnableURLParameters {
|
||||
m["saml2"] = []string{"enabled"}
|
||||
} else {
|
||||
m["saml2"] = []string{"disabled"}
|
||||
}
|
||||
sc.Params = &m
|
||||
}
|
||||
}
|
||||
|
||||
func toUpdatePayload(ctx context.Context, model *Model) (*argus.UpdateScrapeConfigPayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
sc := argus.UpdateScrapeConfigPayload{
|
||||
MetricsPath: model.MetricsPath.ValueStringPointer(),
|
||||
ScrapeInterval: model.ScrapeInterval.ValueStringPointer(),
|
||||
ScrapeTimeout: model.ScrapeTimeout.ValueStringPointer(),
|
||||
Scheme: model.Scheme.ValueStringPointer(),
|
||||
}
|
||||
setDefaultsUpdateScrapeConfig(&sc, model)
|
||||
|
||||
if model.SAML2 != nil && !model.SAML2.EnableURLParameters.ValueBool() {
|
||||
m := make(map[string]interface{})
|
||||
if sc.Params != nil {
|
||||
m = *sc.Params
|
||||
}
|
||||
m["saml2"] = []string{"disabled"}
|
||||
sc.Params = &m
|
||||
}
|
||||
|
||||
if model.BasicAuth != nil {
|
||||
if sc.BasicAuth == nil {
|
||||
sc.BasicAuth = &argus.UpdateScrapeConfigPayloadBasicAuth{
|
||||
Username: model.BasicAuth.Username.ValueStringPointer(),
|
||||
Password: model.BasicAuth.Password.ValueStringPointer(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
t := make([]argus.UpdateScrapeConfigPayloadStaticConfigsInner, len(model.Targets))
|
||||
for i, target := range model.Targets {
|
||||
ti := argus.UpdateScrapeConfigPayloadStaticConfigsInner{}
|
||||
tgts := []string{}
|
||||
for _, v := range target.URLs {
|
||||
tgts = append(tgts, v.ValueString())
|
||||
}
|
||||
ti.Targets = &tgts
|
||||
|
||||
ls := map[string]interface{}{}
|
||||
for k, v := range target.Labels.Elements() {
|
||||
ls[k], _ = conversion.ToString(ctx, v)
|
||||
}
|
||||
ti.Labels = &ls
|
||||
t[i] = ti
|
||||
}
|
||||
sc.StaticConfigs = &t
|
||||
return &sc, nil
|
||||
}
|
||||
|
||||
func setDefaultsUpdateScrapeConfig(sc *argus.UpdateScrapeConfigPayload, model *Model) {
|
||||
if sc == nil {
|
||||
return
|
||||
}
|
||||
if model.Scheme.IsNull() || model.Scheme.IsUnknown() {
|
||||
sc.Scheme = utils.Ptr(DefaultScheme)
|
||||
}
|
||||
if model.ScrapeInterval.IsNull() || model.ScrapeInterval.IsUnknown() {
|
||||
sc.ScrapeInterval = utils.Ptr(DefaultScrapeInterval)
|
||||
}
|
||||
if model.ScrapeTimeout.IsNull() || model.ScrapeTimeout.IsUnknown() {
|
||||
sc.ScrapeTimeout = utils.Ptr(DefaultScrapeTimeout)
|
||||
}
|
||||
}
|
||||
272
stackit/internal/services/argus/scrapeconfig/resource_test.go
Normal file
272
stackit/internal/services/argus/scrapeconfig/resource_test.go
Normal file
|
|
@ -0,0 +1,272 @@
|
|||
package argus
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/argus"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *argus.Job
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_ok",
|
||||
&argus.Job{
|
||||
JobName: utils.Ptr("name"),
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,name"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
Name: types.StringValue("name"),
|
||||
MetricsPath: types.StringNull(),
|
||||
Scheme: types.StringNull(),
|
||||
ScrapeInterval: types.StringNull(),
|
||||
ScrapeTimeout: types.StringNull(),
|
||||
SAML2: nil,
|
||||
BasicAuth: nil,
|
||||
Targets: []Target{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
description: "values_ok",
|
||||
input: &argus.Job{
|
||||
JobName: utils.Ptr("name"),
|
||||
MetricsPath: utils.Ptr("/m"),
|
||||
BasicAuth: &argus.BasicAuth{
|
||||
Password: utils.Ptr("p"),
|
||||
Username: utils.Ptr("u"),
|
||||
},
|
||||
Params: &map[string][]string{"saml2": {"disabled"}, "x": {"y", "z"}},
|
||||
Scheme: utils.Ptr("scheme"),
|
||||
ScrapeInterval: utils.Ptr("1"),
|
||||
ScrapeTimeout: utils.Ptr("2"),
|
||||
StaticConfigs: &[]argus.StaticConfigs{
|
||||
{
|
||||
Labels: &map[string]string{"k1": "v1"},
|
||||
Targets: &[]string{"url1"},
|
||||
},
|
||||
{
|
||||
Labels: &map[string]string{"k2": "v2", "k3": "v3"},
|
||||
Targets: &[]string{"url1", "url3"},
|
||||
},
|
||||
{
|
||||
Labels: nil,
|
||||
Targets: &[]string{},
|
||||
},
|
||||
},
|
||||
},
|
||||
expected: Model{
|
||||
Id: types.StringValue("pid,iid,name"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
Name: types.StringValue("name"),
|
||||
MetricsPath: types.StringValue("/m"),
|
||||
Scheme: types.StringValue("scheme"),
|
||||
ScrapeInterval: types.StringValue("1"),
|
||||
ScrapeTimeout: types.StringValue("2"),
|
||||
SAML2: &SAML2{
|
||||
EnableURLParameters: types.BoolValue(false),
|
||||
},
|
||||
BasicAuth: &BasicAuth{
|
||||
Username: types.StringValue("u"),
|
||||
Password: types.StringValue("p"),
|
||||
},
|
||||
Targets: []Target{
|
||||
{
|
||||
URLs: []types.String{types.StringValue("url1")},
|
||||
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
|
||||
"k1": types.StringValue("v1"),
|
||||
}),
|
||||
},
|
||||
{
|
||||
URLs: []types.String{types.StringValue("url1"), types.StringValue("url3")},
|
||||
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{
|
||||
"k2": types.StringValue("v2"),
|
||||
"k3": types.StringValue("v3"),
|
||||
}),
|
||||
},
|
||||
{
|
||||
URLs: []types.String{},
|
||||
Labels: types.MapNull(types.StringType),
|
||||
},
|
||||
},
|
||||
},
|
||||
isValid: true,
|
||||
},
|
||||
{
|
||||
"response_nil_fail",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&argus.Job{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
state := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
}
|
||||
err := mapFields(tt.input, state)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
expected *argus.CreateScrapeConfigPayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"basic_ok",
|
||||
&Model{
|
||||
MetricsPath: types.StringValue("/metrics"),
|
||||
},
|
||||
&argus.CreateScrapeConfigPayload{
|
||||
MetricsPath: utils.Ptr("/metrics"),
|
||||
// Defaults
|
||||
Scheme: utils.Ptr("https"),
|
||||
ScrapeInterval: utils.Ptr("5m"),
|
||||
ScrapeTimeout: utils.Ptr("2m"),
|
||||
StaticConfigs: &[]argus.CreateScrapeConfigPayloadStaticConfigsInner{},
|
||||
Params: &map[string]any{"saml2": []string{"enabled"}},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"ok",
|
||||
&Model{
|
||||
MetricsPath: types.StringValue("/metrics"),
|
||||
Name: types.StringValue("Name"),
|
||||
},
|
||||
&argus.CreateScrapeConfigPayload{
|
||||
MetricsPath: utils.Ptr("/metrics"),
|
||||
JobName: utils.Ptr("Name"),
|
||||
// Defaults
|
||||
Scheme: utils.Ptr("https"),
|
||||
ScrapeInterval: utils.Ptr("5m"),
|
||||
ScrapeTimeout: utils.Ptr("2m"),
|
||||
StaticConfigs: &[]argus.CreateScrapeConfigPayloadStaticConfigsInner{},
|
||||
Params: &map[string]any{"saml2": []string{"enabled"}},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toCreatePayload(context.Background(), tt.input)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToUpdatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
expected *argus.UpdateScrapeConfigPayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"basic_ok",
|
||||
&Model{
|
||||
MetricsPath: types.StringValue("/metrics"),
|
||||
},
|
||||
&argus.UpdateScrapeConfigPayload{
|
||||
MetricsPath: utils.Ptr("/metrics"),
|
||||
// Defaults
|
||||
Scheme: utils.Ptr("https"),
|
||||
ScrapeInterval: utils.Ptr("5m"),
|
||||
ScrapeTimeout: utils.Ptr("2m"),
|
||||
StaticConfigs: &[]argus.UpdateScrapeConfigPayloadStaticConfigsInner{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"ok",
|
||||
&Model{
|
||||
MetricsPath: types.StringValue("/metrics"),
|
||||
Scheme: types.StringValue("http"),
|
||||
},
|
||||
&argus.UpdateScrapeConfigPayload{
|
||||
MetricsPath: utils.Ptr("/metrics"),
|
||||
// Defaults
|
||||
Scheme: utils.Ptr("http"),
|
||||
ScrapeInterval: utils.Ptr("5m"),
|
||||
ScrapeTimeout: utils.Ptr("2m"),
|
||||
StaticConfigs: &[]argus.UpdateScrapeConfigPayloadStaticConfigsInner{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toUpdatePayload(context.Background(), tt.input)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
558
stackit/internal/services/dns/dns_acc_test.go
Normal file
558
stackit/internal/services/dns/dns_acc_test.go
Normal file
|
|
@ -0,0 +1,558 @@
|
|||
package dns_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-testing/helper/acctest"
|
||||
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
|
||||
"github.com/hashicorp/terraform-plugin-testing/terraform"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/dns"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/testutil"
|
||||
)
|
||||
|
||||
// Zone resource data
|
||||
var zoneResource = map[string]string{
|
||||
"project_id": testutil.ProjectId,
|
||||
"name": testutil.ResourceNameWithDateTime("zone"),
|
||||
"dns_name": fmt.Sprintf("www.%s.com", acctest.RandStringFromCharSet(20, acctest.CharSetAlpha)),
|
||||
"dns_name_min": fmt.Sprintf("www.%s.com", acctest.RandStringFromCharSet(20, acctest.CharSetAlpha)),
|
||||
"description": "my description",
|
||||
"description_updated": "my description updated",
|
||||
"acl": "192.168.0.0/24",
|
||||
"active": "true",
|
||||
"contact_email": "aa@bb.cc",
|
||||
"ttl": "120",
|
||||
"ttl_updated": "4440",
|
||||
"expire_time": "123456",
|
||||
"is_reverse_zone": "false",
|
||||
"negative_cache": "60",
|
||||
"primaries": "1.2.3.4",
|
||||
"refresh_time": "500",
|
||||
"retry_time": "700",
|
||||
"type": "primary",
|
||||
}
|
||||
|
||||
// Record set resource data
|
||||
var recordSetResource = map[string]string{
|
||||
"name": fmt.Sprintf("tf-acc-%s.%s.", acctest.RandStringFromCharSet(5, acctest.CharSetAlpha), zoneResource["dns_name"]),
|
||||
"name_min": fmt.Sprintf("tf-acc-%s.%s.", acctest.RandStringFromCharSet(5, acctest.CharSetAlpha), zoneResource["dns_name_min"]),
|
||||
"records": `"1.2.3.4"`,
|
||||
"records_updated": `"5.6.7.8", "9.10.11.12"`,
|
||||
"ttl": "3700",
|
||||
"type": "A",
|
||||
"active": "true",
|
||||
"comment": "a comment",
|
||||
}
|
||||
|
||||
func inputConfig(zoneName, description, ttl, records string) string {
|
||||
return fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
resource "stackit_dns_zone" "zone" {
|
||||
project_id = "%s"
|
||||
name = "%s"
|
||||
dns_name = "%s"
|
||||
description = "%s"
|
||||
acl = "%s"
|
||||
active = %s
|
||||
contact_email = "%s"
|
||||
default_ttl = %s
|
||||
expire_time = %s
|
||||
is_reverse_zone = %s
|
||||
negative_cache = %s
|
||||
primaries = ["%s"]
|
||||
refresh_time = %s
|
||||
retry_time = %s
|
||||
type = "%s"
|
||||
}
|
||||
|
||||
resource "stackit_dns_record_set" "record_set" {
|
||||
project_id = stackit_dns_zone.zone.project_id
|
||||
zone_id = stackit_dns_zone.zone.zone_id
|
||||
name = "%s"
|
||||
records = [%s]
|
||||
type = "%s"
|
||||
ttl = %s
|
||||
comment = "%s"
|
||||
active = %s
|
||||
|
||||
}
|
||||
`,
|
||||
testutil.DnsProviderConfig(),
|
||||
zoneResource["project_id"],
|
||||
zoneName,
|
||||
zoneResource["dns_name"],
|
||||
description,
|
||||
zoneResource["acl"],
|
||||
zoneResource["active"],
|
||||
zoneResource["contact_email"],
|
||||
ttl,
|
||||
zoneResource["expire_time"],
|
||||
zoneResource["is_reverse_zone"],
|
||||
zoneResource["negative_cache"],
|
||||
zoneResource["primaries"],
|
||||
zoneResource["refresh_time"],
|
||||
zoneResource["retry_time"],
|
||||
zoneResource["type"],
|
||||
recordSetResource["name"],
|
||||
records,
|
||||
recordSetResource["type"],
|
||||
recordSetResource["ttl"],
|
||||
recordSetResource["comment"],
|
||||
recordSetResource["active"],
|
||||
)
|
||||
}
|
||||
|
||||
func TestAccDnsResource(t *testing.T) {
|
||||
resource.ParallelTest(t, resource.TestCase{
|
||||
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
|
||||
CheckDestroy: testAccCheckDnsDestroy,
|
||||
Steps: []resource.TestStep{
|
||||
// Creation
|
||||
{
|
||||
Config: inputConfig(zoneResource["name"], zoneResource["description"], zoneResource["ttl"], recordSetResource["records"]),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Zone data
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "project_id", zoneResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone", "zone_id"),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "name", zoneResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "dns_name", zoneResource["dns_name"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "description", zoneResource["description"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "acl", zoneResource["acl"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "active", zoneResource["active"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "contact_email", zoneResource["contact_email"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "default_ttl", zoneResource["ttl"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "expire_time", zoneResource["expire_time"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "is_reverse_zone", zoneResource["is_reverse_zone"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "negative_cache", zoneResource["negative_cache"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "primaries.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "primaries.0", zoneResource["primaries"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "refresh_time", zoneResource["refresh_time"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "retry_time", zoneResource["retry_time"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "type", zoneResource["type"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone", "primary_name_server"),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone", "serial_number"),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone", "visibility"),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone", "state"),
|
||||
|
||||
// Record set data
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_dns_record_set.record_set", "project_id",
|
||||
"stackit_dns_zone.zone", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_dns_record_set.record_set", "zone_id",
|
||||
"stackit_dns_zone.zone", "zone_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_record_set.record_set", "record_set_id"),
|
||||
resource.TestCheckResourceAttr("stackit_dns_record_set.record_set", "name", recordSetResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_record_set.record_set", "records.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_dns_record_set.record_set", "records.0", strings.ReplaceAll(recordSetResource["records"], "\"", "")),
|
||||
resource.TestCheckResourceAttr("stackit_dns_record_set.record_set", "type", recordSetResource["type"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_record_set.record_set", "ttl", recordSetResource["ttl"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_record_set.record_set", "comment", recordSetResource["comment"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_record_set.record_set", "active", recordSetResource["active"]),
|
||||
),
|
||||
},
|
||||
// Data sources
|
||||
{
|
||||
Config: fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
data "stackit_dns_zone" "zone" {
|
||||
project_id = stackit_dns_zone.zone.project_id
|
||||
zone_id = stackit_dns_zone.zone.zone_id
|
||||
}
|
||||
|
||||
data "stackit_dns_record_set" "record_set" {
|
||||
project_id = stackit_dns_zone.zone.project_id
|
||||
zone_id = stackit_dns_zone.zone.zone_id
|
||||
record_set_id = stackit_dns_record_set.record_set.record_set_id
|
||||
}`,
|
||||
inputConfig(zoneResource["name"], zoneResource["description"], zoneResource["ttl"], recordSetResource["records"]),
|
||||
),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Zone data
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone", "project_id", zoneResource["project_id"]),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_dns_zone.zone", "zone_id",
|
||||
"data.stackit_dns_zone.zone", "zone_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_dns_record_set.record_set", "zone_id",
|
||||
"data.stackit_dns_zone.zone", "zone_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_dns_record_set.record_set", "project_id",
|
||||
"data.stackit_dns_zone.zone", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_dns_record_set.record_set", "project_id",
|
||||
"stackit_dns_record_set.record_set", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone", "name", zoneResource["name"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone", "default_ttl", zoneResource["ttl"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone", "dns_name", zoneResource["dns_name"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone", "description", zoneResource["description"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone", "acl", zoneResource["acl"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone", "active", zoneResource["active"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone", "contact_email", zoneResource["contact_email"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone", "default_ttl", zoneResource["ttl"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone", "expire_time", zoneResource["expire_time"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone", "is_reverse_zone", zoneResource["is_reverse_zone"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone", "negative_cache", zoneResource["negative_cache"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone", "primaries.#", "1"),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone", "primaries.0", zoneResource["primaries"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone", "refresh_time", zoneResource["refresh_time"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone", "retry_time", zoneResource["retry_time"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone", "type", zoneResource["type"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_dns_zone.zone", "primary_name_server"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_dns_zone.zone", "serial_number"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_dns_zone.zone", "visibility"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_dns_zone.zone", "state"),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone", "record_count", "4"),
|
||||
|
||||
// Record set data
|
||||
resource.TestCheckResourceAttrSet("data.stackit_dns_record_set.record_set", "record_set_id"),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_record_set.record_set", "name", recordSetResource["name"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_record_set.record_set", "records.#", "1"),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_record_set.record_set", "type", recordSetResource["type"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_record_set.record_set", "ttl", recordSetResource["ttl"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_record_set.record_set", "comment", recordSetResource["comment"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_record_set.record_set", "active", recordSetResource["active"]),
|
||||
),
|
||||
},
|
||||
// Import
|
||||
{
|
||||
ResourceName: "stackit_dns_zone.zone",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_dns_zone.zone"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_dns_zone.recozonerd_set")
|
||||
}
|
||||
zoneId, ok := r.Primary.Attributes["zone_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute zone_id")
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s,%s", testutil.ProjectId, zoneId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
{
|
||||
ResourceName: "stackit_dns_record_set.record_set",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_dns_record_set.record_set"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_dns_record_set.record_set")
|
||||
}
|
||||
zoneId, ok := r.Primary.Attributes["zone_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute zone_id")
|
||||
}
|
||||
recordSetId, ok := r.Primary.Attributes["record_set_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute record_set_id")
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s,%s,%s", testutil.ProjectId, zoneId, recordSetId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
// Update. The zone ttl should not be updated according to the DNS API.
|
||||
{
|
||||
Config: inputConfig(zoneResource["name"], zoneResource["description_updated"], zoneResource["ttl"], recordSetResource["records_updated"]),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Zone data
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "project_id", zoneResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone", "zone_id"),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "name", zoneResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "dns_name", zoneResource["dns_name"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "description", zoneResource["description_updated"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "acl", zoneResource["acl"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "active", zoneResource["active"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "contact_email", zoneResource["contact_email"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "default_ttl", zoneResource["ttl"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "expire_time", zoneResource["expire_time"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "is_reverse_zone", zoneResource["is_reverse_zone"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "negative_cache", zoneResource["negative_cache"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "primaries.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "primaries.0", zoneResource["primaries"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "refresh_time", zoneResource["refresh_time"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "retry_time", zoneResource["retry_time"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone", "type", zoneResource["type"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone", "primary_name_server"),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone", "serial_number"),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone", "visibility"),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone", "state"),
|
||||
|
||||
// Record set data
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_dns_record_set.record_set", "project_id",
|
||||
"stackit_dns_zone.zone", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_dns_record_set.record_set", "zone_id",
|
||||
"stackit_dns_zone.zone", "zone_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_record_set.record_set", "record_set_id"),
|
||||
resource.TestCheckResourceAttr("stackit_dns_record_set.record_set", "name", recordSetResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_record_set.record_set", "records.#", "2"),
|
||||
resource.TestCheckResourceAttr("stackit_dns_record_set.record_set", "type", recordSetResource["type"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_record_set.record_set", "ttl", recordSetResource["ttl"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_record_set.record_set", "comment", recordSetResource["comment"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_record_set.record_set", "active", recordSetResource["active"]),
|
||||
),
|
||||
},
|
||||
// Deletion is done by the framework implicitly
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func inputConfigMinimal() string {
|
||||
return fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
resource "stackit_dns_zone" "zone_min" {
|
||||
project_id = "%s"
|
||||
name = "%s"
|
||||
dns_name = "%s"
|
||||
contact_email = "%s"
|
||||
type = "%s"
|
||||
acl = "%s"
|
||||
}
|
||||
|
||||
resource "stackit_dns_record_set" "record_set_min" {
|
||||
project_id = stackit_dns_zone.zone_min.project_id
|
||||
zone_id = stackit_dns_zone.zone_min.zone_id
|
||||
name = "%s"
|
||||
records = [%s]
|
||||
type = "%s"
|
||||
}
|
||||
`,
|
||||
testutil.DnsProviderConfig(),
|
||||
zoneResource["project_id"],
|
||||
zoneResource["name"],
|
||||
zoneResource["dns_name_min"],
|
||||
zoneResource["contact_email"],
|
||||
zoneResource["type"],
|
||||
zoneResource["acl"],
|
||||
recordSetResource["name_min"],
|
||||
recordSetResource["records"],
|
||||
recordSetResource["type"],
|
||||
)
|
||||
}
|
||||
|
||||
func TestAccDnsMinimalResource(t *testing.T) {
|
||||
resource.ParallelTest(t, resource.TestCase{
|
||||
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
|
||||
CheckDestroy: testAccCheckDnsDestroy,
|
||||
Steps: []resource.TestStep{
|
||||
// Creation
|
||||
{
|
||||
Config: inputConfigMinimal(),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Zone
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone_min", "project_id", zoneResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone_min", "zone_id"),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone_min", "name", zoneResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone_min", "dns_name", zoneResource["dns_name_min"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone_min", "contact_email", zoneResource["contact_email"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone_min", "type", zoneResource["type"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone_min", "acl"),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone_min", "active", "true"),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone_min", "default_ttl"),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone_min", "expire_time"),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone_min", "is_reverse_zone", "false"),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone_min", "negative_cache"),
|
||||
resource.TestCheckResourceAttr("stackit_dns_zone.zone_min", "primaries.#", "1"),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone_min", "refresh_time"),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone_min", "retry_time"),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone_min", "primary_name_server"),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone_min", "serial_number"),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone_min", "visibility"),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_zone.zone_min", "state"),
|
||||
|
||||
// Record set
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_dns_record_set.record_set_min", "project_id",
|
||||
"stackit_dns_zone.zone_min", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_dns_record_set.record_set_min", "zone_id",
|
||||
"stackit_dns_zone.zone_min", "zone_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_record_set.record_set_min", "record_set_id"),
|
||||
resource.TestCheckResourceAttr("stackit_dns_record_set.record_set_min", "name", recordSetResource["name_min"]),
|
||||
resource.TestCheckResourceAttr("stackit_dns_record_set.record_set_min", "records.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_dns_record_set.record_set_min", "records.0", strings.ReplaceAll(recordSetResource["records"], "\"", "")),
|
||||
resource.TestCheckResourceAttr("stackit_dns_record_set.record_set_min", "type", recordSetResource["type"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_dns_record_set.record_set_min", "ttl"),
|
||||
resource.TestCheckNoResourceAttr("stackit_dns_record_set.record_set_min", "comment"),
|
||||
resource.TestCheckResourceAttr("stackit_dns_record_set.record_set_min", "active", "true"),
|
||||
),
|
||||
},
|
||||
// Data sources
|
||||
{
|
||||
Config: fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
data "stackit_dns_zone" "zone_min" {
|
||||
project_id = stackit_dns_zone.zone_min.project_id
|
||||
zone_id = stackit_dns_zone.zone_min.zone_id
|
||||
}
|
||||
|
||||
data "stackit_dns_record_set" "record_set_min" {
|
||||
project_id = stackit_dns_zone.zone_min.project_id
|
||||
zone_id = stackit_dns_zone.zone_min.zone_id
|
||||
record_set_id = stackit_dns_record_set.record_set_min.record_set_id
|
||||
}`,
|
||||
inputConfigMinimal(),
|
||||
),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Zone data
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone_min", "project_id", zoneResource["project_id"]),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_dns_zone.zone_min", "zone_id",
|
||||
"data.stackit_dns_zone.zone_min", "zone_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_dns_record_set.record_set_min", "zone_id",
|
||||
"data.stackit_dns_zone.zone_min", "zone_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_dns_record_set.record_set_min", "project_id",
|
||||
"data.stackit_dns_zone.zone_min", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_dns_record_set.record_set_min", "project_id",
|
||||
"stackit_dns_record_set.record_set_min", "project_id",
|
||||
),
|
||||
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone_min", "project_id", zoneResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_dns_zone.zone_min", "zone_id"),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone_min", "name", zoneResource["name"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone_min", "dns_name", zoneResource["dns_name_min"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone_min", "contact_email", zoneResource["contact_email"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone_min", "type", zoneResource["type"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_dns_zone.zone_min", "acl"),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone_min", "active", "true"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_dns_zone.zone_min", "default_ttl"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_dns_zone.zone_min", "expire_time"),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone_min", "is_reverse_zone", "false"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_dns_zone.zone_min", "negative_cache"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_dns_zone.zone_min", "primary_name_server"),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone_min", "primaries.#", "1"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_dns_zone.zone_min", "refresh_time"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_dns_zone.zone_min", "retry_time"),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_zone.zone_min", "record_count", "4"),
|
||||
|
||||
// Record set data
|
||||
resource.TestCheckResourceAttrSet("data.stackit_dns_record_set.record_set_min", "record_set_id"),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_record_set.record_set_min", "name", recordSetResource["name_min"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_record_set.record_set_min", "records.#", "1"),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_record_set.record_set_min", "records.0", strings.ReplaceAll(recordSetResource["records"], "\"", "")),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_record_set.record_set_min", "type", recordSetResource["type"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_dns_record_set.record_set_min", "ttl"),
|
||||
resource.TestCheckNoResourceAttr("data.stackit_dns_record_set.record_set_min", "comment"),
|
||||
resource.TestCheckResourceAttr("data.stackit_dns_record_set.record_set_min", "active", "true"),
|
||||
),
|
||||
},
|
||||
// Import
|
||||
{
|
||||
ResourceName: "stackit_dns_zone.zone_min",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_dns_zone.zone_min"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_dns_zone.zone_min")
|
||||
}
|
||||
zoneId, ok := r.Primary.Attributes["zone_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute zone_id")
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s,%s", testutil.ProjectId, zoneId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
{
|
||||
ResourceName: "stackit_dns_record_set.record_set_min",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_dns_record_set.record_set_min"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_dns_record_set.record_set_min")
|
||||
}
|
||||
zoneId, ok := r.Primary.Attributes["zone_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute zone_id")
|
||||
}
|
||||
recordSetId, ok := r.Primary.Attributes["record_set_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute record_set_id")
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s,%s,%s", testutil.ProjectId, zoneId, recordSetId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
// Deletion is done by the framework implicitly
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func testAccCheckDnsDestroy(s *terraform.State) error {
|
||||
ctx := context.Background()
|
||||
var client *dns.APIClient
|
||||
var err error
|
||||
if testutil.DnsCustomEndpoint == "" {
|
||||
client, err = dns.NewAPIClient()
|
||||
} else {
|
||||
client, err = dns.NewAPIClient(
|
||||
config.WithEndpoint(testutil.DnsCustomEndpoint),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating client: %w", err)
|
||||
}
|
||||
|
||||
zonesToDestroy := []string{}
|
||||
for _, rs := range s.RootModule().Resources {
|
||||
if rs.Type != "stackit_dns_zone" {
|
||||
continue
|
||||
}
|
||||
// zone terraform ID: "[projectId],[zoneId]"
|
||||
zoneId := strings.Split(rs.Primary.ID, core.Separator)[1]
|
||||
zonesToDestroy = append(zonesToDestroy, zoneId)
|
||||
}
|
||||
|
||||
zonesResp, err := client.GetZones(ctx, testutil.ProjectId).ActiveEq(true).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting zonesResp: %w", err)
|
||||
}
|
||||
|
||||
zones := *zonesResp.Zones
|
||||
for i := range zones {
|
||||
id := *zones[i].Id
|
||||
if utils.Contains(zonesToDestroy, id) {
|
||||
_, err := client.DeleteZoneExecute(ctx, testutil.ProjectId, id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying zone %s during CheckDestroy: %w", *zones[i].Id, err)
|
||||
}
|
||||
_, err = dns.DeleteZoneWaitHandler(ctx, client, testutil.ProjectId, id).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying zone %s during CheckDestroy: waiting for deletion %w", *zones[i].Id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
174
stackit/internal/services/dns/recordset/datasource.go
Normal file
174
stackit/internal/services/dns/recordset/datasource.go
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/dns"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &recordSetDataSource{}
|
||||
)
|
||||
|
||||
// NewRecordSetDataSource NewZoneDataSource is a helper function to simplify the provider implementation.
|
||||
func NewRecordSetDataSource() datasource.DataSource {
|
||||
return &recordSetDataSource{}
|
||||
}
|
||||
|
||||
// recordSetDataSource is the data source implementation.
|
||||
type recordSetDataSource struct {
|
||||
client *dns.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the data source type name.
|
||||
func (d *recordSetDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_dns_record_set"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (d *recordSetDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *dns.APIClient
|
||||
var err error
|
||||
if providerData.DnsCustomEndpoint != "" {
|
||||
apiClient, err = dns.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.DnsCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = dns.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
d.client = apiClient
|
||||
tflog.Info(ctx, "DNS record set client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the data source.
|
||||
func (d *recordSetDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "DNS Record Set Resource schema.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`zone_id`,`record_set_id`\".",
|
||||
Computed: true,
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: "STACKIT project ID to which the dns record set is associated.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"zone_id": schema.StringAttribute{
|
||||
Description: "The zone ID to which is dns record set is associated.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"record_set_id": schema.StringAttribute{
|
||||
Description: "The rr set id.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: "Name of the record which should be a valid domain according to rfc1035 Section 2.3.4. E.g. `example.com`",
|
||||
Computed: true,
|
||||
},
|
||||
"records": schema.ListAttribute{
|
||||
Description: "Records.",
|
||||
Computed: true,
|
||||
ElementType: types.StringType,
|
||||
},
|
||||
"ttl": schema.Int64Attribute{
|
||||
Description: "Time to live. E.g. 3600",
|
||||
Computed: true,
|
||||
},
|
||||
"type": schema.StringAttribute{
|
||||
Description: "The record set type. E.g. `A` or `CNAME`",
|
||||
Computed: true,
|
||||
},
|
||||
"active": schema.BoolAttribute{
|
||||
Description: "Specifies if the record set is active or not.",
|
||||
Computed: true,
|
||||
},
|
||||
"comment": schema.StringAttribute{
|
||||
Description: "Comment.",
|
||||
Computed: true,
|
||||
},
|
||||
"error": schema.StringAttribute{
|
||||
Description: "Error shows error in case create/update/delete failed.",
|
||||
Computed: true,
|
||||
},
|
||||
"state": schema.StringAttribute{
|
||||
Description: "Record set state.",
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (d *recordSetDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
zoneId := model.ZoneId.ValueString()
|
||||
recordSetId := model.RecordSetId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "zone_id", zoneId)
|
||||
ctx = tflog.SetField(ctx, "record_set_id", recordSetId)
|
||||
zoneResp, err := d.client.GetRecordSet(ctx, projectId, zoneId, recordSetId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading record set", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
err = mapFields(zoneResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading record set", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "DNS record set read")
|
||||
}
|
||||
506
stackit/internal/services/dns/recordset/resource.go
Normal file
506
stackit/internal/services/dns/recordset/resource.go
Normal file
|
|
@ -0,0 +1,506 @@
|
|||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/int64validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/listvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/dns"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &recordSetResource{}
|
||||
_ resource.ResourceWithConfigure = &recordSetResource{}
|
||||
_ resource.ResourceWithImportState = &recordSetResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
RecordSetId types.String `tfsdk:"record_set_id"`
|
||||
ZoneId types.String `tfsdk:"zone_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Active types.Bool `tfsdk:"active"`
|
||||
Comment types.String `tfsdk:"comment"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Records types.List `tfsdk:"records"`
|
||||
TTL types.Int64 `tfsdk:"ttl"`
|
||||
Type types.String `tfsdk:"type"`
|
||||
Error types.String `tfsdk:"error"`
|
||||
State types.String `tfsdk:"state"`
|
||||
}
|
||||
|
||||
// NewRecordSetResource is a helper function to simplify the provider implementation.
|
||||
func NewRecordSetResource() resource.Resource {
|
||||
return &recordSetResource{}
|
||||
}
|
||||
|
||||
// recordSetResource is the resource implementation.
|
||||
type recordSetResource struct {
|
||||
client *dns.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *recordSetResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_dns_record_set"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *recordSetResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *dns.APIClient
|
||||
var err error
|
||||
if providerData.DnsCustomEndpoint != "" {
|
||||
apiClient, err = dns.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.DnsCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = dns.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "DNS record set client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *recordSetResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "DNS Record Set Resource schema.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`zone_id`,`record_set_id`\".",
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: "STACKIT project ID to which the dns record set is associated.",
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"zone_id": schema.StringAttribute{
|
||||
Description: "The zone ID to which is dns record set is associated.",
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"record_set_id": schema.StringAttribute{
|
||||
Description: "The rr set id.",
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: "Name of the record which should be a valid domain according to rfc1035 Section 2.3.4. E.g. `example.com`",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
stringvalidator.LengthAtMost(63),
|
||||
},
|
||||
},
|
||||
"records": schema.ListAttribute{
|
||||
Description: "Records.",
|
||||
ElementType: types.StringType,
|
||||
Required: true,
|
||||
Validators: []validator.List{
|
||||
listvalidator.SizeAtLeast(1),
|
||||
listvalidator.UniqueValues(),
|
||||
listvalidator.ValueStringsAre(validate.IP()),
|
||||
},
|
||||
},
|
||||
"ttl": schema.Int64Attribute{
|
||||
Description: "Time to live. E.g. 3600",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Validators: []validator.Int64{
|
||||
int64validator.AtLeast(30),
|
||||
int64validator.AtMost(99999999),
|
||||
},
|
||||
},
|
||||
"type": schema.StringAttribute{
|
||||
Description: "The record set type. E.g. `A` or `CNAME`",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"active": schema.BoolAttribute{
|
||||
Description: "Specifies if the record set is active or not.",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Default: booldefault.StaticBool(true),
|
||||
},
|
||||
"comment": schema.StringAttribute{
|
||||
Description: "Comment.",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtMost(255),
|
||||
},
|
||||
},
|
||||
"error": schema.StringAttribute{
|
||||
Description: "Error shows error in case create/update/delete failed.",
|
||||
Computed: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtMost(2000),
|
||||
},
|
||||
},
|
||||
"state": schema.StringAttribute{
|
||||
Description: "Record set state.",
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *recordSetResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
zoneId := model.ZoneId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "zone_id", zoneId)
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating record set", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Create new recordset
|
||||
recordSetResp, err := r.client.CreateRecordSet(ctx, projectId, zoneId).CreateRecordSetPayload(*payload).Execute()
|
||||
if err != nil || recordSetResp.Rrset == nil || recordSetResp.Rrset.Id == nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating record set", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
ctx = tflog.SetField(ctx, "record_set_id", *recordSetResp.Rrset.Id)
|
||||
|
||||
wr, err := dns.CreateRecordSetWaitHandler(ctx, r.client, projectId, zoneId, *recordSetResp.Rrset.Id).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating record set", fmt.Sprintf("Instance creation waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*dns.RecordSetResponse)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating record set", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating record set", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "DNS record set created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *recordSetResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
zoneId := model.ZoneId.ValueString()
|
||||
recordSetId := model.RecordSetId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "zone_id", zoneId)
|
||||
ctx = tflog.SetField(ctx, "record_set_id", recordSetId)
|
||||
|
||||
recordSetResp, err := r.client.GetRecordSet(ctx, projectId, zoneId, recordSetId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading record set", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(recordSetResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading record set", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "DNS record set read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *recordSetResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
zoneId := model.ZoneId.ValueString()
|
||||
recordSetId := model.RecordSetId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "zone_id", zoneId)
|
||||
ctx = tflog.SetField(ctx, "record_set_id", recordSetId)
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toUpdatePayload(&model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating record set", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Update recordset
|
||||
_, err = r.client.UpdateRecordSet(ctx, projectId, zoneId, recordSetId).UpdateRecordSetPayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating record set", err.Error())
|
||||
return
|
||||
}
|
||||
wr, err := dns.UpdateRecordSetWaitHandler(ctx, r.client, projectId, zoneId, recordSetId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating record set", fmt.Sprintf("Instance update waiting: %v", err))
|
||||
return
|
||||
}
|
||||
_, ok := wr.(*dns.RecordSetResponse)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating record set", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Fetch updated record set
|
||||
recordSetResp, err := r.client.GetRecordSet(ctx, projectId, zoneId, recordSetId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating record set", fmt.Sprintf("Calling API for updated data: %v", err))
|
||||
return
|
||||
}
|
||||
err = mapFields(recordSetResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating record set", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "DNS record set updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *recordSetResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
zoneId := model.ZoneId.ValueString()
|
||||
recordSetId := model.RecordSetId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "zone_id", zoneId)
|
||||
ctx = tflog.SetField(ctx, "record_set_id", recordSetId)
|
||||
|
||||
// Delete existing record set
|
||||
_, err := r.client.DeleteRecordSet(ctx, projectId, zoneId, recordSetId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting record set", fmt.Sprintf("Calling API: %v", err))
|
||||
}
|
||||
_, err = dns.DeleteRecordSetWaitHandler(ctx, r.client, projectId, zoneId, recordSetId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting record set", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "DNS record set deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,zone_id,record_set_id
|
||||
func (r *recordSetResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing record set",
|
||||
fmt.Sprintf("Expected import identifier with format [project_id],[zone_id],[record_set_id], got %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("zone_id"), idParts[1])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("record_set_id"), idParts[2])...)
|
||||
tflog.Info(ctx, "DNS record set state imported")
|
||||
}
|
||||
|
||||
func mapFields(recordSetResp *dns.RecordSetResponse, model *Model) error {
|
||||
if recordSetResp == nil || recordSetResp.Rrset == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
recordSet := recordSetResp.Rrset
|
||||
|
||||
var recordSetId string
|
||||
if model.RecordSetId.ValueString() != "" {
|
||||
recordSetId = model.RecordSetId.ValueString()
|
||||
} else if recordSet.Id != nil {
|
||||
recordSetId = *recordSet.Id
|
||||
} else {
|
||||
return fmt.Errorf("record set id not present")
|
||||
}
|
||||
|
||||
if recordSet.Records == nil {
|
||||
model.Records = types.ListNull(types.StringType)
|
||||
} else {
|
||||
records := []attr.Value{}
|
||||
for _, record := range *recordSet.Records {
|
||||
records = append(records, types.StringPointerValue(record.Content))
|
||||
}
|
||||
recordsList, diags := types.ListValue(types.StringType, records)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map records: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Records = recordsList
|
||||
}
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
model.ZoneId.ValueString(),
|
||||
recordSetId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.RecordSetId = types.StringPointerValue(recordSet.Id)
|
||||
model.Active = types.BoolPointerValue(recordSet.Active)
|
||||
model.Comment = types.StringPointerValue(recordSet.Comment)
|
||||
model.Error = types.StringPointerValue(recordSet.Error)
|
||||
model.Name = types.StringPointerValue(recordSet.Name)
|
||||
model.State = types.StringPointerValue(recordSet.State)
|
||||
model.TTL = conversion.ToTypeInt64(recordSet.Ttl)
|
||||
model.Type = types.StringPointerValue(recordSet.Type)
|
||||
return nil
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model) (*dns.CreateRecordSetPayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
records := []dns.RecordPayload{}
|
||||
for i, record := range model.Records.Elements() {
|
||||
recordString, ok := record.(types.String)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("expected record at index %d to be of type %T, got %T", i, types.String{}, record)
|
||||
}
|
||||
records = append(records, dns.RecordPayload{
|
||||
Content: recordString.ValueStringPointer(),
|
||||
})
|
||||
}
|
||||
|
||||
return &dns.CreateRecordSetPayload{
|
||||
Comment: model.Comment.ValueStringPointer(),
|
||||
Name: model.Name.ValueStringPointer(),
|
||||
Records: &records,
|
||||
Ttl: conversion.ToPtrInt32(model.TTL),
|
||||
Type: model.Type.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toUpdatePayload(model *Model) (*dns.UpdateRecordSetPayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
records := []dns.RecordPayload{}
|
||||
for i, record := range model.Records.Elements() {
|
||||
recordString, ok := record.(types.String)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("expected record at index %d to be of type %T, got %T", i, types.String{}, record)
|
||||
}
|
||||
records = append(records, dns.RecordPayload{
|
||||
Content: recordString.ValueStringPointer(),
|
||||
})
|
||||
}
|
||||
|
||||
return &dns.UpdateRecordSetPayload{
|
||||
Comment: model.Comment.ValueStringPointer(),
|
||||
Name: model.Name.ValueStringPointer(),
|
||||
Records: &records,
|
||||
Ttl: conversion.ToPtrInt32(model.TTL),
|
||||
}, nil
|
||||
}
|
||||
307
stackit/internal/services/dns/recordset/resource_test.go
Normal file
307
stackit/internal/services/dns/recordset/resource_test.go
Normal file
|
|
@ -0,0 +1,307 @@
|
|||
package dns
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/dns"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *dns.RecordSetResponse
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&dns.RecordSetResponse{
|
||||
Rrset: &dns.RecordSet{
|
||||
Id: utils.Ptr("rid"),
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,zid,rid"),
|
||||
RecordSetId: types.StringValue("rid"),
|
||||
ZoneId: types.StringValue("zid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Active: types.BoolNull(),
|
||||
Comment: types.StringNull(),
|
||||
Error: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Records: types.ListNull(types.StringType),
|
||||
State: types.StringNull(),
|
||||
TTL: types.Int64Null(),
|
||||
Type: types.StringNull(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&dns.RecordSetResponse{
|
||||
Rrset: &dns.RecordSet{
|
||||
Id: utils.Ptr("rid"),
|
||||
Active: utils.Ptr(true),
|
||||
Comment: utils.Ptr("comment"),
|
||||
Error: utils.Ptr("error"),
|
||||
Name: utils.Ptr("name"),
|
||||
Records: &[]dns.Record{
|
||||
{Content: utils.Ptr("record_1")},
|
||||
{Content: utils.Ptr("record_2")},
|
||||
},
|
||||
State: utils.Ptr("state"),
|
||||
Ttl: utils.Ptr(int32(1)),
|
||||
Type: utils.Ptr("type"),
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,zid,rid"),
|
||||
RecordSetId: types.StringValue("rid"),
|
||||
ZoneId: types.StringValue("zid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Active: types.BoolValue(true),
|
||||
Comment: types.StringValue("comment"),
|
||||
Error: types.StringValue("error"),
|
||||
Name: types.StringValue("name"),
|
||||
Records: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("record_1"),
|
||||
types.StringValue("record_2"),
|
||||
}),
|
||||
State: types.StringValue("state"),
|
||||
TTL: types.Int64Value(1),
|
||||
Type: types.StringValue("type"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&dns.RecordSetResponse{
|
||||
Rrset: &dns.RecordSet{
|
||||
Id: utils.Ptr("rid"),
|
||||
Active: nil,
|
||||
Comment: nil,
|
||||
Error: nil,
|
||||
Name: utils.Ptr("name"),
|
||||
Records: nil,
|
||||
State: utils.Ptr("state"),
|
||||
Ttl: utils.Ptr(int32(2123456789)),
|
||||
Type: utils.Ptr("type"),
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,zid,rid"),
|
||||
RecordSetId: types.StringValue("rid"),
|
||||
ZoneId: types.StringValue("zid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Active: types.BoolNull(),
|
||||
Comment: types.StringNull(),
|
||||
Error: types.StringNull(),
|
||||
Name: types.StringValue("name"),
|
||||
Records: types.ListNull(types.StringType),
|
||||
State: types.StringValue("state"),
|
||||
TTL: types.Int64Value(2123456789),
|
||||
Type: types.StringValue("type"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&dns.RecordSetResponse{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
state := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
ZoneId: tt.expected.ZoneId,
|
||||
}
|
||||
err := mapFields(tt.input, state)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
expected *dns.CreateRecordSetPayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default values",
|
||||
&Model{},
|
||||
&dns.CreateRecordSetPayload{
|
||||
Records: &[]dns.RecordPayload{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
Comment: types.StringValue("comment"),
|
||||
Name: types.StringValue("name"),
|
||||
Records: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("record_1"),
|
||||
types.StringValue("record_2"),
|
||||
}),
|
||||
TTL: types.Int64Value(1),
|
||||
Type: types.StringValue("type"),
|
||||
},
|
||||
&dns.CreateRecordSetPayload{
|
||||
Comment: utils.Ptr("comment"),
|
||||
Name: utils.Ptr("name"),
|
||||
Records: &[]dns.RecordPayload{
|
||||
{Content: utils.Ptr("record_1")},
|
||||
{Content: utils.Ptr("record_2")},
|
||||
},
|
||||
Ttl: utils.Ptr(int32(1)),
|
||||
Type: utils.Ptr("type"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
Comment: types.StringNull(),
|
||||
Name: types.StringValue(""),
|
||||
Records: types.ListValueMust(types.StringType, nil),
|
||||
TTL: types.Int64Value(2123456789),
|
||||
Type: types.StringValue(""),
|
||||
},
|
||||
&dns.CreateRecordSetPayload{
|
||||
Comment: nil,
|
||||
Name: utils.Ptr(""),
|
||||
Records: &[]dns.RecordPayload{},
|
||||
Ttl: utils.Ptr(int32(2123456789)),
|
||||
Type: utils.Ptr(""),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toCreatePayload(tt.input)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToUpdatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
expected *dns.UpdateRecordSetPayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
&dns.UpdateRecordSetPayload{
|
||||
Records: &[]dns.RecordPayload{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
Comment: types.StringValue("comment"),
|
||||
Name: types.StringValue("name"),
|
||||
Records: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("record_1"),
|
||||
types.StringValue("record_2"),
|
||||
}),
|
||||
TTL: types.Int64Value(1),
|
||||
},
|
||||
&dns.UpdateRecordSetPayload{
|
||||
Comment: utils.Ptr("comment"),
|
||||
Name: utils.Ptr("name"),
|
||||
Records: &[]dns.RecordPayload{
|
||||
{Content: utils.Ptr("record_1")},
|
||||
{Content: utils.Ptr("record_2")},
|
||||
},
|
||||
Ttl: utils.Ptr(int32(1)),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
Comment: types.StringNull(),
|
||||
Name: types.StringValue(""),
|
||||
Records: types.ListValueMust(types.StringType, nil),
|
||||
TTL: types.Int64Value(2123456789),
|
||||
},
|
||||
&dns.UpdateRecordSetPayload{
|
||||
Comment: nil,
|
||||
Name: utils.Ptr(""),
|
||||
Records: &[]dns.RecordPayload{},
|
||||
Ttl: utils.Ptr(int32(2123456789)),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toUpdatePayload(tt.input)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
208
stackit/internal/services/dns/zone/datasource.go
Normal file
208
stackit/internal/services/dns/zone/datasource.go
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/dns"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &zoneDataSource{}
|
||||
)
|
||||
|
||||
// NewZoneDataSource is a helper function to simplify the provider implementation.
|
||||
func NewZoneDataSource() datasource.DataSource {
|
||||
return &zoneDataSource{}
|
||||
}
|
||||
|
||||
// zoneDataSource is the data source implementation.
|
||||
type zoneDataSource struct {
|
||||
client *dns.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the data source type name.
|
||||
func (d *zoneDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_dns_zone"
|
||||
}
|
||||
|
||||
func (d *zoneDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *dns.APIClient
|
||||
var err error
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
if providerData.DnsCustomEndpoint != "" {
|
||||
apiClient, err = dns.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.DnsCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = dns.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
d.client = apiClient
|
||||
tflog.Info(ctx, "DNS zone client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the data source.
|
||||
func (d *zoneDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "DNS Zone resource schema.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`zone_id`\".",
|
||||
Computed: true,
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: "STACKIT project ID to which the dns zone is associated.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"zone_id": schema.StringAttribute{
|
||||
Description: "The zone ID.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: "The user given name of the zone.",
|
||||
Computed: true,
|
||||
},
|
||||
"dns_name": schema.StringAttribute{
|
||||
Description: "The zone name. E.g. `example.com`",
|
||||
Computed: true,
|
||||
},
|
||||
"description": schema.StringAttribute{
|
||||
Description: "Description of the zone.",
|
||||
Computed: true,
|
||||
},
|
||||
"acl": schema.StringAttribute{
|
||||
Description: "The access control list.",
|
||||
Computed: true,
|
||||
},
|
||||
"active": schema.BoolAttribute{
|
||||
Description: "",
|
||||
Computed: true,
|
||||
},
|
||||
"contact_email": schema.StringAttribute{
|
||||
Description: "A contact e-mail for the zone.",
|
||||
Computed: true,
|
||||
},
|
||||
"default_ttl": schema.Int64Attribute{
|
||||
Description: "Default time to live.",
|
||||
Computed: true,
|
||||
},
|
||||
"expire_time": schema.Int64Attribute{
|
||||
Description: "Expire time.",
|
||||
Computed: true,
|
||||
},
|
||||
"is_reverse_zone": schema.BoolAttribute{
|
||||
Description: "Specifies, if the zone is a reverse zone or not.",
|
||||
Computed: true,
|
||||
},
|
||||
"negative_cache": schema.Int64Attribute{
|
||||
Description: "Negative caching.",
|
||||
Computed: true,
|
||||
},
|
||||
"primary_name_server": schema.StringAttribute{
|
||||
Description: "Primary name server. FQDN.",
|
||||
Computed: true,
|
||||
},
|
||||
"primaries": schema.ListAttribute{
|
||||
Description: `Primary name server for secondary zone.`,
|
||||
Computed: true,
|
||||
ElementType: types.StringType,
|
||||
},
|
||||
"record_count": schema.Int64Attribute{
|
||||
Description: "Record count how many records are in the zone.",
|
||||
Computed: true,
|
||||
},
|
||||
"refresh_time": schema.Int64Attribute{
|
||||
Description: "Refresh time.",
|
||||
Computed: true,
|
||||
},
|
||||
"retry_time": schema.Int64Attribute{
|
||||
Description: "Retry time.",
|
||||
Computed: true,
|
||||
},
|
||||
"serial_number": schema.Int64Attribute{
|
||||
Description: "Serial number.",
|
||||
Computed: true,
|
||||
},
|
||||
"type": schema.StringAttribute{
|
||||
Description: "Zone type.",
|
||||
Computed: true,
|
||||
},
|
||||
"visibility": schema.StringAttribute{
|
||||
Description: "Visibility of the zone.",
|
||||
Computed: true,
|
||||
},
|
||||
"state": schema.StringAttribute{
|
||||
Description: "Zone state.",
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (d *zoneDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
zoneId := model.ZoneId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "zone_id", zoneId)
|
||||
|
||||
zoneResp, err := d.client.GetZone(ctx, projectId, zoneId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading zone", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
err = mapFields(zoneResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading zone", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "DNS zone read")
|
||||
}
|
||||
609
stackit/internal/services/dns/zone/resource.go
Normal file
609
stackit/internal/services/dns/zone/resource.go
Normal file
|
|
@ -0,0 +1,609 @@
|
|||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/int64validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/listvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/listplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/dns"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &zoneResource{}
|
||||
_ resource.ResourceWithConfigure = &zoneResource{}
|
||||
_ resource.ResourceWithImportState = &zoneResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
ZoneId types.String `tfsdk:"zone_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
DnsName types.String `tfsdk:"dns_name"`
|
||||
Description types.String `tfsdk:"description"`
|
||||
Acl types.String `tfsdk:"acl"`
|
||||
Active types.Bool `tfsdk:"active"`
|
||||
ContactEmail types.String `tfsdk:"contact_email"`
|
||||
DefaultTTL types.Int64 `tfsdk:"default_ttl"`
|
||||
ExpireTime types.Int64 `tfsdk:"expire_time"`
|
||||
IsReverseZone types.Bool `tfsdk:"is_reverse_zone"`
|
||||
NegativeCache types.Int64 `tfsdk:"negative_cache"`
|
||||
PrimaryNameServer types.String `tfsdk:"primary_name_server"`
|
||||
Primaries types.List `tfsdk:"primaries"`
|
||||
RecordCount types.Int64 `tfsdk:"record_count"`
|
||||
RefreshTime types.Int64 `tfsdk:"refresh_time"`
|
||||
RetryTime types.Int64 `tfsdk:"retry_time"`
|
||||
SerialNumber types.Int64 `tfsdk:"serial_number"`
|
||||
Type types.String `tfsdk:"type"`
|
||||
Visibility types.String `tfsdk:"visibility"`
|
||||
State types.String `tfsdk:"state"`
|
||||
}
|
||||
|
||||
// NewZoneResource is a helper function to simplify the provider implementation.
|
||||
func NewZoneResource() resource.Resource {
|
||||
return &zoneResource{}
|
||||
}
|
||||
|
||||
// zoneResource is the resource implementation.
|
||||
type zoneResource struct {
|
||||
client *dns.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *zoneResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_dns_zone"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *zoneResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *dns.APIClient
|
||||
var err error
|
||||
if providerData.DnsCustomEndpoint != "" {
|
||||
ctx = tflog.SetField(ctx, "dns_custom_endpoint", providerData.DnsCustomEndpoint)
|
||||
apiClient, err = dns.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.DnsCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = dns.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "DNS zone client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *zoneResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "DNS Zone resource schema.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`zone_id`\".",
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: "STACKIT project ID to which the dns zone is associated.",
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"zone_id": schema.StringAttribute{
|
||||
Description: "The zone ID.",
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: "The user given name of the zone.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
stringvalidator.LengthAtMost(63),
|
||||
},
|
||||
},
|
||||
"dns_name": schema.StringAttribute{
|
||||
Description: "The zone name. E.g. `example.com`",
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
stringvalidator.LengthAtMost(253),
|
||||
},
|
||||
},
|
||||
"description": schema.StringAttribute{
|
||||
Description: "Description of the zone.",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtMost(1024),
|
||||
},
|
||||
},
|
||||
"acl": schema.StringAttribute{
|
||||
Description: "The access control list. E.g. `0.0.0.0/0,::/0`",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtMost(2000),
|
||||
},
|
||||
},
|
||||
"active": schema.BoolAttribute{
|
||||
Description: "",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
},
|
||||
"contact_email": schema.StringAttribute{
|
||||
Description: "A contact e-mail for the zone.",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtMost(255),
|
||||
},
|
||||
},
|
||||
"default_ttl": schema.Int64Attribute{
|
||||
Description: "Default time to live. E.g. 3600.",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Validators: []validator.Int64{
|
||||
int64validator.Between(60, 99999999),
|
||||
},
|
||||
},
|
||||
"expire_time": schema.Int64Attribute{
|
||||
Description: "Expire time. E.g. 1209600.",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Validators: []validator.Int64{
|
||||
int64validator.Between(60, 99999999),
|
||||
},
|
||||
},
|
||||
"is_reverse_zone": schema.BoolAttribute{
|
||||
Description: "Specifies, if the zone is a reverse zone or not.",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Default: booldefault.StaticBool(false),
|
||||
},
|
||||
"negative_cache": schema.Int64Attribute{
|
||||
Description: "Negative caching. E.g. 60",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Validators: []validator.Int64{
|
||||
int64validator.Between(60, 99999999),
|
||||
},
|
||||
},
|
||||
"primaries": schema.ListAttribute{
|
||||
Description: `Primary name server for secondary zone. E.g. ["1.2.3.4"]`,
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
ElementType: types.StringType,
|
||||
PlanModifiers: []planmodifier.List{
|
||||
listplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Validators: []validator.List{
|
||||
listvalidator.SizeAtMost(10),
|
||||
},
|
||||
},
|
||||
"refresh_time": schema.Int64Attribute{
|
||||
Description: "Refresh time. E.g. 3600",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Validators: []validator.Int64{
|
||||
int64validator.Between(60, 99999999),
|
||||
},
|
||||
},
|
||||
"retry_time": schema.Int64Attribute{
|
||||
Description: "Retry time. E.g. 600",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Validators: []validator.Int64{
|
||||
int64validator.Between(60, 99999999),
|
||||
},
|
||||
},
|
||||
"type": schema.StringAttribute{
|
||||
Description: "Zone type. E.g. `primary`",
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
Default: stringdefault.StaticString("primary"),
|
||||
Validators: []validator.String{
|
||||
stringvalidator.OneOf("primary", "secondary"),
|
||||
},
|
||||
},
|
||||
"primary_name_server": schema.StringAttribute{
|
||||
Description: "Primary name server. FQDN.",
|
||||
Computed: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
stringvalidator.LengthAtMost(253),
|
||||
},
|
||||
},
|
||||
"serial_number": schema.Int64Attribute{
|
||||
Description: "Serial number. E.g. `2022111400`.",
|
||||
Computed: true,
|
||||
Validators: []validator.Int64{
|
||||
int64validator.AtLeast(0),
|
||||
int64validator.AtMost(math.MaxInt32 - 1),
|
||||
},
|
||||
},
|
||||
"visibility": schema.StringAttribute{
|
||||
Description: "Visibility of the zone. E.g. `public`.",
|
||||
Computed: true,
|
||||
},
|
||||
"record_count": schema.Int64Attribute{
|
||||
Description: "Record count how many records are in the zone.",
|
||||
Computed: true,
|
||||
},
|
||||
"state": schema.StringAttribute{
|
||||
Description: "Zone state. E.g. `CREATE_SUCCEEDED`.",
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *zoneResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating zone", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Create new zone
|
||||
createResp, err := r.client.CreateZone(ctx, projectId).CreateZonePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating zone", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
zoneId := *createResp.Zone.Id
|
||||
|
||||
ctx = tflog.SetField(ctx, "zone_id", zoneId)
|
||||
wr, err := dns.CreateZoneWaitHandler(ctx, r.client, projectId, zoneId).SetTimeout(10 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating zone", fmt.Sprintf("Zone creation waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*dns.ZoneResponse)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating zone", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating zone", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "DNS zone created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *zoneResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
zoneId := model.ZoneId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "zone_id", zoneId)
|
||||
|
||||
zoneResp, err := r.client.GetZone(ctx, projectId, zoneId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading zone", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(zoneResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading zone", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "DNS zone read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *zoneResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
zoneId := model.ZoneId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "zone_id", zoneId)
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toUpdatePayload(&model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating zone", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Update existing zone
|
||||
_, err = r.client.UpdateZone(ctx, projectId, zoneId).UpdateZonePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating zone", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
wr, err := dns.UpdateZoneWaitHandler(ctx, r.client, projectId, zoneId).SetTimeout(10 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating zone", fmt.Sprintf("Zone update waiting: %v", err))
|
||||
return
|
||||
}
|
||||
_, ok := wr.(*dns.ZoneResponse)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating zone", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Fetch updated zone
|
||||
zoneResp, err := r.client.GetZone(ctx, projectId, zoneId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating zone", fmt.Sprintf("Calling API for updated data: %v", err))
|
||||
return
|
||||
}
|
||||
err = mapFields(zoneResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating zone", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "DNS zone updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *zoneResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from state
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
zoneId := model.ZoneId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "zone_id", zoneId)
|
||||
|
||||
// Delete existing zone
|
||||
_, err := r.client.DeleteZone(ctx, projectId, zoneId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting zone", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
_, err = dns.DeleteZoneWaitHandler(ctx, r.client, projectId, zoneId).SetTimeout(10 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting zone", fmt.Sprintf("Zone deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
tflog.Info(ctx, "DNS zone deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,zone_id
|
||||
func (r *zoneResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
|
||||
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing zone",
|
||||
fmt.Sprintf("Expected import identifier with format: [project_id],[zone_id] Got: %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
projectId := idParts[0]
|
||||
zoneId := idParts[1]
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "zone_id", zoneId)
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), projectId)...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("zone_id"), zoneId)...)
|
||||
tflog.Info(ctx, "DNS zone state imported")
|
||||
}
|
||||
|
||||
func mapFields(zoneResp *dns.ZoneResponse, model *Model) error {
|
||||
if zoneResp == nil || zoneResp.Zone == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
z := zoneResp.Zone
|
||||
|
||||
var rc *int64
|
||||
if z.RecordCount != nil {
|
||||
recordCount64 := int64(*z.RecordCount)
|
||||
rc = &recordCount64
|
||||
} else {
|
||||
rc = nil
|
||||
}
|
||||
|
||||
var zoneId string
|
||||
if model.ZoneId.ValueString() != "" {
|
||||
zoneId = model.ZoneId.ValueString()
|
||||
} else if z.Id != nil {
|
||||
zoneId = *z.Id
|
||||
} else {
|
||||
return fmt.Errorf("zone id not present")
|
||||
}
|
||||
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
zoneId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
|
||||
if z.Primaries == nil {
|
||||
model.Primaries = types.ListNull(types.StringType)
|
||||
} else {
|
||||
respZonePrimaries := []attr.Value{}
|
||||
for _, primary := range *z.Primaries {
|
||||
respZonePrimaries = append(respZonePrimaries, types.StringValue(primary))
|
||||
respZonePrimariesList, diags := types.ListValue(types.StringType, respZonePrimaries)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("creating primaries list: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Primaries = respZonePrimariesList
|
||||
}
|
||||
}
|
||||
model.ZoneId = types.StringValue(zoneId)
|
||||
model.Description = types.StringPointerValue(z.Description)
|
||||
model.Acl = types.StringPointerValue(z.Acl)
|
||||
model.Active = types.BoolPointerValue(z.Active)
|
||||
model.ContactEmail = types.StringPointerValue(z.ContactEmail)
|
||||
model.DefaultTTL = conversion.ToTypeInt64(z.DefaultTTL)
|
||||
model.DnsName = types.StringPointerValue(z.DnsName)
|
||||
model.ExpireTime = conversion.ToTypeInt64(z.ExpireTime)
|
||||
model.IsReverseZone = types.BoolPointerValue(z.IsReverseZone)
|
||||
model.Name = types.StringPointerValue(z.Name)
|
||||
model.NegativeCache = conversion.ToTypeInt64(z.NegativeCache)
|
||||
model.PrimaryNameServer = types.StringPointerValue(z.PrimaryNameServer)
|
||||
model.RecordCount = types.Int64PointerValue(rc)
|
||||
model.RefreshTime = conversion.ToTypeInt64(z.RefreshTime)
|
||||
model.RetryTime = conversion.ToTypeInt64(z.RetryTime)
|
||||
model.SerialNumber = conversion.ToTypeInt64(z.SerialNumber)
|
||||
model.State = types.StringPointerValue(z.State)
|
||||
model.Type = types.StringPointerValue(z.Type)
|
||||
model.Visibility = types.StringPointerValue(z.Visibility)
|
||||
return nil
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model) (*dns.CreateZonePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
modelPrimaries := []string{}
|
||||
for _, primary := range model.Primaries.Elements() {
|
||||
primaryString, ok := primary.(types.String)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("type assertion failed")
|
||||
}
|
||||
modelPrimaries = append(modelPrimaries, primaryString.ValueString())
|
||||
}
|
||||
return &dns.CreateZonePayload{
|
||||
Name: model.Name.ValueStringPointer(),
|
||||
DnsName: model.DnsName.ValueStringPointer(),
|
||||
ContactEmail: model.ContactEmail.ValueStringPointer(),
|
||||
Description: model.Description.ValueStringPointer(),
|
||||
Acl: model.Acl.ValueStringPointer(),
|
||||
Type: model.Type.ValueStringPointer(),
|
||||
DefaultTTL: conversion.ToPtrInt32(model.DefaultTTL),
|
||||
ExpireTime: conversion.ToPtrInt32(model.ExpireTime),
|
||||
RefreshTime: conversion.ToPtrInt32(model.RefreshTime),
|
||||
RetryTime: conversion.ToPtrInt32(model.RetryTime),
|
||||
NegativeCache: conversion.ToPtrInt32(model.NegativeCache),
|
||||
IsReverseZone: model.IsReverseZone.ValueBoolPointer(),
|
||||
Primaries: &modelPrimaries,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toUpdatePayload(model *Model) (*dns.UpdateZonePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
return &dns.UpdateZonePayload{
|
||||
Name: model.Name.ValueStringPointer(),
|
||||
ContactEmail: model.ContactEmail.ValueStringPointer(),
|
||||
Description: model.Description.ValueStringPointer(),
|
||||
Acl: model.Acl.ValueStringPointer(),
|
||||
DefaultTTL: conversion.ToPtrInt32(model.DefaultTTL),
|
||||
ExpireTime: conversion.ToPtrInt32(model.ExpireTime),
|
||||
RefreshTime: conversion.ToPtrInt32(model.RefreshTime),
|
||||
RetryTime: conversion.ToPtrInt32(model.RetryTime),
|
||||
NegativeCache: conversion.ToPtrInt32(model.NegativeCache),
|
||||
Primaries: nil, // API returns error if this field is set, even if nothing changes
|
||||
}, nil
|
||||
}
|
||||
349
stackit/internal/services/dns/zone/resource_test.go
Normal file
349
stackit/internal/services/dns/zone/resource_test.go
Normal file
|
|
@ -0,0 +1,349 @@
|
|||
package dns
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/dns"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *dns.ZoneResponse
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_ok",
|
||||
&dns.ZoneResponse{
|
||||
Zone: &dns.Zone{
|
||||
Id: utils.Ptr("zid"),
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,zid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
ZoneId: types.StringValue("zid"),
|
||||
Name: types.StringNull(),
|
||||
DnsName: types.StringNull(),
|
||||
Acl: types.StringNull(),
|
||||
DefaultTTL: types.Int64Null(),
|
||||
ExpireTime: types.Int64Null(),
|
||||
RefreshTime: types.Int64Null(),
|
||||
RetryTime: types.Int64Null(),
|
||||
SerialNumber: types.Int64Null(),
|
||||
NegativeCache: types.Int64Null(),
|
||||
Type: types.StringNull(),
|
||||
State: types.StringNull(),
|
||||
PrimaryNameServer: types.StringNull(),
|
||||
Primaries: types.ListNull(types.StringType),
|
||||
Visibility: types.StringNull(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"values_ok",
|
||||
&dns.ZoneResponse{
|
||||
Zone: &dns.Zone{
|
||||
Id: utils.Ptr("zid"),
|
||||
Name: utils.Ptr("name"),
|
||||
DnsName: utils.Ptr("dnsname"),
|
||||
Acl: utils.Ptr("acl"),
|
||||
Active: utils.Ptr(false),
|
||||
CreationStarted: utils.Ptr("bar"),
|
||||
CreationFinished: utils.Ptr("foo"),
|
||||
DefaultTTL: utils.Ptr(int32(1)),
|
||||
ExpireTime: utils.Ptr(int32(2)),
|
||||
RefreshTime: utils.Ptr(int32(3)),
|
||||
RetryTime: utils.Ptr(int32(4)),
|
||||
SerialNumber: utils.Ptr(int32(5)),
|
||||
NegativeCache: utils.Ptr(int32(6)),
|
||||
State: utils.Ptr("state"),
|
||||
Type: utils.Ptr("type"),
|
||||
Primaries: &[]string{"primary"},
|
||||
PrimaryNameServer: utils.Ptr("pns"),
|
||||
UpdateStarted: utils.Ptr("ufoo"),
|
||||
UpdateFinished: utils.Ptr("ubar"),
|
||||
Visibility: utils.Ptr("visibility"),
|
||||
Error: utils.Ptr("error"),
|
||||
ContactEmail: utils.Ptr("a@b.cd"),
|
||||
Description: utils.Ptr("description"),
|
||||
IsReverseZone: utils.Ptr(false),
|
||||
RecordCount: utils.Ptr(int32(3)),
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,zid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
ZoneId: types.StringValue("zid"),
|
||||
Name: types.StringValue("name"),
|
||||
DnsName: types.StringValue("dnsname"),
|
||||
Acl: types.StringValue("acl"),
|
||||
Active: types.BoolValue(false),
|
||||
DefaultTTL: types.Int64Value(1),
|
||||
ExpireTime: types.Int64Value(2),
|
||||
RefreshTime: types.Int64Value(3),
|
||||
RetryTime: types.Int64Value(4),
|
||||
SerialNumber: types.Int64Value(5),
|
||||
NegativeCache: types.Int64Value(6),
|
||||
Type: types.StringValue("type"),
|
||||
State: types.StringValue("state"),
|
||||
PrimaryNameServer: types.StringValue("pns"),
|
||||
Primaries: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("primary"),
|
||||
}),
|
||||
Visibility: types.StringValue("visibility"),
|
||||
ContactEmail: types.StringValue("a@b.cd"),
|
||||
Description: types.StringValue("description"),
|
||||
IsReverseZone: types.BoolValue(false),
|
||||
RecordCount: types.Int64Value(3),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nullable_fields_and_int_conversions_ok",
|
||||
&dns.ZoneResponse{
|
||||
Zone: &dns.Zone{
|
||||
Id: utils.Ptr("zid"),
|
||||
Name: utils.Ptr("name"),
|
||||
DnsName: utils.Ptr("dnsname"),
|
||||
Acl: utils.Ptr("acl"),
|
||||
Active: nil,
|
||||
CreationStarted: utils.Ptr("bar"),
|
||||
CreationFinished: utils.Ptr("foo"),
|
||||
DefaultTTL: utils.Ptr(int32(2123456789)),
|
||||
ExpireTime: utils.Ptr(int32(-2)),
|
||||
RefreshTime: utils.Ptr(int32(3)),
|
||||
RetryTime: utils.Ptr(int32(4)),
|
||||
SerialNumber: utils.Ptr(int32(5)),
|
||||
NegativeCache: utils.Ptr(int32(0)),
|
||||
State: utils.Ptr("state"),
|
||||
Type: utils.Ptr("type"),
|
||||
Primaries: nil,
|
||||
PrimaryNameServer: utils.Ptr("pns"),
|
||||
UpdateStarted: utils.Ptr("ufoo"),
|
||||
UpdateFinished: utils.Ptr("ubar"),
|
||||
Visibility: utils.Ptr("visibility"),
|
||||
ContactEmail: nil,
|
||||
Description: nil,
|
||||
IsReverseZone: nil,
|
||||
RecordCount: utils.Ptr(int32(-2123456789)),
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,zid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
ZoneId: types.StringValue("zid"),
|
||||
Name: types.StringValue("name"),
|
||||
DnsName: types.StringValue("dnsname"),
|
||||
Acl: types.StringValue("acl"),
|
||||
Active: types.BoolNull(),
|
||||
DefaultTTL: types.Int64Value(2123456789),
|
||||
ExpireTime: types.Int64Value(-2),
|
||||
RefreshTime: types.Int64Value(3),
|
||||
RetryTime: types.Int64Value(4),
|
||||
SerialNumber: types.Int64Value(5),
|
||||
NegativeCache: types.Int64Value(0),
|
||||
Type: types.StringValue("type"),
|
||||
Primaries: types.ListNull(types.StringType),
|
||||
State: types.StringValue("state"),
|
||||
PrimaryNameServer: types.StringValue("pns"),
|
||||
Visibility: types.StringValue("visibility"),
|
||||
ContactEmail: types.StringNull(),
|
||||
Description: types.StringNull(),
|
||||
IsReverseZone: types.BoolNull(),
|
||||
RecordCount: types.Int64Value(-2123456789),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"response_nil_fail",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&dns.ZoneResponse{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
state := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
}
|
||||
err := mapFields(tt.input, state)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
expected *dns.CreateZonePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_ok",
|
||||
&Model{
|
||||
Name: types.StringValue("Name"),
|
||||
DnsName: types.StringValue("DnsName"),
|
||||
},
|
||||
&dns.CreateZonePayload{
|
||||
Name: utils.Ptr("Name"),
|
||||
DnsName: utils.Ptr("DnsName"),
|
||||
Primaries: &[]string{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"mapping_with_conversions_ok",
|
||||
&Model{
|
||||
Name: types.StringValue("Name"),
|
||||
DnsName: types.StringValue("DnsName"),
|
||||
Acl: types.StringValue("Acl"),
|
||||
Description: types.StringValue("Description"),
|
||||
Type: types.StringValue("Type"),
|
||||
ContactEmail: types.StringValue("ContactEmail"),
|
||||
RetryTime: types.Int64Value(3),
|
||||
RefreshTime: types.Int64Value(4),
|
||||
ExpireTime: types.Int64Value(5),
|
||||
DefaultTTL: types.Int64Value(4534534),
|
||||
NegativeCache: types.Int64Value(-4534534),
|
||||
Primaries: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("primary"),
|
||||
}),
|
||||
IsReverseZone: types.BoolValue(true),
|
||||
},
|
||||
&dns.CreateZonePayload{
|
||||
Name: utils.Ptr("Name"),
|
||||
DnsName: utils.Ptr("DnsName"),
|
||||
Acl: utils.Ptr("Acl"),
|
||||
Description: utils.Ptr("Description"),
|
||||
Type: utils.Ptr("Type"),
|
||||
ContactEmail: utils.Ptr("ContactEmail"),
|
||||
Primaries: &[]string{"primary"},
|
||||
RetryTime: utils.Ptr(int32(3)),
|
||||
RefreshTime: utils.Ptr(int32(4)),
|
||||
ExpireTime: utils.Ptr(int32(5)),
|
||||
DefaultTTL: utils.Ptr(int32(4534534)),
|
||||
NegativeCache: utils.Ptr(int32(-4534534)),
|
||||
IsReverseZone: utils.Ptr(true),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toCreatePayload(tt.input)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToPayloadUpdate(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
expected *dns.UpdateZonePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"single_field_change_ok",
|
||||
&Model{
|
||||
Name: types.StringValue("Name"),
|
||||
},
|
||||
&dns.UpdateZonePayload{
|
||||
Name: utils.Ptr("Name"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"mapping_with_conversions_ok",
|
||||
&Model{
|
||||
Name: types.StringValue("Name"),
|
||||
DnsName: types.StringValue("DnsName"),
|
||||
Acl: types.StringValue("Acl"),
|
||||
Active: types.BoolValue(true),
|
||||
Description: types.StringValue("Description"),
|
||||
Type: types.StringValue("Type"),
|
||||
ContactEmail: types.StringValue("ContactEmail"),
|
||||
PrimaryNameServer: types.StringValue("PrimaryNameServer"),
|
||||
Primaries: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("Primary"),
|
||||
}),
|
||||
RetryTime: types.Int64Value(3),
|
||||
RefreshTime: types.Int64Value(4),
|
||||
ExpireTime: types.Int64Value(5),
|
||||
DefaultTTL: types.Int64Value(4534534),
|
||||
NegativeCache: types.Int64Value(-4534534),
|
||||
IsReverseZone: types.BoolValue(true),
|
||||
},
|
||||
&dns.UpdateZonePayload{
|
||||
Name: utils.Ptr("Name"),
|
||||
Acl: utils.Ptr("Acl"),
|
||||
Description: utils.Ptr("Description"),
|
||||
ContactEmail: utils.Ptr("ContactEmail"),
|
||||
RetryTime: utils.Ptr(int32(3)),
|
||||
RefreshTime: utils.Ptr(int32(4)),
|
||||
ExpireTime: utils.Ptr(int32(5)),
|
||||
DefaultTTL: utils.Ptr(int32(4534534)),
|
||||
NegativeCache: utils.Ptr(int32(-4534534)),
|
||||
},
|
||||
true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toUpdatePayload(tt.input)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
181
stackit/internal/services/logme/credentials/datasource.go
Normal file
181
stackit/internal/services/logme/credentials/datasource.go
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
package logme
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/logme"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &credentialsDataSource{}
|
||||
)
|
||||
|
||||
// NewCredentialsDataSource is a helper function to simplify the provider implementation.
|
||||
func NewCredentialsDataSource() datasource.DataSource {
|
||||
return &credentialsDataSource{}
|
||||
}
|
||||
|
||||
// credentialsDataSource is the data source implementation.
|
||||
type credentialsDataSource struct {
|
||||
client *logme.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *credentialsDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_logme_credentials"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *credentialsDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *logme.APIClient
|
||||
var err error
|
||||
if providerData.LogMeCustomEndpoint != "" {
|
||||
apiClient, err = logme.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.LogMeCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = logme.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "LogMe credentials client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *credentialsDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "LogMe credentials data source schema.",
|
||||
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`,`credentials_id`\".",
|
||||
"credentials_id": "The credentials ID.",
|
||||
"instance_id": "ID of the LogMe instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"credentials_id": schema.StringAttribute{
|
||||
Description: descriptions["credentials_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"hosts": schema.ListAttribute{
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"http_api_uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"password": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *credentialsDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
credentialsId := model.CredentialsId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(recordSetResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "LogMe credentials read")
|
||||
}
|
||||
377
stackit/internal/services/logme/credentials/resource.go
Normal file
377
stackit/internal/services/logme/credentials/resource.go
Normal file
|
|
@ -0,0 +1,377 @@
|
|||
package logme
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/logme"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &credentialsResource{}
|
||||
_ resource.ResourceWithConfigure = &credentialsResource{}
|
||||
_ resource.ResourceWithImportState = &credentialsResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
CredentialsId types.String `tfsdk:"credentials_id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Host types.String `tfsdk:"host"`
|
||||
Hosts types.List `tfsdk:"hosts"`
|
||||
HttpAPIURI types.String `tfsdk:"http_api_uri"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Password types.String `tfsdk:"password"`
|
||||
Port types.Int64 `tfsdk:"port"`
|
||||
Uri types.String `tfsdk:"uri"`
|
||||
Username types.String `tfsdk:"username"`
|
||||
}
|
||||
|
||||
// NewCredentialsResource is a helper function to simplify the provider implementation.
|
||||
func NewCredentialsResource() resource.Resource {
|
||||
return &credentialsResource{}
|
||||
}
|
||||
|
||||
// credentialsResource is the resource implementation.
|
||||
type credentialsResource struct {
|
||||
client *logme.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *credentialsResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_logme_credentials"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *credentialsResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *logme.APIClient
|
||||
var err error
|
||||
if providerData.LogMeCustomEndpoint != "" {
|
||||
apiClient, err = logme.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.LogMeCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = logme.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "LogMe credentials client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *credentialsResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "LogMe credentials resource schema.",
|
||||
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`,`credentials_id`\".",
|
||||
"credentials_id": "The credentials ID.",
|
||||
"instance_id": "ID of the LogMe instance.",
|
||||
"project_id": "STACKIT Project ID to which the instance is associated.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"credentials_id": schema.StringAttribute{
|
||||
Description: descriptions["credentials_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"hosts": schema.ListAttribute{
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"http_api_uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"password": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *credentialsResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
// Create new recordset
|
||||
credentialsResp, err := r.client.CreateCredentials(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
if credentialsResp.Id == nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", "Got empty credentials id")
|
||||
return
|
||||
}
|
||||
credentialsId := *credentialsResp.Id
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
wr, err := logme.CreateCredentialsWaitHandler(ctx, r.client, projectId, instanceId, credentialsId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Instance creation waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*logme.CredentialsResponse)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "LogMe credentials created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *credentialsResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
credentialsId := model.CredentialsId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(recordSetResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "LogMe credentials read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *credentialsResource) Update(ctx context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Update shouldn't be called
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating credentials", "Credentials can't be updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *credentialsResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
credentialsId := model.CredentialsId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
// Delete existing record set
|
||||
err := r.client.DeleteCredentials(ctx, projectId, instanceId, credentialsId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
}
|
||||
_, err = logme.DeleteCredentialsWaitHandler(ctx, r.client, projectId, instanceId, credentialsId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credentials", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "LogMe credentials deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,instance_id,credentials_id
|
||||
func (r *credentialsResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing credentials",
|
||||
fmt.Sprintf("Expected import identifier with format [project_id],[instance_id],[credentials_id], got %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[1])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("credentials_id"), idParts[2])...)
|
||||
tflog.Info(ctx, "LogMe credentials state imported")
|
||||
}
|
||||
|
||||
func mapFields(credentialsResp *logme.CredentialsResponse, model *Model) error {
|
||||
if credentialsResp == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if credentialsResp.Raw == nil {
|
||||
return fmt.Errorf("response credentials raw is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
credentials := credentialsResp.Raw.Credentials
|
||||
|
||||
var credentialsId string
|
||||
if model.CredentialsId.ValueString() != "" {
|
||||
credentialsId = model.CredentialsId.ValueString()
|
||||
} else if credentialsResp.Id != nil {
|
||||
credentialsId = *credentialsResp.Id
|
||||
} else {
|
||||
return fmt.Errorf("credentials id not present")
|
||||
}
|
||||
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
model.InstanceId.ValueString(),
|
||||
credentialsId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.CredentialsId = types.StringValue(credentialsId)
|
||||
model.Hosts = types.ListNull(types.StringType)
|
||||
if credentials != nil {
|
||||
if credentials.Hosts != nil {
|
||||
var hosts []attr.Value
|
||||
for _, host := range *credentials.Hosts {
|
||||
hosts = append(hosts, types.StringValue(host))
|
||||
}
|
||||
hostsList, diags := types.ListValue(types.StringType, hosts)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map hosts: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Hosts = hostsList
|
||||
}
|
||||
model.Host = types.StringPointerValue(credentials.Host)
|
||||
model.HttpAPIURI = types.StringPointerValue(credentials.HttpApiUri)
|
||||
model.Name = types.StringPointerValue(credentials.Name)
|
||||
model.Password = types.StringPointerValue(credentials.Password)
|
||||
model.Port = conversion.ToTypeInt64(credentials.Port)
|
||||
model.Uri = types.StringPointerValue(credentials.Uri)
|
||||
model.Username = types.StringPointerValue(credentials.Username)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
156
stackit/internal/services/logme/credentials/resource_test.go
Normal file
156
stackit/internal/services/logme/credentials/resource_test.go
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
package logme
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/logme"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *logme.CredentialsResponse
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&logme.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
Raw: &logme.RawCredentials{},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,cid"),
|
||||
CredentialsId: types.StringValue("cid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Host: types.StringNull(),
|
||||
Hosts: types.ListNull(types.StringType),
|
||||
HttpAPIURI: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Password: types.StringNull(),
|
||||
Port: types.Int64Null(),
|
||||
Uri: types.StringNull(),
|
||||
Username: types.StringNull(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&logme.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
Raw: &logme.RawCredentials{
|
||||
Credentials: &logme.Credentials{
|
||||
Host: utils.Ptr("host"),
|
||||
Hosts: &[]string{
|
||||
"host_1",
|
||||
"",
|
||||
},
|
||||
HttpApiUri: utils.Ptr("http"),
|
||||
Name: utils.Ptr("name"),
|
||||
Password: utils.Ptr("password"),
|
||||
Port: utils.Ptr(int32(1234)),
|
||||
Uri: utils.Ptr("uri"),
|
||||
Username: utils.Ptr("username"),
|
||||
},
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,cid"),
|
||||
CredentialsId: types.StringValue("cid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Host: types.StringValue("host"),
|
||||
Hosts: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("host_1"),
|
||||
types.StringValue(""),
|
||||
}),
|
||||
HttpAPIURI: types.StringValue("http"),
|
||||
Name: types.StringValue("name"),
|
||||
Password: types.StringValue("password"),
|
||||
Port: types.Int64Value(1234),
|
||||
Uri: types.StringValue("uri"),
|
||||
Username: types.StringValue("username"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&logme.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
Raw: &logme.RawCredentials{
|
||||
Credentials: &logme.Credentials{
|
||||
Host: utils.Ptr(""),
|
||||
Hosts: &[]string{},
|
||||
HttpApiUri: nil,
|
||||
Name: nil,
|
||||
Password: utils.Ptr(""),
|
||||
Port: utils.Ptr(int32(2123456789)),
|
||||
Uri: nil,
|
||||
Username: utils.Ptr(""),
|
||||
},
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,cid"),
|
||||
CredentialsId: types.StringValue("cid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Host: types.StringValue(""),
|
||||
Hosts: types.ListValueMust(types.StringType, []attr.Value{}),
|
||||
HttpAPIURI: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Password: types.StringValue(""),
|
||||
Port: types.Int64Value(2123456789),
|
||||
Uri: types.StringNull(),
|
||||
Username: types.StringValue(""),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&logme.CredentialsResponse{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_raw_credentials",
|
||||
&logme.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
model := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
}
|
||||
err := mapFields(tt.input, model)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(model, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
192
stackit/internal/services/logme/instance/datasource.go
Normal file
192
stackit/internal/services/logme/instance/datasource.go
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
package logme
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/logme"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &instanceDataSource{}
|
||||
)
|
||||
|
||||
// NewInstanceDataSource is a helper function to simplify the provider implementation.
|
||||
func NewInstanceDataSource() datasource.DataSource {
|
||||
return &instanceDataSource{}
|
||||
}
|
||||
|
||||
// instanceDataSource is the data source implementation.
|
||||
type instanceDataSource struct {
|
||||
client *logme.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *instanceDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_logme_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *instanceDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *logme.APIClient
|
||||
var err error
|
||||
if providerData.LogMeCustomEndpoint != "" {
|
||||
apiClient, err = logme.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.LogMeCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = logme.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "LogMe zone client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "LogMe instance data source schema.",
|
||||
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`\".",
|
||||
"instance_id": "ID of the LogMe instance.",
|
||||
"project_id": "STACKIT Project ID to which the instance is associated.",
|
||||
"name": "Instance name.",
|
||||
"version": "The service version.",
|
||||
"plan_name": "The selected plan name.",
|
||||
"plan_id": "The selected plan ID.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Computed: true,
|
||||
},
|
||||
"version": schema.StringAttribute{
|
||||
Description: descriptions["version"],
|
||||
Computed: true,
|
||||
},
|
||||
"plan_name": schema.StringAttribute{
|
||||
Description: descriptions["plan_name"],
|
||||
Computed: true,
|
||||
},
|
||||
"plan_id": schema.StringAttribute{
|
||||
Description: descriptions["plan_id"],
|
||||
Computed: true,
|
||||
},
|
||||
"parameters": schema.SingleNestedAttribute{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"sgw_acl": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
Computed: true,
|
||||
},
|
||||
"cf_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"cf_space_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"dashboard_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"image_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"cf_organization_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *instanceDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
err = mapFields(instanceResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Compute and store values not present in the API response
|
||||
err = loadPlanNameAndVersion(ctx, r.client, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Loading service plan details: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "LogMe instance read")
|
||||
}
|
||||
680
stackit/internal/services/logme/instance/resource.go
Normal file
680
stackit/internal/services/logme/instance/resource.go
Normal file
|
|
@ -0,0 +1,680 @@
|
|||
package logme
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/logme"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &instanceResource{}
|
||||
_ resource.ResourceWithConfigure = &instanceResource{}
|
||||
_ resource.ResourceWithImportState = &instanceResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
CfGuid types.String `tfsdk:"cf_guid"`
|
||||
CfSpaceGuid types.String `tfsdk:"cf_space_guid"`
|
||||
DashboardUrl types.String `tfsdk:"dashboard_url"`
|
||||
ImageUrl types.String `tfsdk:"image_url"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
CfOrganizationGuid types.String `tfsdk:"cf_organization_guid"`
|
||||
Parameters types.Object `tfsdk:"parameters"`
|
||||
Version types.String `tfsdk:"version"`
|
||||
PlanName types.String `tfsdk:"plan_name"`
|
||||
PlanId types.String `tfsdk:"plan_id"`
|
||||
}
|
||||
|
||||
// Struct corresponding to DataSourceModel.Parameters
|
||||
type parametersModel struct {
|
||||
SgwAcl types.String `tfsdk:"sgw_acl"`
|
||||
}
|
||||
|
||||
// Types corresponding to parametersModel
|
||||
var parametersTypes = map[string]attr.Type{
|
||||
"sgw_acl": basetypes.StringType{},
|
||||
}
|
||||
|
||||
// NewInstanceResource is a helper function to simplify the provider implementation.
|
||||
func NewInstanceResource() resource.Resource {
|
||||
return &instanceResource{}
|
||||
}
|
||||
|
||||
// instanceResource is the resource implementation.
|
||||
type instanceResource struct {
|
||||
client *logme.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *instanceResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_logme_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *instanceResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *logme.APIClient
|
||||
var err error
|
||||
if providerData.LogMeCustomEndpoint != "" {
|
||||
apiClient, err = logme.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.LogMeCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = logme.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "LogMe instance client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *instanceResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "LogMe instance resource schema.",
|
||||
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`\".",
|
||||
"instance_id": "ID of the LogMe instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"name": "Instance name.",
|
||||
"version": "The service version.",
|
||||
"plan_name": "The selected plan name.",
|
||||
"plan_id": "The selected plan ID.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
},
|
||||
},
|
||||
"version": schema.StringAttribute{
|
||||
Description: descriptions["version"],
|
||||
Required: true,
|
||||
},
|
||||
"plan_name": schema.StringAttribute{
|
||||
Description: descriptions["plan_name"],
|
||||
Required: true,
|
||||
},
|
||||
"plan_id": schema.StringAttribute{
|
||||
Description: descriptions["plan_id"],
|
||||
Computed: true,
|
||||
},
|
||||
"parameters": schema.SingleNestedAttribute{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"sgw_acl": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
},
|
||||
"cf_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"cf_space_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"dashboard_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"image_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"cf_organization_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *instanceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
|
||||
var parameters = ¶metersModel{}
|
||||
if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) {
|
||||
diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err := r.loadPlanId(ctx, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Loading service plan: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model, parameters)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Create new instance
|
||||
createResp, err := r.client.CreateInstance(ctx, projectId).CreateInstancePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
instanceId := *createResp.InstanceId
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
wr, err := logme.CreateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Instance creation waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*logme.Instance)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "LogMe instance created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(instanceResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Compute and store values not present in the API response
|
||||
err = loadPlanNameAndVersion(ctx, r.client, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Loading service plan details: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "LogMe instance read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *instanceResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
var parameters = ¶metersModel{}
|
||||
if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) {
|
||||
diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err := r.loadPlanId(ctx, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Loading service plan: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toUpdatePayload(&model, parameters)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Update existing instance
|
||||
err = r.client.UpdateInstance(ctx, projectId, instanceId).UpdateInstancePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
wr, err := logme.UpdateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Instance update waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*logme.Instance)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "LogMe instance updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *instanceResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from state
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
// Delete existing instance
|
||||
err := r.client.DeleteInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
_, err = logme.DeleteInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "LogMe instance deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,instance_id
|
||||
func (r *instanceResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
|
||||
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing instance",
|
||||
fmt.Sprintf("Expected import identifier with format: [project_id],[instance_id] Got: %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[1])...)
|
||||
tflog.Info(ctx, "LogMe instance state imported")
|
||||
}
|
||||
|
||||
func mapFields(instance *logme.Instance, model *Model) error {
|
||||
if instance == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
|
||||
var instanceId string
|
||||
if model.InstanceId.ValueString() != "" {
|
||||
instanceId = model.InstanceId.ValueString()
|
||||
} else if instance.InstanceId != nil {
|
||||
instanceId = *instance.InstanceId
|
||||
} else {
|
||||
return fmt.Errorf("instance id not present")
|
||||
}
|
||||
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
instanceId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.InstanceId = types.StringValue(instanceId)
|
||||
model.PlanId = types.StringPointerValue(instance.PlanId)
|
||||
model.CfGuid = types.StringPointerValue(instance.CfGuid)
|
||||
model.CfSpaceGuid = types.StringPointerValue(instance.CfSpaceGuid)
|
||||
model.DashboardUrl = types.StringPointerValue(instance.DashboardUrl)
|
||||
model.ImageUrl = types.StringPointerValue(instance.ImageUrl)
|
||||
model.Name = types.StringPointerValue(instance.Name)
|
||||
model.CfOrganizationGuid = types.StringPointerValue(instance.CfOrganizationGuid)
|
||||
|
||||
if instance.Parameters == nil {
|
||||
model.Parameters = types.ObjectNull(parametersTypes)
|
||||
} else {
|
||||
parameters, err := mapParameters(*instance.Parameters)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mapping parameters: %w", err)
|
||||
}
|
||||
model.Parameters = parameters
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func mapParameters(params map[string]interface{}) (types.Object, error) {
|
||||
attributes := map[string]attr.Value{}
|
||||
for attribute := range parametersTypes {
|
||||
valueInterface, ok := params[attribute]
|
||||
if !ok {
|
||||
// All fields are optional, so this is ok
|
||||
// Set the value as nil, will be handled accordingly
|
||||
valueInterface = nil
|
||||
}
|
||||
|
||||
var value attr.Value
|
||||
switch parametersTypes[attribute].(type) {
|
||||
default:
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found unexpected attribute type '%T'", parametersTypes[attribute])
|
||||
case basetypes.StringType:
|
||||
if valueInterface == nil {
|
||||
value = types.StringNull()
|
||||
} else {
|
||||
valueString, ok := valueInterface.(string)
|
||||
if !ok {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as string", attribute, valueInterface)
|
||||
}
|
||||
value = types.StringValue(valueString)
|
||||
}
|
||||
case basetypes.BoolType:
|
||||
if valueInterface == nil {
|
||||
value = types.BoolNull()
|
||||
} else {
|
||||
valueBool, ok := valueInterface.(bool)
|
||||
if !ok {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as bool", attribute, valueInterface)
|
||||
}
|
||||
value = types.BoolValue(valueBool)
|
||||
}
|
||||
case basetypes.Int64Type:
|
||||
if valueInterface == nil {
|
||||
value = types.Int64Null()
|
||||
} else {
|
||||
// This may be int64, int32, int or float64
|
||||
// We try to assert all 4
|
||||
var valueInt64 int64
|
||||
switch temp := valueInterface.(type) {
|
||||
default:
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as int", attribute, valueInterface)
|
||||
case int64:
|
||||
valueInt64 = temp
|
||||
case int32:
|
||||
valueInt64 = int64(temp)
|
||||
case int:
|
||||
valueInt64 = int64(temp)
|
||||
case float64:
|
||||
valueInt64 = int64(temp)
|
||||
}
|
||||
value = types.Int64Value(valueInt64)
|
||||
}
|
||||
case basetypes.ListType: // Assumed to be a list of strings
|
||||
if valueInterface == nil {
|
||||
value = types.ListNull(types.StringType)
|
||||
} else {
|
||||
// This may be []string{} or []interface{}
|
||||
// We try to assert all 2
|
||||
var valueList []attr.Value
|
||||
switch temp := valueInterface.(type) {
|
||||
default:
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as array of interface", attribute, valueInterface)
|
||||
case []string:
|
||||
for _, x := range temp {
|
||||
valueList = append(valueList, types.StringValue(x))
|
||||
}
|
||||
case []interface{}:
|
||||
for _, x := range temp {
|
||||
xString, ok := x.(string)
|
||||
if !ok {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' with element '%s' of type %T, failed to assert as string", attribute, x, x)
|
||||
}
|
||||
valueList = append(valueList, types.StringValue(xString))
|
||||
}
|
||||
}
|
||||
temp2, diags := types.ListValue(types.StringType, valueList)
|
||||
if diags.HasError() {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("failed to map %s: %w", attribute, core.DiagsToError(diags))
|
||||
}
|
||||
value = temp2
|
||||
}
|
||||
}
|
||||
attributes[attribute] = value
|
||||
}
|
||||
|
||||
output, diags := types.ObjectValue(parametersTypes, attributes)
|
||||
if diags.HasError() {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("failed to create object: %w", core.DiagsToError(diags))
|
||||
}
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model, parameters *parametersModel) (*logme.CreateInstancePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
if parameters == nil {
|
||||
return &logme.CreateInstancePayload{
|
||||
InstanceName: model.Name.ValueStringPointer(),
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
payloadParams := &logme.InstanceParameters{}
|
||||
if parameters.SgwAcl.ValueString() != "" {
|
||||
payloadParams.SgwAcl = parameters.SgwAcl.ValueStringPointer()
|
||||
}
|
||||
return &logme.CreateInstancePayload{
|
||||
InstanceName: model.Name.ValueStringPointer(),
|
||||
Parameters: payloadParams,
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toUpdatePayload(model *Model, parameters *parametersModel) (*logme.UpdateInstancePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
if parameters == nil {
|
||||
return &logme.UpdateInstancePayload{
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
return &logme.UpdateInstancePayload{
|
||||
Parameters: &logme.InstanceParameters{
|
||||
SgwAcl: parameters.SgwAcl.ValueStringPointer(),
|
||||
},
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *instanceResource) loadPlanId(ctx context.Context, model *Model) error {
|
||||
projectId := model.ProjectId.ValueString()
|
||||
res, err := r.client.GetOfferings(ctx, projectId).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting LogMe offerings: %w", err)
|
||||
}
|
||||
|
||||
version := model.Version.ValueString()
|
||||
planName := model.PlanName.ValueString()
|
||||
availableVersions := ""
|
||||
availablePlanNames := ""
|
||||
isValidVersion := false
|
||||
for _, offer := range *res.Offerings {
|
||||
if !strings.EqualFold(*offer.Version, version) {
|
||||
availableVersions = fmt.Sprintf("%s\n- %s", availableVersions, *offer.Version)
|
||||
continue
|
||||
}
|
||||
isValidVersion = true
|
||||
|
||||
for _, plan := range *offer.Plans {
|
||||
if plan.Name == nil {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(*plan.Name, planName) && plan.Id != nil {
|
||||
model.PlanId = types.StringPointerValue(plan.Id)
|
||||
return nil
|
||||
}
|
||||
availablePlanNames = fmt.Sprintf("%s\n- %s", availablePlanNames, *plan.Name)
|
||||
}
|
||||
}
|
||||
|
||||
if !isValidVersion {
|
||||
return fmt.Errorf("couldn't find version '%s', available versions are: %s", version, availableVersions)
|
||||
}
|
||||
return fmt.Errorf("couldn't find plan_name '%s' for version %s, available names are: %s", planName, version, availablePlanNames)
|
||||
}
|
||||
|
||||
func loadPlanNameAndVersion(ctx context.Context, client *logme.APIClient, model *Model) error {
|
||||
projectId := model.ProjectId.ValueString()
|
||||
planId := model.PlanId.ValueString()
|
||||
res, err := client.GetOfferings(ctx, projectId).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting LogMe offerings: %w", err)
|
||||
}
|
||||
|
||||
for _, offer := range *res.Offerings {
|
||||
for _, plan := range *offer.Plans {
|
||||
if strings.EqualFold(*plan.Id, planId) && plan.Id != nil {
|
||||
model.PlanName = types.StringPointerValue(plan.Name)
|
||||
model.Version = types.StringPointerValue(offer.Version)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("couldn't find plan_name and version for plan_id '%s'", planId)
|
||||
}
|
||||
304
stackit/internal/services/logme/instance/resource_test.go
Normal file
304
stackit/internal/services/logme/instance/resource_test.go
Normal file
|
|
@ -0,0 +1,304 @@
|
|||
package logme
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/logme"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *logme.Instance
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&logme.Instance{},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
PlanId: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
CfGuid: types.StringNull(),
|
||||
CfSpaceGuid: types.StringNull(),
|
||||
DashboardUrl: types.StringNull(),
|
||||
ImageUrl: types.StringNull(),
|
||||
CfOrganizationGuid: types.StringNull(),
|
||||
Parameters: types.ObjectNull(parametersTypes),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&logme.Instance{
|
||||
PlanId: utils.Ptr("plan"),
|
||||
CfGuid: utils.Ptr("cf"),
|
||||
CfSpaceGuid: utils.Ptr("space"),
|
||||
DashboardUrl: utils.Ptr("dashboard"),
|
||||
ImageUrl: utils.Ptr("image"),
|
||||
InstanceId: utils.Ptr("iid"),
|
||||
Name: utils.Ptr("name"),
|
||||
CfOrganizationGuid: utils.Ptr("org"),
|
||||
Parameters: &map[string]interface{}{
|
||||
"sgw_acl": "acl",
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
PlanId: types.StringValue("plan"),
|
||||
Name: types.StringValue("name"),
|
||||
CfGuid: types.StringValue("cf"),
|
||||
CfSpaceGuid: types.StringValue("space"),
|
||||
DashboardUrl: types.StringValue("dashboard"),
|
||||
ImageUrl: types.StringValue("image"),
|
||||
CfOrganizationGuid: types.StringValue("org"),
|
||||
Parameters: types.ObjectValueMust(parametersTypes, map[string]attr.Value{
|
||||
"sgw_acl": types.StringValue("acl"),
|
||||
}),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&logme.Instance{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"wrong_param_types_1",
|
||||
&logme.Instance{
|
||||
Parameters: &map[string]interface{}{
|
||||
"sgw_acl": true,
|
||||
},
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"wrong_param_types_2",
|
||||
&logme.Instance{
|
||||
Parameters: &map[string]interface{}{
|
||||
"sgw_acl": 1,
|
||||
},
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
state := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
}
|
||||
err := mapFields(tt.input, state)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputParameters *parametersModel
|
||||
expected *logme.CreateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
¶metersModel{},
|
||||
&logme.CreateInstancePayload{
|
||||
Parameters: &logme.InstanceParameters{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
Name: types.StringValue("name"),
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
¶metersModel{
|
||||
SgwAcl: types.StringValue("sgw"),
|
||||
},
|
||||
&logme.CreateInstancePayload{
|
||||
InstanceName: utils.Ptr("name"),
|
||||
Parameters: &logme.InstanceParameters{
|
||||
SgwAcl: utils.Ptr("sgw"),
|
||||
},
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
Name: types.StringValue(""),
|
||||
PlanId: types.StringValue(""),
|
||||
},
|
||||
¶metersModel{
|
||||
SgwAcl: types.StringNull(),
|
||||
},
|
||||
&logme.CreateInstancePayload{
|
||||
InstanceName: utils.Ptr(""),
|
||||
Parameters: &logme.InstanceParameters{
|
||||
SgwAcl: nil,
|
||||
},
|
||||
PlanId: utils.Ptr(""),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
¶metersModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_parameters",
|
||||
&Model{
|
||||
Name: types.StringValue("name"),
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
nil,
|
||||
&logme.CreateInstancePayload{
|
||||
InstanceName: utils.Ptr("name"),
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toCreatePayload(tt.input, tt.inputParameters)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToUpdatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputParameters *parametersModel
|
||||
expected *logme.UpdateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
¶metersModel{},
|
||||
&logme.UpdateInstancePayload{
|
||||
Parameters: &logme.InstanceParameters{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
¶metersModel{
|
||||
SgwAcl: types.StringValue("sgw"),
|
||||
},
|
||||
&logme.UpdateInstancePayload{
|
||||
Parameters: &logme.InstanceParameters{
|
||||
SgwAcl: utils.Ptr("sgw"),
|
||||
},
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
PlanId: types.StringValue(""),
|
||||
},
|
||||
¶metersModel{
|
||||
SgwAcl: types.StringNull(),
|
||||
},
|
||||
&logme.UpdateInstancePayload{
|
||||
Parameters: &logme.InstanceParameters{
|
||||
SgwAcl: nil,
|
||||
},
|
||||
PlanId: utils.Ptr(""),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
¶metersModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_parameters",
|
||||
&Model{
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
nil,
|
||||
&logme.UpdateInstancePayload{
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toUpdatePayload(tt.input, tt.inputParameters)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
245
stackit/internal/services/logme/logme_acc_test.go
Normal file
245
stackit/internal/services/logme/logme_acc_test.go
Normal file
|
|
@ -0,0 +1,245 @@
|
|||
package logme_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
|
||||
"github.com/hashicorp/terraform-plugin-testing/terraform"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/logme"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/testutil"
|
||||
)
|
||||
|
||||
// Instance resource data
|
||||
var instanceResource = map[string]string{
|
||||
"project_id": testutil.ProjectId,
|
||||
"name": testutil.ResourceNameWithDateTime("logme"),
|
||||
"plan_id": "201d743c-0f06-4af2-8f20-649baf4819ae",
|
||||
"plan_name": "stackit-qa-logme2-1.2.50-replica",
|
||||
"version": "2",
|
||||
"sgw_acl-1": "192.168.0.0/16",
|
||||
"sgw_acl-2": "192.168.0.0/24",
|
||||
}
|
||||
|
||||
func resourceConfig(acls string) string {
|
||||
return fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
resource "stackit_logme_instance" "instance" {
|
||||
project_id = "%s"
|
||||
name = "%s"
|
||||
plan_name = "%s"
|
||||
version = "%s"
|
||||
parameters = {
|
||||
sgw_acl = "%s"
|
||||
}
|
||||
}
|
||||
|
||||
resource "stackit_logme_credentials" "credentials" {
|
||||
project_id = stackit_logme_instance.instance.project_id
|
||||
instance_id = stackit_logme_instance.instance.instance_id
|
||||
}
|
||||
`,
|
||||
testutil.LogMeProviderConfig(),
|
||||
instanceResource["project_id"],
|
||||
instanceResource["name"],
|
||||
instanceResource["plan_name"],
|
||||
instanceResource["version"],
|
||||
acls,
|
||||
)
|
||||
}
|
||||
func TestAccLogMeResource(t *testing.T) {
|
||||
resource.Test(t, resource.TestCase{
|
||||
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
|
||||
CheckDestroy: testAccCheckLogMeDestroy,
|
||||
Steps: []resource.TestStep{
|
||||
|
||||
// Creation
|
||||
{
|
||||
Config: resourceConfig(instanceResource["sgw_acl-1"]),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("stackit_logme_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_logme_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_logme_instance.instance", "plan_id", instanceResource["plan_id"]),
|
||||
resource.TestCheckResourceAttr("stackit_logme_instance.instance", "plan_name", instanceResource["plan_name"]),
|
||||
resource.TestCheckResourceAttr("stackit_logme_instance.instance", "version", instanceResource["version"]),
|
||||
resource.TestCheckResourceAttr("stackit_logme_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_logme_instance.instance", "parameters.sgw_acl", instanceResource["sgw_acl-1"]),
|
||||
|
||||
// Credentials data
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_logme_credentials.credentials", "project_id",
|
||||
"stackit_logme_instance.instance", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_logme_credentials.credentials", "instance_id",
|
||||
"stackit_logme_instance.instance", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrSet("stackit_logme_credentials.credentials", "credentials_id"),
|
||||
resource.TestCheckResourceAttrSet("stackit_logme_credentials.credentials", "host"),
|
||||
),
|
||||
},
|
||||
// Data source
|
||||
{
|
||||
Config: fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
data "stackit_logme_instance" "instance" {
|
||||
project_id = stackit_logme_instance.instance.project_id
|
||||
instance_id = stackit_logme_instance.instance.instance_id
|
||||
}
|
||||
|
||||
data "stackit_logme_credentials" "credentials" {
|
||||
project_id = stackit_logme_credentials.credentials.project_id
|
||||
instance_id = stackit_logme_credentials.credentials.instance_id
|
||||
credentials_id = stackit_logme_credentials.credentials.credentials_id
|
||||
}`,
|
||||
resourceConfig(instanceResource["sgw_acl-1"]),
|
||||
),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("data.stackit_logme_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
|
||||
resource.TestCheckResourceAttrPair("stackit_logme_instance.instance", "instance_id",
|
||||
"data.stackit_logme_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttrPair("stackit_logme_credentials.credentials", "credentials_id",
|
||||
"data.stackit_logme_credentials.credentials", "credentials_id"),
|
||||
resource.TestCheckResourceAttr("data.stackit_logme_instance.instance", "plan_id", instanceResource["plan_id"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_logme_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_logme_instance.instance", "parameters.sgw_acl", instanceResource["sgw_acl-1"]),
|
||||
|
||||
// Credentials data
|
||||
resource.TestCheckResourceAttr("data.stackit_logme_credentials.credentials", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_logme_credentials.credentials", "credentials_id"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_logme_credentials.credentials", "host"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_logme_credentials.credentials", "port"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_logme_credentials.credentials", "uri"),
|
||||
),
|
||||
},
|
||||
// Import
|
||||
{
|
||||
ResourceName: "stackit_logme_instance.instance",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_logme_instance.instance"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_logme_instance.instance")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
return fmt.Sprintf("%s,%s", testutil.ProjectId, instanceId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
{
|
||||
ResourceName: "stackit_logme_credentials.credentials",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_logme_credentials.credentials"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_logme_credentials.credentials")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
credentialsId, ok := r.Primary.Attributes["credentials_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute credentials_id")
|
||||
}
|
||||
return fmt.Sprintf("%s,%s,%s", testutil.ProjectId, instanceId, credentialsId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
// Update
|
||||
{
|
||||
Config: resourceConfig(instanceResource["sgw_acl-2"]),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("stackit_logme_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_logme_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_logme_instance.instance", "plan_id", instanceResource["plan_id"]),
|
||||
resource.TestCheckResourceAttr("stackit_logme_instance.instance", "plan_name", instanceResource["plan_name"]),
|
||||
resource.TestCheckResourceAttr("stackit_logme_instance.instance", "version", instanceResource["version"]),
|
||||
resource.TestCheckResourceAttr("stackit_logme_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_logme_instance.instance", "parameters.sgw_acl", instanceResource["sgw_acl-2"]),
|
||||
),
|
||||
},
|
||||
// Deletion is done by the framework implicitly
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func testAccCheckLogMeDestroy(s *terraform.State) error {
|
||||
ctx := context.Background()
|
||||
var client *logme.APIClient
|
||||
var err error
|
||||
if testutil.LogMeCustomEndpoint == "" {
|
||||
client, err = logme.NewAPIClient()
|
||||
} else {
|
||||
client, err = logme.NewAPIClient(
|
||||
config.WithEndpoint(testutil.LogMeCustomEndpoint),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating client: %w", err)
|
||||
}
|
||||
|
||||
instancesToDestroy := []string{}
|
||||
for _, rs := range s.RootModule().Resources {
|
||||
if rs.Type != "stackit_logme_instance" {
|
||||
continue
|
||||
}
|
||||
// instance terraform ID: "[project_id],[instance_id]"
|
||||
instanceId := strings.Split(rs.Primary.ID, core.Separator)[1]
|
||||
instancesToDestroy = append(instancesToDestroy, instanceId)
|
||||
}
|
||||
|
||||
instancesResp, err := client.GetInstances(ctx, testutil.ProjectId).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting instancesResp: %w", err)
|
||||
}
|
||||
|
||||
instances := *instancesResp.Instances
|
||||
for i := range instances {
|
||||
if instances[i].InstanceId == nil {
|
||||
continue
|
||||
}
|
||||
if utils.Contains(instancesToDestroy, *instances[i].InstanceId) {
|
||||
if !checkInstanceDeleteSuccess(&instances[i]) {
|
||||
err := client.DeleteInstanceExecute(ctx, testutil.ProjectId, *instances[i].InstanceId)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying instance %s during CheckDestroy: %w", *instances[i].InstanceId, err)
|
||||
}
|
||||
_, err = logme.DeleteInstanceWaitHandler(ctx, client, testutil.ProjectId, *instances[i].InstanceId).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying instance %s during CheckDestroy: waiting for deletion %w", *instances[i].InstanceId, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkInstanceDeleteSuccess(i *logme.Instance) bool {
|
||||
if *i.LastOperation.Type != logme.InstanceTypeDelete {
|
||||
return false
|
||||
}
|
||||
|
||||
if *i.LastOperation.Type == logme.InstanceTypeDelete {
|
||||
if *i.LastOperation.State != logme.InstanceStateSuccess {
|
||||
return false
|
||||
} else if strings.Contains(*i.LastOperation.Description, "DeleteFailed") || strings.Contains(*i.LastOperation.Description, "failed") {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
181
stackit/internal/services/mariadb/credentials/datasource.go
Normal file
181
stackit/internal/services/mariadb/credentials/datasource.go
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
package mariadb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/mariadb"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &credentialsDataSource{}
|
||||
)
|
||||
|
||||
// NewCredentialsDataSource is a helper function to simplify the provider implementation.
|
||||
func NewCredentialsDataSource() datasource.DataSource {
|
||||
return &credentialsDataSource{}
|
||||
}
|
||||
|
||||
// credentialsDataSource is the data source implementation.
|
||||
type credentialsDataSource struct {
|
||||
client *mariadb.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *credentialsDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_mariadb_credentials"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *credentialsDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *mariadb.APIClient
|
||||
var err error
|
||||
if providerData.MariaDBCustomEndpoint != "" {
|
||||
apiClient, err = mariadb.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.MariaDBCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = mariadb.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "mariadb credentials client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *credentialsDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "MariaDB credentials data source schema.",
|
||||
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`,`credentials_id`\".",
|
||||
"credentials_id": "The credentials ID.",
|
||||
"instance_id": "ID of the MariaDB instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"credentials_id": schema.StringAttribute{
|
||||
Description: descriptions["credentials_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"hosts": schema.ListAttribute{
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"http_api_uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"password": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *credentialsDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
credentialsId := model.CredentialsId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(recordSetResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "mariadb credentials read")
|
||||
}
|
||||
377
stackit/internal/services/mariadb/credentials/resource.go
Normal file
377
stackit/internal/services/mariadb/credentials/resource.go
Normal file
|
|
@ -0,0 +1,377 @@
|
|||
package mariadb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/mariadb"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &credentialsResource{}
|
||||
_ resource.ResourceWithConfigure = &credentialsResource{}
|
||||
_ resource.ResourceWithImportState = &credentialsResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
CredentialsId types.String `tfsdk:"credentials_id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Host types.String `tfsdk:"host"`
|
||||
Hosts types.List `tfsdk:"hosts"`
|
||||
HttpAPIURI types.String `tfsdk:"http_api_uri"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Password types.String `tfsdk:"password"`
|
||||
Port types.Int64 `tfsdk:"port"`
|
||||
Uri types.String `tfsdk:"uri"`
|
||||
Username types.String `tfsdk:"username"`
|
||||
}
|
||||
|
||||
// NewCredentialsResource is a helper function to simplify the provider implementation.
|
||||
func NewCredentialsResource() resource.Resource {
|
||||
return &credentialsResource{}
|
||||
}
|
||||
|
||||
// credentialsResource is the resource implementation.
|
||||
type credentialsResource struct {
|
||||
client *mariadb.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *credentialsResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_mariadb_credentials"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *credentialsResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *mariadb.APIClient
|
||||
var err error
|
||||
if providerData.MariaDBCustomEndpoint != "" {
|
||||
apiClient, err = mariadb.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.MariaDBCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = mariadb.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "MariaDB credentials client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *credentialsResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "MariaDB credentials resource schema.",
|
||||
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`,`credentials_id`\".",
|
||||
"credentials_id": "The credentials ID.",
|
||||
"instance_id": "ID of the MariaDB instance.",
|
||||
"project_id": "STACKIT Project ID to which the instance is associated.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"credentials_id": schema.StringAttribute{
|
||||
Description: descriptions["credentials_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"hosts": schema.ListAttribute{
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"http_api_uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"password": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *credentialsResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
// Create new recordset
|
||||
credentialsResp, err := r.client.CreateCredentials(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
if credentialsResp.Id == nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", "Got empty credentials id")
|
||||
return
|
||||
}
|
||||
credentialsId := *credentialsResp.Id
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
wr, err := mariadb.CreateCredentialsWaitHandler(ctx, r.client, projectId, instanceId, credentialsId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Instance creation waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*mariadb.CredentialsResponse)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "MariaDB credentials created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *credentialsResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
credentialsId := model.CredentialsId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(recordSetResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "MariaDB credentials read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *credentialsResource) Update(ctx context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Update shouldn't be called
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating credentials", "Credentials can't be updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *credentialsResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
credentialsId := model.CredentialsId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
// Delete existing record set
|
||||
err := r.client.DeleteCredentials(ctx, projectId, instanceId, credentialsId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
}
|
||||
_, err = mariadb.DeleteCredentialsWaitHandler(ctx, r.client, projectId, instanceId, credentialsId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credentials", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "MariaDB credentials deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,instance_id,credentials_id
|
||||
func (r *credentialsResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing credentials",
|
||||
fmt.Sprintf("Expected import identifier with format [project_id],[instance_id],[credentials_id], got %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[1])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("credentials_id"), idParts[2])...)
|
||||
tflog.Info(ctx, "MariaDB credentials state imported")
|
||||
}
|
||||
|
||||
func mapFields(credentialsResp *mariadb.CredentialsResponse, model *Model) error {
|
||||
if credentialsResp == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if credentialsResp.Raw == nil {
|
||||
return fmt.Errorf("response credentials raw is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
credentials := credentialsResp.Raw.Credentials
|
||||
|
||||
var credentialsId string
|
||||
if model.CredentialsId.ValueString() != "" {
|
||||
credentialsId = model.CredentialsId.ValueString()
|
||||
} else if credentialsResp.Id != nil {
|
||||
credentialsId = *credentialsResp.Id
|
||||
} else {
|
||||
return fmt.Errorf("credentials id not present")
|
||||
}
|
||||
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
model.InstanceId.ValueString(),
|
||||
credentialsId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.CredentialsId = types.StringValue(credentialsId)
|
||||
model.Hosts = types.ListNull(types.StringType)
|
||||
if credentials != nil {
|
||||
if credentials.Hosts != nil {
|
||||
var hosts []attr.Value
|
||||
for _, host := range *credentials.Hosts {
|
||||
hosts = append(hosts, types.StringValue(host))
|
||||
}
|
||||
hostsList, diags := types.ListValue(types.StringType, hosts)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map hosts: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Hosts = hostsList
|
||||
}
|
||||
model.Host = types.StringPointerValue(credentials.Host)
|
||||
model.HttpAPIURI = types.StringPointerValue(credentials.HttpApiUri)
|
||||
model.Name = types.StringPointerValue(credentials.Name)
|
||||
model.Password = types.StringPointerValue(credentials.Password)
|
||||
model.Port = conversion.ToTypeInt64(credentials.Port)
|
||||
model.Uri = types.StringPointerValue(credentials.Uri)
|
||||
model.Username = types.StringPointerValue(credentials.Username)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
156
stackit/internal/services/mariadb/credentials/resource_test.go
Normal file
156
stackit/internal/services/mariadb/credentials/resource_test.go
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
package mariadb
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/mariadb"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *mariadb.CredentialsResponse
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&mariadb.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
Raw: &mariadb.RawCredentials{},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,cid"),
|
||||
CredentialsId: types.StringValue("cid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Host: types.StringNull(),
|
||||
Hosts: types.ListNull(types.StringType),
|
||||
HttpAPIURI: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Password: types.StringNull(),
|
||||
Port: types.Int64Null(),
|
||||
Uri: types.StringNull(),
|
||||
Username: types.StringNull(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&mariadb.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
Raw: &mariadb.RawCredentials{
|
||||
Credentials: &mariadb.Credentials{
|
||||
Host: utils.Ptr("host"),
|
||||
Hosts: &[]string{
|
||||
"host_1",
|
||||
"",
|
||||
},
|
||||
HttpApiUri: utils.Ptr("http"),
|
||||
Name: utils.Ptr("name"),
|
||||
Password: utils.Ptr("password"),
|
||||
Port: utils.Ptr(int32(1234)),
|
||||
Uri: utils.Ptr("uri"),
|
||||
Username: utils.Ptr("username"),
|
||||
},
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,cid"),
|
||||
CredentialsId: types.StringValue("cid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Host: types.StringValue("host"),
|
||||
Hosts: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("host_1"),
|
||||
types.StringValue(""),
|
||||
}),
|
||||
HttpAPIURI: types.StringValue("http"),
|
||||
Name: types.StringValue("name"),
|
||||
Password: types.StringValue("password"),
|
||||
Port: types.Int64Value(1234),
|
||||
Uri: types.StringValue("uri"),
|
||||
Username: types.StringValue("username"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&mariadb.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
Raw: &mariadb.RawCredentials{
|
||||
Credentials: &mariadb.Credentials{
|
||||
Host: utils.Ptr(""),
|
||||
Hosts: &[]string{},
|
||||
HttpApiUri: nil,
|
||||
Name: nil,
|
||||
Password: utils.Ptr(""),
|
||||
Port: utils.Ptr(int32(2123456789)),
|
||||
Uri: nil,
|
||||
Username: utils.Ptr(""),
|
||||
},
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,cid"),
|
||||
CredentialsId: types.StringValue("cid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Host: types.StringValue(""),
|
||||
Hosts: types.ListValueMust(types.StringType, []attr.Value{}),
|
||||
HttpAPIURI: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Password: types.StringValue(""),
|
||||
Port: types.Int64Value(2123456789),
|
||||
Uri: types.StringNull(),
|
||||
Username: types.StringValue(""),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&mariadb.CredentialsResponse{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_raw_credentials",
|
||||
&mariadb.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
model := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
}
|
||||
err := mapFields(tt.input, model)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(model, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
192
stackit/internal/services/mariadb/instance/datasource.go
Normal file
192
stackit/internal/services/mariadb/instance/datasource.go
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
package mariadb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/mariadb"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &instanceDataSource{}
|
||||
)
|
||||
|
||||
// NewInstanceDataSource is a helper function to simplify the provider implementation.
|
||||
func NewInstanceDataSource() datasource.DataSource {
|
||||
return &instanceDataSource{}
|
||||
}
|
||||
|
||||
// instanceDataSource is the data source implementation.
|
||||
type instanceDataSource struct {
|
||||
client *mariadb.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *instanceDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_mariadb_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *instanceDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *mariadb.APIClient
|
||||
var err error
|
||||
if providerData.MariaDBCustomEndpoint != "" {
|
||||
apiClient, err = mariadb.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.MariaDBCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = mariadb.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "MariaDB zone client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "MariaDB instance data source schema.",
|
||||
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`\".",
|
||||
"instance_id": "ID of the MariaDB instance.",
|
||||
"project_id": "STACKIT Project ID to which the instance is associated.",
|
||||
"name": "Instance name.",
|
||||
"version": "The service version.",
|
||||
"plan_name": "The selected plan name.",
|
||||
"plan_id": "The selected plan ID.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Computed: true,
|
||||
},
|
||||
"version": schema.StringAttribute{
|
||||
Description: descriptions["version"],
|
||||
Computed: true,
|
||||
},
|
||||
"plan_name": schema.StringAttribute{
|
||||
Description: descriptions["plan_name"],
|
||||
Computed: true,
|
||||
},
|
||||
"plan_id": schema.StringAttribute{
|
||||
Description: descriptions["plan_id"],
|
||||
Computed: true,
|
||||
},
|
||||
"parameters": schema.SingleNestedAttribute{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"sgw_acl": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
Computed: true,
|
||||
},
|
||||
"cf_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"cf_space_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"dashboard_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"image_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"cf_organization_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *instanceDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
err = mapFields(instanceResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Compute and store values not present in the API response
|
||||
err = loadPlanNameAndVersion(ctx, r.client, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Loading service plan details: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "MariaDB instance read")
|
||||
}
|
||||
680
stackit/internal/services/mariadb/instance/resource.go
Normal file
680
stackit/internal/services/mariadb/instance/resource.go
Normal file
|
|
@ -0,0 +1,680 @@
|
|||
package mariadb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/mariadb"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &instanceResource{}
|
||||
_ resource.ResourceWithConfigure = &instanceResource{}
|
||||
_ resource.ResourceWithImportState = &instanceResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
CfGuid types.String `tfsdk:"cf_guid"`
|
||||
CfSpaceGuid types.String `tfsdk:"cf_space_guid"`
|
||||
DashboardUrl types.String `tfsdk:"dashboard_url"`
|
||||
ImageUrl types.String `tfsdk:"image_url"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
CfOrganizationGuid types.String `tfsdk:"cf_organization_guid"`
|
||||
Parameters types.Object `tfsdk:"parameters"`
|
||||
Version types.String `tfsdk:"version"`
|
||||
PlanName types.String `tfsdk:"plan_name"`
|
||||
PlanId types.String `tfsdk:"plan_id"`
|
||||
}
|
||||
|
||||
// Struct corresponding to DataSourceModel.Parameters
|
||||
type parametersModel struct {
|
||||
SgwAcl types.String `tfsdk:"sgw_acl"`
|
||||
}
|
||||
|
||||
// Types corresponding to parametersModel
|
||||
var parametersTypes = map[string]attr.Type{
|
||||
"sgw_acl": basetypes.StringType{},
|
||||
}
|
||||
|
||||
// NewInstanceResource is a helper function to simplify the provider implementation.
|
||||
func NewInstanceResource() resource.Resource {
|
||||
return &instanceResource{}
|
||||
}
|
||||
|
||||
// instanceResource is the resource implementation.
|
||||
type instanceResource struct {
|
||||
client *mariadb.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *instanceResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_mariadb_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *instanceResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *mariadb.APIClient
|
||||
var err error
|
||||
if providerData.MariaDBCustomEndpoint != "" {
|
||||
apiClient, err = mariadb.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.MariaDBCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = mariadb.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "MariaDB instance client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *instanceResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "MariaDB instance resource schema.",
|
||||
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`\".",
|
||||
"instance_id": "ID of the MariaDB instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"name": "Instance name.",
|
||||
"version": "The service version.",
|
||||
"plan_name": "The selected plan name.",
|
||||
"plan_id": "The selected plan ID.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
},
|
||||
},
|
||||
"version": schema.StringAttribute{
|
||||
Description: descriptions["version"],
|
||||
Required: true,
|
||||
},
|
||||
"plan_name": schema.StringAttribute{
|
||||
Description: descriptions["plan_name"],
|
||||
Required: true,
|
||||
},
|
||||
"plan_id": schema.StringAttribute{
|
||||
Description: descriptions["plan_id"],
|
||||
Computed: true,
|
||||
},
|
||||
"parameters": schema.SingleNestedAttribute{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"sgw_acl": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
},
|
||||
"cf_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"cf_space_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"dashboard_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"image_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"cf_organization_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *instanceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
|
||||
var parameters = ¶metersModel{}
|
||||
if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) {
|
||||
diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err := r.loadPlanId(ctx, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Loading service plan: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model, parameters)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Create new instance
|
||||
createResp, err := r.client.CreateInstance(ctx, projectId).CreateInstancePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
instanceId := *createResp.InstanceId
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
wr, err := mariadb.CreateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Instance creation waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*mariadb.Instance)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "MariaDB instance created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(instanceResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Compute and store values not present in the API response
|
||||
err = loadPlanNameAndVersion(ctx, r.client, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Loading service plan details: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "MariaDB instance read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *instanceResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
var parameters = ¶metersModel{}
|
||||
if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) {
|
||||
diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err := r.loadPlanId(ctx, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Loading service plan: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toUpdatePayload(&model, parameters)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Update existing instance
|
||||
err = r.client.UpdateInstance(ctx, projectId, instanceId).UpdateInstancePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
wr, err := mariadb.UpdateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Instance update waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*mariadb.Instance)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "MariaDB instance updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *instanceResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from state
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
// Delete existing instance
|
||||
err := r.client.DeleteInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
_, err = mariadb.DeleteInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "MariaDB instance deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,instance_id
|
||||
func (r *instanceResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
|
||||
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing instance",
|
||||
fmt.Sprintf("Expected import identifier with format: [project_id],[instance_id] Got: %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[1])...)
|
||||
tflog.Info(ctx, "MariaDB instance state imported")
|
||||
}
|
||||
|
||||
func mapFields(instance *mariadb.Instance, model *Model) error {
|
||||
if instance == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
|
||||
var instanceId string
|
||||
if model.InstanceId.ValueString() != "" {
|
||||
instanceId = model.InstanceId.ValueString()
|
||||
} else if instance.InstanceId != nil {
|
||||
instanceId = *instance.InstanceId
|
||||
} else {
|
||||
return fmt.Errorf("instance id not present")
|
||||
}
|
||||
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
instanceId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.InstanceId = types.StringValue(instanceId)
|
||||
model.PlanId = types.StringPointerValue(instance.PlanId)
|
||||
model.CfGuid = types.StringPointerValue(instance.CfGuid)
|
||||
model.CfSpaceGuid = types.StringPointerValue(instance.CfSpaceGuid)
|
||||
model.DashboardUrl = types.StringPointerValue(instance.DashboardUrl)
|
||||
model.ImageUrl = types.StringPointerValue(instance.ImageUrl)
|
||||
model.Name = types.StringPointerValue(instance.Name)
|
||||
model.CfOrganizationGuid = types.StringPointerValue(instance.CfOrganizationGuid)
|
||||
|
||||
if instance.Parameters == nil {
|
||||
model.Parameters = types.ObjectNull(parametersTypes)
|
||||
} else {
|
||||
parameters, err := mapParameters(*instance.Parameters)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mapping parameters: %w", err)
|
||||
}
|
||||
model.Parameters = parameters
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func mapParameters(params map[string]interface{}) (types.Object, error) {
|
||||
attributes := map[string]attr.Value{}
|
||||
for attribute := range parametersTypes {
|
||||
valueInterface, ok := params[attribute]
|
||||
if !ok {
|
||||
// All fields are optional, so this is ok
|
||||
// Set the value as nil, will be handled accordingly
|
||||
valueInterface = nil
|
||||
}
|
||||
|
||||
var value attr.Value
|
||||
switch parametersTypes[attribute].(type) {
|
||||
default:
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found unexpected attribute type '%T'", parametersTypes[attribute])
|
||||
case basetypes.StringType:
|
||||
if valueInterface == nil {
|
||||
value = types.StringNull()
|
||||
} else {
|
||||
valueString, ok := valueInterface.(string)
|
||||
if !ok {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as string", attribute, valueInterface)
|
||||
}
|
||||
value = types.StringValue(valueString)
|
||||
}
|
||||
case basetypes.BoolType:
|
||||
if valueInterface == nil {
|
||||
value = types.BoolNull()
|
||||
} else {
|
||||
valueBool, ok := valueInterface.(bool)
|
||||
if !ok {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as bool", attribute, valueInterface)
|
||||
}
|
||||
value = types.BoolValue(valueBool)
|
||||
}
|
||||
case basetypes.Int64Type:
|
||||
if valueInterface == nil {
|
||||
value = types.Int64Null()
|
||||
} else {
|
||||
// This may be int64, int32, int or float64
|
||||
// We try to assert all 4
|
||||
var valueInt64 int64
|
||||
switch temp := valueInterface.(type) {
|
||||
default:
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as int", attribute, valueInterface)
|
||||
case int64:
|
||||
valueInt64 = temp
|
||||
case int32:
|
||||
valueInt64 = int64(temp)
|
||||
case int:
|
||||
valueInt64 = int64(temp)
|
||||
case float64:
|
||||
valueInt64 = int64(temp)
|
||||
}
|
||||
value = types.Int64Value(valueInt64)
|
||||
}
|
||||
case basetypes.ListType: // Assumed to be a list of strings
|
||||
if valueInterface == nil {
|
||||
value = types.ListNull(types.StringType)
|
||||
} else {
|
||||
// This may be []string{} or []interface{}
|
||||
// We try to assert all 2
|
||||
var valueList []attr.Value
|
||||
switch temp := valueInterface.(type) {
|
||||
default:
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as array of interface", attribute, valueInterface)
|
||||
case []string:
|
||||
for _, x := range temp {
|
||||
valueList = append(valueList, types.StringValue(x))
|
||||
}
|
||||
case []interface{}:
|
||||
for _, x := range temp {
|
||||
xString, ok := x.(string)
|
||||
if !ok {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' with element '%s' of type %T, failed to assert as string", attribute, x, x)
|
||||
}
|
||||
valueList = append(valueList, types.StringValue(xString))
|
||||
}
|
||||
}
|
||||
temp2, diags := types.ListValue(types.StringType, valueList)
|
||||
if diags.HasError() {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("failed to map %s: %w", attribute, core.DiagsToError(diags))
|
||||
}
|
||||
value = temp2
|
||||
}
|
||||
}
|
||||
attributes[attribute] = value
|
||||
}
|
||||
|
||||
output, diags := types.ObjectValue(parametersTypes, attributes)
|
||||
if diags.HasError() {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("failed to create object: %w", core.DiagsToError(diags))
|
||||
}
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model, parameters *parametersModel) (*mariadb.CreateInstancePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
if parameters == nil {
|
||||
return &mariadb.CreateInstancePayload{
|
||||
InstanceName: model.Name.ValueStringPointer(),
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
payloadParams := &mariadb.InstanceParameters{}
|
||||
if parameters.SgwAcl.ValueString() != "" {
|
||||
payloadParams.SgwAcl = parameters.SgwAcl.ValueStringPointer()
|
||||
}
|
||||
return &mariadb.CreateInstancePayload{
|
||||
InstanceName: model.Name.ValueStringPointer(),
|
||||
Parameters: payloadParams,
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toUpdatePayload(model *Model, parameters *parametersModel) (*mariadb.UpdateInstancePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
if parameters == nil {
|
||||
return &mariadb.UpdateInstancePayload{
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
return &mariadb.UpdateInstancePayload{
|
||||
Parameters: &mariadb.InstanceParameters{
|
||||
SgwAcl: parameters.SgwAcl.ValueStringPointer(),
|
||||
},
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *instanceResource) loadPlanId(ctx context.Context, model *Model) error {
|
||||
projectId := model.ProjectId.ValueString()
|
||||
res, err := r.client.GetOfferings(ctx, projectId).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting MariaDB offerings: %w", err)
|
||||
}
|
||||
|
||||
version := model.Version.ValueString()
|
||||
planName := model.PlanName.ValueString()
|
||||
availableVersions := ""
|
||||
availablePlanNames := ""
|
||||
isValidVersion := false
|
||||
for _, offer := range *res.Offerings {
|
||||
if !strings.EqualFold(*offer.Version, version) {
|
||||
availableVersions = fmt.Sprintf("%s\n- %s", availableVersions, *offer.Version)
|
||||
continue
|
||||
}
|
||||
isValidVersion = true
|
||||
|
||||
for _, plan := range *offer.Plans {
|
||||
if plan.Name == nil {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(*plan.Name, planName) && plan.Id != nil {
|
||||
model.PlanId = types.StringPointerValue(plan.Id)
|
||||
return nil
|
||||
}
|
||||
availablePlanNames = fmt.Sprintf("%s\n- %s", availablePlanNames, *plan.Name)
|
||||
}
|
||||
}
|
||||
|
||||
if !isValidVersion {
|
||||
return fmt.Errorf("couldn't find version '%s', available versions are: %s", version, availableVersions)
|
||||
}
|
||||
return fmt.Errorf("couldn't find plan_name '%s' for version %s, available names are: %s", planName, version, availablePlanNames)
|
||||
}
|
||||
|
||||
func loadPlanNameAndVersion(ctx context.Context, client *mariadb.APIClient, model *Model) error {
|
||||
projectId := model.ProjectId.ValueString()
|
||||
planId := model.PlanId.ValueString()
|
||||
res, err := client.GetOfferings(ctx, projectId).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting MariaDB offerings: %w", err)
|
||||
}
|
||||
|
||||
for _, offer := range *res.Offerings {
|
||||
for _, plan := range *offer.Plans {
|
||||
if strings.EqualFold(*plan.Id, planId) && plan.Id != nil {
|
||||
model.PlanName = types.StringPointerValue(plan.Name)
|
||||
model.Version = types.StringPointerValue(offer.Version)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("couldn't find plan_name and version for plan_id '%s'", planId)
|
||||
}
|
||||
304
stackit/internal/services/mariadb/instance/resource_test.go
Normal file
304
stackit/internal/services/mariadb/instance/resource_test.go
Normal file
|
|
@ -0,0 +1,304 @@
|
|||
package mariadb
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/mariadb"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *mariadb.Instance
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&mariadb.Instance{},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
PlanId: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
CfGuid: types.StringNull(),
|
||||
CfSpaceGuid: types.StringNull(),
|
||||
DashboardUrl: types.StringNull(),
|
||||
ImageUrl: types.StringNull(),
|
||||
CfOrganizationGuid: types.StringNull(),
|
||||
Parameters: types.ObjectNull(parametersTypes),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&mariadb.Instance{
|
||||
PlanId: utils.Ptr("plan"),
|
||||
CfGuid: utils.Ptr("cf"),
|
||||
CfSpaceGuid: utils.Ptr("space"),
|
||||
DashboardUrl: utils.Ptr("dashboard"),
|
||||
ImageUrl: utils.Ptr("image"),
|
||||
InstanceId: utils.Ptr("iid"),
|
||||
Name: utils.Ptr("name"),
|
||||
CfOrganizationGuid: utils.Ptr("org"),
|
||||
Parameters: &map[string]interface{}{
|
||||
"sgw_acl": "acl",
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
PlanId: types.StringValue("plan"),
|
||||
Name: types.StringValue("name"),
|
||||
CfGuid: types.StringValue("cf"),
|
||||
CfSpaceGuid: types.StringValue("space"),
|
||||
DashboardUrl: types.StringValue("dashboard"),
|
||||
ImageUrl: types.StringValue("image"),
|
||||
CfOrganizationGuid: types.StringValue("org"),
|
||||
Parameters: types.ObjectValueMust(parametersTypes, map[string]attr.Value{
|
||||
"sgw_acl": types.StringValue("acl"),
|
||||
}),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&mariadb.Instance{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"wrong_param_types_1",
|
||||
&mariadb.Instance{
|
||||
Parameters: &map[string]interface{}{
|
||||
"sgw_acl": true,
|
||||
},
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"wrong_param_types_2",
|
||||
&mariadb.Instance{
|
||||
Parameters: &map[string]interface{}{
|
||||
"sgw_acl": 1,
|
||||
},
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
state := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
}
|
||||
err := mapFields(tt.input, state)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputParameters *parametersModel
|
||||
expected *mariadb.CreateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
¶metersModel{},
|
||||
&mariadb.CreateInstancePayload{
|
||||
Parameters: &mariadb.InstanceParameters{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
Name: types.StringValue("name"),
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
¶metersModel{
|
||||
SgwAcl: types.StringValue("sgw"),
|
||||
},
|
||||
&mariadb.CreateInstancePayload{
|
||||
InstanceName: utils.Ptr("name"),
|
||||
Parameters: &mariadb.InstanceParameters{
|
||||
SgwAcl: utils.Ptr("sgw"),
|
||||
},
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
Name: types.StringValue(""),
|
||||
PlanId: types.StringValue(""),
|
||||
},
|
||||
¶metersModel{
|
||||
SgwAcl: types.StringNull(),
|
||||
},
|
||||
&mariadb.CreateInstancePayload{
|
||||
InstanceName: utils.Ptr(""),
|
||||
Parameters: &mariadb.InstanceParameters{
|
||||
SgwAcl: nil,
|
||||
},
|
||||
PlanId: utils.Ptr(""),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
¶metersModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_parameters",
|
||||
&Model{
|
||||
Name: types.StringValue("name"),
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
nil,
|
||||
&mariadb.CreateInstancePayload{
|
||||
InstanceName: utils.Ptr("name"),
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toCreatePayload(tt.input, tt.inputParameters)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToUpdatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputParameters *parametersModel
|
||||
expected *mariadb.UpdateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
¶metersModel{},
|
||||
&mariadb.UpdateInstancePayload{
|
||||
Parameters: &mariadb.InstanceParameters{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
¶metersModel{
|
||||
SgwAcl: types.StringValue("sgw"),
|
||||
},
|
||||
&mariadb.UpdateInstancePayload{
|
||||
Parameters: &mariadb.InstanceParameters{
|
||||
SgwAcl: utils.Ptr("sgw"),
|
||||
},
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
PlanId: types.StringValue(""),
|
||||
},
|
||||
¶metersModel{
|
||||
SgwAcl: types.StringNull(),
|
||||
},
|
||||
&mariadb.UpdateInstancePayload{
|
||||
Parameters: &mariadb.InstanceParameters{
|
||||
SgwAcl: nil,
|
||||
},
|
||||
PlanId: utils.Ptr(""),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
¶metersModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_parameters",
|
||||
&Model{
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
nil,
|
||||
&mariadb.UpdateInstancePayload{
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toUpdatePayload(tt.input, tt.inputParameters)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
244
stackit/internal/services/mariadb/mariadb_acc_test.go
Normal file
244
stackit/internal/services/mariadb/mariadb_acc_test.go
Normal file
|
|
@ -0,0 +1,244 @@
|
|||
package mariadb_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
|
||||
"github.com/hashicorp/terraform-plugin-testing/terraform"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/mariadb"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/testutil"
|
||||
)
|
||||
|
||||
// Instance resource data
|
||||
var instanceResource = map[string]string{
|
||||
"project_id": testutil.ProjectId,
|
||||
"name": testutil.ResourceNameWithDateTime("mariadb"),
|
||||
"plan_id": "683be856-3587-42de-b1b5-a792ff854f52",
|
||||
"plan_name": "stackit-qa-mariadb-1.4.10-single",
|
||||
"version": "10.6",
|
||||
"sgw_acl-1": "192.168.0.0/16",
|
||||
"sgw_acl-2": "192.168.0.0/24",
|
||||
}
|
||||
|
||||
func resourceConfig(acls string) string {
|
||||
return fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
resource "stackit_mariadb_instance" "instance" {
|
||||
project_id = "%s"
|
||||
name = "%s"
|
||||
plan_name = "%s"
|
||||
version = "%s"
|
||||
parameters = {
|
||||
sgw_acl = "%s"
|
||||
}
|
||||
}
|
||||
|
||||
resource "stackit_mariadb_credentials" "credentials" {
|
||||
project_id = stackit_mariadb_instance.instance.project_id
|
||||
instance_id = stackit_mariadb_instance.instance.instance_id
|
||||
}
|
||||
`,
|
||||
testutil.MariaDBProviderConfig(),
|
||||
instanceResource["project_id"],
|
||||
instanceResource["name"],
|
||||
instanceResource["plan_name"],
|
||||
instanceResource["version"],
|
||||
acls,
|
||||
)
|
||||
}
|
||||
func TestAccMariaDBResource(t *testing.T) {
|
||||
resource.Test(t, resource.TestCase{
|
||||
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
|
||||
CheckDestroy: testAccCheckMariaDBDestroy,
|
||||
Steps: []resource.TestStep{
|
||||
|
||||
// Creation
|
||||
{
|
||||
Config: resourceConfig(instanceResource["sgw_acl-1"]),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("stackit_mariadb_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_mariadb_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_mariadb_instance.instance", "plan_id", instanceResource["plan_id"]),
|
||||
resource.TestCheckResourceAttr("stackit_mariadb_instance.instance", "plan_name", instanceResource["plan_name"]),
|
||||
resource.TestCheckResourceAttr("stackit_mariadb_instance.instance", "version", instanceResource["version"]),
|
||||
resource.TestCheckResourceAttr("stackit_mariadb_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_mariadb_instance.instance", "parameters.sgw_acl", instanceResource["sgw_acl-1"]),
|
||||
|
||||
// Credentials data
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_mariadb_credentials.credentials", "project_id",
|
||||
"stackit_mariadb_instance.instance", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_mariadb_credentials.credentials", "instance_id",
|
||||
"stackit_mariadb_instance.instance", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrSet("stackit_mariadb_credentials.credentials", "credentials_id"),
|
||||
resource.TestCheckResourceAttrSet("stackit_mariadb_credentials.credentials", "host"),
|
||||
),
|
||||
},
|
||||
// Data source
|
||||
{
|
||||
Config: fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
data "stackit_mariadb_instance" "instance" {
|
||||
project_id = stackit_mariadb_instance.instance.project_id
|
||||
instance_id = stackit_mariadb_instance.instance.instance_id
|
||||
}
|
||||
|
||||
data "stackit_mariadb_credentials" "credentials" {
|
||||
project_id = stackit_mariadb_credentials.credentials.project_id
|
||||
instance_id = stackit_mariadb_credentials.credentials.instance_id
|
||||
credentials_id = stackit_mariadb_credentials.credentials.credentials_id
|
||||
}`,
|
||||
resourceConfig(instanceResource["sgw_acl-1"]),
|
||||
),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("data.stackit_mariadb_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrPair("stackit_mariadb_instance.instance", "instance_id",
|
||||
"data.stackit_mariadb_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttrPair("stackit_mariadb_credentials.credentials", "credentials_id",
|
||||
"data.stackit_mariadb_credentials.credentials", "credentials_id"),
|
||||
resource.TestCheckResourceAttr("data.stackit_mariadb_instance.instance", "plan_id", instanceResource["plan_id"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_mariadb_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_mariadb_instance.instance", "parameters.sgw_acl", instanceResource["sgw_acl-1"]),
|
||||
|
||||
// Credentials data
|
||||
resource.TestCheckResourceAttr("data.stackit_mariadb_credentials.credentials", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_mariadb_credentials.credentials", "credentials_id"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_mariadb_credentials.credentials", "host"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_mariadb_credentials.credentials", "port"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_mariadb_credentials.credentials", "uri"),
|
||||
),
|
||||
},
|
||||
// Import
|
||||
{
|
||||
ResourceName: "stackit_mariadb_instance.instance",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_mariadb_instance.instance"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_mariadb_instance.instance")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
return fmt.Sprintf("%s,%s", testutil.ProjectId, instanceId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
{
|
||||
ResourceName: "stackit_mariadb_credentials.credentials",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_mariadb_credentials.credentials"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_mariadb_credentials.credentials")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
credentialsId, ok := r.Primary.Attributes["credentials_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute credentials_id")
|
||||
}
|
||||
return fmt.Sprintf("%s,%s,%s", testutil.ProjectId, instanceId, credentialsId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
// Update
|
||||
{
|
||||
Config: resourceConfig(instanceResource["sgw_acl-2"]),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("stackit_mariadb_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_mariadb_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_mariadb_instance.instance", "plan_id", instanceResource["plan_id"]),
|
||||
resource.TestCheckResourceAttr("stackit_mariadb_instance.instance", "plan_name", instanceResource["plan_name"]),
|
||||
resource.TestCheckResourceAttr("stackit_mariadb_instance.instance", "version", instanceResource["version"]),
|
||||
resource.TestCheckResourceAttr("stackit_mariadb_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_mariadb_instance.instance", "parameters.sgw_acl", instanceResource["sgw_acl-2"]),
|
||||
),
|
||||
},
|
||||
// Deletion is done by the framework implicitly
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func testAccCheckMariaDBDestroy(s *terraform.State) error {
|
||||
ctx := context.Background()
|
||||
var client *mariadb.APIClient
|
||||
var err error
|
||||
if testutil.MariaDBCustomEndpoint == "" {
|
||||
client, err = mariadb.NewAPIClient()
|
||||
} else {
|
||||
client, err = mariadb.NewAPIClient(
|
||||
config.WithEndpoint(testutil.MariaDBCustomEndpoint),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating client: %w", err)
|
||||
}
|
||||
|
||||
instancesToDestroy := []string{}
|
||||
for _, rs := range s.RootModule().Resources {
|
||||
if rs.Type != "stackit_mariadb_instance" {
|
||||
continue
|
||||
}
|
||||
// instance terraform ID: "[project_id],[instance_id]"
|
||||
instanceId := strings.Split(rs.Primary.ID, core.Separator)[1]
|
||||
instancesToDestroy = append(instancesToDestroy, instanceId)
|
||||
}
|
||||
|
||||
instancesResp, err := client.GetInstances(ctx, testutil.ProjectId).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting instancesResp: %w", err)
|
||||
}
|
||||
|
||||
instances := *instancesResp.Instances
|
||||
for i := range instances {
|
||||
if instances[i].InstanceId == nil {
|
||||
continue
|
||||
}
|
||||
if utils.Contains(instancesToDestroy, *instances[i].InstanceId) {
|
||||
if !checkInstanceDeleteSuccess(&instances[i]) {
|
||||
err := client.DeleteInstanceExecute(ctx, testutil.ProjectId, *instances[i].InstanceId)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying instance %s during CheckDestroy: %w", *instances[i].InstanceId, err)
|
||||
}
|
||||
_, err = mariadb.DeleteInstanceWaitHandler(ctx, client, testutil.ProjectId, *instances[i].InstanceId).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying instance %s during CheckDestroy: waiting for deletion %w", *instances[i].InstanceId, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkInstanceDeleteSuccess(i *mariadb.Instance) bool {
|
||||
if *i.LastOperation.Type != mariadb.InstanceTypeDelete {
|
||||
return false
|
||||
}
|
||||
|
||||
if *i.LastOperation.Type == mariadb.InstanceTypeDelete {
|
||||
if *i.LastOperation.State != mariadb.InstanceStateSuccess {
|
||||
return false
|
||||
} else if strings.Contains(*i.LastOperation.Description, "DeleteFailed") || strings.Contains(*i.LastOperation.Description, "failed") {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
181
stackit/internal/services/opensearch/credentials/datasource.go
Normal file
181
stackit/internal/services/opensearch/credentials/datasource.go
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
package opensearch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/opensearch"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &credentialsDataSource{}
|
||||
)
|
||||
|
||||
// NewCredentialsDataSource is a helper function to simplify the provider implementation.
|
||||
func NewCredentialsDataSource() datasource.DataSource {
|
||||
return &credentialsDataSource{}
|
||||
}
|
||||
|
||||
// credentialsDataSource is the data source implementation.
|
||||
type credentialsDataSource struct {
|
||||
client *opensearch.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *credentialsDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_opensearch_credentials"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *credentialsDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *opensearch.APIClient
|
||||
var err error
|
||||
if providerData.OpenSearchCustomEndpoint != "" {
|
||||
apiClient, err = opensearch.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.OpenSearchCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = opensearch.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "OpenSearch credentials client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *credentialsDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "OpenSearch credentials data source schema.",
|
||||
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`,`credentials_id`\".",
|
||||
"credentials_id": "The credentials ID.",
|
||||
"instance_id": "ID of the OpenSearch instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"credentials_id": schema.StringAttribute{
|
||||
Description: descriptions["credentials_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"hosts": schema.ListAttribute{
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"http_api_uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"password": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *credentialsDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
credentialsId := model.CredentialsId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(recordSetResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "OpenSearch credentials read")
|
||||
}
|
||||
377
stackit/internal/services/opensearch/credentials/resource.go
Normal file
377
stackit/internal/services/opensearch/credentials/resource.go
Normal file
|
|
@ -0,0 +1,377 @@
|
|||
package opensearch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/opensearch"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &credentialsResource{}
|
||||
_ resource.ResourceWithConfigure = &credentialsResource{}
|
||||
_ resource.ResourceWithImportState = &credentialsResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
CredentialsId types.String `tfsdk:"credentials_id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Host types.String `tfsdk:"host"`
|
||||
Hosts types.List `tfsdk:"hosts"`
|
||||
HttpAPIURI types.String `tfsdk:"http_api_uri"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Password types.String `tfsdk:"password"`
|
||||
Port types.Int64 `tfsdk:"port"`
|
||||
Uri types.String `tfsdk:"uri"`
|
||||
Username types.String `tfsdk:"username"`
|
||||
}
|
||||
|
||||
// NewCredentialsResource is a helper function to simplify the provider implementation.
|
||||
func NewCredentialsResource() resource.Resource {
|
||||
return &credentialsResource{}
|
||||
}
|
||||
|
||||
// credentialsResource is the resource implementation.
|
||||
type credentialsResource struct {
|
||||
client *opensearch.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *credentialsResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_opensearch_credentials"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *credentialsResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *opensearch.APIClient
|
||||
var err error
|
||||
if providerData.OpenSearchCustomEndpoint != "" {
|
||||
apiClient, err = opensearch.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.OpenSearchCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = opensearch.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "OpenSearch credentials client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *credentialsResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "OpenSearch credentials resource schema.",
|
||||
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`,`credentials_id`\".",
|
||||
"credentials_id": "The credentials ID.",
|
||||
"instance_id": "ID of the OpenSearch instance.",
|
||||
"project_id": "STACKIT Project ID to which the instance is associated.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"credentials_id": schema.StringAttribute{
|
||||
Description: descriptions["credentials_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"hosts": schema.ListAttribute{
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"http_api_uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"password": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *credentialsResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
// Create new recordset
|
||||
credentialsResp, err := r.client.CreateCredentials(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
if credentialsResp.Id == nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", "Got empty credentials id")
|
||||
return
|
||||
}
|
||||
credentialsId := *credentialsResp.Id
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
wr, err := opensearch.CreateCredentialsWaitHandler(ctx, r.client, projectId, instanceId, credentialsId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Instance creation waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*opensearch.CredentialsResponse)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "OpenSearch credentials created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *credentialsResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
credentialsId := model.CredentialsId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(recordSetResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "OpenSearch credentials read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *credentialsResource) Update(ctx context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Update shouldn't be called
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating credentials", "Credentials can't be updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *credentialsResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
credentialsId := model.CredentialsId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
// Delete existing record set
|
||||
err := r.client.DeleteCredentials(ctx, projectId, instanceId, credentialsId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
}
|
||||
_, err = opensearch.DeleteCredentialsWaitHandler(ctx, r.client, projectId, instanceId, credentialsId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credentials", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "OpenSearch credentials deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,instance_id,credentials_id
|
||||
func (r *credentialsResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing credentials",
|
||||
fmt.Sprintf("Expected import identifier with format [project_id],[instance_id],[credentials_id], got %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[1])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("credentials_id"), idParts[2])...)
|
||||
tflog.Info(ctx, "OpenSearch credentials state imported")
|
||||
}
|
||||
|
||||
func mapFields(credentialsResp *opensearch.CredentialsResponse, model *Model) error {
|
||||
if credentialsResp == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if credentialsResp.Raw == nil {
|
||||
return fmt.Errorf("response credentials raw is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
credentials := credentialsResp.Raw.Credentials
|
||||
|
||||
var credentialsId string
|
||||
if model.CredentialsId.ValueString() != "" {
|
||||
credentialsId = model.CredentialsId.ValueString()
|
||||
} else if credentialsResp.Id != nil {
|
||||
credentialsId = *credentialsResp.Id
|
||||
} else {
|
||||
return fmt.Errorf("credentials id not present")
|
||||
}
|
||||
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
model.InstanceId.ValueString(),
|
||||
credentialsId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.CredentialsId = types.StringValue(credentialsId)
|
||||
model.Hosts = types.ListNull(types.StringType)
|
||||
if credentials != nil {
|
||||
if credentials.Hosts != nil {
|
||||
var hosts []attr.Value
|
||||
for _, host := range *credentials.Hosts {
|
||||
hosts = append(hosts, types.StringValue(host))
|
||||
}
|
||||
hostsList, diags := types.ListValue(types.StringType, hosts)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map hosts: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Hosts = hostsList
|
||||
}
|
||||
model.Host = types.StringPointerValue(credentials.Host)
|
||||
model.HttpAPIURI = types.StringPointerValue(credentials.HttpApiUri)
|
||||
model.Name = types.StringPointerValue(credentials.Name)
|
||||
model.Password = types.StringPointerValue(credentials.Password)
|
||||
model.Port = conversion.ToTypeInt64(credentials.Port)
|
||||
model.Uri = types.StringPointerValue(credentials.Uri)
|
||||
model.Username = types.StringPointerValue(credentials.Username)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,156 @@
|
|||
package opensearch
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/opensearch"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *opensearch.CredentialsResponse
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&opensearch.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
Raw: &opensearch.RawCredentials{},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,cid"),
|
||||
CredentialsId: types.StringValue("cid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Host: types.StringNull(),
|
||||
Hosts: types.ListNull(types.StringType),
|
||||
HttpAPIURI: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Password: types.StringNull(),
|
||||
Port: types.Int64Null(),
|
||||
Uri: types.StringNull(),
|
||||
Username: types.StringNull(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&opensearch.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
Raw: &opensearch.RawCredentials{
|
||||
Credentials: &opensearch.Credentials{
|
||||
Host: utils.Ptr("host"),
|
||||
Hosts: &[]string{
|
||||
"host_1",
|
||||
"",
|
||||
},
|
||||
HttpApiUri: utils.Ptr("http"),
|
||||
Name: utils.Ptr("name"),
|
||||
Password: utils.Ptr("password"),
|
||||
Port: utils.Ptr(int32(1234)),
|
||||
Uri: utils.Ptr("uri"),
|
||||
Username: utils.Ptr("username"),
|
||||
},
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,cid"),
|
||||
CredentialsId: types.StringValue("cid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Host: types.StringValue("host"),
|
||||
Hosts: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("host_1"),
|
||||
types.StringValue(""),
|
||||
}),
|
||||
HttpAPIURI: types.StringValue("http"),
|
||||
Name: types.StringValue("name"),
|
||||
Password: types.StringValue("password"),
|
||||
Port: types.Int64Value(1234),
|
||||
Uri: types.StringValue("uri"),
|
||||
Username: types.StringValue("username"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&opensearch.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
Raw: &opensearch.RawCredentials{
|
||||
Credentials: &opensearch.Credentials{
|
||||
Host: utils.Ptr(""),
|
||||
Hosts: &[]string{},
|
||||
HttpApiUri: nil,
|
||||
Name: nil,
|
||||
Password: utils.Ptr(""),
|
||||
Port: utils.Ptr(int32(2123456789)),
|
||||
Uri: nil,
|
||||
Username: utils.Ptr(""),
|
||||
},
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,cid"),
|
||||
CredentialsId: types.StringValue("cid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Host: types.StringValue(""),
|
||||
Hosts: types.ListValueMust(types.StringType, []attr.Value{}),
|
||||
HttpAPIURI: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Password: types.StringValue(""),
|
||||
Port: types.Int64Value(2123456789),
|
||||
Uri: types.StringNull(),
|
||||
Username: types.StringValue(""),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&opensearch.CredentialsResponse{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_raw_credentials",
|
||||
&opensearch.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
model := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
}
|
||||
err := mapFields(tt.input, model)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(model, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
192
stackit/internal/services/opensearch/instance/datasource.go
Normal file
192
stackit/internal/services/opensearch/instance/datasource.go
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
package opensearch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/opensearch"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &instanceDataSource{}
|
||||
)
|
||||
|
||||
// NewInstanceDataSource is a helper function to simplify the provider implementation.
|
||||
func NewInstanceDataSource() datasource.DataSource {
|
||||
return &instanceDataSource{}
|
||||
}
|
||||
|
||||
// instanceDataSource is the data source implementation.
|
||||
type instanceDataSource struct {
|
||||
client *opensearch.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *instanceDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_opensearch_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *instanceDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *opensearch.APIClient
|
||||
var err error
|
||||
if providerData.OpenSearchCustomEndpoint != "" {
|
||||
apiClient, err = opensearch.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.OpenSearchCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = opensearch.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "OpenSearch zone client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "OpenSearch instance data source schema.",
|
||||
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`\".",
|
||||
"instance_id": "ID of the OpenSearch instance.",
|
||||
"project_id": "STACKIT Project ID to which the instance is associated.",
|
||||
"name": "Instance name.",
|
||||
"version": "The service version.",
|
||||
"plan_name": "The selected plan name.",
|
||||
"plan_id": "The selected plan ID.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Computed: true,
|
||||
},
|
||||
"version": schema.StringAttribute{
|
||||
Description: descriptions["version"],
|
||||
Computed: true,
|
||||
},
|
||||
"plan_name": schema.StringAttribute{
|
||||
Description: descriptions["plan_name"],
|
||||
Computed: true,
|
||||
},
|
||||
"plan_id": schema.StringAttribute{
|
||||
Description: descriptions["plan_id"],
|
||||
Computed: true,
|
||||
},
|
||||
"parameters": schema.SingleNestedAttribute{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"sgw_acl": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
Computed: true,
|
||||
},
|
||||
"cf_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"cf_space_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"dashboard_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"image_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"cf_organization_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *instanceDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
err = mapFields(instanceResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Compute and store values not present in the API response
|
||||
err = loadPlanNameAndVersion(ctx, r.client, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Loading service plan details: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "OpenSearch instance read")
|
||||
}
|
||||
680
stackit/internal/services/opensearch/instance/resource.go
Normal file
680
stackit/internal/services/opensearch/instance/resource.go
Normal file
|
|
@ -0,0 +1,680 @@
|
|||
package opensearch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/opensearch"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &instanceResource{}
|
||||
_ resource.ResourceWithConfigure = &instanceResource{}
|
||||
_ resource.ResourceWithImportState = &instanceResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
CfGuid types.String `tfsdk:"cf_guid"`
|
||||
CfSpaceGuid types.String `tfsdk:"cf_space_guid"`
|
||||
DashboardUrl types.String `tfsdk:"dashboard_url"`
|
||||
ImageUrl types.String `tfsdk:"image_url"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
CfOrganizationGuid types.String `tfsdk:"cf_organization_guid"`
|
||||
Parameters types.Object `tfsdk:"parameters"`
|
||||
Version types.String `tfsdk:"version"`
|
||||
PlanName types.String `tfsdk:"plan_name"`
|
||||
PlanId types.String `tfsdk:"plan_id"`
|
||||
}
|
||||
|
||||
// Struct corresponding to DataSourceModel.Parameters
|
||||
type parametersModel struct {
|
||||
SgwAcl types.String `tfsdk:"sgw_acl"`
|
||||
}
|
||||
|
||||
// Types corresponding to parametersModel
|
||||
var parametersTypes = map[string]attr.Type{
|
||||
"sgw_acl": basetypes.StringType{},
|
||||
}
|
||||
|
||||
// NewInstanceResource is a helper function to simplify the provider implementation.
|
||||
func NewInstanceResource() resource.Resource {
|
||||
return &instanceResource{}
|
||||
}
|
||||
|
||||
// instanceResource is the resource implementation.
|
||||
type instanceResource struct {
|
||||
client *opensearch.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *instanceResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_opensearch_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *instanceResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *opensearch.APIClient
|
||||
var err error
|
||||
if providerData.OpenSearchCustomEndpoint != "" {
|
||||
apiClient, err = opensearch.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.OpenSearchCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = opensearch.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "OpenSearch instance client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *instanceResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "OpenSearch instance resource schema.",
|
||||
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`\".",
|
||||
"instance_id": "ID of the OpenSearch instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"name": "Instance name.",
|
||||
"version": "The service version.",
|
||||
"plan_name": "The selected plan name.",
|
||||
"plan_id": "The selected plan ID.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
},
|
||||
},
|
||||
"version": schema.StringAttribute{
|
||||
Description: descriptions["version"],
|
||||
Required: true,
|
||||
},
|
||||
"plan_name": schema.StringAttribute{
|
||||
Description: descriptions["plan_name"],
|
||||
Required: true,
|
||||
},
|
||||
"plan_id": schema.StringAttribute{
|
||||
Description: descriptions["plan_id"],
|
||||
Computed: true,
|
||||
},
|
||||
"parameters": schema.SingleNestedAttribute{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"sgw_acl": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
},
|
||||
"cf_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"cf_space_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"dashboard_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"image_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"cf_organization_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *instanceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
|
||||
var parameters = ¶metersModel{}
|
||||
if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) {
|
||||
diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err := r.loadPlanId(ctx, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Loading service plan: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model, parameters)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Create new instance
|
||||
createResp, err := r.client.CreateInstance(ctx, projectId).CreateInstancePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
instanceId := *createResp.InstanceId
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
wr, err := opensearch.CreateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Instance creation waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*opensearch.Instance)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "OpenSearch instance created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(instanceResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Compute and store values not present in the API response
|
||||
err = loadPlanNameAndVersion(ctx, r.client, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Loading service plan details: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "OpenSearch instance read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *instanceResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
var parameters = ¶metersModel{}
|
||||
if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) {
|
||||
diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err := r.loadPlanId(ctx, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Loading service plan: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toUpdatePayload(&model, parameters)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Update existing instance
|
||||
err = r.client.UpdateInstance(ctx, projectId, instanceId).UpdateInstancePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
wr, err := opensearch.UpdateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Instance update waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*opensearch.Instance)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "OpenSearch instance updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *instanceResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from state
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
// Delete existing instance
|
||||
err := r.client.DeleteInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
_, err = opensearch.DeleteInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "OpenSearch instance deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,instance_id
|
||||
func (r *instanceResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
|
||||
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing instance",
|
||||
fmt.Sprintf("Expected import identifier with format: [project_id],[instance_id] Got: %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[1])...)
|
||||
tflog.Info(ctx, "OpenSearch instance state imported")
|
||||
}
|
||||
|
||||
func mapFields(instance *opensearch.Instance, model *Model) error {
|
||||
if instance == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
|
||||
var instanceId string
|
||||
if model.InstanceId.ValueString() != "" {
|
||||
instanceId = model.InstanceId.ValueString()
|
||||
} else if instance.InstanceId != nil {
|
||||
instanceId = *instance.InstanceId
|
||||
} else {
|
||||
return fmt.Errorf("instance id not present")
|
||||
}
|
||||
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
instanceId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.InstanceId = types.StringValue(instanceId)
|
||||
model.PlanId = types.StringPointerValue(instance.PlanId)
|
||||
model.CfGuid = types.StringPointerValue(instance.CfGuid)
|
||||
model.CfSpaceGuid = types.StringPointerValue(instance.CfSpaceGuid)
|
||||
model.DashboardUrl = types.StringPointerValue(instance.DashboardUrl)
|
||||
model.ImageUrl = types.StringPointerValue(instance.ImageUrl)
|
||||
model.Name = types.StringPointerValue(instance.Name)
|
||||
model.CfOrganizationGuid = types.StringPointerValue(instance.CfOrganizationGuid)
|
||||
|
||||
if instance.Parameters == nil {
|
||||
model.Parameters = types.ObjectNull(parametersTypes)
|
||||
} else {
|
||||
parameters, err := mapParameters(*instance.Parameters)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mapping parameters: %w", err)
|
||||
}
|
||||
model.Parameters = parameters
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func mapParameters(params map[string]interface{}) (types.Object, error) {
|
||||
attributes := map[string]attr.Value{}
|
||||
for attribute := range parametersTypes {
|
||||
valueInterface, ok := params[attribute]
|
||||
if !ok {
|
||||
// All fields are optional, so this is ok
|
||||
// Set the value as nil, will be handled accordingly
|
||||
valueInterface = nil
|
||||
}
|
||||
|
||||
var value attr.Value
|
||||
switch parametersTypes[attribute].(type) {
|
||||
default:
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found unexpected attribute type '%T'", parametersTypes[attribute])
|
||||
case basetypes.StringType:
|
||||
if valueInterface == nil {
|
||||
value = types.StringNull()
|
||||
} else {
|
||||
valueString, ok := valueInterface.(string)
|
||||
if !ok {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as string", attribute, valueInterface)
|
||||
}
|
||||
value = types.StringValue(valueString)
|
||||
}
|
||||
case basetypes.BoolType:
|
||||
if valueInterface == nil {
|
||||
value = types.BoolNull()
|
||||
} else {
|
||||
valueBool, ok := valueInterface.(bool)
|
||||
if !ok {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as bool", attribute, valueInterface)
|
||||
}
|
||||
value = types.BoolValue(valueBool)
|
||||
}
|
||||
case basetypes.Int64Type:
|
||||
if valueInterface == nil {
|
||||
value = types.Int64Null()
|
||||
} else {
|
||||
// This may be int64, int32, int or float64
|
||||
// We try to assert all 4
|
||||
var valueInt64 int64
|
||||
switch temp := valueInterface.(type) {
|
||||
default:
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as int", attribute, valueInterface)
|
||||
case int64:
|
||||
valueInt64 = temp
|
||||
case int32:
|
||||
valueInt64 = int64(temp)
|
||||
case int:
|
||||
valueInt64 = int64(temp)
|
||||
case float64:
|
||||
valueInt64 = int64(temp)
|
||||
}
|
||||
value = types.Int64Value(valueInt64)
|
||||
}
|
||||
case basetypes.ListType: // Assumed to be a list of strings
|
||||
if valueInterface == nil {
|
||||
value = types.ListNull(types.StringType)
|
||||
} else {
|
||||
// This may be []string{} or []interface{}
|
||||
// We try to assert all 2
|
||||
var valueList []attr.Value
|
||||
switch temp := valueInterface.(type) {
|
||||
default:
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as array of interface", attribute, valueInterface)
|
||||
case []string:
|
||||
for _, x := range temp {
|
||||
valueList = append(valueList, types.StringValue(x))
|
||||
}
|
||||
case []interface{}:
|
||||
for _, x := range temp {
|
||||
xString, ok := x.(string)
|
||||
if !ok {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' with element '%s' of type %T, failed to assert as string", attribute, x, x)
|
||||
}
|
||||
valueList = append(valueList, types.StringValue(xString))
|
||||
}
|
||||
}
|
||||
temp2, diags := types.ListValue(types.StringType, valueList)
|
||||
if diags.HasError() {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("failed to map %s: %w", attribute, core.DiagsToError(diags))
|
||||
}
|
||||
value = temp2
|
||||
}
|
||||
}
|
||||
attributes[attribute] = value
|
||||
}
|
||||
|
||||
output, diags := types.ObjectValue(parametersTypes, attributes)
|
||||
if diags.HasError() {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("failed to create object: %w", core.DiagsToError(diags))
|
||||
}
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model, parameters *parametersModel) (*opensearch.CreateInstancePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
if parameters == nil {
|
||||
return &opensearch.CreateInstancePayload{
|
||||
InstanceName: model.Name.ValueStringPointer(),
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
payloadParams := &opensearch.InstanceParameters{}
|
||||
if parameters.SgwAcl.ValueString() != "" {
|
||||
payloadParams.SgwAcl = parameters.SgwAcl.ValueStringPointer()
|
||||
}
|
||||
return &opensearch.CreateInstancePayload{
|
||||
InstanceName: model.Name.ValueStringPointer(),
|
||||
Parameters: payloadParams,
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toUpdatePayload(model *Model, parameters *parametersModel) (*opensearch.UpdateInstancePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
if parameters == nil {
|
||||
return &opensearch.UpdateInstancePayload{
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
return &opensearch.UpdateInstancePayload{
|
||||
Parameters: &opensearch.InstanceParameters{
|
||||
SgwAcl: parameters.SgwAcl.ValueStringPointer(),
|
||||
},
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *instanceResource) loadPlanId(ctx context.Context, model *Model) error {
|
||||
projectId := model.ProjectId.ValueString()
|
||||
res, err := r.client.GetOfferings(ctx, projectId).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting OpenSearch offerings: %w", err)
|
||||
}
|
||||
|
||||
version := model.Version.ValueString()
|
||||
planName := model.PlanName.ValueString()
|
||||
availableVersions := ""
|
||||
availablePlanNames := ""
|
||||
isValidVersion := false
|
||||
for _, offer := range *res.Offerings {
|
||||
if !strings.EqualFold(*offer.Version, version) {
|
||||
availableVersions = fmt.Sprintf("%s\n- %s", availableVersions, *offer.Version)
|
||||
continue
|
||||
}
|
||||
isValidVersion = true
|
||||
|
||||
for _, plan := range *offer.Plans {
|
||||
if plan.Name == nil {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(*plan.Name, planName) && plan.Id != nil {
|
||||
model.PlanId = types.StringPointerValue(plan.Id)
|
||||
return nil
|
||||
}
|
||||
availablePlanNames = fmt.Sprintf("%s\n- %s", availablePlanNames, *plan.Name)
|
||||
}
|
||||
}
|
||||
|
||||
if !isValidVersion {
|
||||
return fmt.Errorf("couldn't find version '%s', available versions are: %s", version, availableVersions)
|
||||
}
|
||||
return fmt.Errorf("couldn't find plan_name '%s' for version %s, available names are: %s", planName, version, availablePlanNames)
|
||||
}
|
||||
|
||||
func loadPlanNameAndVersion(ctx context.Context, client *opensearch.APIClient, model *Model) error {
|
||||
projectId := model.ProjectId.ValueString()
|
||||
planId := model.PlanId.ValueString()
|
||||
res, err := client.GetOfferings(ctx, projectId).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting OpenSearch offerings: %w", err)
|
||||
}
|
||||
|
||||
for _, offer := range *res.Offerings {
|
||||
for _, plan := range *offer.Plans {
|
||||
if strings.EqualFold(*plan.Id, planId) && plan.Id != nil {
|
||||
model.PlanName = types.StringPointerValue(plan.Name)
|
||||
model.Version = types.StringPointerValue(offer.Version)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("couldn't find plan_name and version for plan_id '%s'", planId)
|
||||
}
|
||||
304
stackit/internal/services/opensearch/instance/resource_test.go
Normal file
304
stackit/internal/services/opensearch/instance/resource_test.go
Normal file
|
|
@ -0,0 +1,304 @@
|
|||
package opensearch
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/opensearch"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *opensearch.Instance
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&opensearch.Instance{},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
PlanId: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
CfGuid: types.StringNull(),
|
||||
CfSpaceGuid: types.StringNull(),
|
||||
DashboardUrl: types.StringNull(),
|
||||
ImageUrl: types.StringNull(),
|
||||
CfOrganizationGuid: types.StringNull(),
|
||||
Parameters: types.ObjectNull(parametersTypes),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&opensearch.Instance{
|
||||
PlanId: utils.Ptr("plan"),
|
||||
CfGuid: utils.Ptr("cf"),
|
||||
CfSpaceGuid: utils.Ptr("space"),
|
||||
DashboardUrl: utils.Ptr("dashboard"),
|
||||
ImageUrl: utils.Ptr("image"),
|
||||
InstanceId: utils.Ptr("iid"),
|
||||
Name: utils.Ptr("name"),
|
||||
CfOrganizationGuid: utils.Ptr("org"),
|
||||
Parameters: &map[string]interface{}{
|
||||
"sgw_acl": "acl",
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
PlanId: types.StringValue("plan"),
|
||||
Name: types.StringValue("name"),
|
||||
CfGuid: types.StringValue("cf"),
|
||||
CfSpaceGuid: types.StringValue("space"),
|
||||
DashboardUrl: types.StringValue("dashboard"),
|
||||
ImageUrl: types.StringValue("image"),
|
||||
CfOrganizationGuid: types.StringValue("org"),
|
||||
Parameters: types.ObjectValueMust(parametersTypes, map[string]attr.Value{
|
||||
"sgw_acl": types.StringValue("acl"),
|
||||
}),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&opensearch.Instance{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"wrong_param_types_1",
|
||||
&opensearch.Instance{
|
||||
Parameters: &map[string]interface{}{
|
||||
"sgw_acl": true,
|
||||
},
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"wrong_param_types_2",
|
||||
&opensearch.Instance{
|
||||
Parameters: &map[string]interface{}{
|
||||
"sgw_acl": 1,
|
||||
},
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
state := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
}
|
||||
err := mapFields(tt.input, state)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputParameters *parametersModel
|
||||
expected *opensearch.CreateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
¶metersModel{},
|
||||
&opensearch.CreateInstancePayload{
|
||||
Parameters: &opensearch.InstanceParameters{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
Name: types.StringValue("name"),
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
¶metersModel{
|
||||
SgwAcl: types.StringValue("sgw"),
|
||||
},
|
||||
&opensearch.CreateInstancePayload{
|
||||
InstanceName: utils.Ptr("name"),
|
||||
Parameters: &opensearch.InstanceParameters{
|
||||
SgwAcl: utils.Ptr("sgw"),
|
||||
},
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
Name: types.StringValue(""),
|
||||
PlanId: types.StringValue(""),
|
||||
},
|
||||
¶metersModel{
|
||||
SgwAcl: types.StringNull(),
|
||||
},
|
||||
&opensearch.CreateInstancePayload{
|
||||
InstanceName: utils.Ptr(""),
|
||||
Parameters: &opensearch.InstanceParameters{
|
||||
SgwAcl: nil,
|
||||
},
|
||||
PlanId: utils.Ptr(""),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
¶metersModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_parameters",
|
||||
&Model{
|
||||
Name: types.StringValue("name"),
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
nil,
|
||||
&opensearch.CreateInstancePayload{
|
||||
InstanceName: utils.Ptr("name"),
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toCreatePayload(tt.input, tt.inputParameters)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToUpdatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputParameters *parametersModel
|
||||
expected *opensearch.UpdateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
¶metersModel{},
|
||||
&opensearch.UpdateInstancePayload{
|
||||
Parameters: &opensearch.InstanceParameters{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
¶metersModel{
|
||||
SgwAcl: types.StringValue("sgw"),
|
||||
},
|
||||
&opensearch.UpdateInstancePayload{
|
||||
Parameters: &opensearch.InstanceParameters{
|
||||
SgwAcl: utils.Ptr("sgw"),
|
||||
},
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
PlanId: types.StringValue(""),
|
||||
},
|
||||
¶metersModel{
|
||||
SgwAcl: types.StringNull(),
|
||||
},
|
||||
&opensearch.UpdateInstancePayload{
|
||||
Parameters: &opensearch.InstanceParameters{
|
||||
SgwAcl: nil,
|
||||
},
|
||||
PlanId: utils.Ptr(""),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
¶metersModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_parameters",
|
||||
&Model{
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
nil,
|
||||
&opensearch.UpdateInstancePayload{
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toUpdatePayload(tt.input, tt.inputParameters)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
269
stackit/internal/services/opensearch/opensearch_acc_test.go
Normal file
269
stackit/internal/services/opensearch/opensearch_acc_test.go
Normal file
|
|
@ -0,0 +1,269 @@
|
|||
package opensearch_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
|
||||
"github.com/hashicorp/terraform-plugin-testing/terraform"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/opensearch"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/testutil"
|
||||
)
|
||||
|
||||
// Instance resource data
|
||||
var instanceResource = map[string]string{
|
||||
"project_id": testutil.ProjectId,
|
||||
"name": testutil.ResourceNameWithDateTime("opensearch"),
|
||||
"plan_id": "9e4eac4b-b03d-4d7b-b01b-6d1224aa2d68",
|
||||
"plan_name": "stackit-qa-opensearch-1.2.10-replica",
|
||||
"version": "2",
|
||||
"sgw_acl": "192.168.0.0/24",
|
||||
}
|
||||
|
||||
func resourceConfig() string {
|
||||
return fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
resource "stackit_opensearch_instance" "instance" {
|
||||
project_id = "%s"
|
||||
name = "%s"
|
||||
plan_name = "%s"
|
||||
version = "%s"
|
||||
}
|
||||
|
||||
resource "stackit_opensearch_credentials" "credentials" {
|
||||
project_id = stackit_opensearch_instance.instance.project_id
|
||||
instance_id = stackit_opensearch_instance.instance.instance_id
|
||||
}
|
||||
`,
|
||||
testutil.OpenSearchProviderConfig(),
|
||||
instanceResource["project_id"],
|
||||
instanceResource["name"],
|
||||
instanceResource["plan_name"],
|
||||
instanceResource["version"],
|
||||
)
|
||||
}
|
||||
|
||||
func resourceConfigUpdate() string {
|
||||
return fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
resource "stackit_opensearch_instance" "instance" {
|
||||
project_id = "%s"
|
||||
name = "%s"
|
||||
plan_name = "%s"
|
||||
version = "%s"
|
||||
parameters = {
|
||||
sgw_acl = "%s"
|
||||
}
|
||||
}
|
||||
|
||||
resource "stackit_opensearch_credentials" "credentials" {
|
||||
project_id = stackit_opensearch_instance.instance.project_id
|
||||
instance_id = stackit_opensearch_instance.instance.instance_id
|
||||
}
|
||||
`,
|
||||
testutil.OpenSearchProviderConfig(),
|
||||
instanceResource["project_id"],
|
||||
instanceResource["name"],
|
||||
instanceResource["plan_name"],
|
||||
instanceResource["version"],
|
||||
instanceResource["sgw_acl"],
|
||||
)
|
||||
}
|
||||
|
||||
func TestAccOpenSearchResource(t *testing.T) {
|
||||
resource.Test(t, resource.TestCase{
|
||||
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
|
||||
CheckDestroy: testAccCheckOpenSearchDestroy,
|
||||
Steps: []resource.TestStep{
|
||||
|
||||
// Creation
|
||||
{
|
||||
Config: resourceConfig(),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("stackit_opensearch_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_opensearch_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_opensearch_instance.instance", "plan_id", instanceResource["plan_id"]),
|
||||
resource.TestCheckResourceAttr("stackit_opensearch_instance.instance", "plan_name", instanceResource["plan_name"]),
|
||||
resource.TestCheckResourceAttr("stackit_opensearch_instance.instance", "version", instanceResource["version"]),
|
||||
resource.TestCheckResourceAttr("stackit_opensearch_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_opensearch_instance.instance", "parameters.sgw_acl"),
|
||||
|
||||
// Credentials data
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_opensearch_credentials.credentials", "project_id",
|
||||
"stackit_opensearch_instance.instance", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_opensearch_credentials.credentials", "instance_id",
|
||||
"stackit_opensearch_instance.instance", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrSet("stackit_opensearch_credentials.credentials", "credentials_id"),
|
||||
resource.TestCheckResourceAttrSet("stackit_opensearch_credentials.credentials", "host"),
|
||||
),
|
||||
},
|
||||
// Data source
|
||||
{
|
||||
Config: fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
data "stackit_opensearch_instance" "instance" {
|
||||
project_id = stackit_opensearch_instance.instance.project_id
|
||||
instance_id = stackit_opensearch_instance.instance.instance_id
|
||||
}
|
||||
|
||||
data "stackit_opensearch_credentials" "credentials" {
|
||||
project_id = stackit_opensearch_credentials.credentials.project_id
|
||||
instance_id = stackit_opensearch_credentials.credentials.instance_id
|
||||
credentials_id = stackit_opensearch_credentials.credentials.credentials_id
|
||||
}`,
|
||||
resourceConfig(),
|
||||
),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("data.stackit_opensearch_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrPair("stackit_opensearch_instance.instance", "instance_id",
|
||||
"data.stackit_opensearch_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttrPair("stackit_opensearch_credentials.credentials", "credentials_id",
|
||||
"data.stackit_opensearch_credentials.credentials", "credentials_id"),
|
||||
resource.TestCheckResourceAttr("data.stackit_opensearch_instance.instance", "plan_id", instanceResource["plan_id"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_opensearch_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_opensearch_instance.instance", "parameters.sgw_acl"),
|
||||
|
||||
// Credentials data
|
||||
resource.TestCheckResourceAttr("data.stackit_opensearch_credentials.credentials", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_opensearch_credentials.credentials", "credentials_id"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_opensearch_credentials.credentials", "host"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_opensearch_credentials.credentials", "port"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_opensearch_credentials.credentials", "uri"),
|
||||
),
|
||||
},
|
||||
// Import
|
||||
{
|
||||
ResourceName: "stackit_opensearch_instance.instance",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_opensearch_instance.instance"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_opensearch_instance.instance")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s,%s", testutil.ProjectId, instanceId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
{
|
||||
ResourceName: "stackit_opensearch_credentials.credentials",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_opensearch_credentials.credentials"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_opensearch_credentials.credentials")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
credentialsId, ok := r.Primary.Attributes["credentials_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute credentials_id")
|
||||
}
|
||||
return fmt.Sprintf("%s,%s,%s", testutil.ProjectId, instanceId, credentialsId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
// Update
|
||||
{
|
||||
Config: resourceConfigUpdate(),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("stackit_opensearch_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_opensearch_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_opensearch_instance.instance", "plan_id", instanceResource["plan_id"]),
|
||||
resource.TestCheckResourceAttr("stackit_opensearch_instance.instance", "plan_name", instanceResource["plan_name"]),
|
||||
resource.TestCheckResourceAttr("stackit_opensearch_instance.instance", "version", instanceResource["version"]),
|
||||
resource.TestCheckResourceAttr("stackit_opensearch_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_opensearch_instance.instance", "parameters.sgw_acl", instanceResource["sgw_acl"]),
|
||||
),
|
||||
},
|
||||
// Deletion is done by the framework implicitly
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func testAccCheckOpenSearchDestroy(s *terraform.State) error {
|
||||
ctx := context.Background()
|
||||
var client *opensearch.APIClient
|
||||
var err error
|
||||
if testutil.OpenSearchCustomEndpoint == "" {
|
||||
client, err = opensearch.NewAPIClient()
|
||||
} else {
|
||||
client, err = opensearch.NewAPIClient(
|
||||
config.WithEndpoint(testutil.OpenSearchCustomEndpoint),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating client: %w", err)
|
||||
}
|
||||
|
||||
instancesToDestroy := []string{}
|
||||
for _, rs := range s.RootModule().Resources {
|
||||
if rs.Type != "stackit_opensearch_instance" {
|
||||
continue
|
||||
}
|
||||
// instance terraform ID: "[project_id],[instance_id]"
|
||||
instanceId := strings.Split(rs.Primary.ID, core.Separator)[1]
|
||||
instancesToDestroy = append(instancesToDestroy, instanceId)
|
||||
}
|
||||
|
||||
instancesResp, err := client.GetInstances(ctx, testutil.ProjectId).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting instancesResp: %w", err)
|
||||
}
|
||||
|
||||
instances := *instancesResp.Instances
|
||||
for i := range instances {
|
||||
if instances[i].InstanceId == nil {
|
||||
continue
|
||||
}
|
||||
if utils.Contains(instancesToDestroy, *instances[i].InstanceId) {
|
||||
if !checkInstanceDeleteSuccess(&instances[i]) {
|
||||
err := client.DeleteInstanceExecute(ctx, testutil.ProjectId, *instances[i].InstanceId)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying instance %s during CheckDestroy: %w", *instances[i].InstanceId, err)
|
||||
}
|
||||
_, err = opensearch.DeleteInstanceWaitHandler(ctx, client, testutil.ProjectId, *instances[i].InstanceId).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying instance %s during CheckDestroy: waiting for deletion %w", *instances[i].InstanceId, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkInstanceDeleteSuccess(i *opensearch.Instance) bool {
|
||||
if *i.LastOperation.Type != opensearch.InstanceTypeDelete {
|
||||
return false
|
||||
}
|
||||
|
||||
if *i.LastOperation.Type == opensearch.InstanceTypeDelete {
|
||||
if *i.LastOperation.State != opensearch.InstanceStateSuccess {
|
||||
return false
|
||||
} else if strings.Contains(*i.LastOperation.Description, "DeleteFailed") || strings.Contains(*i.LastOperation.Description, "failed") {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
208
stackit/internal/services/postgresflex/instance/datasource.go
Normal file
208
stackit/internal/services/postgresflex/instance/datasource.go
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
package postgresflex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &instanceDataSource{}
|
||||
)
|
||||
|
||||
// NewInstanceDataSource is a helper function to simplify the provider implementation.
|
||||
func NewInstanceDataSource() datasource.DataSource {
|
||||
return &instanceDataSource{}
|
||||
}
|
||||
|
||||
// instanceDataSource is the data source implementation.
|
||||
type instanceDataSource struct {
|
||||
client *postgresflex.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *instanceDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_postgresflex_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *instanceDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *postgresflex.APIClient
|
||||
var err error
|
||||
if providerData.PostgresFlexCustomEndpoint != "" {
|
||||
apiClient, err = postgresflex.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.PostgresFlexCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = postgresflex.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "PostgresFlex instance client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "PostgresFlex instance data source schema.",
|
||||
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`\".",
|
||||
"instance_id": "ID of the PostgresFlex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"name": "Instance name.",
|
||||
"acl": "The Access Control List (ACL) for the PostgresFlex instance.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Computed: true,
|
||||
},
|
||||
"acl": schema.ListAttribute{
|
||||
Description: descriptions["acl"],
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"backup_schedule": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"flavor": schema.SingleNestedAttribute{
|
||||
Computed: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"description": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"cpu": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"ram": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
"replicas": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"storage": schema.SingleNestedAttribute{
|
||||
Computed: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"class": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"size": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
"version": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *instanceDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
var flavor = &flavorModel{}
|
||||
if !(model.Flavor.IsNull() || model.Flavor.IsUnknown()) {
|
||||
diags = model.Flavor.As(ctx, flavor, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
var storage = &storageModel{}
|
||||
if !(model.Storage.IsNull() || model.Storage.IsUnknown()) {
|
||||
diags = model.Storage.As(ctx, storage, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err = mapFields(instanceResp, &model, flavor, storage)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgresFlex instance read")
|
||||
}
|
||||
708
stackit/internal/services/postgresflex/instance/resource.go
Normal file
708
stackit/internal/services/postgresflex/instance/resource.go
Normal file
|
|
@ -0,0 +1,708 @@
|
|||
package postgresflex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/diag"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &instanceResource{}
|
||||
_ resource.ResourceWithConfigure = &instanceResource{}
|
||||
_ resource.ResourceWithImportState = &instanceResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
ACL types.List `tfsdk:"acl"`
|
||||
BackupSchedule types.String `tfsdk:"backup_schedule"`
|
||||
Flavor types.Object `tfsdk:"flavor"`
|
||||
Replicas types.Int64 `tfsdk:"replicas"`
|
||||
Storage types.Object `tfsdk:"storage"`
|
||||
Version types.String `tfsdk:"version"`
|
||||
}
|
||||
|
||||
// Struct corresponding to Model.Flavor
|
||||
type flavorModel struct {
|
||||
Id types.String `tfsdk:"id"`
|
||||
Description types.String `tfsdk:"description"`
|
||||
CPU types.Int64 `tfsdk:"cpu"`
|
||||
RAM types.Int64 `tfsdk:"ram"`
|
||||
}
|
||||
|
||||
// Types corresponding to flavorModel
|
||||
var flavorTypes = map[string]attr.Type{
|
||||
"id": basetypes.StringType{},
|
||||
"description": basetypes.StringType{},
|
||||
"cpu": basetypes.Int64Type{},
|
||||
"ram": basetypes.Int64Type{},
|
||||
}
|
||||
|
||||
// Struct corresponding to DataSourceModel.Storage
|
||||
type storageModel struct {
|
||||
Class types.String `tfsdk:"class"`
|
||||
Size types.Int64 `tfsdk:"size"`
|
||||
}
|
||||
|
||||
// Types corresponding to storageModel
|
||||
var storageTypes = map[string]attr.Type{
|
||||
"class": basetypes.StringType{},
|
||||
"size": basetypes.Int64Type{},
|
||||
}
|
||||
|
||||
// NewInstanceResource is a helper function to simplify the provider implementation.
|
||||
func NewInstanceResource() resource.Resource {
|
||||
return &instanceResource{}
|
||||
}
|
||||
|
||||
// instanceResource is the resource implementation.
|
||||
type instanceResource struct {
|
||||
client *postgresflex.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *instanceResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_postgresflex_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *instanceResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *postgresflex.APIClient
|
||||
var err error
|
||||
if providerData.PostgresFlexCustomEndpoint != "" {
|
||||
apiClient, err = postgresflex.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.PostgresFlexCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = postgresflex.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "PostgresFlex instance client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *instanceResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "PostgresFlex instance resource schema.",
|
||||
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`\".",
|
||||
"instance_id": "ID of the PostgresFlex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"name": "Instance name.",
|
||||
"acl": "The Access Control List (ACL) for the PostgresFlex instance.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
stringvalidator.RegexMatches(
|
||||
regexp.MustCompile("^[a-z]([-a-z0-9]*[a-z0-9])?$"),
|
||||
"must start with a letter, must have lower case letters, numbers or hyphens, and no hyphen at the end",
|
||||
),
|
||||
},
|
||||
},
|
||||
"acl": schema.ListAttribute{
|
||||
Description: descriptions["acl"],
|
||||
ElementType: types.StringType,
|
||||
Required: true,
|
||||
},
|
||||
"backup_schedule": schema.StringAttribute{
|
||||
Required: true,
|
||||
},
|
||||
"flavor": schema.SingleNestedAttribute{
|
||||
Required: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"description": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"cpu": schema.Int64Attribute{
|
||||
Required: true,
|
||||
},
|
||||
"ram": schema.Int64Attribute{
|
||||
Required: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
"replicas": schema.Int64Attribute{
|
||||
Required: true,
|
||||
},
|
||||
"storage": schema.SingleNestedAttribute{
|
||||
Required: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"class": schema.StringAttribute{
|
||||
Required: true,
|
||||
},
|
||||
"size": schema.Int64Attribute{
|
||||
Required: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
"version": schema.StringAttribute{
|
||||
Required: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *instanceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
|
||||
var acl []string
|
||||
if !(model.ACL.IsNull() || model.ACL.IsUnknown()) {
|
||||
diags = model.ACL.ElementsAs(ctx, &acl, false)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
var flavor = &flavorModel{}
|
||||
if !(model.Flavor.IsNull() || model.Flavor.IsUnknown()) {
|
||||
diags = model.Flavor.As(ctx, flavor, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
r.loadFlavorId(ctx, &resp.Diagnostics, &model, flavor)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
var storage = &storageModel{}
|
||||
if !(model.Storage.IsNull() || model.Storage.IsUnknown()) {
|
||||
diags = model.Storage.As(ctx, storage, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model, acl, flavor, storage)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Create new instance
|
||||
createResp, err := r.client.CreateInstance(ctx, projectId).CreateInstancePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
instanceId := *createResp.Id
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
wr, err := postgresflex.CreateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Instance creation waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*postgresflex.InstanceResponse)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model, flavor, storage)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgresFlex instance created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
var flavor = &flavorModel{}
|
||||
if !(model.Flavor.IsNull() || model.Flavor.IsUnknown()) {
|
||||
diags = model.Flavor.As(ctx, flavor, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
var storage = &storageModel{}
|
||||
if !(model.Storage.IsNull() || model.Storage.IsUnknown()) {
|
||||
diags = model.Storage.As(ctx, storage, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(instanceResp, &model, flavor, storage)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgresFlex instance read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *instanceResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
var acl []string
|
||||
if !(model.ACL.IsNull() || model.ACL.IsUnknown()) {
|
||||
diags = model.ACL.ElementsAs(ctx, &acl, false)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
var flavor = &flavorModel{}
|
||||
if !(model.Flavor.IsNull() || model.Flavor.IsUnknown()) {
|
||||
diags = model.Flavor.As(ctx, flavor, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
r.loadFlavorId(ctx, &resp.Diagnostics, &model, flavor)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
var storage = &storageModel{}
|
||||
if !(model.Storage.IsNull() || model.Storage.IsUnknown()) {
|
||||
diags = model.Storage.As(ctx, storage, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toUpdatePayload(&model, acl, flavor, storage)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Update existing instance
|
||||
_, err = r.client.UpdateInstance(ctx, projectId, instanceId).UpdateInstancePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", err.Error())
|
||||
return
|
||||
}
|
||||
wr, err := postgresflex.UpdateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Instance update waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*postgresflex.InstanceResponse)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model, flavor, storage)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields in update", err.Error())
|
||||
return
|
||||
}
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Postgresflex instance updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *instanceResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from state
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
// Delete existing instance
|
||||
err := r.client.DeleteInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
_, err = postgresflex.DeleteInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgresFlex instance deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,instance_id
|
||||
func (r *instanceResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
|
||||
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing instance",
|
||||
fmt.Sprintf("Expected import identifier with format: [project_id],[instance_id] Got: %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[1])...)
|
||||
tflog.Info(ctx, "Postgresql instance state imported")
|
||||
}
|
||||
|
||||
func mapFields(resp *postgresflex.InstanceResponse, model *Model, flavor *flavorModel, storage *storageModel) error {
|
||||
if resp == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if resp.Item == nil {
|
||||
return fmt.Errorf("no instance provided")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
instance := resp.Item
|
||||
|
||||
var instanceId string
|
||||
if model.InstanceId.ValueString() != "" {
|
||||
instanceId = model.InstanceId.ValueString()
|
||||
} else if instance.Id != nil {
|
||||
instanceId = *instance.Id
|
||||
} else {
|
||||
return fmt.Errorf("instance id not present")
|
||||
}
|
||||
|
||||
var aclList basetypes.ListValue
|
||||
var diags diag.Diagnostics
|
||||
if instance.Acl == nil || instance.Acl.Items == nil {
|
||||
aclList = types.ListNull(types.StringType)
|
||||
} else {
|
||||
acl := []attr.Value{}
|
||||
for _, ip := range *instance.Acl.Items {
|
||||
acl = append(acl, types.StringValue(ip))
|
||||
}
|
||||
aclList, diags = types.ListValue(types.StringType, acl)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map ACL: %w", core.DiagsToError(diags))
|
||||
}
|
||||
}
|
||||
|
||||
var flavorValues map[string]attr.Value
|
||||
if instance.Flavor == nil {
|
||||
flavorValues = map[string]attr.Value{
|
||||
"id": types.StringNull(),
|
||||
"description": types.StringNull(),
|
||||
"cpu": flavor.CPU,
|
||||
"ram": flavor.RAM,
|
||||
}
|
||||
} else {
|
||||
flavorValues = map[string]attr.Value{
|
||||
"id": types.StringValue(*instance.Flavor.Id),
|
||||
"description": types.StringValue(*instance.Flavor.Description),
|
||||
"cpu": types.Int64Value(int64(*instance.Flavor.Cpu)),
|
||||
"ram": types.Int64Value(int64(*instance.Flavor.Memory)),
|
||||
}
|
||||
}
|
||||
flavorObject, diags := types.ObjectValue(flavorTypes, flavorValues)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to create flavor: %w", core.DiagsToError(diags))
|
||||
}
|
||||
|
||||
var storageValues map[string]attr.Value
|
||||
if instance.Storage == nil {
|
||||
storageValues = map[string]attr.Value{
|
||||
"class": storage.Class,
|
||||
"size": storage.Size,
|
||||
}
|
||||
} else {
|
||||
storageValues = map[string]attr.Value{
|
||||
"class": types.StringValue(*instance.Storage.Class),
|
||||
"size": types.Int64Value(int64(*instance.Storage.Size)),
|
||||
}
|
||||
}
|
||||
storageObject, diags := types.ObjectValue(storageTypes, storageValues)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to create storage: %w", core.DiagsToError(diags))
|
||||
}
|
||||
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
instanceId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.InstanceId = types.StringValue(instanceId)
|
||||
if instance.Name == nil {
|
||||
model.Name = types.StringNull()
|
||||
} else {
|
||||
model.Name = types.StringValue(*instance.Name)
|
||||
}
|
||||
model.ACL = aclList
|
||||
if instance.BackupSchedule == nil {
|
||||
model.BackupSchedule = types.StringNull()
|
||||
} else {
|
||||
model.BackupSchedule = types.StringValue(*instance.BackupSchedule)
|
||||
}
|
||||
model.Flavor = flavorObject
|
||||
if instance.Replicas == nil {
|
||||
model.Replicas = types.Int64Null()
|
||||
} else {
|
||||
model.Replicas = types.Int64Value(int64(*instance.Replicas))
|
||||
}
|
||||
model.Storage = storageObject
|
||||
if instance.Version == nil {
|
||||
model.Version = types.StringNull()
|
||||
} else {
|
||||
model.Version = types.StringValue(*instance.Version)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model, acl []string, flavor *flavorModel, storage *storageModel) (*postgresflex.CreateInstancePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
if acl == nil {
|
||||
return nil, fmt.Errorf("nil acl")
|
||||
}
|
||||
if flavor == nil {
|
||||
return nil, fmt.Errorf("nil flavor")
|
||||
}
|
||||
if storage == nil {
|
||||
return nil, fmt.Errorf("nil storage")
|
||||
}
|
||||
|
||||
return &postgresflex.CreateInstancePayload{
|
||||
Acl: &postgresflex.InstanceAcl{
|
||||
Items: &acl,
|
||||
},
|
||||
BackupSchedule: model.BackupSchedule.ValueStringPointer(),
|
||||
FlavorId: flavor.Id.ValueStringPointer(),
|
||||
Name: model.Name.ValueStringPointer(),
|
||||
Replicas: conversion.ToPtrInt32(model.Replicas),
|
||||
Storage: &postgresflex.InstanceStorage{
|
||||
Class: storage.Class.ValueStringPointer(),
|
||||
Size: conversion.ToPtrInt32(storage.Size),
|
||||
},
|
||||
Version: model.Version.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toUpdatePayload(model *Model, acl []string, flavor *flavorModel, storage *storageModel) (*postgresflex.UpdateInstancePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
if acl == nil {
|
||||
return nil, fmt.Errorf("nil acl")
|
||||
}
|
||||
if flavor == nil {
|
||||
return nil, fmt.Errorf("nil flavor")
|
||||
}
|
||||
if storage == nil {
|
||||
return nil, fmt.Errorf("nil storage")
|
||||
}
|
||||
|
||||
return &postgresflex.UpdateInstancePayload{
|
||||
Acl: &postgresflex.InstanceAcl{
|
||||
Items: &acl,
|
||||
},
|
||||
BackupSchedule: model.BackupSchedule.ValueStringPointer(),
|
||||
FlavorId: flavor.Id.ValueStringPointer(),
|
||||
Name: model.Name.ValueStringPointer(),
|
||||
Replicas: conversion.ToPtrInt32(model.Replicas),
|
||||
Storage: &postgresflex.InstanceStorage{
|
||||
Class: storage.Class.ValueStringPointer(),
|
||||
Size: conversion.ToPtrInt32(storage.Size),
|
||||
},
|
||||
Version: model.Version.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *instanceResource) loadFlavorId(ctx context.Context, diags *diag.Diagnostics, model *Model, flavor *flavorModel) {
|
||||
if model == nil {
|
||||
diags.AddError("invalid model", "nil model")
|
||||
return
|
||||
}
|
||||
if flavor == nil {
|
||||
diags.AddError("invalid flavor", "nil flavor")
|
||||
return
|
||||
}
|
||||
cpu := conversion.ToPtrInt32(flavor.CPU)
|
||||
if cpu == nil {
|
||||
diags.AddError("invalid flavor", "nil CPU")
|
||||
return
|
||||
}
|
||||
ram := conversion.ToPtrInt32(flavor.RAM)
|
||||
if ram == nil {
|
||||
diags.AddError("invalid flavor", "nil RAM")
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
res, err := r.client.GetFlavors(ctx, projectId).Execute()
|
||||
if err != nil {
|
||||
diags.AddError("failed to list postgresflex flavors", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
avl := ""
|
||||
if res.Flavors == nil {
|
||||
diags.AddError("no flavors", fmt.Sprintf("couldn't find flavors for id %s", flavor.Id.ValueString()))
|
||||
return
|
||||
}
|
||||
for _, f := range *res.Flavors {
|
||||
if f.Id == nil || f.Cpu == nil || f.Memory == nil {
|
||||
continue
|
||||
}
|
||||
if *f.Cpu == *cpu && *f.Memory == *ram {
|
||||
flavor.Id = types.StringValue(*f.Id)
|
||||
break
|
||||
}
|
||||
avl = fmt.Sprintf("%s\n- %d CPU, %d GB RAM", avl, *f.Cpu, *f.Cpu)
|
||||
}
|
||||
if flavor.Id.ValueString() == "" {
|
||||
diags.AddError("invalid flavor", fmt.Sprintf("couldn't find flavor.\navailable specs are:%s", avl))
|
||||
return
|
||||
}
|
||||
}
|
||||
509
stackit/internal/services/postgresflex/instance/resource_test.go
Normal file
509
stackit/internal/services/postgresflex/instance/resource_test.go
Normal file
|
|
@ -0,0 +1,509 @@
|
|||
package postgresflex
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *postgresflex.InstanceResponse
|
||||
flavor *flavorModel
|
||||
storage *storageModel
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&postgresflex.InstanceResponse{
|
||||
Item: &postgresflex.InstanceSingleInstance{},
|
||||
},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringNull(),
|
||||
ACL: types.ListNull(types.StringType),
|
||||
BackupSchedule: types.StringNull(),
|
||||
Flavor: types.ObjectValueMust(flavorTypes, map[string]attr.Value{
|
||||
"id": types.StringNull(),
|
||||
"description": types.StringNull(),
|
||||
"cpu": types.Int64Null(),
|
||||
"ram": types.Int64Null(),
|
||||
}),
|
||||
Replicas: types.Int64Null(),
|
||||
Storage: types.ObjectValueMust(storageTypes, map[string]attr.Value{
|
||||
"class": types.StringNull(),
|
||||
"size": types.Int64Null(),
|
||||
}),
|
||||
Version: types.StringNull(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&postgresflex.InstanceResponse{
|
||||
Item: &postgresflex.InstanceSingleInstance{
|
||||
Acl: &postgresflex.InstanceAcl{
|
||||
Items: &[]string{
|
||||
"ip1",
|
||||
"ip2",
|
||||
"",
|
||||
},
|
||||
},
|
||||
BackupSchedule: utils.Ptr("schedule"),
|
||||
Flavor: &postgresflex.InstanceFlavor{
|
||||
Cpu: utils.Ptr(int32(12)),
|
||||
Description: utils.Ptr("description"),
|
||||
Id: utils.Ptr("flavor_id"),
|
||||
Memory: utils.Ptr(int32(34)),
|
||||
},
|
||||
Id: utils.Ptr("iid"),
|
||||
Name: utils.Ptr("name"),
|
||||
Replicas: utils.Ptr(int32(56)),
|
||||
Status: utils.Ptr("status"),
|
||||
Storage: &postgresflex.InstanceStorage{
|
||||
Class: utils.Ptr("class"),
|
||||
Size: utils.Ptr(int32(78)),
|
||||
},
|
||||
Version: utils.Ptr("version"),
|
||||
},
|
||||
},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringValue("name"),
|
||||
ACL: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("ip1"),
|
||||
types.StringValue("ip2"),
|
||||
types.StringValue(""),
|
||||
}),
|
||||
BackupSchedule: types.StringValue("schedule"),
|
||||
Flavor: types.ObjectValueMust(flavorTypes, map[string]attr.Value{
|
||||
"id": types.StringValue("flavor_id"),
|
||||
"description": types.StringValue("description"),
|
||||
"cpu": types.Int64Value(12),
|
||||
"ram": types.Int64Value(34),
|
||||
}),
|
||||
Replicas: types.Int64Value(56),
|
||||
Storage: types.ObjectValueMust(storageTypes, map[string]attr.Value{
|
||||
"class": types.StringValue("class"),
|
||||
"size": types.Int64Value(78),
|
||||
}),
|
||||
Version: types.StringValue("version"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values_no_flavor_and_storage",
|
||||
&postgresflex.InstanceResponse{
|
||||
Item: &postgresflex.InstanceSingleInstance{
|
||||
Acl: &postgresflex.InstanceAcl{
|
||||
Items: &[]string{
|
||||
"ip1",
|
||||
"ip2",
|
||||
"",
|
||||
},
|
||||
},
|
||||
BackupSchedule: utils.Ptr("schedule"),
|
||||
Flavor: nil,
|
||||
Id: utils.Ptr("iid"),
|
||||
Name: utils.Ptr("name"),
|
||||
Replicas: utils.Ptr(int32(56)),
|
||||
Status: utils.Ptr("status"),
|
||||
Storage: nil,
|
||||
Version: utils.Ptr("version"),
|
||||
},
|
||||
},
|
||||
&flavorModel{
|
||||
CPU: types.Int64Value(12),
|
||||
RAM: types.Int64Value(34),
|
||||
},
|
||||
&storageModel{
|
||||
Class: types.StringValue("class"),
|
||||
Size: types.Int64Value(78),
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringValue("name"),
|
||||
ACL: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("ip1"),
|
||||
types.StringValue("ip2"),
|
||||
types.StringValue(""),
|
||||
}),
|
||||
BackupSchedule: types.StringValue("schedule"),
|
||||
Flavor: types.ObjectValueMust(flavorTypes, map[string]attr.Value{
|
||||
"id": types.StringNull(),
|
||||
"description": types.StringNull(),
|
||||
"cpu": types.Int64Value(12),
|
||||
"ram": types.Int64Value(34),
|
||||
}),
|
||||
Replicas: types.Int64Value(56),
|
||||
Storage: types.ObjectValueMust(storageTypes, map[string]attr.Value{
|
||||
"class": types.StringValue("class"),
|
||||
"size": types.Int64Value(78),
|
||||
}),
|
||||
Version: types.StringValue("version"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&postgresflex.InstanceResponse{},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
state := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
}
|
||||
err := mapFields(tt.input, state, tt.flavor, tt.storage)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputAcl []string
|
||||
inputFlavor *flavorModel
|
||||
inputStorage *storageModel
|
||||
expected *postgresflex.CreateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
[]string{},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
&postgresflex.CreateInstancePayload{
|
||||
Acl: &postgresflex.InstanceAcl{
|
||||
Items: &[]string{},
|
||||
},
|
||||
Storage: &postgresflex.InstanceStorage{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
BackupSchedule: types.StringValue("schedule"),
|
||||
Name: types.StringValue("name"),
|
||||
Replicas: types.Int64Value(12),
|
||||
Version: types.StringValue("version"),
|
||||
},
|
||||
[]string{
|
||||
"ip_1",
|
||||
"ip_2",
|
||||
},
|
||||
&flavorModel{
|
||||
Id: types.StringValue("flavor_id"),
|
||||
},
|
||||
&storageModel{
|
||||
Class: types.StringValue("class"),
|
||||
Size: types.Int64Value(34),
|
||||
},
|
||||
&postgresflex.CreateInstancePayload{
|
||||
Acl: &postgresflex.InstanceAcl{
|
||||
Items: &[]string{
|
||||
"ip_1",
|
||||
"ip_2",
|
||||
},
|
||||
},
|
||||
BackupSchedule: utils.Ptr("schedule"),
|
||||
FlavorId: utils.Ptr("flavor_id"),
|
||||
Name: utils.Ptr("name"),
|
||||
Replicas: utils.Ptr(int32(12)),
|
||||
Storage: &postgresflex.InstanceStorage{
|
||||
Class: utils.Ptr("class"),
|
||||
Size: utils.Ptr(int32(34)),
|
||||
},
|
||||
Version: utils.Ptr("version"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
BackupSchedule: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Replicas: types.Int64Value(2123456789),
|
||||
Version: types.StringNull(),
|
||||
},
|
||||
[]string{
|
||||
"",
|
||||
},
|
||||
&flavorModel{
|
||||
Id: types.StringNull(),
|
||||
},
|
||||
&storageModel{
|
||||
Class: types.StringNull(),
|
||||
Size: types.Int64Null(),
|
||||
},
|
||||
&postgresflex.CreateInstancePayload{
|
||||
Acl: &postgresflex.InstanceAcl{
|
||||
Items: &[]string{
|
||||
"",
|
||||
},
|
||||
},
|
||||
BackupSchedule: nil,
|
||||
FlavorId: nil,
|
||||
Name: nil,
|
||||
Replicas: utils.Ptr(int32(2123456789)),
|
||||
Storage: &postgresflex.InstanceStorage{
|
||||
Class: nil,
|
||||
Size: nil,
|
||||
},
|
||||
Version: nil,
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
[]string{},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_acl",
|
||||
&Model{},
|
||||
nil,
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_flavor",
|
||||
&Model{},
|
||||
[]string{},
|
||||
nil,
|
||||
&storageModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_storage",
|
||||
&Model{},
|
||||
[]string{},
|
||||
&flavorModel{},
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toCreatePayload(tt.input, tt.inputAcl, tt.inputFlavor, tt.inputStorage)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToUpdatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputAcl []string
|
||||
inputFlavor *flavorModel
|
||||
inputStorage *storageModel
|
||||
expected *postgresflex.UpdateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
[]string{},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
&postgresflex.UpdateInstancePayload{
|
||||
Acl: &postgresflex.InstanceAcl{
|
||||
Items: &[]string{},
|
||||
},
|
||||
Storage: &postgresflex.InstanceStorage{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
BackupSchedule: types.StringValue("schedule"),
|
||||
Name: types.StringValue("name"),
|
||||
Replicas: types.Int64Value(12),
|
||||
Version: types.StringValue("version"),
|
||||
},
|
||||
[]string{
|
||||
"ip_1",
|
||||
"ip_2",
|
||||
},
|
||||
&flavorModel{
|
||||
Id: types.StringValue("flavor_id"),
|
||||
},
|
||||
&storageModel{
|
||||
Class: types.StringValue("class"),
|
||||
Size: types.Int64Value(34),
|
||||
},
|
||||
&postgresflex.UpdateInstancePayload{
|
||||
Acl: &postgresflex.InstanceAcl{
|
||||
Items: &[]string{
|
||||
"ip_1",
|
||||
"ip_2",
|
||||
},
|
||||
},
|
||||
BackupSchedule: utils.Ptr("schedule"),
|
||||
FlavorId: utils.Ptr("flavor_id"),
|
||||
Name: utils.Ptr("name"),
|
||||
Replicas: utils.Ptr(int32(12)),
|
||||
Storage: &postgresflex.InstanceStorage{
|
||||
Class: utils.Ptr("class"),
|
||||
Size: utils.Ptr(int32(34)),
|
||||
},
|
||||
Version: utils.Ptr("version"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
BackupSchedule: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Replicas: types.Int64Value(2123456789),
|
||||
Version: types.StringNull(),
|
||||
},
|
||||
[]string{
|
||||
"",
|
||||
},
|
||||
&flavorModel{
|
||||
Id: types.StringNull(),
|
||||
},
|
||||
&storageModel{
|
||||
Class: types.StringNull(),
|
||||
Size: types.Int64Null(),
|
||||
},
|
||||
&postgresflex.UpdateInstancePayload{
|
||||
Acl: &postgresflex.InstanceAcl{
|
||||
Items: &[]string{
|
||||
"",
|
||||
},
|
||||
},
|
||||
BackupSchedule: nil,
|
||||
FlavorId: nil,
|
||||
Name: nil,
|
||||
Replicas: utils.Ptr(int32(2123456789)),
|
||||
Storage: &postgresflex.InstanceStorage{
|
||||
Class: nil,
|
||||
Size: nil,
|
||||
},
|
||||
Version: nil,
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
[]string{},
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_acl",
|
||||
&Model{},
|
||||
nil,
|
||||
&flavorModel{},
|
||||
&storageModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_flavor",
|
||||
&Model{},
|
||||
[]string{},
|
||||
nil,
|
||||
&storageModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_storage",
|
||||
&Model{},
|
||||
[]string{},
|
||||
&flavorModel{},
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toUpdatePayload(tt.input, tt.inputAcl, tt.inputFlavor, tt.inputStorage)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
324
stackit/internal/services/postgresflex/postgresflex_acc_test.go
Normal file
324
stackit/internal/services/postgresflex/postgresflex_acc_test.go
Normal file
|
|
@ -0,0 +1,324 @@
|
|||
package postgresflex_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-testing/helper/acctest"
|
||||
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
|
||||
"github.com/hashicorp/terraform-plugin-testing/terraform"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/testutil"
|
||||
)
|
||||
|
||||
// Instance resource data
|
||||
var instanceResource = map[string]string{
|
||||
"project_id": testutil.ProjectId,
|
||||
"name": fmt.Sprintf("tf-acc-%s", acctest.RandStringFromCharSet(7, acctest.CharSetAlphaNum)),
|
||||
"acl": "192.168.0.0/16",
|
||||
"backup_schedule": "00 16 * * *",
|
||||
"backup_schedule_update": "00 12 * * *",
|
||||
"flavor_cpu": "2",
|
||||
"flavor_ram": "4",
|
||||
"flavor_description": "Small, Compute optimized",
|
||||
"replicas": "1",
|
||||
"storage_class": "premium-perf12-stackit",
|
||||
"storage_size": "5",
|
||||
"version": "14",
|
||||
"flavor_id": "2.4",
|
||||
}
|
||||
|
||||
// User resource data
|
||||
var userResource = map[string]string{
|
||||
"username": fmt.Sprintf("tf-acc-user-%s", acctest.RandStringFromCharSet(7, acctest.CharSetAlpha)),
|
||||
"role": "login",
|
||||
"project_id": instanceResource["project_id"],
|
||||
}
|
||||
|
||||
func configResources() string {
|
||||
return fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
resource "stackit_postgresflex_instance" "instance" {
|
||||
project_id = "%s"
|
||||
name = "%s"
|
||||
acl = ["%s"]
|
||||
backup_schedule = "%s"
|
||||
flavor = {
|
||||
cpu = %s
|
||||
ram = %s
|
||||
}
|
||||
replicas = %s
|
||||
storage = {
|
||||
class = "%s"
|
||||
size = %s
|
||||
}
|
||||
version = "%s"
|
||||
}
|
||||
|
||||
resource "stackit_postgresflex_user" "user" {
|
||||
project_id = stackit_postgresflex_instance.instance.project_id
|
||||
instance_id = stackit_postgresflex_instance.instance.instance_id
|
||||
username = "%s"
|
||||
roles = ["%s"]
|
||||
}
|
||||
`,
|
||||
testutil.PostgresFlexProviderConfig(),
|
||||
instanceResource["project_id"],
|
||||
instanceResource["name"],
|
||||
instanceResource["acl"],
|
||||
instanceResource["backup_schedule"],
|
||||
instanceResource["flavor_cpu"],
|
||||
instanceResource["flavor_ram"],
|
||||
instanceResource["replicas"],
|
||||
instanceResource["storage_class"],
|
||||
instanceResource["storage_size"],
|
||||
instanceResource["version"],
|
||||
userResource["username"],
|
||||
userResource["role"],
|
||||
)
|
||||
}
|
||||
|
||||
func TestAccPostgresFlexFlexResource(t *testing.T) {
|
||||
resource.Test(t, resource.TestCase{
|
||||
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
|
||||
CheckDestroy: testAccCheckPostgresFlexDestroy,
|
||||
Steps: []resource.TestStep{
|
||||
// Creation
|
||||
{
|
||||
Config: configResources(),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresflex_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "acl.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "acl.0", instanceResource["acl"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresflex_instance.instance", "flavor.id"),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresflex_instance.instance", "flavor.description"),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "backup_schedule", instanceResource["backup_schedule"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "flavor.cpu", instanceResource["flavor_cpu"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "flavor.ram", instanceResource["flavor_ram"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "replicas", instanceResource["replicas"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "storage.class", instanceResource["storage_class"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "storage.size", instanceResource["storage_size"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "version", instanceResource["version"]),
|
||||
|
||||
// User
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_postgresflex_user.user", "project_id",
|
||||
"stackit_postgresflex_instance.instance", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_postgresflex_user.user", "instance_id",
|
||||
"stackit_postgresflex_instance.instance", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresflex_user.user", "user_id"),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresflex_user.user", "password"),
|
||||
),
|
||||
},
|
||||
// data source
|
||||
{
|
||||
Config: fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
data "stackit_postgresflex_instance" "instance" {
|
||||
project_id = stackit_postgresflex_instance.instance.project_id
|
||||
instance_id = stackit_postgresflex_instance.instance.instance_id
|
||||
}
|
||||
|
||||
data "stackit_postgresflex_user" "user" {
|
||||
project_id = stackit_postgresflex_instance.instance.project_id
|
||||
instance_id = stackit_postgresflex_instance.instance.instance_id
|
||||
user_id = stackit_postgresflex_user.user.user_id
|
||||
}
|
||||
`,
|
||||
configResources(),
|
||||
),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_postgresflex_instance.instance", "project_id",
|
||||
"stackit_postgresflex_instance.instance", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_postgresflex_instance.instance", "instance_id",
|
||||
"stackit_postgresflex_instance.instance", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"data.stackit_postgresflex_user.user", "instance_id",
|
||||
"stackit_postgresflex_user.user", "instance_id",
|
||||
),
|
||||
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_instance.instance", "acl.#", "1"),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_instance.instance", "acl.0", instanceResource["acl"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_instance.instance", "backup_schedule", instanceResource["backup_schedule"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_instance.instance", "flavor.id", instanceResource["flavor_id"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_instance.instance", "flavor.description", instanceResource["flavor_description"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_instance.instance", "flavor.cpu", instanceResource["flavor_cpu"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_instance.instance", "flavor.ram", instanceResource["flavor_ram"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_instance.instance", "replicas", instanceResource["replicas"]),
|
||||
|
||||
// User data
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_user.user", "project_id", userResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_postgresflex_user.user", "user_id"),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_user.user", "username", userResource["username"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_user.user", "roles.#", "1"),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresflex_user.user", "roles.0", userResource["role"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_postgresflex_user.user", "host"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_postgresflex_user.user", "port"),
|
||||
),
|
||||
},
|
||||
// Import
|
||||
{
|
||||
ResourceName: "stackit_postgresflex_instance.instance",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_postgresflex_instance.instance"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_postgresflex_instance.instance")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s,%s", testutil.ProjectId, instanceId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
{
|
||||
ResourceName: "stackit_postgresflex_user.user",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_postgresflex_user.user"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_postgresflex_user.user")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
userId, ok := r.Primary.Attributes["user_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute user_id")
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s,%s,%s", testutil.ProjectId, instanceId, userId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
ImportStateVerifyIgnore: []string{"password"},
|
||||
},
|
||||
// Update
|
||||
{
|
||||
Config: fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
resource "stackit_postgresflex_instance" "instance" {
|
||||
project_id = "%s"
|
||||
name = "%s"
|
||||
acl = ["%s"]
|
||||
backup_schedule = "%s"
|
||||
flavor = {
|
||||
cpu = %s
|
||||
ram = %s
|
||||
}
|
||||
replicas = %s
|
||||
storage = {
|
||||
class = "%s"
|
||||
size = %s
|
||||
}
|
||||
version = "%s"
|
||||
}
|
||||
`,
|
||||
testutil.PostgresFlexProviderConfig(),
|
||||
instanceResource["project_id"],
|
||||
instanceResource["name"],
|
||||
instanceResource["acl"],
|
||||
instanceResource["backup_schedule_update"],
|
||||
instanceResource["flavor_cpu"],
|
||||
instanceResource["flavor_ram"],
|
||||
instanceResource["replicas"],
|
||||
instanceResource["storage_class"],
|
||||
instanceResource["storage_size"],
|
||||
instanceResource["version"],
|
||||
),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresflex_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "acl.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "acl.0", instanceResource["acl"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "backup_schedule", instanceResource["backup_schedule_update"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresflex_instance.instance", "flavor.id"),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresflex_instance.instance", "flavor.description"),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "flavor.cpu", instanceResource["flavor_cpu"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "flavor.ram", instanceResource["flavor_ram"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "replicas", instanceResource["replicas"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "storage.class", instanceResource["storage_class"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "storage.size", instanceResource["storage_size"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresflex_instance.instance", "version", instanceResource["version"]),
|
||||
),
|
||||
},
|
||||
// Deletion is done by the framework implicitly
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func testAccCheckPostgresFlexDestroy(s *terraform.State) error {
|
||||
ctx := context.Background()
|
||||
var client *postgresflex.APIClient
|
||||
var err error
|
||||
if testutil.PostgresFlexCustomEndpoint == "" {
|
||||
client, err = postgresflex.NewAPIClient()
|
||||
} else {
|
||||
client, err = postgresflex.NewAPIClient(
|
||||
config.WithEndpoint(testutil.PostgresFlexCustomEndpoint),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating client: %w", err)
|
||||
}
|
||||
|
||||
instancesToDestroy := []string{}
|
||||
for _, rs := range s.RootModule().Resources {
|
||||
if rs.Type != "stackit_postgresql_instance" {
|
||||
continue
|
||||
}
|
||||
// instance terraform ID: = "[project_id],[instance_id]"
|
||||
instanceId := strings.Split(rs.Primary.ID, core.Separator)[1]
|
||||
instancesToDestroy = append(instancesToDestroy, instanceId)
|
||||
}
|
||||
|
||||
instancesResp, err := client.GetInstances(ctx, testutil.ProjectId).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting instancesResp: %w", err)
|
||||
}
|
||||
|
||||
items := *instancesResp.Items
|
||||
for i := range items {
|
||||
if items[i].Id == nil {
|
||||
continue
|
||||
}
|
||||
if utils.Contains(instancesToDestroy, *items[i].Id) {
|
||||
err := client.DeleteInstanceExecute(ctx, testutil.ProjectId, *items[i].Id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying instance %s during CheckDestroy: %w", *items[i].Id, err)
|
||||
}
|
||||
_, err = postgresflex.DeleteInstanceWaitHandler(ctx, client, testutil.ProjectId, *items[i].Id).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying instance %s during CheckDestroy: waiting for deletion %w", *items[i].Id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
227
stackit/internal/services/postgresflex/user/datasource.go
Normal file
227
stackit/internal/services/postgresflex/user/datasource.go
Normal file
|
|
@ -0,0 +1,227 @@
|
|||
package postgresflex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &userDataSource{}
|
||||
)
|
||||
|
||||
type DataSourceModel struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
UserId types.String `tfsdk:"user_id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Username types.String `tfsdk:"username"`
|
||||
Roles types.Set `tfsdk:"roles"`
|
||||
Host types.String `tfsdk:"host"`
|
||||
Port types.Int64 `tfsdk:"port"`
|
||||
}
|
||||
|
||||
// NewUserDataSource is a helper function to simplify the provider implementation.
|
||||
func NewUserDataSource() datasource.DataSource {
|
||||
return &userDataSource{}
|
||||
}
|
||||
|
||||
// userDataSource is the data source implementation.
|
||||
type userDataSource struct {
|
||||
client *postgresflex.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *userDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_postgresflex_user"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *userDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *postgresflex.APIClient
|
||||
var err error
|
||||
if providerData.PostgresFlexCustomEndpoint != "" {
|
||||
apiClient, err = postgresflex.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.PostgresFlexCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = postgresflex.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "PostgresFlex user client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *userDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "PostgresFlex user data source schema.",
|
||||
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`,`user_id`\".",
|
||||
"user_id": "User ID.",
|
||||
"instance_id": "ID of the PostgresFlex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"user_id": schema.StringAttribute{
|
||||
Description: descriptions["user_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"roles": schema.SetAttribute{
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *userDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model DataSourceModel
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
userId := model.UserId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "user_id", userId)
|
||||
|
||||
recordSetResp, err := r.client.GetUser(ctx, projectId, instanceId, userId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading user", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema and populate Computed attribute values
|
||||
err = mapDataSourceFields(recordSetResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading user", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgresFlex user read")
|
||||
}
|
||||
|
||||
func mapDataSourceFields(userResp *postgresflex.UserResponse, model *DataSourceModel) error {
|
||||
if userResp == nil || userResp.Item == nil {
|
||||
return fmt.Errorf("response is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
user := userResp.Item
|
||||
|
||||
var userId string
|
||||
if model.UserId.ValueString() != "" {
|
||||
userId = model.UserId.ValueString()
|
||||
} else if user.Id != nil {
|
||||
userId = *user.Id
|
||||
} else {
|
||||
return fmt.Errorf("user id not present")
|
||||
}
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
model.InstanceId.ValueString(),
|
||||
userId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.UserId = types.StringValue(userId)
|
||||
model.Username = types.StringPointerValue(user.Username)
|
||||
|
||||
if user.Roles == nil {
|
||||
model.Roles = types.SetNull(types.StringType)
|
||||
} else {
|
||||
roles := []attr.Value{}
|
||||
for _, role := range *user.Roles {
|
||||
roles = append(roles, types.StringValue(role))
|
||||
}
|
||||
rolesSet, diags := types.SetValue(types.StringType, roles)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map roles: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Roles = rolesSet
|
||||
}
|
||||
model.Host = types.StringPointerValue(user.Host)
|
||||
model.Port = conversion.ToTypeInt64(user.Port)
|
||||
return nil
|
||||
}
|
||||
441
stackit/internal/services/postgresflex/user/resource.go
Normal file
441
stackit/internal/services/postgresflex/user/resource.go
Normal file
|
|
@ -0,0 +1,441 @@
|
|||
package postgresflex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/setvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/setplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &userResource{}
|
||||
_ resource.ResourceWithConfigure = &userResource{}
|
||||
_ resource.ResourceWithImportState = &userResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
UserId types.String `tfsdk:"user_id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Username types.String `tfsdk:"username"`
|
||||
Roles types.Set `tfsdk:"roles"`
|
||||
Password types.String `tfsdk:"password"`
|
||||
Host types.String `tfsdk:"host"`
|
||||
Port types.Int64 `tfsdk:"port"`
|
||||
}
|
||||
|
||||
// NewUserResource is a helper function to simplify the provider implementation.
|
||||
func NewUserResource() resource.Resource {
|
||||
return &userResource{}
|
||||
}
|
||||
|
||||
// userResource is the resource implementation.
|
||||
type userResource struct {
|
||||
client *postgresflex.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *userResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_postgresflex_user"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *userResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *postgresflex.APIClient
|
||||
var err error
|
||||
if providerData.PostgresFlexCustomEndpoint != "" {
|
||||
apiClient, err = postgresflex.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.PostgresFlexCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = postgresflex.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "PostgresFlex user client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *userResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "PostgresFlex user resource schema.",
|
||||
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`,`user_id`\".",
|
||||
"user_id": "User ID.",
|
||||
"instance_id": "ID of the PostgresFlex instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"user_id": schema.StringAttribute{
|
||||
Description: descriptions["user_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
"roles": schema.SetAttribute{
|
||||
ElementType: types.StringType,
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.Set{
|
||||
setplanmodifier.RequiresReplace(),
|
||||
},
|
||||
Validators: []validator.Set{
|
||||
setvalidator.ValueStringsAre(
|
||||
stringvalidator.OneOf("login", "createdb"),
|
||||
),
|
||||
},
|
||||
},
|
||||
"password": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *userResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
var roles []string
|
||||
if !(model.Roles.IsNull() || model.Roles.IsUnknown()) {
|
||||
diags = model.Roles.ElementsAs(ctx, &roles, false)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model, roles)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating user", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Create new user
|
||||
userResp, err := r.client.CreateUser(ctx, projectId, instanceId).CreateUserPayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating user", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
if userResp == nil || userResp.Item == nil || userResp.Item.Id == nil || *userResp.Item.Id == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating user", "API didn't return user Id. A user might have been created")
|
||||
return
|
||||
}
|
||||
userId := *userResp.Item.Id
|
||||
ctx = tflog.SetField(ctx, "user_id", userId)
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFieldsCreate(userResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating user", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgresFlex user created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *userResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
userId := model.UserId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "user_id", userId)
|
||||
|
||||
recordSetResp, err := r.client.GetUser(ctx, projectId, instanceId, userId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading user", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(recordSetResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading user", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgresFlex user read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *userResource) Update(ctx context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Update shouldn't be called
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating user", "User can't be updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *userResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
userId := model.UserId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "user_id", userId)
|
||||
|
||||
// Delete existing record set
|
||||
err := r.client.DeleteUser(ctx, projectId, instanceId, userId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting user", fmt.Sprintf("Calling API: %v", err))
|
||||
}
|
||||
_, err = postgresflex.DeleteUserWaitHandler(ctx, r.client, projectId, instanceId, userId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting user", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgresFlex user deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,zone_id,record_set_id
|
||||
func (r *userResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing user",
|
||||
fmt.Sprintf("Expected import identifier with format [project_id],[instance_id],[user_id], got %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[1])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("user_id"), idParts[2])...)
|
||||
core.LogAndAddWarning(ctx, &resp.Diagnostics,
|
||||
"Postgresflex user imported with empty password",
|
||||
"The user password is not imported as it is only available upon creation of a new user. The password field will be empty.",
|
||||
)
|
||||
tflog.Info(ctx, "Postgresflex user state imported")
|
||||
}
|
||||
|
||||
func mapFieldsCreate(userResp *postgresflex.CreateUserResponse, model *Model) error {
|
||||
if userResp == nil || userResp.Item == nil {
|
||||
return fmt.Errorf("response is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
user := userResp.Item
|
||||
|
||||
if user.Id == nil {
|
||||
return fmt.Errorf("user id not present")
|
||||
}
|
||||
userId := *user.Id
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
model.InstanceId.ValueString(),
|
||||
userId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.UserId = types.StringValue(userId)
|
||||
model.Username = types.StringPointerValue(user.Username)
|
||||
|
||||
if user.Password == nil {
|
||||
return fmt.Errorf("user password not present")
|
||||
}
|
||||
model.Password = types.StringValue(*user.Password)
|
||||
|
||||
if user.Roles == nil {
|
||||
model.Roles = types.SetNull(types.StringType)
|
||||
} else {
|
||||
roles := []attr.Value{}
|
||||
for _, role := range *user.Roles {
|
||||
roles = append(roles, types.StringValue(role))
|
||||
}
|
||||
rolesSet, diags := types.SetValue(types.StringType, roles)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map roles: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Roles = rolesSet
|
||||
}
|
||||
model.Host = types.StringPointerValue(user.Host)
|
||||
model.Port = conversion.ToTypeInt64(user.Port)
|
||||
return nil
|
||||
}
|
||||
|
||||
func mapFields(userResp *postgresflex.UserResponse, model *Model) error {
|
||||
if userResp == nil || userResp.Item == nil {
|
||||
return fmt.Errorf("response is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
user := userResp.Item
|
||||
|
||||
var userId string
|
||||
if model.UserId.ValueString() != "" {
|
||||
userId = model.UserId.ValueString()
|
||||
} else if user.Id != nil {
|
||||
userId = *user.Id
|
||||
} else {
|
||||
return fmt.Errorf("user id not present")
|
||||
}
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
model.InstanceId.ValueString(),
|
||||
userId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.UserId = types.StringValue(userId)
|
||||
model.Username = types.StringPointerValue(user.Username)
|
||||
|
||||
if user.Roles == nil {
|
||||
model.Roles = types.SetNull(types.StringType)
|
||||
} else {
|
||||
roles := []attr.Value{}
|
||||
for _, role := range *user.Roles {
|
||||
roles = append(roles, types.StringValue(role))
|
||||
}
|
||||
rolesSet, diags := types.SetValue(types.StringType, roles)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map roles: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Roles = rolesSet
|
||||
}
|
||||
model.Host = types.StringPointerValue(user.Host)
|
||||
model.Port = conversion.ToTypeInt64(user.Port)
|
||||
return nil
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model, roles []string) (*postgresflex.CreateUserPayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
if roles == nil {
|
||||
return nil, fmt.Errorf("nil roles")
|
||||
}
|
||||
|
||||
return &postgresflex.CreateUserPayload{
|
||||
Roles: &roles,
|
||||
Username: model.Username.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
359
stackit/internal/services/postgresflex/user/resource_test.go
Normal file
359
stackit/internal/services/postgresflex/user/resource_test.go
Normal file
|
|
@ -0,0 +1,359 @@
|
|||
package postgresflex
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex"
|
||||
)
|
||||
|
||||
func TestMapFieldsCreate(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *postgresflex.CreateUserResponse
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&postgresflex.CreateUserResponse{
|
||||
Item: &postgresflex.InstanceUser{
|
||||
Id: utils.Ptr("uid"),
|
||||
Password: utils.Ptr(""),
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,uid"),
|
||||
UserId: types.StringValue("uid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Username: types.StringNull(),
|
||||
Roles: types.SetNull(types.StringType),
|
||||
Password: types.StringValue(""),
|
||||
Host: types.StringNull(),
|
||||
Port: types.Int64Null(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&postgresflex.CreateUserResponse{
|
||||
Item: &postgresflex.InstanceUser{
|
||||
Id: utils.Ptr("uid"),
|
||||
Roles: &[]string{
|
||||
"role_1",
|
||||
"role_2",
|
||||
"",
|
||||
},
|
||||
Username: utils.Ptr("username"),
|
||||
Password: utils.Ptr("password"),
|
||||
Host: utils.Ptr("host"),
|
||||
Port: utils.Ptr(int32(1234)),
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,uid"),
|
||||
UserId: types.StringValue("uid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Username: types.StringValue("username"),
|
||||
Roles: types.SetValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("role_1"),
|
||||
types.StringValue("role_2"),
|
||||
types.StringValue(""),
|
||||
}),
|
||||
Password: types.StringValue("password"),
|
||||
Host: types.StringValue("host"),
|
||||
Port: types.Int64Value(1234),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&postgresflex.CreateUserResponse{
|
||||
Item: &postgresflex.InstanceUser{
|
||||
Id: utils.Ptr("uid"),
|
||||
Roles: &[]string{},
|
||||
Username: nil,
|
||||
Password: utils.Ptr(""),
|
||||
Host: nil,
|
||||
Port: utils.Ptr(int32(2123456789)),
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,uid"),
|
||||
UserId: types.StringValue("uid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Username: types.StringNull(),
|
||||
Roles: types.SetValueMust(types.StringType, []attr.Value{}),
|
||||
Password: types.StringValue(""),
|
||||
Host: types.StringNull(),
|
||||
Port: types.Int64Value(2123456789),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_response_2",
|
||||
&postgresflex.CreateUserResponse{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&postgresflex.CreateUserResponse{
|
||||
Item: &postgresflex.InstanceUser{},
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_password",
|
||||
&postgresflex.CreateUserResponse{
|
||||
Item: &postgresflex.InstanceUser{
|
||||
Id: utils.Ptr("uid"),
|
||||
},
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
state := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
}
|
||||
err := mapFieldsCreate(tt.input, state)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapCreate(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *postgresflex.UserResponse
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&postgresflex.UserResponse{
|
||||
Item: &postgresflex.UserResponseUser{},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,uid"),
|
||||
UserId: types.StringValue("uid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Username: types.StringNull(),
|
||||
Roles: types.SetNull(types.StringType),
|
||||
Host: types.StringNull(),
|
||||
Port: types.Int64Null(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&postgresflex.UserResponse{
|
||||
Item: &postgresflex.UserResponseUser{
|
||||
Roles: &[]string{
|
||||
"role_1",
|
||||
"role_2",
|
||||
"",
|
||||
},
|
||||
Username: utils.Ptr("username"),
|
||||
Host: utils.Ptr("host"),
|
||||
Port: utils.Ptr(int32(1234)),
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,uid"),
|
||||
UserId: types.StringValue("uid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Username: types.StringValue("username"),
|
||||
Roles: types.SetValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("role_1"),
|
||||
types.StringValue("role_2"),
|
||||
types.StringValue(""),
|
||||
}),
|
||||
Host: types.StringValue("host"),
|
||||
Port: types.Int64Value(1234),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&postgresflex.UserResponse{
|
||||
Item: &postgresflex.UserResponseUser{
|
||||
Id: utils.Ptr("uid"),
|
||||
Roles: &[]string{},
|
||||
Username: nil,
|
||||
Host: nil,
|
||||
Port: utils.Ptr(int32(2123456789)),
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,uid"),
|
||||
UserId: types.StringValue("uid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Username: types.StringNull(),
|
||||
Roles: types.SetValueMust(types.StringType, []attr.Value{}),
|
||||
Host: types.StringNull(),
|
||||
Port: types.Int64Value(2123456789),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_response_2",
|
||||
&postgresflex.UserResponse{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&postgresflex.UserResponse{
|
||||
Item: &postgresflex.UserResponseUser{},
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
state := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
UserId: tt.expected.UserId,
|
||||
}
|
||||
err := mapFields(tt.input, state)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputRoles []string
|
||||
expected *postgresflex.CreateUserPayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
[]string{},
|
||||
&postgresflex.CreateUserPayload{
|
||||
Roles: &[]string{},
|
||||
Username: nil,
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"default_values",
|
||||
&Model{
|
||||
Username: types.StringValue("username"),
|
||||
},
|
||||
[]string{
|
||||
"role_1",
|
||||
"role_2",
|
||||
},
|
||||
&postgresflex.CreateUserPayload{
|
||||
Roles: &[]string{
|
||||
"role_1",
|
||||
"role_2",
|
||||
},
|
||||
Username: utils.Ptr("username"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
Username: types.StringNull(),
|
||||
},
|
||||
[]string{
|
||||
"",
|
||||
},
|
||||
&postgresflex.CreateUserPayload{
|
||||
Roles: &[]string{
|
||||
"",
|
||||
},
|
||||
Username: nil,
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
[]string{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_roles",
|
||||
&Model{},
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toCreatePayload(tt.input, tt.inputRoles)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
181
stackit/internal/services/postgresql/credentials/datasource.go
Normal file
181
stackit/internal/services/postgresql/credentials/datasource.go
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
package postgresql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresql"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &credentialsDataSource{}
|
||||
)
|
||||
|
||||
// NewCredentialsDataSource is a helper function to simplify the provider implementation.
|
||||
func NewCredentialsDataSource() datasource.DataSource {
|
||||
return &credentialsDataSource{}
|
||||
}
|
||||
|
||||
// credentialsDataSource is the data source implementation.
|
||||
type credentialsDataSource struct {
|
||||
client *postgresql.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *credentialsDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_postgresql_credentials"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *credentialsDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *postgresql.APIClient
|
||||
var err error
|
||||
if providerData.PostgreSQLCustomEndpoint != "" {
|
||||
apiClient, err = postgresql.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.PostgreSQLCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = postgresql.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "PostgreSQL credentials client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *credentialsDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "PostgreSQL credentials data source schema.",
|
||||
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`,`credentials_id`\".",
|
||||
"credentials_id": "The credentials ID.",
|
||||
"instance_id": "ID of the PostgreSQL instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"credentials_id": schema.StringAttribute{
|
||||
Description: descriptions["credentials_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"hosts": schema.ListAttribute{
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"http_api_uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"password": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *credentialsDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
credentialsId := model.CredentialsId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(recordSetResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgreSQL credentials read")
|
||||
}
|
||||
377
stackit/internal/services/postgresql/credentials/resource.go
Normal file
377
stackit/internal/services/postgresql/credentials/resource.go
Normal file
|
|
@ -0,0 +1,377 @@
|
|||
package postgresql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresql"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &credentialsResource{}
|
||||
_ resource.ResourceWithConfigure = &credentialsResource{}
|
||||
_ resource.ResourceWithImportState = &credentialsResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
CredentialsId types.String `tfsdk:"credentials_id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Host types.String `tfsdk:"host"`
|
||||
Hosts types.List `tfsdk:"hosts"`
|
||||
HttpAPIURI types.String `tfsdk:"http_api_uri"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Password types.String `tfsdk:"password"`
|
||||
Port types.Int64 `tfsdk:"port"`
|
||||
Uri types.String `tfsdk:"uri"`
|
||||
Username types.String `tfsdk:"username"`
|
||||
}
|
||||
|
||||
// NewCredentialsResource is a helper function to simplify the provider implementation.
|
||||
func NewCredentialsResource() resource.Resource {
|
||||
return &credentialsResource{}
|
||||
}
|
||||
|
||||
// credentialsResource is the resource implementation.
|
||||
type credentialsResource struct {
|
||||
client *postgresql.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *credentialsResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_postgresql_credentials"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *credentialsResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *postgresql.APIClient
|
||||
var err error
|
||||
if providerData.PostgreSQLCustomEndpoint != "" {
|
||||
apiClient, err = postgresql.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.PostgreSQLCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = postgresql.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "PostgreSQL credentials client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *credentialsResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "PostgreSQL credentials resource schema.",
|
||||
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`,`credentials_id`\".",
|
||||
"credentials_id": "The credentials ID.",
|
||||
"instance_id": "ID of the PostgreSQL instance.",
|
||||
"project_id": "STACKIT Project ID to which the instance is associated.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"credentials_id": schema.StringAttribute{
|
||||
Description: descriptions["credentials_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"hosts": schema.ListAttribute{
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"http_api_uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"password": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *credentialsResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
// Create new recordset
|
||||
credentialsResp, err := r.client.CreateCredentials(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
if credentialsResp.Id == nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", "Got empty credentials id")
|
||||
return
|
||||
}
|
||||
credentialsId := *credentialsResp.Id
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
wr, err := postgresql.CreateCredentialsWaitHandler(ctx, r.client, projectId, instanceId, credentialsId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Instance creation waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*postgresql.CredentialsResponse)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgreSQL credentials created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *credentialsResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
credentialsId := model.CredentialsId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(recordSetResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgreSQL credentials read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *credentialsResource) Update(ctx context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Update shouldn't be called
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating credentials", "Credentials can't be updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *credentialsResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
credentialsId := model.CredentialsId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
// Delete existing record set
|
||||
err := r.client.DeleteCredentials(ctx, projectId, instanceId, credentialsId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
}
|
||||
_, err = postgresql.DeleteCredentialsWaitHandler(ctx, r.client, projectId, instanceId, credentialsId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credentials", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgreSQL credentials deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,instance_id,credentials_id
|
||||
func (r *credentialsResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing credentials",
|
||||
fmt.Sprintf("Expected import identifier with format [project_id],[instance_id],[credentials_id], got %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[1])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("credentials_id"), idParts[2])...)
|
||||
tflog.Info(ctx, "PostgreSQL credentials state imported")
|
||||
}
|
||||
|
||||
func mapFields(credentialsResp *postgresql.CredentialsResponse, model *Model) error {
|
||||
if credentialsResp == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if credentialsResp.Raw == nil {
|
||||
return fmt.Errorf("response credentials raw is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
credentials := credentialsResp.Raw.Credentials
|
||||
|
||||
var credentialsId string
|
||||
if model.CredentialsId.ValueString() != "" {
|
||||
credentialsId = model.CredentialsId.ValueString()
|
||||
} else if credentialsResp.Id != nil {
|
||||
credentialsId = *credentialsResp.Id
|
||||
} else {
|
||||
return fmt.Errorf("credentials id not present")
|
||||
}
|
||||
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
model.InstanceId.ValueString(),
|
||||
credentialsId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.CredentialsId = types.StringValue(credentialsId)
|
||||
model.Hosts = types.ListNull(types.StringType)
|
||||
if credentials != nil {
|
||||
if credentials.Hosts != nil {
|
||||
var hosts []attr.Value
|
||||
for _, host := range *credentials.Hosts {
|
||||
hosts = append(hosts, types.StringValue(host))
|
||||
}
|
||||
hostsList, diags := types.ListValue(types.StringType, hosts)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map hosts: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Hosts = hostsList
|
||||
}
|
||||
model.Host = types.StringPointerValue(credentials.Host)
|
||||
model.HttpAPIURI = types.StringPointerValue(credentials.HttpApiUri)
|
||||
model.Name = types.StringPointerValue(credentials.Name)
|
||||
model.Password = types.StringPointerValue(credentials.Password)
|
||||
model.Port = conversion.ToTypeInt64(credentials.Port)
|
||||
model.Uri = types.StringPointerValue(credentials.Uri)
|
||||
model.Username = types.StringPointerValue(credentials.Username)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,156 @@
|
|||
package postgresql
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresql"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *postgresql.CredentialsResponse
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&postgresql.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
Raw: &postgresql.RawCredentials{},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,cid"),
|
||||
CredentialsId: types.StringValue("cid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Host: types.StringNull(),
|
||||
Hosts: types.ListNull(types.StringType),
|
||||
HttpAPIURI: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Password: types.StringNull(),
|
||||
Port: types.Int64Null(),
|
||||
Uri: types.StringNull(),
|
||||
Username: types.StringNull(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&postgresql.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
Raw: &postgresql.RawCredentials{
|
||||
Credentials: &postgresql.Credentials{
|
||||
Host: utils.Ptr("host"),
|
||||
Hosts: &[]string{
|
||||
"host_1",
|
||||
"",
|
||||
},
|
||||
HttpApiUri: utils.Ptr("http"),
|
||||
Name: utils.Ptr("name"),
|
||||
Password: utils.Ptr("password"),
|
||||
Port: utils.Ptr(int32(1234)),
|
||||
Uri: utils.Ptr("uri"),
|
||||
Username: utils.Ptr("username"),
|
||||
},
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,cid"),
|
||||
CredentialsId: types.StringValue("cid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Host: types.StringValue("host"),
|
||||
Hosts: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("host_1"),
|
||||
types.StringValue(""),
|
||||
}),
|
||||
HttpAPIURI: types.StringValue("http"),
|
||||
Name: types.StringValue("name"),
|
||||
Password: types.StringValue("password"),
|
||||
Port: types.Int64Value(1234),
|
||||
Uri: types.StringValue("uri"),
|
||||
Username: types.StringValue("username"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&postgresql.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
Raw: &postgresql.RawCredentials{
|
||||
Credentials: &postgresql.Credentials{
|
||||
Host: utils.Ptr(""),
|
||||
Hosts: &[]string{},
|
||||
HttpApiUri: nil,
|
||||
Name: nil,
|
||||
Password: nil,
|
||||
Port: utils.Ptr(int32(2123456789)),
|
||||
Uri: nil,
|
||||
Username: nil,
|
||||
},
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,cid"),
|
||||
CredentialsId: types.StringValue("cid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Host: types.StringValue(""),
|
||||
Hosts: types.ListValueMust(types.StringType, []attr.Value{}),
|
||||
HttpAPIURI: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Password: types.StringNull(),
|
||||
Port: types.Int64Value(2123456789),
|
||||
Uri: types.StringNull(),
|
||||
Username: types.StringNull(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&postgresql.CredentialsResponse{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_raw_credentials",
|
||||
&postgresql.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
state := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
}
|
||||
err := mapFields(tt.input, state)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
209
stackit/internal/services/postgresql/instance/datasource.go
Normal file
209
stackit/internal/services/postgresql/instance/datasource.go
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
package postgresql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresql"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &instanceDataSource{}
|
||||
)
|
||||
|
||||
// NewInstanceDataSource is a helper function to simplify the provider implementation.
|
||||
func NewInstanceDataSource() datasource.DataSource {
|
||||
return &instanceDataSource{}
|
||||
}
|
||||
|
||||
// instanceDataSource is the data source implementation.
|
||||
type instanceDataSource struct {
|
||||
client *postgresql.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *instanceDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_postgresql_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *instanceDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *postgresql.APIClient
|
||||
var err error
|
||||
if providerData.PostgreSQLCustomEndpoint != "" {
|
||||
apiClient, err = postgresql.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.PostgreSQLCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = postgresql.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "PostgreSQL zone client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "PostgreSQL instance data source schema.",
|
||||
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`\".",
|
||||
"instance_id": "ID of the PostgreSQL instance.",
|
||||
"project_id": "STACKIT Project ID to which the instance is associated.",
|
||||
"name": "Instance name.",
|
||||
"version": "The service version.",
|
||||
"plan_name": "The selected plan name.",
|
||||
"plan_id": "The selected plan ID.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Computed: true,
|
||||
},
|
||||
"version": schema.StringAttribute{
|
||||
Description: descriptions["version"],
|
||||
Computed: true,
|
||||
},
|
||||
"plan_name": schema.StringAttribute{
|
||||
Description: descriptions["plan_name"],
|
||||
Computed: true,
|
||||
},
|
||||
"plan_id": schema.StringAttribute{
|
||||
Description: descriptions["plan_id"],
|
||||
Computed: true,
|
||||
},
|
||||
"parameters": schema.SingleNestedAttribute{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"enable_monitoring": schema.BoolAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"metrics_frequency": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"metrics_prefix": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"monitoring_instance_id": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"plugins": schema.ListAttribute{
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"sgw_acl": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
Computed: true,
|
||||
},
|
||||
"cf_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"cf_space_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"dashboard_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"image_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"cf_organization_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *instanceDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
err = mapFields(instanceResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Compute and store values not present in the API response
|
||||
err = loadPlanNameAndVersion(ctx, r.client, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Loading service plan details: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgreSQL instance read")
|
||||
}
|
||||
741
stackit/internal/services/postgresql/instance/resource.go
Normal file
741
stackit/internal/services/postgresql/instance/resource.go
Normal file
|
|
@ -0,0 +1,741 @@
|
|||
package postgresql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresql"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &instanceResource{}
|
||||
_ resource.ResourceWithConfigure = &instanceResource{}
|
||||
_ resource.ResourceWithImportState = &instanceResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
CfGuid types.String `tfsdk:"cf_guid"`
|
||||
CfSpaceGuid types.String `tfsdk:"cf_space_guid"`
|
||||
DashboardUrl types.String `tfsdk:"dashboard_url"`
|
||||
ImageUrl types.String `tfsdk:"image_url"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
CfOrganizationGuid types.String `tfsdk:"cf_organization_guid"`
|
||||
Parameters types.Object `tfsdk:"parameters"`
|
||||
Version types.String `tfsdk:"version"`
|
||||
PlanName types.String `tfsdk:"plan_name"`
|
||||
PlanId types.String `tfsdk:"plan_id"`
|
||||
}
|
||||
|
||||
// Struct corresponding to DataSourceModel.Parameters
|
||||
type parametersModel struct {
|
||||
EnableMonitoring types.Bool `tfsdk:"enable_monitoring"`
|
||||
MetricsFrequency types.Int64 `tfsdk:"metrics_frequency"`
|
||||
MetricsPrefix types.String `tfsdk:"metrics_prefix"`
|
||||
MonitoringInstanceId types.String `tfsdk:"monitoring_instance_id"`
|
||||
Plugins types.List `tfsdk:"plugins"`
|
||||
SgwAcl types.String `tfsdk:"sgw_acl"`
|
||||
}
|
||||
|
||||
// Types corresponding to parametersModel
|
||||
var parametersTypes = map[string]attr.Type{
|
||||
"enable_monitoring": basetypes.BoolType{},
|
||||
"metrics_frequency": basetypes.Int64Type{},
|
||||
"metrics_prefix": basetypes.StringType{},
|
||||
"monitoring_instance_id": basetypes.StringType{},
|
||||
"plugins": basetypes.ListType{ElemType: types.StringType},
|
||||
"sgw_acl": basetypes.StringType{},
|
||||
}
|
||||
|
||||
// NewInstanceResource is a helper function to simplify the provider implementation.
|
||||
func NewInstanceResource() resource.Resource {
|
||||
return &instanceResource{}
|
||||
}
|
||||
|
||||
// instanceResource is the resource implementation.
|
||||
type instanceResource struct {
|
||||
client *postgresql.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *instanceResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_postgresql_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *instanceResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *postgresql.APIClient
|
||||
var err error
|
||||
if providerData.PostgreSQLCustomEndpoint != "" {
|
||||
apiClient, err = postgresql.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.PostgreSQLCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = postgresql.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "PostgreSQL instance client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *instanceResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "PostgreSQL instance resource schema.",
|
||||
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`\".",
|
||||
"instance_id": "ID of the PostgreSQL instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"name": "Instance name.",
|
||||
"version": "The service version.",
|
||||
"plan_name": "The selected plan name.",
|
||||
"plan_id": "The selected plan ID.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
},
|
||||
},
|
||||
"version": schema.StringAttribute{
|
||||
Description: descriptions["version"],
|
||||
Required: true,
|
||||
},
|
||||
"plan_name": schema.StringAttribute{
|
||||
Description: descriptions["plan_name"],
|
||||
Required: true,
|
||||
},
|
||||
"plan_id": schema.StringAttribute{
|
||||
Description: descriptions["plan_id"],
|
||||
Computed: true,
|
||||
},
|
||||
"parameters": schema.SingleNestedAttribute{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"enable_monitoring": schema.BoolAttribute{
|
||||
Optional: true,
|
||||
},
|
||||
"metrics_frequency": schema.Int64Attribute{
|
||||
Optional: true,
|
||||
},
|
||||
"metrics_prefix": schema.StringAttribute{
|
||||
Optional: true,
|
||||
},
|
||||
"monitoring_instance_id": schema.StringAttribute{
|
||||
Optional: true,
|
||||
},
|
||||
"plugins": schema.ListAttribute{
|
||||
ElementType: types.StringType,
|
||||
Optional: true,
|
||||
},
|
||||
"sgw_acl": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
},
|
||||
"cf_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"cf_space_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"dashboard_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"image_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"cf_organization_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *instanceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
|
||||
var parameters = ¶metersModel{}
|
||||
var parametersPlugins *[]string
|
||||
if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) {
|
||||
diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
if !(parameters.Plugins.IsNull() || parameters.Plugins.IsUnknown()) {
|
||||
var pp []types.String
|
||||
var res []string
|
||||
diags = parameters.Plugins.ElementsAs(ctx, &pp, false)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
for _, v := range pp {
|
||||
res = append(res, v.ValueString())
|
||||
}
|
||||
parametersPlugins = &res
|
||||
}
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err := r.loadPlanId(ctx, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Loading service plan: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model, parameters, parametersPlugins)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Create new instance
|
||||
createResp, err := r.client.CreateInstance(ctx, projectId).CreateInstancePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
instanceId := *createResp.InstanceId
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
wr, err := postgresql.CreateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Instance creation waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*postgresql.Instance)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Postgresql instance created")
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model, parameters *parametersModel, parametersPlugins *[]string) (*postgresql.CreateInstancePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
if parameters == nil {
|
||||
return &postgresql.CreateInstancePayload{
|
||||
InstanceName: model.Name.ValueStringPointer(),
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
return &postgresql.CreateInstancePayload{
|
||||
InstanceName: model.Name.ValueStringPointer(),
|
||||
Parameters: &postgresql.InstanceParameters{
|
||||
EnableMonitoring: parameters.EnableMonitoring.ValueBoolPointer(),
|
||||
MetricsFrequency: conversion.ToPtrInt32(parameters.MetricsFrequency),
|
||||
MetricsPrefix: parameters.MetricsPrefix.ValueStringPointer(),
|
||||
MonitoringInstanceId: parameters.MonitoringInstanceId.ValueStringPointer(),
|
||||
Plugins: parametersPlugins,
|
||||
SgwAcl: parameters.SgwAcl.ValueStringPointer(),
|
||||
},
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(instanceResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Compute and store values not present in the API response
|
||||
err = loadPlanNameAndVersion(ctx, r.client, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Loading service plan details: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgreSQL instance read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *instanceResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
var parameters = ¶metersModel{}
|
||||
var parametersPlugins *[]string
|
||||
if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) {
|
||||
diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
if !(parameters.Plugins.IsNull() || parameters.Plugins.IsUnknown()) {
|
||||
var pp []types.String
|
||||
var res []string
|
||||
diags = parameters.Plugins.ElementsAs(ctx, &pp, false)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
for _, v := range pp {
|
||||
res = append(res, v.ValueString())
|
||||
}
|
||||
parametersPlugins = &res
|
||||
}
|
||||
}
|
||||
|
||||
err := r.loadPlanId(ctx, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Loading service plan: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toUpdatePayload(&model, parameters, parametersPlugins)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Update existing instance
|
||||
err = r.client.UpdateInstance(ctx, projectId, instanceId).UpdateInstancePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
wr, err := postgresql.UpdateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Instance update waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*postgresql.Instance)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgreSQL instance updated")
|
||||
}
|
||||
|
||||
func toUpdatePayload(model *Model, parameters *parametersModel, parametersPlugins *[]string) (*postgresql.UpdateInstancePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
if parameters == nil {
|
||||
return &postgresql.UpdateInstancePayload{
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
return &postgresql.UpdateInstancePayload{
|
||||
Parameters: &postgresql.InstanceParameters{
|
||||
EnableMonitoring: parameters.EnableMonitoring.ValueBoolPointer(),
|
||||
MetricsFrequency: conversion.ToPtrInt32(parameters.MetricsFrequency),
|
||||
MetricsPrefix: parameters.MetricsPrefix.ValueStringPointer(),
|
||||
MonitoringInstanceId: parameters.MonitoringInstanceId.ValueStringPointer(),
|
||||
Plugins: parametersPlugins,
|
||||
SgwAcl: parameters.SgwAcl.ValueStringPointer(),
|
||||
},
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *instanceResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from state
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
// Delete existing instance
|
||||
err := r.client.DeleteInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
_, err = postgresql.DeleteInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "PostgreSQL instance deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,instance_id
|
||||
func (r *instanceResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
|
||||
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing instance",
|
||||
fmt.Sprintf("Expected import identifier with format: [project_id],[instance_id] Got: %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[1])...)
|
||||
tflog.Info(ctx, "PostgreSQL instance state imported")
|
||||
}
|
||||
|
||||
func mapFields(instance *postgresql.Instance, model *Model) error {
|
||||
if instance == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
|
||||
var instanceId string
|
||||
if model.InstanceId.ValueString() != "" {
|
||||
instanceId = model.InstanceId.ValueString()
|
||||
} else if instance.InstanceId != nil {
|
||||
instanceId = *instance.InstanceId
|
||||
} else {
|
||||
return fmt.Errorf("instance id not present")
|
||||
}
|
||||
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
instanceId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.InstanceId = types.StringValue(instanceId)
|
||||
model.PlanId = types.StringPointerValue(instance.PlanId)
|
||||
model.CfGuid = types.StringPointerValue(instance.CfGuid)
|
||||
model.CfSpaceGuid = types.StringPointerValue(instance.CfSpaceGuid)
|
||||
model.DashboardUrl = types.StringPointerValue(instance.DashboardUrl)
|
||||
model.ImageUrl = types.StringPointerValue(instance.ImageUrl)
|
||||
model.Name = types.StringPointerValue(instance.Name)
|
||||
model.CfOrganizationGuid = types.StringPointerValue(instance.CfOrganizationGuid)
|
||||
|
||||
if instance.Parameters == nil {
|
||||
model.Parameters = types.ObjectNull(parametersTypes)
|
||||
} else {
|
||||
parameters, err := mapParameters(*instance.Parameters)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mapping parameters: %w", err)
|
||||
}
|
||||
model.Parameters = parameters
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func mapParameters(params map[string]interface{}) (types.Object, error) {
|
||||
attributes := map[string]attr.Value{}
|
||||
for attribute := range parametersTypes {
|
||||
valueInterface, ok := params[attribute]
|
||||
if !ok {
|
||||
// All fields are optional, so this is ok
|
||||
// Set the value as nil, will be handled accordingly
|
||||
valueInterface = nil
|
||||
}
|
||||
|
||||
var value attr.Value
|
||||
switch parametersTypes[attribute].(type) {
|
||||
default:
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found unexpected attribute type '%T'", parametersTypes[attribute])
|
||||
case basetypes.StringType:
|
||||
if valueInterface == nil {
|
||||
value = types.StringNull()
|
||||
} else {
|
||||
valueString, ok := valueInterface.(string)
|
||||
if !ok {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as string", attribute, valueInterface)
|
||||
}
|
||||
value = types.StringValue(valueString)
|
||||
}
|
||||
case basetypes.BoolType:
|
||||
if valueInterface == nil {
|
||||
value = types.BoolNull()
|
||||
} else {
|
||||
valueBool, ok := valueInterface.(bool)
|
||||
if !ok {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as bool", attribute, valueInterface)
|
||||
}
|
||||
value = types.BoolValue(valueBool)
|
||||
}
|
||||
case basetypes.Int64Type:
|
||||
if valueInterface == nil {
|
||||
value = types.Int64Null()
|
||||
} else {
|
||||
// This may be int64, int32, int or float64
|
||||
// We try to assert all 4
|
||||
var valueInt64 int64
|
||||
switch temp := valueInterface.(type) {
|
||||
default:
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as int", attribute, valueInterface)
|
||||
case int64:
|
||||
valueInt64 = temp
|
||||
case int32:
|
||||
valueInt64 = int64(temp)
|
||||
case int:
|
||||
valueInt64 = int64(temp)
|
||||
case float64:
|
||||
valueInt64 = int64(temp)
|
||||
}
|
||||
value = types.Int64Value(valueInt64)
|
||||
}
|
||||
case basetypes.ListType: // Assumed to be a list of strings
|
||||
if valueInterface == nil {
|
||||
value = types.ListNull(types.StringType)
|
||||
} else {
|
||||
// This may be []string{} or []interface{}
|
||||
// We try to assert all 2
|
||||
var valueList []attr.Value
|
||||
switch temp := valueInterface.(type) {
|
||||
default:
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as array of interface", attribute, valueInterface)
|
||||
case []string:
|
||||
for _, x := range temp {
|
||||
valueList = append(valueList, types.StringValue(x))
|
||||
}
|
||||
case []interface{}:
|
||||
for _, x := range temp {
|
||||
xString, ok := x.(string)
|
||||
if !ok {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' with element '%s' of type %T, failed to assert as string", attribute, x, x)
|
||||
}
|
||||
valueList = append(valueList, types.StringValue(xString))
|
||||
}
|
||||
}
|
||||
temp2, diags := types.ListValue(types.StringType, valueList)
|
||||
if diags.HasError() {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("failed to map %s: %w", attribute, core.DiagsToError(diags))
|
||||
}
|
||||
value = temp2
|
||||
}
|
||||
}
|
||||
attributes[attribute] = value
|
||||
}
|
||||
|
||||
output, diags := types.ObjectValue(parametersTypes, attributes)
|
||||
if diags.HasError() {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("failed to create object: %w", core.DiagsToError(diags))
|
||||
}
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func (r *instanceResource) loadPlanId(ctx context.Context, model *Model) error {
|
||||
projectId := model.ProjectId.ValueString()
|
||||
res, err := r.client.GetOfferings(ctx, projectId).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting PostgreSQL offerings: %w", err)
|
||||
}
|
||||
|
||||
version := model.Version.ValueString()
|
||||
planName := model.PlanName.ValueString()
|
||||
availableVersions := ""
|
||||
availablePlanNames := ""
|
||||
isValidVersion := false
|
||||
for _, offer := range *res.Offerings {
|
||||
if !strings.EqualFold(*offer.Version, version) {
|
||||
availableVersions = fmt.Sprintf("%s\n- %s", availableVersions, *offer.Version)
|
||||
continue
|
||||
}
|
||||
isValidVersion = true
|
||||
|
||||
for _, plan := range *offer.Plans {
|
||||
if plan.Name == nil {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(*plan.Name, planName) && plan.Id != nil {
|
||||
model.PlanId = types.StringPointerValue(plan.Id)
|
||||
return nil
|
||||
}
|
||||
availablePlanNames = fmt.Sprintf("%s\n- %s", availablePlanNames, *plan.Name)
|
||||
}
|
||||
}
|
||||
|
||||
if !isValidVersion {
|
||||
return fmt.Errorf("couldn't find version '%s', available versions are: %s", version, availableVersions)
|
||||
}
|
||||
return fmt.Errorf("couldn't find plan_name '%s' for version %s, available names are: %s", planName, version, availablePlanNames)
|
||||
}
|
||||
|
||||
func loadPlanNameAndVersion(ctx context.Context, client *postgresql.APIClient, model *Model) error {
|
||||
projectId := model.ProjectId.ValueString()
|
||||
planId := model.PlanId.ValueString()
|
||||
res, err := client.GetOfferings(ctx, projectId).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting PostgreSQL offerings: %w", err)
|
||||
}
|
||||
|
||||
for _, offer := range *res.Offerings {
|
||||
for _, plan := range *offer.Plans {
|
||||
if strings.EqualFold(*plan.Id, planId) && plan.Id != nil {
|
||||
model.PlanName = types.StringPointerValue(plan.Name)
|
||||
model.Version = types.StringPointerValue(offer.Version)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("couldn't find plan_name and version for plan_id '%s'", planId)
|
||||
}
|
||||
435
stackit/internal/services/postgresql/instance/resource_test.go
Normal file
435
stackit/internal/services/postgresql/instance/resource_test.go
Normal file
|
|
@ -0,0 +1,435 @@
|
|||
package postgresql
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresql"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *postgresql.Instance
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&postgresql.Instance{},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
PlanId: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
CfGuid: types.StringNull(),
|
||||
CfSpaceGuid: types.StringNull(),
|
||||
DashboardUrl: types.StringNull(),
|
||||
ImageUrl: types.StringNull(),
|
||||
CfOrganizationGuid: types.StringNull(),
|
||||
Parameters: types.ObjectNull(parametersTypes),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&postgresql.Instance{
|
||||
PlanId: utils.Ptr("plan"),
|
||||
CfGuid: utils.Ptr("cf"),
|
||||
CfSpaceGuid: utils.Ptr("space"),
|
||||
DashboardUrl: utils.Ptr("dashboard"),
|
||||
ImageUrl: utils.Ptr("image"),
|
||||
InstanceId: utils.Ptr("iid"),
|
||||
Name: utils.Ptr("name"),
|
||||
CfOrganizationGuid: utils.Ptr("org"),
|
||||
Parameters: &map[string]interface{}{
|
||||
"enable_monitoring": true,
|
||||
"metrics_frequency": 1234,
|
||||
"plugins": []string{
|
||||
"plugin_1",
|
||||
"plugin_2",
|
||||
"",
|
||||
},
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
PlanId: types.StringValue("plan"),
|
||||
Name: types.StringValue("name"),
|
||||
CfGuid: types.StringValue("cf"),
|
||||
CfSpaceGuid: types.StringValue("space"),
|
||||
DashboardUrl: types.StringValue("dashboard"),
|
||||
ImageUrl: types.StringValue("image"),
|
||||
CfOrganizationGuid: types.StringValue("org"),
|
||||
Parameters: types.ObjectValueMust(parametersTypes, map[string]attr.Value{
|
||||
"enable_monitoring": types.BoolValue(true),
|
||||
"metrics_frequency": types.Int64Value(1234),
|
||||
"metrics_prefix": types.StringNull(),
|
||||
"monitoring_instance_id": types.StringNull(),
|
||||
"plugins": types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("plugin_1"),
|
||||
types.StringValue("plugin_2"),
|
||||
types.StringValue(""),
|
||||
}),
|
||||
"sgw_acl": types.StringNull(),
|
||||
}),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&postgresql.Instance{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"wrong_param_types_1",
|
||||
&postgresql.Instance{
|
||||
Parameters: &map[string]interface{}{
|
||||
"enable_monitoring": "true",
|
||||
},
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"wrong_param_types_2",
|
||||
&postgresql.Instance{
|
||||
Parameters: &map[string]interface{}{
|
||||
"metrics_frequency": true,
|
||||
},
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"wrong_param_types_3",
|
||||
&postgresql.Instance{
|
||||
Parameters: &map[string]interface{}{
|
||||
"metrics_frequency": 12.34,
|
||||
},
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"wrong_param_types_4",
|
||||
&postgresql.Instance{
|
||||
Parameters: &map[string]interface{}{
|
||||
"plugins": "foo",
|
||||
},
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"wrong_param_types_5",
|
||||
&postgresql.Instance{
|
||||
Parameters: &map[string]interface{}{
|
||||
"plugins": []bool{
|
||||
true,
|
||||
},
|
||||
},
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
state := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
}
|
||||
err := mapFields(tt.input, state)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputParameters *parametersModel
|
||||
inputParametersPlugins *[]string
|
||||
expected *postgresql.CreateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
¶metersModel{},
|
||||
&[]string{},
|
||||
&postgresql.CreateInstancePayload{
|
||||
Parameters: &postgresql.InstanceParameters{
|
||||
Plugins: &[]string{},
|
||||
},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_values",
|
||||
&Model{},
|
||||
¶metersModel{},
|
||||
nil,
|
||||
&postgresql.CreateInstancePayload{
|
||||
Parameters: &postgresql.InstanceParameters{
|
||||
Plugins: nil,
|
||||
},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
Name: types.StringValue("name"),
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
¶metersModel{
|
||||
EnableMonitoring: types.BoolValue(true),
|
||||
MetricsFrequency: types.Int64Value(123),
|
||||
MetricsPrefix: types.StringValue("prefix"),
|
||||
MonitoringInstanceId: types.StringValue("monitoring"),
|
||||
SgwAcl: types.StringValue("sgw"),
|
||||
},
|
||||
&[]string{
|
||||
"plugin_1",
|
||||
"plugin_2",
|
||||
},
|
||||
&postgresql.CreateInstancePayload{
|
||||
InstanceName: utils.Ptr("name"),
|
||||
Parameters: &postgresql.InstanceParameters{
|
||||
EnableMonitoring: utils.Ptr(true),
|
||||
MetricsFrequency: utils.Ptr(int32(123)),
|
||||
MetricsPrefix: utils.Ptr("prefix"),
|
||||
MonitoringInstanceId: utils.Ptr("monitoring"),
|
||||
Plugins: &[]string{
|
||||
"plugin_1",
|
||||
"plugin_2",
|
||||
},
|
||||
SgwAcl: utils.Ptr("sgw"),
|
||||
},
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
Name: types.StringValue(""),
|
||||
PlanId: types.StringValue(""),
|
||||
},
|
||||
¶metersModel{
|
||||
EnableMonitoring: types.BoolNull(),
|
||||
MetricsFrequency: types.Int64Value(2123456789),
|
||||
MetricsPrefix: types.StringNull(),
|
||||
MonitoringInstanceId: types.StringNull(),
|
||||
SgwAcl: types.StringNull(),
|
||||
},
|
||||
&[]string{
|
||||
"",
|
||||
},
|
||||
&postgresql.CreateInstancePayload{
|
||||
InstanceName: utils.Ptr(""),
|
||||
Parameters: &postgresql.InstanceParameters{
|
||||
EnableMonitoring: nil,
|
||||
MetricsFrequency: utils.Ptr(int32(2123456789)),
|
||||
MetricsPrefix: nil,
|
||||
MonitoringInstanceId: nil,
|
||||
Plugins: &[]string{
|
||||
"",
|
||||
},
|
||||
SgwAcl: nil,
|
||||
},
|
||||
PlanId: utils.Ptr(""),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
¶metersModel{},
|
||||
&[]string{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_parameters",
|
||||
&Model{
|
||||
Name: types.StringValue("name"),
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
nil,
|
||||
nil,
|
||||
&postgresql.CreateInstancePayload{
|
||||
InstanceName: utils.Ptr("name"),
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toCreatePayload(tt.input, tt.inputParameters, tt.inputParametersPlugins)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToUpdatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputParameters *parametersModel
|
||||
inputParametersPlugins *[]string
|
||||
expected *postgresql.UpdateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
¶metersModel{},
|
||||
&[]string{},
|
||||
&postgresql.UpdateInstancePayload{
|
||||
Parameters: &postgresql.InstanceParameters{
|
||||
Plugins: &[]string{},
|
||||
},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
¶metersModel{
|
||||
EnableMonitoring: types.BoolValue(true),
|
||||
MetricsFrequency: types.Int64Value(123),
|
||||
MetricsPrefix: types.StringValue("prefix"),
|
||||
MonitoringInstanceId: types.StringValue("monitoring"),
|
||||
SgwAcl: types.StringValue("sgw"),
|
||||
},
|
||||
&[]string{
|
||||
"plugin_1",
|
||||
"plugin_2",
|
||||
},
|
||||
&postgresql.UpdateInstancePayload{
|
||||
Parameters: &postgresql.InstanceParameters{
|
||||
EnableMonitoring: utils.Ptr(true),
|
||||
MetricsFrequency: utils.Ptr(int32(123)),
|
||||
MetricsPrefix: utils.Ptr("prefix"),
|
||||
MonitoringInstanceId: utils.Ptr("monitoring"),
|
||||
Plugins: &[]string{
|
||||
"plugin_1",
|
||||
"plugin_2",
|
||||
},
|
||||
SgwAcl: utils.Ptr("sgw"),
|
||||
},
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
PlanId: types.StringValue(""),
|
||||
},
|
||||
¶metersModel{
|
||||
EnableMonitoring: types.BoolNull(),
|
||||
MetricsFrequency: types.Int64Value(2123456789),
|
||||
MetricsPrefix: types.StringNull(),
|
||||
MonitoringInstanceId: types.StringNull(),
|
||||
SgwAcl: types.StringNull(),
|
||||
},
|
||||
&[]string{
|
||||
"",
|
||||
},
|
||||
&postgresql.UpdateInstancePayload{
|
||||
Parameters: &postgresql.InstanceParameters{
|
||||
EnableMonitoring: nil,
|
||||
MetricsFrequency: utils.Ptr(int32(2123456789)),
|
||||
MetricsPrefix: nil,
|
||||
MonitoringInstanceId: nil,
|
||||
Plugins: &[]string{
|
||||
"",
|
||||
},
|
||||
SgwAcl: nil,
|
||||
},
|
||||
PlanId: utils.Ptr(""),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
¶metersModel{},
|
||||
&[]string{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_parameters",
|
||||
&Model{
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
nil,
|
||||
nil,
|
||||
&postgresql.UpdateInstancePayload{
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toUpdatePayload(tt.input, tt.inputParameters, tt.inputParametersPlugins)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
254
stackit/internal/services/postgresql/postgresql_acc_test.go
Normal file
254
stackit/internal/services/postgresql/postgresql_acc_test.go
Normal file
|
|
@ -0,0 +1,254 @@
|
|||
package postgresql_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
|
||||
"github.com/hashicorp/terraform-plugin-testing/terraform"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/postgresql"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/testutil"
|
||||
)
|
||||
|
||||
// Instance resource data
|
||||
var instanceResource = map[string]string{
|
||||
"project_id": testutil.ProjectId,
|
||||
"name": testutil.ResourceNameWithDateTime("postgresql"),
|
||||
"plan_id": "57d40175-0f4c-4bcc-b52d-cf5d2ee9f5a7",
|
||||
"plan_name": "stackit-qa-postgresql-1.4.10-single",
|
||||
"version": "13",
|
||||
"sgw_acl": "192.168.0.0/16",
|
||||
"metrics_frequency": "34",
|
||||
"plugins": "foo-bar",
|
||||
}
|
||||
|
||||
func resourceConfig(acls, frequency, plugins string) string {
|
||||
return fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
resource "stackit_postgresql_instance" "instance" {
|
||||
project_id = "%s"
|
||||
name = "%s"
|
||||
plan_name = "%s"
|
||||
version = "%s"
|
||||
parameters = {
|
||||
sgw_acl = "%s"
|
||||
plugins = ["%s"]
|
||||
# metrics_frequency = %s
|
||||
# metrics_prefix = "pre"
|
||||
# enable_monitoring = true
|
||||
# monitoring_instance_id = "b9e38481-4f3d-4a28-8ed0-43fd32c024c7"
|
||||
}
|
||||
}
|
||||
|
||||
resource "stackit_postgresql_credentials" "credentials" {
|
||||
project_id = stackit_postgresql_instance.instance.project_id
|
||||
instance_id = stackit_postgresql_instance.instance.instance_id
|
||||
}
|
||||
`,
|
||||
testutil.PostgreSQLProviderConfig(),
|
||||
instanceResource["project_id"],
|
||||
instanceResource["name"],
|
||||
instanceResource["plan_name"],
|
||||
instanceResource["version"],
|
||||
acls,
|
||||
plugins,
|
||||
frequency,
|
||||
)
|
||||
}
|
||||
func TestAccPostgreSQLResource(t *testing.T) {
|
||||
resource.Test(t, resource.TestCase{
|
||||
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
|
||||
CheckDestroy: testAccCheckPostgreSQLDestroy,
|
||||
Steps: []resource.TestStep{
|
||||
|
||||
// Creation
|
||||
{
|
||||
Config: resourceConfig(instanceResource["sgw_acl"], instanceResource["metrics_frequency"], instanceResource["plugins"]),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("stackit_postgresql_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresql_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_postgresql_instance.instance", "plan_id", instanceResource["plan_id"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresql_instance.instance", "plan_name", instanceResource["plan_name"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresql_instance.instance", "version", instanceResource["version"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresql_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresql_instance.instance", "parameters.sgw_acl", instanceResource["sgw_acl"]),
|
||||
|
||||
// Credentials data
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_postgresql_credentials.credentials", "project_id",
|
||||
"stackit_postgresql_instance.instance", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_postgresql_credentials.credentials", "instance_id",
|
||||
"stackit_postgresql_instance.instance", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresql_credentials.credentials", "credentials_id"),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresql_credentials.credentials", "host"),
|
||||
),
|
||||
},
|
||||
{ // Data source
|
||||
Config: fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
data "stackit_postgresql_instance" "instance" {
|
||||
project_id = stackit_postgresql_instance.instance.project_id
|
||||
instance_id = stackit_postgresql_instance.instance.instance_id
|
||||
}
|
||||
|
||||
data "stackit_postgresql_credentials" "credentials" {
|
||||
project_id = stackit_postgresql_credentials.credentials.project_id
|
||||
instance_id = stackit_postgresql_credentials.credentials.instance_id
|
||||
credentials_id = stackit_postgresql_credentials.credentials.credentials_id
|
||||
}`,
|
||||
resourceConfig(instanceResource["sgw_acl"], instanceResource["metrics_frequency"], instanceResource["plugins"]),
|
||||
),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresql_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrPair("stackit_postgresql_instance.instance", "instance_id",
|
||||
"data.stackit_postgresql_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttrPair("stackit_postgresql_credentials.credentials", "credentials_id",
|
||||
"data.stackit_postgresql_credentials.credentials", "credentials_id"),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresql_instance.instance", "plan_id", instanceResource["plan_id"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresql_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresql_instance.instance", "parameters.sgw_acl", instanceResource["sgw_acl"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresql_instance.instance", "parameters.plugins.#", "1"),
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresql_instance.instance", "parameters.plugins.0", instanceResource["plugins"]),
|
||||
|
||||
// Credentials data
|
||||
resource.TestCheckResourceAttr("data.stackit_postgresql_credentials.credentials", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_postgresql_credentials.credentials", "credentials_id"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_postgresql_credentials.credentials", "host"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_postgresql_credentials.credentials", "port"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_postgresql_credentials.credentials", "uri"),
|
||||
),
|
||||
},
|
||||
// Import
|
||||
{
|
||||
ResourceName: "stackit_postgresql_instance.instance",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_postgresql_instance.instance"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_postgresql_instance.instance")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
return fmt.Sprintf("%s,%s", testutil.ProjectId, instanceId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
{
|
||||
ResourceName: "stackit_postgresql_credentials.credentials",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_postgresql_credentials.credentials"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_postgresql_credentials.credentials")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
credentialsId, ok := r.Primary.Attributes["credentials_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute credentials_id")
|
||||
}
|
||||
return fmt.Sprintf("%s,%s,%s", testutil.ProjectId, instanceId, credentialsId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
// Update
|
||||
{
|
||||
Config: resourceConfig(instanceResource["sgw_acl"], fmt.Sprintf("%s0", instanceResource["metrics_frequency"]), fmt.Sprintf("%s-baz", instanceResource["plugins"])),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("stackit_postgresql_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_postgresql_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_postgresql_instance.instance", "plan_id", instanceResource["plan_id"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresql_instance.instance", "plan_name", instanceResource["plan_name"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresql_instance.instance", "version", instanceResource["version"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresql_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresql_instance.instance", "parameters.sgw_acl", instanceResource["sgw_acl"]),
|
||||
resource.TestCheckResourceAttr("stackit_postgresql_instance.instance", "parameters.plugins.0", fmt.Sprintf("%s-baz", instanceResource["plugins"])),
|
||||
),
|
||||
},
|
||||
// Deletion is done by the framework implicitly
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func testAccCheckPostgreSQLDestroy(s *terraform.State) error {
|
||||
ctx := context.Background()
|
||||
var client *postgresql.APIClient
|
||||
var err error
|
||||
if testutil.PostgreSQLCustomEndpoint == "" {
|
||||
client, err = postgresql.NewAPIClient()
|
||||
} else {
|
||||
client, err = postgresql.NewAPIClient(
|
||||
config.WithEndpoint(testutil.PostgreSQLCustomEndpoint),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating client: %w", err)
|
||||
}
|
||||
|
||||
instancesToDestroy := []string{}
|
||||
for _, rs := range s.RootModule().Resources {
|
||||
if rs.Type != "stackit_postgresql_instance" {
|
||||
continue
|
||||
}
|
||||
// instance terraform ID: "[project_id],[instance_id]"
|
||||
instanceId := strings.Split(rs.Primary.ID, core.Separator)[1]
|
||||
instancesToDestroy = append(instancesToDestroy, instanceId)
|
||||
}
|
||||
|
||||
instancesResp, err := client.GetInstances(ctx, testutil.ProjectId).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting instancesResp: %w", err)
|
||||
}
|
||||
|
||||
instances := *instancesResp.Instances
|
||||
for i := range instances {
|
||||
if instances[i].InstanceId == nil {
|
||||
continue
|
||||
}
|
||||
if utils.Contains(instancesToDestroy, *instances[i].InstanceId) {
|
||||
if !checkInstanceDeleteSuccess(&instances[i]) {
|
||||
err := client.DeleteInstanceExecute(ctx, testutil.ProjectId, *instances[i].InstanceId)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying instance %s during CheckDestroy: %w", *instances[i].InstanceId, err)
|
||||
}
|
||||
_, err = postgresql.DeleteInstanceWaitHandler(ctx, client, testutil.ProjectId, *instances[i].InstanceId).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying instance %s during CheckDestroy: waiting for deletion %w", *instances[i].InstanceId, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkInstanceDeleteSuccess(i *postgresql.Instance) bool {
|
||||
if *i.LastOperation.Type != postgresql.InstanceTypeDelete {
|
||||
return false
|
||||
}
|
||||
|
||||
if *i.LastOperation.Type == postgresql.InstanceTypeDelete {
|
||||
if *i.LastOperation.State != postgresql.InstanceStateSuccess {
|
||||
return false
|
||||
} else if strings.Contains(*i.LastOperation.Description, "DeleteFailed") || strings.Contains(*i.LastOperation.Description, "failed") {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
181
stackit/internal/services/rabbitmq/credentials/datasource.go
Normal file
181
stackit/internal/services/rabbitmq/credentials/datasource.go
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
package rabbitmq
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/rabbitmq"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &credentialsDataSource{}
|
||||
)
|
||||
|
||||
// NewCredentialsDataSource is a helper function to simplify the provider implementation.
|
||||
func NewCredentialsDataSource() datasource.DataSource {
|
||||
return &credentialsDataSource{}
|
||||
}
|
||||
|
||||
// credentialsDataSource is the data source implementation.
|
||||
type credentialsDataSource struct {
|
||||
client *rabbitmq.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *credentialsDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_rabbitmq_credentials"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *credentialsDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *rabbitmq.APIClient
|
||||
var err error
|
||||
if providerData.RabbitMQCustomEndpoint != "" {
|
||||
apiClient, err = rabbitmq.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.RabbitMQCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = rabbitmq.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "RabbitMQ credentials client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *credentialsDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "RabbitMQ credentials data source schema.",
|
||||
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`,`credentials_id`\".",
|
||||
"credentials_id": "The credentials ID.",
|
||||
"instance_id": "ID of the RabbitMQ instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"credentials_id": schema.StringAttribute{
|
||||
Description: descriptions["credentials_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"hosts": schema.ListAttribute{
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"http_api_uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"password": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *credentialsDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
credentialsId := model.CredentialsId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(recordSetResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "RabbitMQ credentials read")
|
||||
}
|
||||
377
stackit/internal/services/rabbitmq/credentials/resource.go
Normal file
377
stackit/internal/services/rabbitmq/credentials/resource.go
Normal file
|
|
@ -0,0 +1,377 @@
|
|||
package rabbitmq
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/rabbitmq"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &credentialsResource{}
|
||||
_ resource.ResourceWithConfigure = &credentialsResource{}
|
||||
_ resource.ResourceWithImportState = &credentialsResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
CredentialsId types.String `tfsdk:"credentials_id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Host types.String `tfsdk:"host"`
|
||||
Hosts types.List `tfsdk:"hosts"`
|
||||
HttpAPIURI types.String `tfsdk:"http_api_uri"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Password types.String `tfsdk:"password"`
|
||||
Port types.Int64 `tfsdk:"port"`
|
||||
Uri types.String `tfsdk:"uri"`
|
||||
Username types.String `tfsdk:"username"`
|
||||
}
|
||||
|
||||
// NewCredentialsResource is a helper function to simplify the provider implementation.
|
||||
func NewCredentialsResource() resource.Resource {
|
||||
return &credentialsResource{}
|
||||
}
|
||||
|
||||
// credentialsResource is the resource implementation.
|
||||
type credentialsResource struct {
|
||||
client *rabbitmq.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *credentialsResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_rabbitmq_credentials"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *credentialsResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *rabbitmq.APIClient
|
||||
var err error
|
||||
if providerData.RabbitMQCustomEndpoint != "" {
|
||||
apiClient, err = rabbitmq.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.RabbitMQCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = rabbitmq.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "RabbitMQ credentials client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *credentialsResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "RabbitMQ credentials resource schema.",
|
||||
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`,`credentials_id`\".",
|
||||
"credentials_id": "The credentials ID.",
|
||||
"instance_id": "ID of the RabbitMQ instance.",
|
||||
"project_id": "STACKIT Project ID to which the instance is associated.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"credentials_id": schema.StringAttribute{
|
||||
Description: descriptions["credentials_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"hosts": schema.ListAttribute{
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"http_api_uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"password": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *credentialsResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
// Create new recordset
|
||||
credentialsResp, err := r.client.CreateCredentials(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
if credentialsResp.Id == nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", "Got empty credentials id")
|
||||
return
|
||||
}
|
||||
credentialsId := *credentialsResp.Id
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
wr, err := rabbitmq.CreateCredentialsWaitHandler(ctx, r.client, projectId, instanceId, credentialsId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Instance creation waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*rabbitmq.CredentialsResponse)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "RabbitMQ credentials created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *credentialsResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
credentialsId := model.CredentialsId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(recordSetResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "RabbitMQ credentials read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *credentialsResource) Update(ctx context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Update shouldn't be called
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating credentials", "Credentials can't be updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *credentialsResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
credentialsId := model.CredentialsId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
// Delete existing record set
|
||||
err := r.client.DeleteCredentials(ctx, projectId, instanceId, credentialsId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
}
|
||||
_, err = rabbitmq.DeleteCredentialsWaitHandler(ctx, r.client, projectId, instanceId, credentialsId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credentials", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "RabbitMQ credentials deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,instance_id,credentials_id
|
||||
func (r *credentialsResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing credentials",
|
||||
fmt.Sprintf("Expected import identifier with format [project_id],[instance_id],[credentials_id], got %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[1])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("credentials_id"), idParts[2])...)
|
||||
tflog.Info(ctx, "RabbitMQ credentials state imported")
|
||||
}
|
||||
|
||||
func mapFields(credentialsResp *rabbitmq.CredentialsResponse, model *Model) error {
|
||||
if credentialsResp == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if credentialsResp.Raw == nil {
|
||||
return fmt.Errorf("response credentials raw is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
credentials := credentialsResp.Raw.Credentials
|
||||
|
||||
var credentialsId string
|
||||
if model.CredentialsId.ValueString() != "" {
|
||||
credentialsId = model.CredentialsId.ValueString()
|
||||
} else if credentialsResp.Id != nil {
|
||||
credentialsId = *credentialsResp.Id
|
||||
} else {
|
||||
return fmt.Errorf("credentials id not present")
|
||||
}
|
||||
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
model.InstanceId.ValueString(),
|
||||
credentialsId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.CredentialsId = types.StringValue(credentialsId)
|
||||
model.Hosts = types.ListNull(types.StringType)
|
||||
if credentials != nil {
|
||||
if credentials.Hosts != nil {
|
||||
var hosts []attr.Value
|
||||
for _, host := range *credentials.Hosts {
|
||||
hosts = append(hosts, types.StringValue(host))
|
||||
}
|
||||
hostsList, diags := types.ListValue(types.StringType, hosts)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map hosts: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Hosts = hostsList
|
||||
}
|
||||
model.Host = types.StringPointerValue(credentials.Host)
|
||||
model.HttpAPIURI = types.StringPointerValue(credentials.HttpApiUri)
|
||||
model.Name = types.StringPointerValue(credentials.Name)
|
||||
model.Password = types.StringPointerValue(credentials.Password)
|
||||
model.Port = conversion.ToTypeInt64(credentials.Port)
|
||||
model.Uri = types.StringPointerValue(credentials.Uri)
|
||||
model.Username = types.StringPointerValue(credentials.Username)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
156
stackit/internal/services/rabbitmq/credentials/resource_test.go
Normal file
156
stackit/internal/services/rabbitmq/credentials/resource_test.go
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
package rabbitmq
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/rabbitmq"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *rabbitmq.CredentialsResponse
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&rabbitmq.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
Raw: &rabbitmq.RawCredentials{},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,cid"),
|
||||
CredentialsId: types.StringValue("cid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Host: types.StringNull(),
|
||||
Hosts: types.ListNull(types.StringType),
|
||||
HttpAPIURI: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Password: types.StringNull(),
|
||||
Port: types.Int64Null(),
|
||||
Uri: types.StringNull(),
|
||||
Username: types.StringNull(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&rabbitmq.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
Raw: &rabbitmq.RawCredentials{
|
||||
Credentials: &rabbitmq.Credentials{
|
||||
Host: utils.Ptr("host"),
|
||||
Hosts: &[]string{
|
||||
"host_1",
|
||||
"",
|
||||
},
|
||||
HttpApiUri: utils.Ptr("http"),
|
||||
Name: utils.Ptr("name"),
|
||||
Password: utils.Ptr("password"),
|
||||
Port: utils.Ptr(int32(1234)),
|
||||
Uri: utils.Ptr("uri"),
|
||||
Username: utils.Ptr("username"),
|
||||
},
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,cid"),
|
||||
CredentialsId: types.StringValue("cid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Host: types.StringValue("host"),
|
||||
Hosts: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("host_1"),
|
||||
types.StringValue(""),
|
||||
}),
|
||||
HttpAPIURI: types.StringValue("http"),
|
||||
Name: types.StringValue("name"),
|
||||
Password: types.StringValue("password"),
|
||||
Port: types.Int64Value(1234),
|
||||
Uri: types.StringValue("uri"),
|
||||
Username: types.StringValue("username"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&rabbitmq.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
Raw: &rabbitmq.RawCredentials{
|
||||
Credentials: &rabbitmq.Credentials{
|
||||
Host: utils.Ptr(""),
|
||||
Hosts: &[]string{},
|
||||
HttpApiUri: nil,
|
||||
Name: nil,
|
||||
Password: utils.Ptr(""),
|
||||
Port: utils.Ptr(int32(2123456789)),
|
||||
Uri: nil,
|
||||
Username: utils.Ptr(""),
|
||||
},
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,cid"),
|
||||
CredentialsId: types.StringValue("cid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Host: types.StringValue(""),
|
||||
Hosts: types.ListValueMust(types.StringType, []attr.Value{}),
|
||||
HttpAPIURI: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Password: types.StringValue(""),
|
||||
Port: types.Int64Value(2123456789),
|
||||
Uri: types.StringNull(),
|
||||
Username: types.StringValue(""),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&rabbitmq.CredentialsResponse{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_raw_credentials",
|
||||
&rabbitmq.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
model := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
}
|
||||
err := mapFields(tt.input, model)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(model, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
192
stackit/internal/services/rabbitmq/instance/datasource.go
Normal file
192
stackit/internal/services/rabbitmq/instance/datasource.go
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
package rabbitmq
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/rabbitmq"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &instanceDataSource{}
|
||||
)
|
||||
|
||||
// NewInstanceDataSource is a helper function to simplify the provider implementation.
|
||||
func NewInstanceDataSource() datasource.DataSource {
|
||||
return &instanceDataSource{}
|
||||
}
|
||||
|
||||
// instanceDataSource is the data source implementation.
|
||||
type instanceDataSource struct {
|
||||
client *rabbitmq.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *instanceDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_rabbitmq_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *instanceDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *rabbitmq.APIClient
|
||||
var err error
|
||||
if providerData.RabbitMQCustomEndpoint != "" {
|
||||
apiClient, err = rabbitmq.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.RabbitMQCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = rabbitmq.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "RabbitMQ zone client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "RabbitMQ instance data source schema.",
|
||||
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`\".",
|
||||
"instance_id": "ID of the RabbitMQ instance.",
|
||||
"project_id": "STACKIT Project ID to which the instance is associated.",
|
||||
"name": "Instance name.",
|
||||
"version": "The service version.",
|
||||
"plan_name": "The selected plan name.",
|
||||
"plan_id": "The selected plan ID.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Computed: true,
|
||||
},
|
||||
"version": schema.StringAttribute{
|
||||
Description: descriptions["version"],
|
||||
Computed: true,
|
||||
},
|
||||
"plan_name": schema.StringAttribute{
|
||||
Description: descriptions["plan_name"],
|
||||
Computed: true,
|
||||
},
|
||||
"plan_id": schema.StringAttribute{
|
||||
Description: descriptions["plan_id"],
|
||||
Computed: true,
|
||||
},
|
||||
"parameters": schema.SingleNestedAttribute{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"sgw_acl": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
Computed: true,
|
||||
},
|
||||
"cf_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"cf_space_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"dashboard_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"image_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"cf_organization_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *instanceDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
err = mapFields(instanceResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Compute and store values not present in the API response
|
||||
err = loadPlanNameAndVersion(ctx, r.client, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Loading service plan details: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "RabbitMQ instance read")
|
||||
}
|
||||
680
stackit/internal/services/rabbitmq/instance/resource.go
Normal file
680
stackit/internal/services/rabbitmq/instance/resource.go
Normal file
|
|
@ -0,0 +1,680 @@
|
|||
package rabbitmq
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/rabbitmq"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &instanceResource{}
|
||||
_ resource.ResourceWithConfigure = &instanceResource{}
|
||||
_ resource.ResourceWithImportState = &instanceResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
CfGuid types.String `tfsdk:"cf_guid"`
|
||||
CfSpaceGuid types.String `tfsdk:"cf_space_guid"`
|
||||
DashboardUrl types.String `tfsdk:"dashboard_url"`
|
||||
ImageUrl types.String `tfsdk:"image_url"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
CfOrganizationGuid types.String `tfsdk:"cf_organization_guid"`
|
||||
Parameters types.Object `tfsdk:"parameters"`
|
||||
Version types.String `tfsdk:"version"`
|
||||
PlanName types.String `tfsdk:"plan_name"`
|
||||
PlanId types.String `tfsdk:"plan_id"`
|
||||
}
|
||||
|
||||
// Struct corresponding to DataSourceModel.Parameters
|
||||
type parametersModel struct {
|
||||
SgwAcl types.String `tfsdk:"sgw_acl"`
|
||||
}
|
||||
|
||||
// Types corresponding to parametersModel
|
||||
var parametersTypes = map[string]attr.Type{
|
||||
"sgw_acl": basetypes.StringType{},
|
||||
}
|
||||
|
||||
// NewInstanceResource is a helper function to simplify the provider implementation.
|
||||
func NewInstanceResource() resource.Resource {
|
||||
return &instanceResource{}
|
||||
}
|
||||
|
||||
// instanceResource is the resource implementation.
|
||||
type instanceResource struct {
|
||||
client *rabbitmq.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *instanceResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_rabbitmq_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *instanceResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *rabbitmq.APIClient
|
||||
var err error
|
||||
if providerData.RabbitMQCustomEndpoint != "" {
|
||||
apiClient, err = rabbitmq.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.RabbitMQCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = rabbitmq.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "RabbitMQ instance client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *instanceResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "RabbitMQ instance resource schema.",
|
||||
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`\".",
|
||||
"instance_id": "ID of the RabbitMQ instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"name": "Instance name.",
|
||||
"version": "The service version.",
|
||||
"plan_name": "The selected plan name.",
|
||||
"plan_id": "The selected plan ID.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
},
|
||||
},
|
||||
"version": schema.StringAttribute{
|
||||
Description: descriptions["version"],
|
||||
Required: true,
|
||||
},
|
||||
"plan_name": schema.StringAttribute{
|
||||
Description: descriptions["plan_name"],
|
||||
Required: true,
|
||||
},
|
||||
"plan_id": schema.StringAttribute{
|
||||
Description: descriptions["plan_id"],
|
||||
Computed: true,
|
||||
},
|
||||
"parameters": schema.SingleNestedAttribute{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"sgw_acl": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
},
|
||||
"cf_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"cf_space_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"dashboard_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"image_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"cf_organization_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *instanceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
|
||||
var parameters = ¶metersModel{}
|
||||
if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) {
|
||||
diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err := r.loadPlanId(ctx, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Loading service plan: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model, parameters)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Create new instance
|
||||
createResp, err := r.client.CreateInstance(ctx, projectId).CreateInstancePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
instanceId := *createResp.InstanceId
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
wr, err := rabbitmq.CreateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Instance creation waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*rabbitmq.Instance)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "RabbitMQ instance created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(instanceResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Compute and store values not present in the API response
|
||||
err = loadPlanNameAndVersion(ctx, r.client, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Loading service plan details: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "RabbitMQ instance read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *instanceResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
var parameters = ¶metersModel{}
|
||||
if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) {
|
||||
diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err := r.loadPlanId(ctx, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Loading service plan: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toUpdatePayload(&model, parameters)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Update existing instance
|
||||
err = r.client.UpdateInstance(ctx, projectId, instanceId).UpdateInstancePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
wr, err := rabbitmq.UpdateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Instance update waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*rabbitmq.Instance)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "RabbitMQ instance updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *instanceResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from state
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
// Delete existing instance
|
||||
err := r.client.DeleteInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
_, err = rabbitmq.DeleteInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "RabbitMQ instance deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,instance_id
|
||||
func (r *instanceResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
|
||||
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing instance",
|
||||
fmt.Sprintf("Expected import identifier with format: [project_id],[instance_id] Got: %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[1])...)
|
||||
tflog.Info(ctx, "RabbitMQ instance state imported")
|
||||
}
|
||||
|
||||
func mapFields(instance *rabbitmq.Instance, model *Model) error {
|
||||
if instance == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
|
||||
var instanceId string
|
||||
if model.InstanceId.ValueString() != "" {
|
||||
instanceId = model.InstanceId.ValueString()
|
||||
} else if instance.InstanceId != nil {
|
||||
instanceId = *instance.InstanceId
|
||||
} else {
|
||||
return fmt.Errorf("instance id not present")
|
||||
}
|
||||
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
instanceId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.InstanceId = types.StringValue(instanceId)
|
||||
model.PlanId = types.StringPointerValue(instance.PlanId)
|
||||
model.CfGuid = types.StringPointerValue(instance.CfGuid)
|
||||
model.CfSpaceGuid = types.StringPointerValue(instance.CfSpaceGuid)
|
||||
model.DashboardUrl = types.StringPointerValue(instance.DashboardUrl)
|
||||
model.ImageUrl = types.StringPointerValue(instance.ImageUrl)
|
||||
model.Name = types.StringPointerValue(instance.Name)
|
||||
model.CfOrganizationGuid = types.StringPointerValue(instance.CfOrganizationGuid)
|
||||
|
||||
if instance.Parameters == nil {
|
||||
model.Parameters = types.ObjectNull(parametersTypes)
|
||||
} else {
|
||||
parameters, err := mapParameters(*instance.Parameters)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mapping parameters: %w", err)
|
||||
}
|
||||
model.Parameters = parameters
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func mapParameters(params map[string]interface{}) (types.Object, error) {
|
||||
attributes := map[string]attr.Value{}
|
||||
for attribute := range parametersTypes {
|
||||
valueInterface, ok := params[attribute]
|
||||
if !ok {
|
||||
// All fields are optional, so this is ok
|
||||
// Set the value as nil, will be handled accordingly
|
||||
valueInterface = nil
|
||||
}
|
||||
|
||||
var value attr.Value
|
||||
switch parametersTypes[attribute].(type) {
|
||||
default:
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found unexpected attribute type '%T'", parametersTypes[attribute])
|
||||
case basetypes.StringType:
|
||||
if valueInterface == nil {
|
||||
value = types.StringNull()
|
||||
} else {
|
||||
valueString, ok := valueInterface.(string)
|
||||
if !ok {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as string", attribute, valueInterface)
|
||||
}
|
||||
value = types.StringValue(valueString)
|
||||
}
|
||||
case basetypes.BoolType:
|
||||
if valueInterface == nil {
|
||||
value = types.BoolNull()
|
||||
} else {
|
||||
valueBool, ok := valueInterface.(bool)
|
||||
if !ok {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as bool", attribute, valueInterface)
|
||||
}
|
||||
value = types.BoolValue(valueBool)
|
||||
}
|
||||
case basetypes.Int64Type:
|
||||
if valueInterface == nil {
|
||||
value = types.Int64Null()
|
||||
} else {
|
||||
// This may be int64, int32, int or float64
|
||||
// We try to assert all 4
|
||||
var valueInt64 int64
|
||||
switch temp := valueInterface.(type) {
|
||||
default:
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as int", attribute, valueInterface)
|
||||
case int64:
|
||||
valueInt64 = temp
|
||||
case int32:
|
||||
valueInt64 = int64(temp)
|
||||
case int:
|
||||
valueInt64 = int64(temp)
|
||||
case float64:
|
||||
valueInt64 = int64(temp)
|
||||
}
|
||||
value = types.Int64Value(valueInt64)
|
||||
}
|
||||
case basetypes.ListType: // Assumed to be a list of strings
|
||||
if valueInterface == nil {
|
||||
value = types.ListNull(types.StringType)
|
||||
} else {
|
||||
// This may be []string{} or []interface{}
|
||||
// We try to assert all 2
|
||||
var valueList []attr.Value
|
||||
switch temp := valueInterface.(type) {
|
||||
default:
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as array of interface", attribute, valueInterface)
|
||||
case []string:
|
||||
for _, x := range temp {
|
||||
valueList = append(valueList, types.StringValue(x))
|
||||
}
|
||||
case []interface{}:
|
||||
for _, x := range temp {
|
||||
xString, ok := x.(string)
|
||||
if !ok {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' with element '%s' of type %T, failed to assert as string", attribute, x, x)
|
||||
}
|
||||
valueList = append(valueList, types.StringValue(xString))
|
||||
}
|
||||
}
|
||||
temp2, diags := types.ListValue(types.StringType, valueList)
|
||||
if diags.HasError() {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("failed to map %s: %w", attribute, core.DiagsToError(diags))
|
||||
}
|
||||
value = temp2
|
||||
}
|
||||
}
|
||||
attributes[attribute] = value
|
||||
}
|
||||
|
||||
output, diags := types.ObjectValue(parametersTypes, attributes)
|
||||
if diags.HasError() {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("failed to create object: %w", core.DiagsToError(diags))
|
||||
}
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model, parameters *parametersModel) (*rabbitmq.CreateInstancePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
if parameters == nil {
|
||||
return &rabbitmq.CreateInstancePayload{
|
||||
InstanceName: model.Name.ValueStringPointer(),
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
payloadParams := &rabbitmq.InstanceParameters{}
|
||||
if parameters.SgwAcl.ValueString() != "" {
|
||||
payloadParams.SgwAcl = parameters.SgwAcl.ValueStringPointer()
|
||||
}
|
||||
return &rabbitmq.CreateInstancePayload{
|
||||
InstanceName: model.Name.ValueStringPointer(),
|
||||
Parameters: payloadParams,
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toUpdatePayload(model *Model, parameters *parametersModel) (*rabbitmq.UpdateInstancePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
if parameters == nil {
|
||||
return &rabbitmq.UpdateInstancePayload{
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
return &rabbitmq.UpdateInstancePayload{
|
||||
Parameters: &rabbitmq.InstanceParameters{
|
||||
SgwAcl: parameters.SgwAcl.ValueStringPointer(),
|
||||
},
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *instanceResource) loadPlanId(ctx context.Context, model *Model) error {
|
||||
projectId := model.ProjectId.ValueString()
|
||||
res, err := r.client.GetOfferings(ctx, projectId).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting RabbitMQ offerings: %w", err)
|
||||
}
|
||||
|
||||
version := model.Version.ValueString()
|
||||
planName := model.PlanName.ValueString()
|
||||
availableVersions := ""
|
||||
availablePlanNames := ""
|
||||
isValidVersion := false
|
||||
for _, offer := range *res.Offerings {
|
||||
if !strings.EqualFold(*offer.Version, version) {
|
||||
availableVersions = fmt.Sprintf("%s\n- %s", availableVersions, *offer.Version)
|
||||
continue
|
||||
}
|
||||
isValidVersion = true
|
||||
|
||||
for _, plan := range *offer.Plans {
|
||||
if plan.Name == nil {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(*plan.Name, planName) && plan.Id != nil {
|
||||
model.PlanId = types.StringPointerValue(plan.Id)
|
||||
return nil
|
||||
}
|
||||
availablePlanNames = fmt.Sprintf("%s\n- %s", availablePlanNames, *plan.Name)
|
||||
}
|
||||
}
|
||||
|
||||
if !isValidVersion {
|
||||
return fmt.Errorf("couldn't find version '%s', available versions are: %s", version, availableVersions)
|
||||
}
|
||||
return fmt.Errorf("couldn't find plan_name '%s' for version %s, available names are: %s", planName, version, availablePlanNames)
|
||||
}
|
||||
|
||||
func loadPlanNameAndVersion(ctx context.Context, client *rabbitmq.APIClient, model *Model) error {
|
||||
projectId := model.ProjectId.ValueString()
|
||||
planId := model.PlanId.ValueString()
|
||||
res, err := client.GetOfferings(ctx, projectId).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting RabbitMQ offerings: %w", err)
|
||||
}
|
||||
|
||||
for _, offer := range *res.Offerings {
|
||||
for _, plan := range *offer.Plans {
|
||||
if strings.EqualFold(*plan.Id, planId) && plan.Id != nil {
|
||||
model.PlanName = types.StringPointerValue(plan.Name)
|
||||
model.Version = types.StringPointerValue(offer.Version)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("couldn't find plan_name and version for plan_id '%s'", planId)
|
||||
}
|
||||
304
stackit/internal/services/rabbitmq/instance/resource_test.go
Normal file
304
stackit/internal/services/rabbitmq/instance/resource_test.go
Normal file
|
|
@ -0,0 +1,304 @@
|
|||
package rabbitmq
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/rabbitmq"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *rabbitmq.Instance
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&rabbitmq.Instance{},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
PlanId: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
CfGuid: types.StringNull(),
|
||||
CfSpaceGuid: types.StringNull(),
|
||||
DashboardUrl: types.StringNull(),
|
||||
ImageUrl: types.StringNull(),
|
||||
CfOrganizationGuid: types.StringNull(),
|
||||
Parameters: types.ObjectNull(parametersTypes),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&rabbitmq.Instance{
|
||||
PlanId: utils.Ptr("plan"),
|
||||
CfGuid: utils.Ptr("cf"),
|
||||
CfSpaceGuid: utils.Ptr("space"),
|
||||
DashboardUrl: utils.Ptr("dashboard"),
|
||||
ImageUrl: utils.Ptr("image"),
|
||||
InstanceId: utils.Ptr("iid"),
|
||||
Name: utils.Ptr("name"),
|
||||
CfOrganizationGuid: utils.Ptr("org"),
|
||||
Parameters: &map[string]interface{}{
|
||||
"sgw_acl": "acl",
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
PlanId: types.StringValue("plan"),
|
||||
Name: types.StringValue("name"),
|
||||
CfGuid: types.StringValue("cf"),
|
||||
CfSpaceGuid: types.StringValue("space"),
|
||||
DashboardUrl: types.StringValue("dashboard"),
|
||||
ImageUrl: types.StringValue("image"),
|
||||
CfOrganizationGuid: types.StringValue("org"),
|
||||
Parameters: types.ObjectValueMust(parametersTypes, map[string]attr.Value{
|
||||
"sgw_acl": types.StringValue("acl"),
|
||||
}),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&rabbitmq.Instance{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"wrong_param_types_1",
|
||||
&rabbitmq.Instance{
|
||||
Parameters: &map[string]interface{}{
|
||||
"sgw_acl": true,
|
||||
},
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"wrong_param_types_2",
|
||||
&rabbitmq.Instance{
|
||||
Parameters: &map[string]interface{}{
|
||||
"sgw_acl": 1,
|
||||
},
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
state := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
}
|
||||
err := mapFields(tt.input, state)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputParameters *parametersModel
|
||||
expected *rabbitmq.CreateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
¶metersModel{},
|
||||
&rabbitmq.CreateInstancePayload{
|
||||
Parameters: &rabbitmq.InstanceParameters{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
Name: types.StringValue("name"),
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
¶metersModel{
|
||||
SgwAcl: types.StringValue("sgw"),
|
||||
},
|
||||
&rabbitmq.CreateInstancePayload{
|
||||
InstanceName: utils.Ptr("name"),
|
||||
Parameters: &rabbitmq.InstanceParameters{
|
||||
SgwAcl: utils.Ptr("sgw"),
|
||||
},
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
Name: types.StringValue(""),
|
||||
PlanId: types.StringValue(""),
|
||||
},
|
||||
¶metersModel{
|
||||
SgwAcl: types.StringNull(),
|
||||
},
|
||||
&rabbitmq.CreateInstancePayload{
|
||||
InstanceName: utils.Ptr(""),
|
||||
Parameters: &rabbitmq.InstanceParameters{
|
||||
SgwAcl: nil,
|
||||
},
|
||||
PlanId: utils.Ptr(""),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
¶metersModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_parameters",
|
||||
&Model{
|
||||
Name: types.StringValue("name"),
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
nil,
|
||||
&rabbitmq.CreateInstancePayload{
|
||||
InstanceName: utils.Ptr("name"),
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toCreatePayload(tt.input, tt.inputParameters)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToUpdatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputParameters *parametersModel
|
||||
expected *rabbitmq.UpdateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
¶metersModel{},
|
||||
&rabbitmq.UpdateInstancePayload{
|
||||
Parameters: &rabbitmq.InstanceParameters{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
¶metersModel{
|
||||
SgwAcl: types.StringValue("sgw"),
|
||||
},
|
||||
&rabbitmq.UpdateInstancePayload{
|
||||
Parameters: &rabbitmq.InstanceParameters{
|
||||
SgwAcl: utils.Ptr("sgw"),
|
||||
},
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
PlanId: types.StringValue(""),
|
||||
},
|
||||
¶metersModel{
|
||||
SgwAcl: types.StringNull(),
|
||||
},
|
||||
&rabbitmq.UpdateInstancePayload{
|
||||
Parameters: &rabbitmq.InstanceParameters{
|
||||
SgwAcl: nil,
|
||||
},
|
||||
PlanId: utils.Ptr(""),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
¶metersModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_parameters",
|
||||
&Model{
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
nil,
|
||||
&rabbitmq.UpdateInstancePayload{
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toUpdatePayload(tt.input, tt.inputParameters)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
290
stackit/internal/services/rabbitmq/rabbitmq_acc_test.go
Normal file
290
stackit/internal/services/rabbitmq/rabbitmq_acc_test.go
Normal file
|
|
@ -0,0 +1,290 @@
|
|||
package rabbitmq_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
|
||||
"github.com/hashicorp/terraform-plugin-testing/terraform"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/rabbitmq"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/testutil"
|
||||
)
|
||||
|
||||
// Instance resource data
|
||||
var instanceResource = map[string]string{
|
||||
"project_id": testutil.ProjectId,
|
||||
"name": testutil.ResourceNameWithDateTime("rabbitmq"),
|
||||
"plan_id": "7e1f8394-5dd5-40b1-8608-16b4344eb51b",
|
||||
"plan_name": "stackit-qa-rabbitmq-2.4.10-single",
|
||||
"version": "3.10",
|
||||
"sgw_acl_invalid": "1.2.3.4/4",
|
||||
"sgw_acl_valid": "1.2.3.4/31",
|
||||
}
|
||||
|
||||
func resourceConfig(acls *string) string {
|
||||
aclsLine := ""
|
||||
if acls != nil {
|
||||
aclsLine = fmt.Sprintf(`sgw_acl = %q`, *acls)
|
||||
}
|
||||
return fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
resource "stackit_rabbitmq_instance" "instance" {
|
||||
project_id = "%s"
|
||||
name = "%s"
|
||||
plan_name = "%s"
|
||||
version = "%s"
|
||||
parameters = {
|
||||
%s
|
||||
metrics_frequency = "%s"
|
||||
}
|
||||
}
|
||||
|
||||
%s
|
||||
`,
|
||||
testutil.RabbitMQProviderConfig(),
|
||||
instanceResource["project_id"],
|
||||
instanceResource["name"],
|
||||
instanceResource["plan_name"],
|
||||
instanceResource["version"],
|
||||
aclsLine,
|
||||
instanceResource["metrics_frequency"],
|
||||
resourceConfigCredentials(),
|
||||
)
|
||||
}
|
||||
|
||||
func resourceConfigWithUpdate() string {
|
||||
return fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
resource "stackit_rabbitmq_instance" "instance" {
|
||||
project_id = "%s"
|
||||
name = "%s"
|
||||
plan_name = "%s"
|
||||
version = "%s"
|
||||
parameters = {
|
||||
sgw_acl = "%s"
|
||||
}
|
||||
}
|
||||
|
||||
%s
|
||||
`,
|
||||
testutil.RabbitMQProviderConfig(),
|
||||
instanceResource["project_id"],
|
||||
instanceResource["name"],
|
||||
instanceResource["plan_name"],
|
||||
instanceResource["version"],
|
||||
instanceResource["sgw_acl_valid"],
|
||||
resourceConfigCredentials(),
|
||||
)
|
||||
}
|
||||
|
||||
func resourceConfigCredentials() string {
|
||||
return `
|
||||
resource "stackit_rabbitmq_credentials" "credentials" {
|
||||
project_id = stackit_rabbitmq_instance.instance.project_id
|
||||
instance_id = stackit_rabbitmq_instance.instance.instance_id
|
||||
}
|
||||
`
|
||||
}
|
||||
|
||||
func TestAccRabbitMQResource(t *testing.T) {
|
||||
acls := instanceResource["sgw_acl_invalid"]
|
||||
resource.Test(t, resource.TestCase{
|
||||
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
|
||||
CheckDestroy: testAccCheckRabbitMQDestroy,
|
||||
Steps: []resource.TestStep{
|
||||
// Creation fail
|
||||
{
|
||||
Config: resourceConfig(&acls),
|
||||
ExpectError: regexp.MustCompile(`.*sgw_acl is invalid.*`),
|
||||
},
|
||||
// Creation
|
||||
{
|
||||
Config: resourceConfig(nil),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("stackit_rabbitmq_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_rabbitmq_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_rabbitmq_instance.instance", "plan_id", instanceResource["plan_id"]),
|
||||
resource.TestCheckResourceAttr("stackit_rabbitmq_instance.instance", "plan_name", instanceResource["plan_name"]),
|
||||
resource.TestCheckResourceAttr("stackit_rabbitmq_instance.instance", "version", instanceResource["version"]),
|
||||
resource.TestCheckResourceAttr("stackit_rabbitmq_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_rabbitmq_instance.instance", "parameters.sgw_acl"),
|
||||
|
||||
// Credentials data
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_rabbitmq_credentials.credentials", "project_id",
|
||||
"stackit_rabbitmq_instance.instance", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_rabbitmq_credentials.credentials", "instance_id",
|
||||
"stackit_rabbitmq_instance.instance", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrSet("stackit_rabbitmq_credentials.credentials", "credentials_id"),
|
||||
resource.TestCheckResourceAttrSet("stackit_rabbitmq_credentials.credentials", "host"),
|
||||
),
|
||||
},
|
||||
// data source
|
||||
{
|
||||
Config: fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
data "stackit_rabbitmq_instance" "instance" {
|
||||
project_id = stackit_rabbitmq_instance.instance.project_id
|
||||
instance_id = stackit_rabbitmq_instance.instance.instance_id
|
||||
}
|
||||
|
||||
data "stackit_rabbitmq_credentials" "credentials" {
|
||||
project_id = stackit_rabbitmq_credentials.credentials.project_id
|
||||
instance_id = stackit_rabbitmq_credentials.credentials.instance_id
|
||||
credentials_id = stackit_rabbitmq_credentials.credentials.credentials_id
|
||||
}`,
|
||||
resourceConfig(nil),
|
||||
),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("data.stackit_rabbitmq_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrPair("stackit_rabbitmq_instance.instance", "instance_id",
|
||||
"data.stackit_rabbitmq_credentials.credentials", "instance_id"),
|
||||
resource.TestCheckResourceAttrPair("data.stackit_rabbitmq_instance.instance", "instance_id",
|
||||
"data.stackit_rabbitmq_credentials.credentials", "instance_id"),
|
||||
resource.TestCheckResourceAttr("data.stackit_rabbitmq_instance.instance", "plan_id", instanceResource["plan_id"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_rabbitmq_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_rabbitmq_instance.instance", "parameters.sgw_acl"),
|
||||
|
||||
// Credentials data
|
||||
resource.TestCheckResourceAttr("data.stackit_rabbitmq_credentials.credentials", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_rabbitmq_credentials.credentials", "credentials_id"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_rabbitmq_credentials.credentials", "host"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_rabbitmq_credentials.credentials", "port"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_rabbitmq_credentials.credentials", "uri"),
|
||||
),
|
||||
},
|
||||
// Import
|
||||
{
|
||||
ResourceName: "stackit_rabbitmq_instance.instance",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_rabbitmq_instance.instance"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_rabbitmq_instance.instance")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
return fmt.Sprintf("%s,%s", testutil.ProjectId, instanceId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
{
|
||||
ResourceName: "stackit_rabbitmq_credentials.credentials",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_rabbitmq_credentials.credentials"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_rabbitmq_credentials.credentials")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
credentialsId, ok := r.Primary.Attributes["credentials_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute credentials_id")
|
||||
}
|
||||
return fmt.Sprintf("%s,%s,%s", testutil.ProjectId, instanceId, credentialsId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
// Update
|
||||
{
|
||||
Config: resourceConfigWithUpdate(),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("stackit_rabbitmq_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_rabbitmq_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_rabbitmq_instance.instance", "plan_id", instanceResource["plan_id"]),
|
||||
resource.TestCheckResourceAttr("stackit_rabbitmq_instance.instance", "plan_name", instanceResource["plan_name"]),
|
||||
resource.TestCheckResourceAttr("stackit_rabbitmq_instance.instance", "version", instanceResource["version"]),
|
||||
resource.TestCheckResourceAttr("stackit_rabbitmq_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_rabbitmq_instance.instance", "parameters.sgw_acl", instanceResource["sgw_acl_valid"]),
|
||||
),
|
||||
},
|
||||
// Deletion is done by the framework implicitly
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func testAccCheckRabbitMQDestroy(s *terraform.State) error {
|
||||
ctx := context.Background()
|
||||
var client *rabbitmq.APIClient
|
||||
var err error
|
||||
if testutil.RabbitMQCustomEndpoint == "" {
|
||||
client, err = rabbitmq.NewAPIClient()
|
||||
} else {
|
||||
client, err = rabbitmq.NewAPIClient(
|
||||
config.WithEndpoint(testutil.RabbitMQCustomEndpoint),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating client: %w", err)
|
||||
}
|
||||
|
||||
instancesToDestroy := []string{}
|
||||
for _, rs := range s.RootModule().Resources {
|
||||
if rs.Type != "stackit_rabbitmq_instance" {
|
||||
continue
|
||||
}
|
||||
// instance terraform ID: "[project_id],[instance_id]"
|
||||
instanceId := strings.Split(rs.Primary.ID, core.Separator)[1]
|
||||
instancesToDestroy = append(instancesToDestroy, instanceId)
|
||||
}
|
||||
|
||||
instancesResp, err := client.GetInstances(ctx, testutil.ProjectId).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting instancesResp: %w", err)
|
||||
}
|
||||
|
||||
instances := *instancesResp.Instances
|
||||
for i := range instances {
|
||||
if instances[i].InstanceId == nil {
|
||||
continue
|
||||
}
|
||||
if utils.Contains(instancesToDestroy, *instances[i].InstanceId) {
|
||||
if !checkInstanceDeleteSuccess(&instances[i]) {
|
||||
err := client.DeleteInstanceExecute(ctx, testutil.ProjectId, *instances[i].InstanceId)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying instance %s during CheckDestroy: %w", *instances[i].InstanceId, err)
|
||||
}
|
||||
_, err = rabbitmq.DeleteInstanceWaitHandler(ctx, client, testutil.ProjectId, *instances[i].InstanceId).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying instance %s during CheckDestroy: waiting for deletion %w", *instances[i].InstanceId, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkInstanceDeleteSuccess(i *rabbitmq.Instance) bool {
|
||||
if *i.LastOperation.Type != rabbitmq.InstanceTypeDelete {
|
||||
return false
|
||||
}
|
||||
|
||||
if *i.LastOperation.Type == rabbitmq.InstanceTypeDelete {
|
||||
if *i.LastOperation.State != rabbitmq.InstanceStateSuccess {
|
||||
return false
|
||||
} else if strings.Contains(*i.LastOperation.Description, "DeleteFailed") || strings.Contains(*i.LastOperation.Description, "failed") {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
181
stackit/internal/services/redis/credentials/datasource.go
Normal file
181
stackit/internal/services/redis/credentials/datasource.go
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/redis"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &credentialsDataSource{}
|
||||
)
|
||||
|
||||
// NewCredentialsDataSource is a helper function to simplify the provider implementation.
|
||||
func NewCredentialsDataSource() datasource.DataSource {
|
||||
return &credentialsDataSource{}
|
||||
}
|
||||
|
||||
// credentialsDataSource is the data source implementation.
|
||||
type credentialsDataSource struct {
|
||||
client *redis.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *credentialsDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_redis_credentials"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *credentialsDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *redis.APIClient
|
||||
var err error
|
||||
if providerData.RedisCustomEndpoint != "" {
|
||||
apiClient, err = redis.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.RedisCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = redis.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "Redis credentials client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *credentialsDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "Redis credentials data source schema.",
|
||||
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`,`credentials_id`\".",
|
||||
"credentials_id": "The credentials ID.",
|
||||
"instance_id": "ID of the Redis instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"credentials_id": schema.StringAttribute{
|
||||
Description: descriptions["credentials_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"hosts": schema.ListAttribute{
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"http_api_uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"password": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *credentialsDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
credentialsId := model.CredentialsId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(recordSetResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Redis credentials read")
|
||||
}
|
||||
377
stackit/internal/services/redis/credentials/resource.go
Normal file
377
stackit/internal/services/redis/credentials/resource.go
Normal file
|
|
@ -0,0 +1,377 @@
|
|||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/redis"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &redisCredentialsResource{}
|
||||
_ resource.ResourceWithConfigure = &redisCredentialsResource{}
|
||||
_ resource.ResourceWithImportState = &redisCredentialsResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
CredentialsId types.String `tfsdk:"credentials_id"`
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
Host types.String `tfsdk:"host"`
|
||||
Hosts types.List `tfsdk:"hosts"`
|
||||
HttpAPIURI types.String `tfsdk:"http_api_uri"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Password types.String `tfsdk:"password"`
|
||||
Port types.Int64 `tfsdk:"port"`
|
||||
Uri types.String `tfsdk:"uri"`
|
||||
Username types.String `tfsdk:"username"`
|
||||
}
|
||||
|
||||
// NewCredentialsResource is a helper function to simplify the provider implementation.
|
||||
func NewCredentialsResource() resource.Resource {
|
||||
return &redisCredentialsResource{}
|
||||
}
|
||||
|
||||
// credentialsResource is the resource implementation.
|
||||
type redisCredentialsResource struct {
|
||||
client *redis.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *redisCredentialsResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_redis_credentials"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *redisCredentialsResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *redis.APIClient
|
||||
var err error
|
||||
if providerData.RedisCustomEndpoint != "" {
|
||||
apiClient, err = redis.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.RedisCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = redis.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "Redis credentials client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *redisCredentialsResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "Redis credentials resource schema.",
|
||||
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`,`credentials_id`\".",
|
||||
"credentials_id": "The credentials ID.",
|
||||
"instance_id": "ID of the Redis instance.",
|
||||
"project_id": "STACKIT Project ID to which the instance is associated.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"credentials_id": schema.StringAttribute{
|
||||
Description: descriptions["credentials_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"host": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"hosts": schema.ListAttribute{
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
"http_api_uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"password": schema.StringAttribute{
|
||||
Computed: true,
|
||||
Sensitive: true,
|
||||
},
|
||||
"port": schema.Int64Attribute{
|
||||
Computed: true,
|
||||
},
|
||||
"uri": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"username": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *redisCredentialsResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
// Create new recordset
|
||||
credentialsResp, err := r.client.CreateCredentials(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
if credentialsResp.Id == nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", "Got empty credentials id")
|
||||
return
|
||||
}
|
||||
credentialsId := *credentialsResp.Id
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
wr, err := redis.CreateCredentialsWaitHandler(ctx, r.client, projectId, instanceId, credentialsId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Instance creation waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*redis.CredentialsResponse)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating credentials", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Redis credentials created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *redisCredentialsResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
credentialsId := model.CredentialsId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
recordSetResp, err := r.client.GetCredentials(ctx, projectId, instanceId, credentialsId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(recordSetResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading credentials", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Redis credentials read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *redisCredentialsResource) Update(ctx context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Update shouldn't be called
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating credentials", "Credentials can't be updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *redisCredentialsResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
credentialsId := model.CredentialsId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
ctx = tflog.SetField(ctx, "credentials_id", credentialsId)
|
||||
|
||||
// Delete existing record set
|
||||
err := r.client.DeleteCredentials(ctx, projectId, instanceId, credentialsId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credentials", fmt.Sprintf("Calling API: %v", err))
|
||||
}
|
||||
_, err = redis.DeleteCredentialsWaitHandler(ctx, r.client, projectId, instanceId, credentialsId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credentials", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Redis credentials deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,instance_id,credentials_id
|
||||
func (r *redisCredentialsResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing credentials",
|
||||
fmt.Sprintf("Expected import identifier with format [project_id],[instance_id],[credentials_id], got %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[1])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("credentials_id"), idParts[2])...)
|
||||
tflog.Info(ctx, "Redis credentials state imported")
|
||||
}
|
||||
|
||||
func mapFields(credentialsResp *redis.CredentialsResponse, model *Model) error {
|
||||
if credentialsResp == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if credentialsResp.Raw == nil {
|
||||
return fmt.Errorf("response credentials raw is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
credentials := credentialsResp.Raw.Credentials
|
||||
|
||||
var credentialsId string
|
||||
if model.CredentialsId.ValueString() != "" {
|
||||
credentialsId = model.CredentialsId.ValueString()
|
||||
} else if credentialsResp.Id != nil {
|
||||
credentialsId = *credentialsResp.Id
|
||||
} else {
|
||||
return fmt.Errorf("credentials id not present")
|
||||
}
|
||||
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
model.InstanceId.ValueString(),
|
||||
credentialsId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.CredentialsId = types.StringValue(credentialsId)
|
||||
model.Hosts = types.ListNull(types.StringType)
|
||||
if credentials != nil {
|
||||
if credentials.Hosts != nil {
|
||||
var hosts []attr.Value
|
||||
for _, host := range *credentials.Hosts {
|
||||
hosts = append(hosts, types.StringValue(host))
|
||||
}
|
||||
hostsList, diags := types.ListValue(types.StringType, hosts)
|
||||
if diags.HasError() {
|
||||
return fmt.Errorf("failed to map hosts: %w", core.DiagsToError(diags))
|
||||
}
|
||||
model.Hosts = hostsList
|
||||
}
|
||||
model.Host = types.StringPointerValue(credentials.Host)
|
||||
model.HttpAPIURI = types.StringPointerValue(credentials.HttpApiUri)
|
||||
model.Name = types.StringPointerValue(credentials.Name)
|
||||
model.Password = types.StringPointerValue(credentials.Password)
|
||||
model.Port = conversion.ToTypeInt64(credentials.Port)
|
||||
model.Uri = types.StringPointerValue(credentials.Uri)
|
||||
model.Username = types.StringPointerValue(credentials.Username)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
156
stackit/internal/services/redis/credentials/resource_test.go
Normal file
156
stackit/internal/services/redis/credentials/resource_test.go
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
package redis
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/redis"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *redis.CredentialsResponse
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&redis.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
Raw: &redis.RawCredentials{},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,cid"),
|
||||
CredentialsId: types.StringValue("cid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Host: types.StringNull(),
|
||||
Hosts: types.ListNull(types.StringType),
|
||||
HttpAPIURI: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Password: types.StringNull(),
|
||||
Port: types.Int64Null(),
|
||||
Uri: types.StringNull(),
|
||||
Username: types.StringNull(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&redis.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
Raw: &redis.RawCredentials{
|
||||
Credentials: &redis.Credentials{
|
||||
Host: utils.Ptr("host"),
|
||||
Hosts: &[]string{
|
||||
"host_1",
|
||||
"",
|
||||
},
|
||||
HttpApiUri: utils.Ptr("http"),
|
||||
Name: utils.Ptr("name"),
|
||||
Password: utils.Ptr("password"),
|
||||
Port: utils.Ptr(int32(1234)),
|
||||
Uri: utils.Ptr("uri"),
|
||||
Username: utils.Ptr("username"),
|
||||
},
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,cid"),
|
||||
CredentialsId: types.StringValue("cid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Host: types.StringValue("host"),
|
||||
Hosts: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("host_1"),
|
||||
types.StringValue(""),
|
||||
}),
|
||||
HttpAPIURI: types.StringValue("http"),
|
||||
Name: types.StringValue("name"),
|
||||
Password: types.StringValue("password"),
|
||||
Port: types.Int64Value(1234),
|
||||
Uri: types.StringValue("uri"),
|
||||
Username: types.StringValue("username"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&redis.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
Raw: &redis.RawCredentials{
|
||||
Credentials: &redis.Credentials{
|
||||
Host: utils.Ptr(""),
|
||||
Hosts: &[]string{},
|
||||
HttpApiUri: nil,
|
||||
Name: nil,
|
||||
Password: utils.Ptr(""),
|
||||
Port: utils.Ptr(int32(2123456789)),
|
||||
Uri: nil,
|
||||
Username: utils.Ptr(""),
|
||||
},
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid,cid"),
|
||||
CredentialsId: types.StringValue("cid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Host: types.StringValue(""),
|
||||
Hosts: types.ListValueMust(types.StringType, []attr.Value{}),
|
||||
HttpAPIURI: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
Password: types.StringValue(""),
|
||||
Port: types.Int64Value(2123456789),
|
||||
Uri: types.StringNull(),
|
||||
Username: types.StringValue(""),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&redis.CredentialsResponse{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_raw_credentials",
|
||||
&redis.CredentialsResponse{
|
||||
Id: utils.Ptr("cid"),
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
model := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
}
|
||||
err := mapFields(tt.input, model)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(model, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
192
stackit/internal/services/redis/instance/datasource.go
Normal file
192
stackit/internal/services/redis/instance/datasource.go
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/redis"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &instanceDataSource{}
|
||||
)
|
||||
|
||||
// NewInstanceDataSource is a helper function to simplify the provider implementation.
|
||||
func NewInstanceDataSource() datasource.DataSource {
|
||||
return &instanceDataSource{}
|
||||
}
|
||||
|
||||
// instanceDataSource is the data source implementation.
|
||||
type instanceDataSource struct {
|
||||
client *redis.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *instanceDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_redis_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *instanceDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *redis.APIClient
|
||||
var err error
|
||||
if providerData.RedisCustomEndpoint != "" {
|
||||
apiClient, err = redis.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.RedisCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = redis.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "Redis zone client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *instanceDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "Redis instance data source schema.",
|
||||
"id": "Terraform's internal resource identifier. It is structured as \"`project_id`,`instance_id`\".",
|
||||
"instance_id": "ID of the Redis instance.",
|
||||
"project_id": "STACKIT Project ID to which the instance is associated.",
|
||||
"name": "Instance name.",
|
||||
"version": "The service version.",
|
||||
"plan_name": "The selected plan name.",
|
||||
"plan_id": "The selected plan ID.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Computed: true,
|
||||
},
|
||||
"version": schema.StringAttribute{
|
||||
Description: descriptions["version"],
|
||||
Computed: true,
|
||||
},
|
||||
"plan_name": schema.StringAttribute{
|
||||
Description: descriptions["plan_name"],
|
||||
Computed: true,
|
||||
},
|
||||
"plan_id": schema.StringAttribute{
|
||||
Description: descriptions["plan_id"],
|
||||
Computed: true,
|
||||
},
|
||||
"parameters": schema.SingleNestedAttribute{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"sgw_acl": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
Computed: true,
|
||||
},
|
||||
"cf_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"cf_space_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"dashboard_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"image_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
"cf_organization_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *instanceDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
err = mapFields(instanceResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Compute and store values not present in the API response
|
||||
err = loadPlanNameAndVersion(ctx, r.client, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Loading service plan details: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Redis instance read")
|
||||
}
|
||||
680
stackit/internal/services/redis/instance/resource.go
Normal file
680
stackit/internal/services/redis/instance/resource.go
Normal file
|
|
@ -0,0 +1,680 @@
|
|||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/redis"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &instanceResource{}
|
||||
_ resource.ResourceWithConfigure = &instanceResource{}
|
||||
_ resource.ResourceWithImportState = &instanceResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
InstanceId types.String `tfsdk:"instance_id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
CfGuid types.String `tfsdk:"cf_guid"`
|
||||
CfSpaceGuid types.String `tfsdk:"cf_space_guid"`
|
||||
DashboardUrl types.String `tfsdk:"dashboard_url"`
|
||||
ImageUrl types.String `tfsdk:"image_url"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
CfOrganizationGuid types.String `tfsdk:"cf_organization_guid"`
|
||||
Parameters types.Object `tfsdk:"parameters"`
|
||||
Version types.String `tfsdk:"version"`
|
||||
PlanName types.String `tfsdk:"plan_name"`
|
||||
PlanId types.String `tfsdk:"plan_id"`
|
||||
}
|
||||
|
||||
// Struct corresponding to DataSourceModel.Parameters
|
||||
type parametersModel struct {
|
||||
SgwAcl types.String `tfsdk:"sgw_acl"`
|
||||
}
|
||||
|
||||
// Types corresponding to parametersModel
|
||||
var parametersTypes = map[string]attr.Type{
|
||||
"sgw_acl": basetypes.StringType{},
|
||||
}
|
||||
|
||||
// NewInstanceResource is a helper function to simplify the provider implementation.
|
||||
func NewInstanceResource() resource.Resource {
|
||||
return &instanceResource{}
|
||||
}
|
||||
|
||||
// instanceResource is the resource implementation.
|
||||
type instanceResource struct {
|
||||
client *redis.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *instanceResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_redis_instance"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *instanceResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *redis.APIClient
|
||||
var err error
|
||||
if providerData.RedisCustomEndpoint != "" {
|
||||
apiClient, err = redis.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.RedisCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = redis.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "Redis instance client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *instanceResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "Redis instance resource schema.",
|
||||
"id": "Terraform's internal resource ID. It is structured as \"`project_id`,`instance_id`\".",
|
||||
"instance_id": "ID of the Redis instance.",
|
||||
"project_id": "STACKIT project ID to which the instance is associated.",
|
||||
"name": "Instance name.",
|
||||
"version": "The service version.",
|
||||
"plan_name": "The selected plan name.",
|
||||
"plan_id": "The selected plan ID.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"instance_id": schema.StringAttribute{
|
||||
Description: descriptions["instance_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: descriptions["project_id"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Required: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
},
|
||||
},
|
||||
"version": schema.StringAttribute{
|
||||
Description: descriptions["version"],
|
||||
Required: true,
|
||||
},
|
||||
"plan_name": schema.StringAttribute{
|
||||
Description: descriptions["plan_name"],
|
||||
Required: true,
|
||||
},
|
||||
"plan_id": schema.StringAttribute{
|
||||
Description: descriptions["plan_id"],
|
||||
Computed: true,
|
||||
},
|
||||
"parameters": schema.SingleNestedAttribute{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"sgw_acl": schema.StringAttribute{
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
Optional: true,
|
||||
Computed: true,
|
||||
},
|
||||
"cf_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"cf_space_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"dashboard_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"image_url": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"cf_organization_guid": schema.StringAttribute{
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *instanceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
|
||||
var parameters = ¶metersModel{}
|
||||
if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) {
|
||||
diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err := r.loadPlanId(ctx, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Loading service plan: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model, parameters)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Create new instance
|
||||
createResp, err := r.client.CreateInstance(ctx, projectId).CreateInstancePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
instanceId := *createResp.InstanceId
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
wr, err := redis.CreateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Instance creation waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*redis.Instance)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Redis instance created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *instanceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
instanceResp, err := r.client.GetInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(instanceResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Compute and store values not present in the API response
|
||||
err = loadPlanNameAndVersion(ctx, r.client, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading instance", fmt.Sprintf("Loading service plan details: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Redis instance read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *instanceResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
var parameters = ¶metersModel{}
|
||||
if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) {
|
||||
diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{})
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err := r.loadPlanId(ctx, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Loading service plan: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toUpdatePayload(&model, parameters)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Update existing instance
|
||||
err = r.client.UpdateInstance(ctx, projectId, instanceId).UpdateInstancePayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
wr, err := redis.UpdateInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Instance update waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*redis.Instance)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating instance", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Redis instance updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *instanceResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from state
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
instanceId := model.InstanceId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "instance_id", instanceId)
|
||||
|
||||
// Delete existing instance
|
||||
err := r.client.DeleteInstance(ctx, projectId, instanceId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
_, err = redis.DeleteInstanceWaitHandler(ctx, r.client, projectId, instanceId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting instance", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Redis instance deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id,instance_id
|
||||
func (r *instanceResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
|
||||
if len(idParts) != 2 || idParts[0] == "" || idParts[1] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing instance",
|
||||
fmt.Sprintf("Expected import identifier with format: [project_id],[instance_id] Got: %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("instance_id"), idParts[1])...)
|
||||
tflog.Info(ctx, "Redis instance state imported")
|
||||
}
|
||||
|
||||
func mapFields(instance *redis.Instance, model *Model) error {
|
||||
if instance == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
|
||||
var instanceId string
|
||||
if model.InstanceId.ValueString() != "" {
|
||||
instanceId = model.InstanceId.ValueString()
|
||||
} else if instance.InstanceId != nil {
|
||||
instanceId = *instance.InstanceId
|
||||
} else {
|
||||
return fmt.Errorf("instance id not present")
|
||||
}
|
||||
|
||||
idParts := []string{
|
||||
model.ProjectId.ValueString(),
|
||||
instanceId,
|
||||
}
|
||||
model.Id = types.StringValue(
|
||||
strings.Join(idParts, core.Separator),
|
||||
)
|
||||
model.InstanceId = types.StringValue(instanceId)
|
||||
model.PlanId = types.StringPointerValue(instance.PlanId)
|
||||
model.CfGuid = types.StringPointerValue(instance.CfGuid)
|
||||
model.CfSpaceGuid = types.StringPointerValue(instance.CfSpaceGuid)
|
||||
model.DashboardUrl = types.StringPointerValue(instance.DashboardUrl)
|
||||
model.ImageUrl = types.StringPointerValue(instance.ImageUrl)
|
||||
model.Name = types.StringPointerValue(instance.Name)
|
||||
model.CfOrganizationGuid = types.StringPointerValue(instance.CfOrganizationGuid)
|
||||
|
||||
if instance.Parameters == nil {
|
||||
model.Parameters = types.ObjectNull(parametersTypes)
|
||||
} else {
|
||||
parameters, err := mapParameters(*instance.Parameters)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mapping parameters: %w", err)
|
||||
}
|
||||
model.Parameters = parameters
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func mapParameters(params map[string]interface{}) (types.Object, error) {
|
||||
attributes := map[string]attr.Value{}
|
||||
for attribute := range parametersTypes {
|
||||
valueInterface, ok := params[attribute]
|
||||
if !ok {
|
||||
// All fields are optional, so this is ok
|
||||
// Set the value as nil, will be handled accordingly
|
||||
valueInterface = nil
|
||||
}
|
||||
|
||||
var value attr.Value
|
||||
switch parametersTypes[attribute].(type) {
|
||||
default:
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found unexpected attribute type '%T'", parametersTypes[attribute])
|
||||
case basetypes.StringType:
|
||||
if valueInterface == nil {
|
||||
value = types.StringNull()
|
||||
} else {
|
||||
valueString, ok := valueInterface.(string)
|
||||
if !ok {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as string", attribute, valueInterface)
|
||||
}
|
||||
value = types.StringValue(valueString)
|
||||
}
|
||||
case basetypes.BoolType:
|
||||
if valueInterface == nil {
|
||||
value = types.BoolNull()
|
||||
} else {
|
||||
valueBool, ok := valueInterface.(bool)
|
||||
if !ok {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as bool", attribute, valueInterface)
|
||||
}
|
||||
value = types.BoolValue(valueBool)
|
||||
}
|
||||
case basetypes.Int64Type:
|
||||
if valueInterface == nil {
|
||||
value = types.Int64Null()
|
||||
} else {
|
||||
// This may be int64, int32, int or float64
|
||||
// We try to assert all 4
|
||||
var valueInt64 int64
|
||||
switch temp := valueInterface.(type) {
|
||||
default:
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as int", attribute, valueInterface)
|
||||
case int64:
|
||||
valueInt64 = temp
|
||||
case int32:
|
||||
valueInt64 = int64(temp)
|
||||
case int:
|
||||
valueInt64 = int64(temp)
|
||||
case float64:
|
||||
valueInt64 = int64(temp)
|
||||
}
|
||||
value = types.Int64Value(valueInt64)
|
||||
}
|
||||
case basetypes.ListType: // Assumed to be a list of strings
|
||||
if valueInterface == nil {
|
||||
value = types.ListNull(types.StringType)
|
||||
} else {
|
||||
// This may be []string{} or []interface{}
|
||||
// We try to assert all 2
|
||||
var valueList []attr.Value
|
||||
switch temp := valueInterface.(type) {
|
||||
default:
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' of type %T, failed to assert as array of interface", attribute, valueInterface)
|
||||
case []string:
|
||||
for _, x := range temp {
|
||||
valueList = append(valueList, types.StringValue(x))
|
||||
}
|
||||
case []interface{}:
|
||||
for _, x := range temp {
|
||||
xString, ok := x.(string)
|
||||
if !ok {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("found attribute '%s' with element '%s' of type %T, failed to assert as string", attribute, x, x)
|
||||
}
|
||||
valueList = append(valueList, types.StringValue(xString))
|
||||
}
|
||||
}
|
||||
temp2, diags := types.ListValue(types.StringType, valueList)
|
||||
if diags.HasError() {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("failed to map %s: %w", attribute, core.DiagsToError(diags))
|
||||
}
|
||||
value = temp2
|
||||
}
|
||||
}
|
||||
attributes[attribute] = value
|
||||
}
|
||||
|
||||
output, diags := types.ObjectValue(parametersTypes, attributes)
|
||||
if diags.HasError() {
|
||||
return types.ObjectNull(parametersTypes), fmt.Errorf("failed to create object: %w", core.DiagsToError(diags))
|
||||
}
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model, parameters *parametersModel) (*redis.CreateInstancePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
if parameters == nil {
|
||||
return &redis.CreateInstancePayload{
|
||||
InstanceName: model.Name.ValueStringPointer(),
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
payloadParams := &redis.InstanceParameters{}
|
||||
if parameters.SgwAcl.ValueString() != "" {
|
||||
payloadParams.SgwAcl = parameters.SgwAcl.ValueStringPointer()
|
||||
}
|
||||
return &redis.CreateInstancePayload{
|
||||
InstanceName: model.Name.ValueStringPointer(),
|
||||
Parameters: payloadParams,
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toUpdatePayload(model *Model, parameters *parametersModel) (*redis.UpdateInstancePayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
if parameters == nil {
|
||||
return &redis.UpdateInstancePayload{
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
return &redis.UpdateInstancePayload{
|
||||
Parameters: &redis.InstanceParameters{
|
||||
SgwAcl: parameters.SgwAcl.ValueStringPointer(),
|
||||
},
|
||||
PlanId: model.PlanId.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *instanceResource) loadPlanId(ctx context.Context, model *Model) error {
|
||||
projectId := model.ProjectId.ValueString()
|
||||
res, err := r.client.GetOfferings(ctx, projectId).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting Redis offerings: %w", err)
|
||||
}
|
||||
|
||||
version := model.Version.ValueString()
|
||||
planName := model.PlanName.ValueString()
|
||||
availableVersions := ""
|
||||
availablePlanNames := ""
|
||||
isValidVersion := false
|
||||
for _, offer := range *res.Offerings {
|
||||
if !strings.EqualFold(*offer.Version, version) {
|
||||
availableVersions = fmt.Sprintf("%s\n- %s", availableVersions, *offer.Version)
|
||||
continue
|
||||
}
|
||||
isValidVersion = true
|
||||
|
||||
for _, plan := range *offer.Plans {
|
||||
if plan.Name == nil {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(*plan.Name, planName) && plan.Id != nil {
|
||||
model.PlanId = types.StringPointerValue(plan.Id)
|
||||
return nil
|
||||
}
|
||||
availablePlanNames = fmt.Sprintf("%s\n- %s", availablePlanNames, *plan.Name)
|
||||
}
|
||||
}
|
||||
|
||||
if !isValidVersion {
|
||||
return fmt.Errorf("couldn't find version '%s', available versions are: %s", version, availableVersions)
|
||||
}
|
||||
return fmt.Errorf("couldn't find plan_name '%s' for version %s, available names are: %s", planName, version, availablePlanNames)
|
||||
}
|
||||
|
||||
func loadPlanNameAndVersion(ctx context.Context, client *redis.APIClient, model *Model) error {
|
||||
projectId := model.ProjectId.ValueString()
|
||||
planId := model.PlanId.ValueString()
|
||||
res, err := client.GetOfferings(ctx, projectId).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting Redis offerings: %w", err)
|
||||
}
|
||||
|
||||
for _, offer := range *res.Offerings {
|
||||
for _, plan := range *offer.Plans {
|
||||
if strings.EqualFold(*plan.Id, planId) && plan.Id != nil {
|
||||
model.PlanName = types.StringPointerValue(plan.Name)
|
||||
model.Version = types.StringPointerValue(offer.Version)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("couldn't find plan_name and version for plan_id '%s'", planId)
|
||||
}
|
||||
304
stackit/internal/services/redis/instance/resource_test.go
Normal file
304
stackit/internal/services/redis/instance/resource_test.go
Normal file
|
|
@ -0,0 +1,304 @@
|
|||
package redis
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/redis"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *redis.Instance
|
||||
expected Model
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&redis.Instance{},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
PlanId: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
CfGuid: types.StringNull(),
|
||||
CfSpaceGuid: types.StringNull(),
|
||||
DashboardUrl: types.StringNull(),
|
||||
ImageUrl: types.StringNull(),
|
||||
CfOrganizationGuid: types.StringNull(),
|
||||
Parameters: types.ObjectNull(parametersTypes),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&redis.Instance{
|
||||
PlanId: utils.Ptr("plan"),
|
||||
CfGuid: utils.Ptr("cf"),
|
||||
CfSpaceGuid: utils.Ptr("space"),
|
||||
DashboardUrl: utils.Ptr("dashboard"),
|
||||
ImageUrl: utils.Ptr("image"),
|
||||
InstanceId: utils.Ptr("iid"),
|
||||
Name: utils.Ptr("name"),
|
||||
CfOrganizationGuid: utils.Ptr("org"),
|
||||
Parameters: &map[string]interface{}{
|
||||
"sgw_acl": "acl",
|
||||
},
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("pid,iid"),
|
||||
InstanceId: types.StringValue("iid"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
PlanId: types.StringValue("plan"),
|
||||
Name: types.StringValue("name"),
|
||||
CfGuid: types.StringValue("cf"),
|
||||
CfSpaceGuid: types.StringValue("space"),
|
||||
DashboardUrl: types.StringValue("dashboard"),
|
||||
ImageUrl: types.StringValue("image"),
|
||||
CfOrganizationGuid: types.StringValue("org"),
|
||||
Parameters: types.ObjectValueMust(parametersTypes, map[string]attr.Value{
|
||||
"sgw_acl": types.StringValue("acl"),
|
||||
}),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&redis.Instance{},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"wrong_param_types_1",
|
||||
&redis.Instance{
|
||||
Parameters: &map[string]interface{}{
|
||||
"sgw_acl": true,
|
||||
},
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"wrong_param_types_2",
|
||||
&redis.Instance{
|
||||
Parameters: &map[string]interface{}{
|
||||
"sgw_acl": 1,
|
||||
},
|
||||
},
|
||||
Model{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
state := &Model{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
InstanceId: tt.expected.InstanceId,
|
||||
}
|
||||
err := mapFields(tt.input, state)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputParameters *parametersModel
|
||||
expected *redis.CreateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
¶metersModel{},
|
||||
&redis.CreateInstancePayload{
|
||||
Parameters: &redis.InstanceParameters{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
Name: types.StringValue("name"),
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
¶metersModel{
|
||||
SgwAcl: types.StringValue("sgw"),
|
||||
},
|
||||
&redis.CreateInstancePayload{
|
||||
InstanceName: utils.Ptr("name"),
|
||||
Parameters: &redis.InstanceParameters{
|
||||
SgwAcl: utils.Ptr("sgw"),
|
||||
},
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
Name: types.StringValue(""),
|
||||
PlanId: types.StringValue(""),
|
||||
},
|
||||
¶metersModel{
|
||||
SgwAcl: types.StringNull(),
|
||||
},
|
||||
&redis.CreateInstancePayload{
|
||||
InstanceName: utils.Ptr(""),
|
||||
Parameters: &redis.InstanceParameters{
|
||||
SgwAcl: nil,
|
||||
},
|
||||
PlanId: utils.Ptr(""),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
¶metersModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_parameters",
|
||||
&Model{
|
||||
Name: types.StringValue("name"),
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
nil,
|
||||
&redis.CreateInstancePayload{
|
||||
InstanceName: utils.Ptr("name"),
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toCreatePayload(tt.input, tt.inputParameters)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToUpdatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputParameters *parametersModel
|
||||
expected *redis.UpdateInstancePayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&Model{},
|
||||
¶metersModel{},
|
||||
&redis.UpdateInstancePayload{
|
||||
Parameters: &redis.InstanceParameters{},
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&Model{
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
¶metersModel{
|
||||
SgwAcl: types.StringValue("sgw"),
|
||||
},
|
||||
&redis.UpdateInstancePayload{
|
||||
Parameters: &redis.InstanceParameters{
|
||||
SgwAcl: utils.Ptr("sgw"),
|
||||
},
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"null_fields_and_int_conversions",
|
||||
&Model{
|
||||
PlanId: types.StringValue(""),
|
||||
},
|
||||
¶metersModel{
|
||||
SgwAcl: types.StringNull(),
|
||||
},
|
||||
&redis.UpdateInstancePayload{
|
||||
Parameters: &redis.InstanceParameters{
|
||||
SgwAcl: nil,
|
||||
},
|
||||
PlanId: utils.Ptr(""),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
¶metersModel{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_parameters",
|
||||
&Model{
|
||||
PlanId: types.StringValue("plan"),
|
||||
},
|
||||
nil,
|
||||
&redis.UpdateInstancePayload{
|
||||
PlanId: utils.Ptr("plan"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
output, err := toUpdatePayload(tt.input, tt.inputParameters)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
290
stackit/internal/services/redis/redis_acc_test.go
Normal file
290
stackit/internal/services/redis/redis_acc_test.go
Normal file
|
|
@ -0,0 +1,290 @@
|
|||
package redis_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
|
||||
"github.com/hashicorp/terraform-plugin-testing/terraform"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/redis"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/testutil"
|
||||
)
|
||||
|
||||
// Instance resource data
|
||||
var instanceResource = map[string]string{
|
||||
"project_id": testutil.ProjectId,
|
||||
"name": testutil.ResourceNameWithDateTime("redis"),
|
||||
"plan_id": "96e24604-7a43-4ff8-9ba4-609d4235a137",
|
||||
"plan_name": "stackit-qa-redis-1.4.10-single",
|
||||
"version": "6",
|
||||
"sgw_acl_invalid": "1.2.3.4/4",
|
||||
"sgw_acl_valid": "1.2.3.4/31",
|
||||
}
|
||||
|
||||
func resourceConfig(acls *string) string {
|
||||
aclsLine := ""
|
||||
if acls != nil {
|
||||
aclsLine = fmt.Sprintf(`sgw_acl = %q`, *acls)
|
||||
}
|
||||
return fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
resource "stackit_redis_instance" "instance" {
|
||||
project_id = "%s"
|
||||
name = "%s"
|
||||
plan_name = "%s"
|
||||
version = "%s"
|
||||
parameters = {
|
||||
%s
|
||||
metrics_frequency = "%s"
|
||||
}
|
||||
}
|
||||
|
||||
%s
|
||||
`,
|
||||
testutil.RedisProviderConfig(),
|
||||
instanceResource["project_id"],
|
||||
instanceResource["name"],
|
||||
instanceResource["plan_name"],
|
||||
instanceResource["version"],
|
||||
aclsLine,
|
||||
instanceResource["metrics_frequency"],
|
||||
resourceConfigCredentials(),
|
||||
)
|
||||
}
|
||||
|
||||
func resourceConfigWithUpdate() string {
|
||||
return fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
resource "stackit_redis_instance" "instance" {
|
||||
project_id = "%s"
|
||||
name = "%s"
|
||||
plan_name = "%s"
|
||||
version = "%s"
|
||||
parameters = {
|
||||
sgw_acl = "%s"
|
||||
}
|
||||
}
|
||||
|
||||
%s
|
||||
`,
|
||||
testutil.RedisProviderConfig(),
|
||||
instanceResource["project_id"],
|
||||
instanceResource["name"],
|
||||
instanceResource["plan_name"],
|
||||
instanceResource["version"],
|
||||
instanceResource["sgw_acl_valid"],
|
||||
resourceConfigCredentials(),
|
||||
)
|
||||
}
|
||||
|
||||
func resourceConfigCredentials() string {
|
||||
return `
|
||||
resource "stackit_redis_credentials" "credentials" {
|
||||
project_id = stackit_redis_instance.instance.project_id
|
||||
instance_id = stackit_redis_instance.instance.instance_id
|
||||
}
|
||||
`
|
||||
}
|
||||
|
||||
func TestAccRedisResource(t *testing.T) {
|
||||
acls := instanceResource["sgw_acl_invalid"]
|
||||
resource.Test(t, resource.TestCase{
|
||||
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
|
||||
CheckDestroy: testAccCheckRedisDestroy,
|
||||
Steps: []resource.TestStep{
|
||||
// Creation fail
|
||||
{
|
||||
Config: resourceConfig(&acls),
|
||||
ExpectError: regexp.MustCompile(`.*sgw_acl is invalid.*`),
|
||||
},
|
||||
// Creation
|
||||
{
|
||||
Config: resourceConfig(nil),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("stackit_redis_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_redis_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_redis_instance.instance", "plan_id", instanceResource["plan_id"]),
|
||||
resource.TestCheckResourceAttr("stackit_redis_instance.instance", "plan_name", instanceResource["plan_name"]),
|
||||
resource.TestCheckResourceAttr("stackit_redis_instance.instance", "version", instanceResource["version"]),
|
||||
resource.TestCheckResourceAttr("stackit_redis_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_redis_instance.instance", "parameters.sgw_acl"),
|
||||
|
||||
// Credentials data
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_redis_credentials.credentials", "project_id",
|
||||
"stackit_redis_instance.instance", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_redis_credentials.credentials", "instance_id",
|
||||
"stackit_redis_instance.instance", "instance_id",
|
||||
),
|
||||
resource.TestCheckResourceAttrSet("stackit_redis_credentials.credentials", "credentials_id"),
|
||||
resource.TestCheckResourceAttrSet("stackit_redis_credentials.credentials", "host"),
|
||||
),
|
||||
},
|
||||
// data source
|
||||
{
|
||||
Config: fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
data "stackit_redis_instance" "instance" {
|
||||
project_id = stackit_redis_instance.instance.project_id
|
||||
instance_id = stackit_redis_instance.instance.instance_id
|
||||
}
|
||||
|
||||
data "stackit_redis_credentials" "credentials" {
|
||||
project_id = stackit_redis_credentials.credentials.project_id
|
||||
instance_id = stackit_redis_credentials.credentials.instance_id
|
||||
credentials_id = stackit_redis_credentials.credentials.credentials_id
|
||||
}`,
|
||||
resourceConfig(nil),
|
||||
),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("data.stackit_redis_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrPair("stackit_redis_instance.instance", "instance_id",
|
||||
"data.stackit_redis_credentials.credentials", "instance_id"),
|
||||
resource.TestCheckResourceAttrPair("data.stackit_redis_instance.instance", "instance_id",
|
||||
"data.stackit_redis_credentials.credentials", "instance_id"),
|
||||
resource.TestCheckResourceAttr("data.stackit_redis_instance.instance", "plan_id", instanceResource["plan_id"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_redis_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_redis_instance.instance", "parameters.sgw_acl"),
|
||||
|
||||
// Credentials data
|
||||
resource.TestCheckResourceAttr("data.stackit_redis_credentials.credentials", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_redis_credentials.credentials", "credentials_id"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_redis_credentials.credentials", "host"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_redis_credentials.credentials", "port"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_redis_credentials.credentials", "uri"),
|
||||
),
|
||||
},
|
||||
// Import
|
||||
{
|
||||
ResourceName: "stackit_redis_instance.instance",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_redis_instance.instance"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_redis_instance.instance")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
return fmt.Sprintf("%s,%s", testutil.ProjectId, instanceId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
{
|
||||
ResourceName: "stackit_redis_credentials.credentials",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_redis_credentials.credentials"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_redis_credentials.credentials")
|
||||
}
|
||||
instanceId, ok := r.Primary.Attributes["instance_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute instance_id")
|
||||
}
|
||||
credentialsId, ok := r.Primary.Attributes["credentials_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute credentials_id")
|
||||
}
|
||||
return fmt.Sprintf("%s,%s,%s", testutil.ProjectId, instanceId, credentialsId), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
// Update
|
||||
{
|
||||
Config: resourceConfigWithUpdate(),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Instance data
|
||||
resource.TestCheckResourceAttr("stackit_redis_instance.instance", "project_id", instanceResource["project_id"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_redis_instance.instance", "instance_id"),
|
||||
resource.TestCheckResourceAttr("stackit_redis_instance.instance", "plan_id", instanceResource["plan_id"]),
|
||||
resource.TestCheckResourceAttr("stackit_redis_instance.instance", "plan_name", instanceResource["plan_name"]),
|
||||
resource.TestCheckResourceAttr("stackit_redis_instance.instance", "version", instanceResource["version"]),
|
||||
resource.TestCheckResourceAttr("stackit_redis_instance.instance", "name", instanceResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_redis_instance.instance", "parameters.sgw_acl", instanceResource["sgw_acl_valid"]),
|
||||
),
|
||||
},
|
||||
// Deletion is done by the framework implicitly
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func checkInstanceDeleteSuccess(i *redis.Instance) bool {
|
||||
if *i.LastOperation.Type != redis.InstanceTypeDelete {
|
||||
return false
|
||||
}
|
||||
|
||||
if *i.LastOperation.Type == redis.InstanceTypeDelete {
|
||||
if *i.LastOperation.State != redis.InstanceStateSuccess {
|
||||
return false
|
||||
} else if strings.Contains(*i.LastOperation.Description, "DeleteFailed") || strings.Contains(*i.LastOperation.Description, "failed") {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func testAccCheckRedisDestroy(s *terraform.State) error {
|
||||
ctx := context.Background()
|
||||
var client *redis.APIClient
|
||||
var err error
|
||||
if testutil.RedisCustomEndpoint == "" {
|
||||
client, err = redis.NewAPIClient()
|
||||
} else {
|
||||
client, err = redis.NewAPIClient(
|
||||
config.WithEndpoint(testutil.RedisCustomEndpoint),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating client: %w", err)
|
||||
}
|
||||
|
||||
instancesToDestroy := []string{}
|
||||
for _, rs := range s.RootModule().Resources {
|
||||
if rs.Type != "stackit_redis_instance" {
|
||||
continue
|
||||
}
|
||||
// instance terraform ID: "[project_id],[instance_id]"
|
||||
instanceId := strings.Split(rs.Primary.ID, core.Separator)[1]
|
||||
instancesToDestroy = append(instancesToDestroy, instanceId)
|
||||
}
|
||||
|
||||
instancesResp, err := client.GetInstances(ctx, testutil.ProjectId).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting instancesResp: %w", err)
|
||||
}
|
||||
|
||||
instances := *instancesResp.Instances
|
||||
for i := range instances {
|
||||
if instances[i].InstanceId == nil {
|
||||
continue
|
||||
}
|
||||
if utils.Contains(instancesToDestroy, *instances[i].InstanceId) {
|
||||
if !checkInstanceDeleteSuccess(&instances[i]) {
|
||||
err := client.DeleteInstanceExecute(ctx, testutil.ProjectId, *instances[i].InstanceId)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying instance %s during CheckDestroy: %w", *instances[i].InstanceId, err)
|
||||
}
|
||||
_, err = redis.DeleteInstanceWaitHandler(ctx, client, testutil.ProjectId, *instances[i].InstanceId).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying instance %s during CheckDestroy: waiting for deletion %w", *instances[i].InstanceId, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
213
stackit/internal/services/resourcemanager/project/datasource.go
Normal file
213
stackit/internal/services/resourcemanager/project/datasource.go
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
package project
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"regexp"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/mapvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/resourcemanager"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &projectDataSource{}
|
||||
)
|
||||
|
||||
type ModelData struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
ContainerId types.String `tfsdk:"container_id"`
|
||||
ContainerParentId types.String `tfsdk:"parent_container_id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Labels types.Map `tfsdk:"labels"`
|
||||
}
|
||||
|
||||
// NewProjectDataSource is a helper function to simplify the provider implementation.
|
||||
func NewProjectDataSource() datasource.DataSource {
|
||||
return &projectDataSource{}
|
||||
}
|
||||
|
||||
// projectDataSource is the data source implementation.
|
||||
type projectDataSource struct {
|
||||
client *resourcemanager.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the data source type name.
|
||||
func (d *projectDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_resourcemanager_project"
|
||||
}
|
||||
|
||||
func (d *projectDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *resourcemanager.APIClient
|
||||
var err error
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
if providerData.ResourceManagerCustomEndpoint != "" {
|
||||
apiClient, err = resourcemanager.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithServiceAccountEmail(providerData.ServiceAccountEmail),
|
||||
config.WithEndpoint(providerData.ResourceManagerCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = resourcemanager.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithServiceAccountEmail(providerData.ServiceAccountEmail),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
d.client = apiClient
|
||||
tflog.Info(ctx, "Resource Manager project client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the data source.
|
||||
func (d *projectDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "Resource Manager project data source schema.",
|
||||
"id": "Terraform's internal resource ID. It is structured as \"`container_id`\".",
|
||||
"container_id": "Project container ID.",
|
||||
"parent_container_id": "Parent container ID",
|
||||
"name": "Project name.",
|
||||
"labels": `Labels are key-value string pairs which can be attached to a resource container. A label key must match the regex [A-ZÄÜÖa-zäüöß0-9_-]{1,64}. A label value must match the regex ^$|[A-ZÄÜÖa-zäüöß0-9_-]{1,64}`,
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
},
|
||||
"container_id": schema.StringAttribute{
|
||||
Description: descriptions["container_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"parent_container_id": schema.StringAttribute{
|
||||
Description: descriptions["parent_container_id"],
|
||||
Computed: true,
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Computed: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
stringvalidator.LengthAtMost(63),
|
||||
},
|
||||
},
|
||||
"labels": schema.MapAttribute{
|
||||
Description: descriptions["labels"],
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
Validators: []validator.Map{
|
||||
mapvalidator.KeysAre(
|
||||
stringvalidator.RegexMatches(
|
||||
regexp.MustCompile(`[A-ZÄÜÖa-zäüöß0-9_-]{1,64}`),
|
||||
"must match expression"),
|
||||
),
|
||||
mapvalidator.ValueStringsAre(
|
||||
stringvalidator.RegexMatches(
|
||||
regexp.MustCompile(`[A-ZÄÜÖa-zäüöß0-9_-]{1,64}`),
|
||||
"must match expression"),
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (d *projectDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var state ModelData
|
||||
diags := req.Config.Get(ctx, &state)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
containerId := state.ContainerId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", containerId)
|
||||
|
||||
projectResp, err := d.client.GetProject(ctx, containerId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading project", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
err = mapDataFields(ctx, projectResp, &state)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading project", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
diags = resp.State.Set(ctx, &state)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Resource Manager project read")
|
||||
}
|
||||
|
||||
func mapDataFields(ctx context.Context, projectResp *resourcemanager.ProjectResponseWithParents, model *ModelData) (err error) {
|
||||
if projectResp == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
|
||||
var containerId string
|
||||
if model.ContainerId.ValueString() != "" {
|
||||
containerId = model.ContainerId.ValueString()
|
||||
} else if projectResp.ContainerId != nil {
|
||||
containerId = *projectResp.ContainerId
|
||||
} else {
|
||||
return fmt.Errorf("container id not present")
|
||||
}
|
||||
|
||||
var labels basetypes.MapValue
|
||||
if projectResp.Labels != nil {
|
||||
labels, err = conversion.ToTerraformStringMap(ctx, *projectResp.Labels)
|
||||
if err != nil {
|
||||
return fmt.Errorf("converting to StringValue map: %w", err)
|
||||
}
|
||||
} else {
|
||||
labels = types.MapNull(types.StringType)
|
||||
}
|
||||
|
||||
model.Id = types.StringValue(containerId)
|
||||
model.ContainerId = types.StringValue(containerId)
|
||||
model.ContainerParentId = types.StringPointerValue(projectResp.Parent.ContainerId)
|
||||
model.Name = types.StringPointerValue(projectResp.Name)
|
||||
model.Labels = labels
|
||||
return nil
|
||||
}
|
||||
450
stackit/internal/services/resourcemanager/project/resource.go
Normal file
450
stackit/internal/services/resourcemanager/project/resource.go
Normal file
|
|
@ -0,0 +1,450 @@
|
|||
package project
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/mapvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/resourcemanager"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &projectResource{}
|
||||
_ resource.ResourceWithConfigure = &projectResource{}
|
||||
_ resource.ResourceWithImportState = &projectResource{}
|
||||
)
|
||||
|
||||
const (
|
||||
projectOwner = "project.owner"
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"` // needed by TF
|
||||
ContainerId types.String `tfsdk:"container_id"`
|
||||
ContainerParentId types.String `tfsdk:"parent_container_id"`
|
||||
Name types.String `tfsdk:"name"`
|
||||
Labels types.Map `tfsdk:"labels"`
|
||||
OwnerEmail types.String `tfsdk:"owner_email"`
|
||||
}
|
||||
|
||||
// NewProjectResource is a helper function to simplify the provider implementation.
|
||||
func NewProjectResource() resource.Resource {
|
||||
return &projectResource{}
|
||||
}
|
||||
|
||||
// projectResource is the resource implementation.
|
||||
type projectResource struct {
|
||||
client *resourcemanager.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *projectResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_resourcemanager_project"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *projectResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *resourcemanager.APIClient
|
||||
var err error
|
||||
if providerData.ResourceManagerCustomEndpoint != "" {
|
||||
ctx = tflog.SetField(ctx, "resourcemanager_custom_endpoint", providerData.ResourceManagerCustomEndpoint)
|
||||
apiClient, err = resourcemanager.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithServiceAccountEmail(providerData.ServiceAccountEmail),
|
||||
config.WithEndpoint(providerData.ResourceManagerCustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = resourcemanager.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithServiceAccountEmail(providerData.ServiceAccountEmail),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "Resource Manager project client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *projectResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
descriptions := map[string]string{
|
||||
"main": "Resource Manager project resource schema.",
|
||||
"id": "Terraform's internal resource ID. It is structured as \"`container_id`\".",
|
||||
"container_id": "Project container ID. Globally unique, user-friendly identifier.",
|
||||
"parent_container_id": "Parent container ID",
|
||||
"name": "Project name.",
|
||||
"labels": "Labels are key-value string pairs which can be attached to a resource container. A label key must match the regex [A-ZÄÜÖa-zäüöß0-9_-]{1,64}. A label value must match the regex ^$|[A-ZÄÜÖa-zäüöß0-9_-]{1,64}",
|
||||
"owner_email": "Email address of the owner of the project. This value is only considered during creation. Changing it afterwards will have no effect.",
|
||||
}
|
||||
|
||||
resp.Schema = schema.Schema{
|
||||
Description: descriptions["main"],
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: descriptions["id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"container_id": schema.StringAttribute{
|
||||
Description: descriptions["container_id"],
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"parent_container_id": schema.StringAttribute{
|
||||
Description: descriptions["parent_container_id"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: descriptions["name"],
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
stringvalidator.LengthAtLeast(1),
|
||||
stringvalidator.LengthAtMost(63),
|
||||
},
|
||||
},
|
||||
"labels": schema.MapAttribute{
|
||||
Description: descriptions["labels"],
|
||||
ElementType: types.StringType,
|
||||
Optional: true,
|
||||
Validators: []validator.Map{
|
||||
mapvalidator.KeysAre(
|
||||
stringvalidator.RegexMatches(
|
||||
regexp.MustCompile(`[A-ZÄÜÖa-zäüöß0-9_-]{1,64}`),
|
||||
"must match expression"),
|
||||
),
|
||||
mapvalidator.ValueStringsAre(
|
||||
stringvalidator.RegexMatches(
|
||||
regexp.MustCompile(`[A-ZÄÜÖa-zäüöß0-9_-]{1,64}`),
|
||||
"must match expression"),
|
||||
),
|
||||
},
|
||||
},
|
||||
"owner_email": schema.StringAttribute{
|
||||
Description: descriptions["owner_email"],
|
||||
Required: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *projectResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
containerId := model.ContainerId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_container_id", containerId)
|
||||
|
||||
serviceAccountEmail := r.client.GetConfig().ServiceAccountEmail
|
||||
if serviceAccountEmail == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating project", "The service account e-mail cannot be empty: set it in the provider configuration or through the STACKIT_SERVICE_ACCOUNT_EMAIL or in your credentials file (default filepath is ~/.stackit/credentials.json)")
|
||||
return
|
||||
}
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toCreatePayload(&model, serviceAccountEmail)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating project", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Create new project
|
||||
createResp, err := r.client.CreateProject(ctx).CreateProjectPayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating project", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
respContainerId := *createResp.ContainerId
|
||||
|
||||
// If the request has not been processed yet and the containerId doesnt exist,
|
||||
// the waiter will fail with authentication error, so wait some time before checking the creation
|
||||
wr, err := resourcemanager.CreateProjectWaitHandler(ctx, r.client, respContainerId).SetSleepBeforeWait(1 * time.Minute).SetTimeout(10 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating project", fmt.Sprintf("Instance creation waiting: %v", err))
|
||||
return
|
||||
}
|
||||
got, ok := wr.(*resourcemanager.ProjectResponseWithParents)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating project", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(ctx, got, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating project", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Set state to fully populated data
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Resource Manager project created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *projectResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
containerId := model.ContainerId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "container_id", containerId)
|
||||
|
||||
projectResp, err := r.client.GetProject(ctx, containerId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading project", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Map response body to schema
|
||||
err = mapFields(ctx, projectResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading project", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Set refreshed model
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Resource Manager project read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *projectResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from plan
|
||||
var model Model
|
||||
diags := req.Plan.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
containerId := model.ContainerId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "container_id", containerId)
|
||||
|
||||
// Generate API request body from model
|
||||
payload, err := toUpdatePayload(&model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating project", fmt.Sprintf("Creating API payload: %v", err))
|
||||
return
|
||||
}
|
||||
// Update existing project
|
||||
_, err = r.client.UpdateProject(ctx, containerId).UpdateProjectPayload(*payload).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating project", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Fetch updated zone
|
||||
projectResp, err := r.client.GetProject(ctx, containerId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating zone", fmt.Sprintf("Calling API for updated data: %v", err))
|
||||
return
|
||||
}
|
||||
err = mapFields(ctx, projectResp, &model)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating zone", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "Resource Manager project updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *projectResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Retrieve values from state
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
containerId := model.ContainerId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "container_id", containerId)
|
||||
|
||||
// Delete existing project
|
||||
err := r.client.DeleteProject(ctx, containerId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting project", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
_, err = resourcemanager.DeleteProjectWaitHandler(ctx, r.client, containerId).SetTimeout(10 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting project", fmt.Sprintf("Instance deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
tflog.Info(ctx, "Resource Manager project deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: container_id
|
||||
func (r *projectResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
if len(idParts) != 1 || idParts[0] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing project",
|
||||
fmt.Sprintf("Expected import identifier with format: [container_id] Got: %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
ctx = tflog.SetField(ctx, "container_id", req.ID)
|
||||
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("container_id"), req.ID)...)
|
||||
tflog.Info(ctx, "Resource Manager Project state imported")
|
||||
}
|
||||
|
||||
func mapFields(ctx context.Context, projectResp *resourcemanager.ProjectResponseWithParents, model *Model) (err error) {
|
||||
if projectResp == nil {
|
||||
return fmt.Errorf("response input is nil")
|
||||
}
|
||||
if model == nil {
|
||||
return fmt.Errorf("model input is nil")
|
||||
}
|
||||
|
||||
var containerId string
|
||||
if model.ContainerId.ValueString() != "" {
|
||||
containerId = model.ContainerId.ValueString()
|
||||
} else if projectResp.ContainerId != nil {
|
||||
containerId = *projectResp.ContainerId
|
||||
} else {
|
||||
return fmt.Errorf("container id not present")
|
||||
}
|
||||
|
||||
var labels basetypes.MapValue
|
||||
if projectResp.Labels != nil && len(*projectResp.Labels) != 0 {
|
||||
labels, err = conversion.ToTerraformStringMap(ctx, *projectResp.Labels)
|
||||
if err != nil {
|
||||
return fmt.Errorf("converting to StringValue map: %w", err)
|
||||
}
|
||||
} else {
|
||||
labels = types.MapNull(types.StringType)
|
||||
}
|
||||
|
||||
model.Id = types.StringValue(containerId)
|
||||
model.ContainerId = types.StringValue(containerId)
|
||||
if projectResp.Parent != nil {
|
||||
model.ContainerParentId = types.StringPointerValue(projectResp.Parent.ContainerId)
|
||||
} else {
|
||||
model.ContainerParentId = types.StringNull()
|
||||
}
|
||||
model.Name = types.StringPointerValue(projectResp.Name)
|
||||
model.Labels = labels
|
||||
return nil
|
||||
}
|
||||
|
||||
func toCreatePayload(model *Model, serviceAccountEmail string) (*resourcemanager.CreateProjectPayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
owner := projectOwner
|
||||
serviceAccountSubject := serviceAccountEmail
|
||||
members := []resourcemanager.ProjectMember{
|
||||
{
|
||||
Subject: &serviceAccountSubject,
|
||||
Role: &owner,
|
||||
},
|
||||
}
|
||||
|
||||
ownerSubject := model.OwnerEmail.ValueString()
|
||||
if ownerSubject != "" && ownerSubject != serviceAccountSubject {
|
||||
members = append(members,
|
||||
resourcemanager.ProjectMember{
|
||||
Subject: &ownerSubject,
|
||||
Role: &owner,
|
||||
})
|
||||
}
|
||||
|
||||
modelLabels := model.Labels.Elements()
|
||||
labels, err := conversion.ToOptStringMap(modelLabels)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("converting to GO map: %w", err)
|
||||
}
|
||||
|
||||
return &resourcemanager.CreateProjectPayload{
|
||||
ContainerParentId: model.ContainerParentId.ValueStringPointer(),
|
||||
Labels: labels,
|
||||
Members: &members,
|
||||
Name: model.Name.ValueStringPointer(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toUpdatePayload(model *Model) (*resourcemanager.UpdateProjectPayload, error) {
|
||||
if model == nil {
|
||||
return nil, fmt.Errorf("nil model")
|
||||
}
|
||||
|
||||
modelLabels := model.Labels.Elements()
|
||||
labels, err := conversion.ToOptStringMap(modelLabels)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("converting to GO map: %w", err)
|
||||
}
|
||||
|
||||
return &resourcemanager.UpdateProjectPayload{
|
||||
ContainerParentId: model.ContainerParentId.ValueStringPointer(),
|
||||
Name: model.Name.ValueStringPointer(),
|
||||
Labels: labels,
|
||||
}, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,278 @@
|
|||
package project
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/resourcemanager"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/conversion"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *resourcemanager.ProjectResponseWithParents
|
||||
expected Model
|
||||
expectedLabels *map[string]string
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_ok",
|
||||
&resourcemanager.ProjectResponseWithParents{
|
||||
ContainerId: utils.Ptr("cid"),
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("cid"),
|
||||
ContainerId: types.StringValue("cid"),
|
||||
ContainerParentId: types.StringNull(),
|
||||
Name: types.StringNull(),
|
||||
},
|
||||
nil,
|
||||
true,
|
||||
},
|
||||
{
|
||||
"values_ok",
|
||||
&resourcemanager.ProjectResponseWithParents{
|
||||
ContainerId: utils.Ptr("cid"),
|
||||
Labels: &map[string]string{
|
||||
"label1": "ref1",
|
||||
"label2": "ref2",
|
||||
},
|
||||
Parent: &resourcemanager.Parent{
|
||||
ContainerId: utils.Ptr("pid"),
|
||||
},
|
||||
Name: utils.Ptr("name"),
|
||||
},
|
||||
Model{
|
||||
Id: types.StringValue("cid"),
|
||||
ContainerId: types.StringValue("cid"),
|
||||
ContainerParentId: types.StringValue("pid"),
|
||||
Name: types.StringValue("name"),
|
||||
},
|
||||
&map[string]string{
|
||||
"label1": "ref1",
|
||||
"label2": "ref2",
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"response_nil_fail",
|
||||
nil,
|
||||
Model{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&resourcemanager.ProjectResponseWithParents{},
|
||||
Model{},
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
if tt.expectedLabels == nil {
|
||||
tt.expected.Labels = types.MapNull(types.StringType)
|
||||
} else {
|
||||
convertedLabels, err := conversion.ToTerraformStringMap(context.Background(), *tt.expectedLabels)
|
||||
if err != nil {
|
||||
t.Fatalf("Error converting to terraform string map: %v", err)
|
||||
}
|
||||
tt.expected.Labels = convertedLabels
|
||||
}
|
||||
state := &Model{
|
||||
ContainerId: tt.expected.ContainerId,
|
||||
}
|
||||
|
||||
err := mapFields(context.Background(), tt.input, state)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToCreatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputLabels *map[string]string
|
||||
expected *resourcemanager.CreateProjectPayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_ok",
|
||||
&Model{},
|
||||
nil,
|
||||
&resourcemanager.CreateProjectPayload{
|
||||
ContainerParentId: nil,
|
||||
Labels: nil,
|
||||
Members: &[]resourcemanager.ProjectMember{
|
||||
{
|
||||
Role: utils.Ptr(projectOwner),
|
||||
Subject: utils.Ptr("service_account_email"),
|
||||
},
|
||||
},
|
||||
Name: nil,
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"mapping_with_conversions_ok",
|
||||
&Model{
|
||||
ContainerParentId: types.StringValue("pid"),
|
||||
Name: types.StringValue("name"),
|
||||
OwnerEmail: types.StringValue("owner_email"),
|
||||
},
|
||||
&map[string]string{
|
||||
"label1": "1",
|
||||
"label2": "2",
|
||||
},
|
||||
&resourcemanager.CreateProjectPayload{
|
||||
ContainerParentId: utils.Ptr("pid"),
|
||||
Labels: &map[string]string{
|
||||
"label1": "1",
|
||||
"label2": "2",
|
||||
},
|
||||
Members: &[]resourcemanager.ProjectMember{
|
||||
{
|
||||
Role: utils.Ptr(projectOwner),
|
||||
Subject: utils.Ptr("service_account_email"),
|
||||
},
|
||||
{
|
||||
Role: utils.Ptr(projectOwner),
|
||||
Subject: utils.Ptr("owner_email"),
|
||||
},
|
||||
},
|
||||
Name: utils.Ptr("name"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
if tt.input != nil {
|
||||
if tt.inputLabels == nil {
|
||||
tt.input.Labels = types.MapNull(types.StringType)
|
||||
} else {
|
||||
convertedLabels, err := conversion.ToTerraformStringMap(context.Background(), *tt.inputLabels)
|
||||
if err != nil {
|
||||
t.Fatalf("Error converting to terraform string map: %v", err)
|
||||
}
|
||||
tt.input.Labels = convertedLabels
|
||||
}
|
||||
}
|
||||
output, err := toCreatePayload(tt.input, "service_account_email")
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToUpdatePayload(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
input *Model
|
||||
inputLabels *map[string]string
|
||||
expected *resourcemanager.UpdateProjectPayload
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_ok",
|
||||
&Model{},
|
||||
nil,
|
||||
&resourcemanager.UpdateProjectPayload{
|
||||
ContainerParentId: nil,
|
||||
Labels: nil,
|
||||
Name: nil,
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"mapping_with_conversions_ok",
|
||||
&Model{
|
||||
ContainerParentId: types.StringValue("pid"),
|
||||
Name: types.StringValue("name"),
|
||||
OwnerEmail: types.StringValue("owner_email"),
|
||||
},
|
||||
&map[string]string{
|
||||
"label1": "1",
|
||||
"label2": "2",
|
||||
},
|
||||
&resourcemanager.UpdateProjectPayload{
|
||||
ContainerParentId: utils.Ptr("pid"),
|
||||
Labels: &map[string]string{
|
||||
"label1": "1",
|
||||
"label2": "2",
|
||||
},
|
||||
Name: utils.Ptr("name"),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_model",
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
if tt.input != nil {
|
||||
if tt.inputLabels == nil {
|
||||
tt.input.Labels = types.MapNull(types.StringType)
|
||||
} else {
|
||||
convertedLabels, err := conversion.ToTerraformStringMap(context.Background(), *tt.inputLabels)
|
||||
if err != nil {
|
||||
t.Fatalf("Error converting to terraform string map: %v", err)
|
||||
}
|
||||
tt.input.Labels = convertedLabels
|
||||
}
|
||||
}
|
||||
output, err := toUpdatePayload(tt.input)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(output, tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,170 @@
|
|||
package resourcemanager_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-testing/helper/acctest"
|
||||
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
|
||||
"github.com/hashicorp/terraform-plugin-testing/terraform"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/resourcemanager"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/testutil"
|
||||
)
|
||||
|
||||
// Project resource data
|
||||
var projectResource = map[string]string{
|
||||
"name": fmt.Sprintf("acc-pj-%s", acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)),
|
||||
"parent_container_id": testutil.TestProjectParentContainerID,
|
||||
"billing_reference": "TEST-REF",
|
||||
"new_label": "a-label",
|
||||
}
|
||||
|
||||
func resourceConfig(name, label string) string {
|
||||
return fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
resource "stackit_resourcemanager_project" "project" {
|
||||
parent_container_id = "%s"
|
||||
name = "%s"
|
||||
labels = {
|
||||
"billing_reference" = "%s"
|
||||
%s
|
||||
}
|
||||
owner_email = "%s"
|
||||
}
|
||||
`,
|
||||
testutil.ResourceManagerProviderConfig(),
|
||||
projectResource["parent_container_id"],
|
||||
name,
|
||||
projectResource["billing_reference"],
|
||||
label,
|
||||
testutil.TestProjectServiceAccountEmail,
|
||||
)
|
||||
}
|
||||
|
||||
func TestAccResourceManagerResource(t *testing.T) {
|
||||
resource.Test(t, resource.TestCase{
|
||||
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
|
||||
CheckDestroy: testAccCheckResourceManagerDestroy,
|
||||
Steps: []resource.TestStep{
|
||||
// Creation
|
||||
{
|
||||
Config: resourceConfig(projectResource["name"], ""),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Project data
|
||||
resource.TestCheckResourceAttrSet("stackit_resourcemanager_project.project", "container_id"),
|
||||
resource.TestCheckResourceAttr("stackit_resourcemanager_project.project", "name", projectResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_resourcemanager_project.project", "parent_container_id", projectResource["parent_container_id"]),
|
||||
resource.TestCheckResourceAttr("stackit_resourcemanager_project.project", "labels.%", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_resourcemanager_project.project", "labels.billing_reference", projectResource["billing_reference"]),
|
||||
),
|
||||
},
|
||||
// Data source
|
||||
{
|
||||
Config: fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
data "stackit_resourcemanager_project" "project" {
|
||||
container_id = stackit_resourcemanager_project.project.container_id
|
||||
}`,
|
||||
resourceConfig(projectResource["name"], ""),
|
||||
),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Project data
|
||||
resource.TestCheckResourceAttrSet("data.stackit_resourcemanager_project.project", "id"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_resourcemanager_project.project", "container_id"),
|
||||
resource.TestCheckResourceAttr("data.stackit_resourcemanager_project.project", "name", projectResource["name"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_resourcemanager_project.project", "parent_container_id"),
|
||||
resource.TestCheckResourceAttr("data.stackit_resourcemanager_project.project", "labels.%", "1"),
|
||||
resource.TestCheckResourceAttr("data.stackit_resourcemanager_project.project", "labels.billing_reference", projectResource["billing_reference"]),
|
||||
resource.TestCheckResourceAttrPair("data.stackit_resourcemanager_project.project", "project_id",
|
||||
"stackit_resourcemanager_project.project", "project_id"),
|
||||
),
|
||||
},
|
||||
// Import
|
||||
{
|
||||
ResourceName: "stackit_resourcemanager_project.project",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_resourcemanager_project.project"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_resourcemanager_project.project")
|
||||
}
|
||||
containerId, ok := r.Primary.Attributes["container_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute container_id")
|
||||
}
|
||||
|
||||
return containerId, nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
// The owner_email attributes don't exist in the
|
||||
// API, therefore there is no value for it during import.
|
||||
ImportStateVerifyIgnore: []string{"owner_email"},
|
||||
},
|
||||
// Update
|
||||
{
|
||||
Config: resourceConfig(fmt.Sprintf("%s-new", projectResource["name"]), "new_label='a-label'"),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// Project data
|
||||
resource.TestCheckResourceAttrSet("stackit_resourcemanager_project.project", "container_id"),
|
||||
resource.TestCheckResourceAttr("stackit_resourcemanager_project.project", "name", fmt.Sprintf("%s-new", projectResource["name"])),
|
||||
resource.TestCheckResourceAttr("stackit_resourcemanager_project.project", "parent_container_id", projectResource["parent_container_id"]),
|
||||
resource.TestCheckResourceAttr("stackit_resourcemanager_project.project", "labels.%", "2"),
|
||||
resource.TestCheckResourceAttr("stackit_resourcemanager_project.project", "labels.billing_reference", projectResource["billing_reference"]),
|
||||
resource.TestCheckResourceAttr("stackit_resourcemanager_project.project", "labels.new_label", projectResource["new_label"]),
|
||||
),
|
||||
},
|
||||
// Deletion is done by the framework implicitly
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func testAccCheckResourceManagerDestroy(s *terraform.State) error {
|
||||
ctx := context.Background()
|
||||
var client *resourcemanager.APIClient
|
||||
var err error
|
||||
if testutil.ResourceManagerCustomEndpoint == "" {
|
||||
client, err = resourcemanager.NewAPIClient()
|
||||
} else {
|
||||
client, err = resourcemanager.NewAPIClient(
|
||||
config.WithEndpoint(testutil.ResourceManagerCustomEndpoint),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating client: %w", err)
|
||||
}
|
||||
|
||||
projectsToDestroy := []string{}
|
||||
for _, rs := range s.RootModule().Resources {
|
||||
if rs.Type != "stackit_resourcemanager_project" {
|
||||
continue
|
||||
}
|
||||
// project terraform ID: "[container_id]"
|
||||
containerId := rs.Primary.ID
|
||||
projectsToDestroy = append(projectsToDestroy, containerId)
|
||||
}
|
||||
|
||||
projectsResp, err := client.GetProjects(ctx).ContainerParentId(projectResource["parent_container_id"]).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting projectsResp: %w", err)
|
||||
}
|
||||
|
||||
items := *projectsResp.Items
|
||||
for i := range items {
|
||||
if utils.Contains(projectsToDestroy, *items[i].ContainerId) {
|
||||
err := client.DeleteProjectExecute(ctx, *items[i].ContainerId)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying project %s during CheckDestroy: %w", *items[i].ContainerId, err)
|
||||
}
|
||||
_, err = resourcemanager.DeleteProjectWaitHandler(ctx, client, *items[i].ContainerId).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying project %s during CheckDestroy: waiting for deletion %w", *items[i].ContainerId, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
322
stackit/internal/services/ske/cluster/datasource.go
Normal file
322
stackit/internal/services/ske/cluster/datasource.go
Normal file
|
|
@ -0,0 +1,322 @@
|
|||
package ske
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/diag"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/ske"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &clusterDataSource{}
|
||||
)
|
||||
|
||||
// NewClusterDataSource is a helper function to simplify the provider implementation.
|
||||
func NewClusterDataSource() datasource.DataSource {
|
||||
return &clusterDataSource{}
|
||||
}
|
||||
|
||||
// clusterDataSource is the data source implementation.
|
||||
type clusterDataSource struct {
|
||||
client *ske.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *clusterDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_ske_cluster"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *clusterDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *ske.APIClient
|
||||
var err error
|
||||
if providerData.SKECustomEndpoint != "" {
|
||||
apiClient, err = ske.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.SKECustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = ske.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "SKE client configured")
|
||||
}
|
||||
func (r *clusterDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Description: "SKE Cluster data source schema.",
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: "Terraform's internal resource ID. It is structured as \"`project_id`,`name`\".",
|
||||
Computed: true,
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: "STACKIT project ID to which the cluster is associated.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
"name": schema.StringAttribute{
|
||||
Description: "The cluster name.",
|
||||
Required: true,
|
||||
},
|
||||
"kubernetes_version": schema.StringAttribute{
|
||||
Description: "Kubernetes version.",
|
||||
Computed: true,
|
||||
},
|
||||
"kubernetes_version_used": schema.StringAttribute{
|
||||
Description: "Full Kubernetes version used. For example, if `1.22` was selected, this value may result to `1.22.15`",
|
||||
Computed: true,
|
||||
},
|
||||
"allow_privileged_containers": schema.BoolAttribute{
|
||||
Description: "DEPRECATED as of Kubernetes 1.25+\n Flag to specify if privileged mode for containers is enabled or not.\nThis should be used with care since it also disables a couple of other features like the use of some volume type (e.g. PVCs).",
|
||||
DeprecationMessage: "Please remove this flag from your configuration when using Kubernetes version 1.25+.",
|
||||
Computed: true,
|
||||
},
|
||||
|
||||
"node_pools": schema.ListNestedAttribute{
|
||||
Description: "One or more `node_pool` block as defined below.",
|
||||
Computed: true,
|
||||
NestedObject: schema.NestedAttributeObject{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"name": schema.StringAttribute{
|
||||
Description: "Specifies the name of the node pool.",
|
||||
Computed: true,
|
||||
},
|
||||
"machine_type": schema.StringAttribute{
|
||||
Description: "The machine type.",
|
||||
Computed: true,
|
||||
},
|
||||
"os_name": schema.StringAttribute{
|
||||
Description: "The name of the OS image.",
|
||||
Computed: true,
|
||||
},
|
||||
"os_version": schema.StringAttribute{
|
||||
Description: "The OS image version.",
|
||||
Computed: true,
|
||||
},
|
||||
"minimum": schema.Int64Attribute{
|
||||
Description: "Minimum number of nodes in the pool.",
|
||||
Computed: true,
|
||||
},
|
||||
|
||||
"maximum": schema.Int64Attribute{
|
||||
Description: "Maximum number of nodes in the pool.",
|
||||
Computed: true,
|
||||
},
|
||||
|
||||
"max_surge": schema.Int64Attribute{
|
||||
Description: "The maximum number of nodes upgraded simultaneously.",
|
||||
Computed: true,
|
||||
},
|
||||
"max_unavailable": schema.Int64Attribute{
|
||||
Description: "The maximum number of nodes unavailable during upgraded.",
|
||||
Computed: true,
|
||||
},
|
||||
"volume_type": schema.StringAttribute{
|
||||
Description: "Specifies the volume type.",
|
||||
Computed: true,
|
||||
},
|
||||
"volume_size": schema.Int64Attribute{
|
||||
Description: "The volume size in GB.",
|
||||
Computed: true,
|
||||
},
|
||||
"labels": schema.MapAttribute{
|
||||
Description: "Labels to add to each node.",
|
||||
Computed: true,
|
||||
ElementType: types.StringType,
|
||||
},
|
||||
"taints": schema.ListNestedAttribute{
|
||||
Description: "Specifies a taint list as defined below.",
|
||||
Computed: true,
|
||||
NestedObject: schema.NestedAttributeObject{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"effect": schema.StringAttribute{
|
||||
Description: "The taint effect.",
|
||||
Computed: true,
|
||||
},
|
||||
"key": schema.StringAttribute{
|
||||
Description: "Taint key to be applied to a node.",
|
||||
Computed: true,
|
||||
},
|
||||
"value": schema.StringAttribute{
|
||||
Description: "Taint value corresponding to the taint key.",
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"cri": schema.StringAttribute{
|
||||
Description: "Specifies the container runtime.",
|
||||
Computed: true,
|
||||
},
|
||||
"availability_zones": schema.ListAttribute{
|
||||
Description: "Specify a list of availability zones.",
|
||||
ElementType: types.StringType,
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"maintenance": schema.SingleNestedAttribute{
|
||||
Description: "A single maintenance block as defined below",
|
||||
Computed: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"enable_kubernetes_version_updates": schema.BoolAttribute{
|
||||
Description: "Flag to enable/disable auto-updates of the Kubernetes version.",
|
||||
Computed: true,
|
||||
},
|
||||
"enable_machine_image_version_updates": schema.BoolAttribute{
|
||||
Description: "Flag to enable/disable auto-updates of the OS image version.",
|
||||
Computed: true,
|
||||
},
|
||||
"start": schema.StringAttribute{
|
||||
Description: "Date time for maintenance window start.",
|
||||
Computed: true,
|
||||
},
|
||||
"end": schema.StringAttribute{
|
||||
Description: "Date time for maintenance window end.",
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
"hibernations": schema.ListNestedAttribute{
|
||||
Description: "One or more hibernation block as defined below.",
|
||||
Computed: true,
|
||||
NestedObject: schema.NestedAttributeObject{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"start": schema.StringAttribute{
|
||||
Description: "Start time of cluster hibernation in crontab syntax.",
|
||||
Computed: true,
|
||||
},
|
||||
"end": schema.StringAttribute{
|
||||
Description: "End time of hibernation, in crontab syntax.",
|
||||
Computed: true,
|
||||
},
|
||||
"timezone": schema.StringAttribute{
|
||||
Description: "Timezone name corresponding to a file in the IANA Time Zone database.",
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
"extensions": schema.SingleNestedAttribute{
|
||||
Description: "A single extensions block as defined below",
|
||||
Computed: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"argus": schema.SingleNestedAttribute{
|
||||
Description: "A single argus block as defined below",
|
||||
Computed: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"enabled": schema.BoolAttribute{
|
||||
Description: "Flag to enable/disable argus extensions.",
|
||||
Computed: true,
|
||||
},
|
||||
"argus_instance_id": schema.StringAttribute{
|
||||
Description: "Instance ID of argus",
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
"acl": schema.SingleNestedAttribute{
|
||||
Description: "Cluster access control configuration",
|
||||
Computed: true,
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"enabled": schema.BoolAttribute{
|
||||
Description: "Is ACL enabled?",
|
||||
Computed: true,
|
||||
},
|
||||
"allowed_cidrs": schema.ListAttribute{
|
||||
Description: "Specify a list of CIDRs to whitelist",
|
||||
Computed: true,
|
||||
ElementType: types.StringType,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"kube_config": schema.StringAttribute{
|
||||
Description: "Kube config file used for connecting to the cluster",
|
||||
Sensitive: true,
|
||||
Computed: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *clusterDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var state Cluster
|
||||
diags := req.Config.Get(ctx, &state)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := state.ProjectId.ValueString()
|
||||
name := state.Name.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
ctx = tflog.SetField(ctx, "name", name)
|
||||
clusterResp, err := r.client.GetCluster(ctx, projectId, name).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading cluster", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
err = mapFields(ctx, clusterResp, &state)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading cluster", fmt.Sprintf("Processing API payload: %v", err))
|
||||
return
|
||||
}
|
||||
r.getCredential(ctx, &diags, &state)
|
||||
// Set refreshed state
|
||||
diags = resp.State.Set(ctx, state)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "SKE cluster read")
|
||||
}
|
||||
|
||||
func (r *clusterDataSource) getCredential(ctx context.Context, diags *diag.Diagnostics, model *Cluster) {
|
||||
c := r.client
|
||||
res, err := c.GetCredentials(ctx, model.ProjectId.ValueString(), model.Name.ValueString()).Execute()
|
||||
if err != nil {
|
||||
diags.AddError("failed fetching cluster credentials for data source", err.Error())
|
||||
return
|
||||
}
|
||||
model.KubeConfig = types.StringPointerValue(res.Kubeconfig)
|
||||
}
|
||||
1175
stackit/internal/services/ske/cluster/resource.go
Normal file
1175
stackit/internal/services/ske/cluster/resource.go
Normal file
File diff suppressed because it is too large
Load diff
635
stackit/internal/services/ske/cluster/resource_test.go
Normal file
635
stackit/internal/services/ske/cluster/resource_test.go
Normal file
|
|
@ -0,0 +1,635 @@
|
|||
package ske
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/terraform-plugin-framework/attr"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/ske"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
)
|
||||
|
||||
func TestMapFields(t *testing.T) {
|
||||
cs := ske.ClusterStatusState("OK")
|
||||
tests := []struct {
|
||||
description string
|
||||
input *ske.ClusterResponse
|
||||
expected Cluster
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"default_values",
|
||||
&ske.ClusterResponse{
|
||||
Name: utils.Ptr("name"),
|
||||
},
|
||||
Cluster{
|
||||
Id: types.StringValue("pid,name"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringValue("name"),
|
||||
KubernetesVersion: types.StringNull(),
|
||||
AllowPrivilegedContainers: types.BoolNull(),
|
||||
NodePools: []NodePool{},
|
||||
Maintenance: types.ObjectNull(map[string]attr.Type{}),
|
||||
Hibernations: nil,
|
||||
Extensions: nil,
|
||||
KubeConfig: types.StringNull(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"simple_values",
|
||||
&ske.ClusterResponse{
|
||||
Extensions: &ske.Extension{
|
||||
Acl: &ske.ACL{
|
||||
AllowedCidrs: &[]string{"cidr1"},
|
||||
Enabled: utils.Ptr(true),
|
||||
},
|
||||
Argus: &ske.Argus{
|
||||
ArgusInstanceId: utils.Ptr("aid"),
|
||||
Enabled: utils.Ptr(true),
|
||||
},
|
||||
},
|
||||
Hibernation: &ske.Hibernation{
|
||||
Schedules: &[]ske.HibernationSchedule{
|
||||
{
|
||||
End: utils.Ptr("2"),
|
||||
Start: utils.Ptr("1"),
|
||||
Timezone: utils.Ptr("CET"),
|
||||
},
|
||||
},
|
||||
},
|
||||
Kubernetes: &ske.Kubernetes{
|
||||
AllowPrivilegedContainers: utils.Ptr(true),
|
||||
Version: utils.Ptr("1.2.3"),
|
||||
},
|
||||
Maintenance: &ske.Maintenance{
|
||||
AutoUpdate: &ske.MaintenanceAutoUpdate{
|
||||
KubernetesVersion: utils.Ptr(true),
|
||||
MachineImageVersion: utils.Ptr(true),
|
||||
},
|
||||
TimeWindow: &ske.TimeWindow{
|
||||
Start: utils.Ptr("0000-01-02T03:04:05+06:00"),
|
||||
End: utils.Ptr("0010-11-12T13:14:15Z"),
|
||||
},
|
||||
},
|
||||
Name: utils.Ptr("name"),
|
||||
Nodepools: &[]ske.Nodepool{
|
||||
{
|
||||
AvailabilityZones: &[]string{"z1", "z2"},
|
||||
Cri: &ske.CRI{
|
||||
Name: utils.Ptr("cri"),
|
||||
},
|
||||
Labels: &map[string]string{"k": "v"},
|
||||
Machine: &ske.Machine{
|
||||
Image: &ske.Image{
|
||||
Name: utils.Ptr("os"),
|
||||
Version: utils.Ptr("os-ver"),
|
||||
},
|
||||
Type: utils.Ptr("B"),
|
||||
},
|
||||
MaxSurge: utils.Ptr(int32(3)),
|
||||
MaxUnavailable: nil,
|
||||
Maximum: utils.Ptr(int32(5)),
|
||||
Minimum: utils.Ptr(int32(1)),
|
||||
Name: utils.Ptr("node"),
|
||||
Taints: &[]ske.Taint{
|
||||
{
|
||||
Effect: utils.Ptr("effect"),
|
||||
Key: utils.Ptr("key"),
|
||||
Value: utils.Ptr("value"),
|
||||
},
|
||||
},
|
||||
Volume: &ske.Volume{
|
||||
Size: utils.Ptr(int32(3)),
|
||||
Type: utils.Ptr("type"),
|
||||
},
|
||||
},
|
||||
},
|
||||
Status: &ske.ClusterStatus{
|
||||
Aggregated: &cs,
|
||||
Error: nil,
|
||||
Hibernated: nil,
|
||||
},
|
||||
},
|
||||
Cluster{
|
||||
Id: types.StringValue("pid,name"),
|
||||
ProjectId: types.StringValue("pid"),
|
||||
Name: types.StringValue("name"),
|
||||
KubernetesVersion: types.StringValue("1.2"),
|
||||
KubernetesVersionUsed: types.StringValue("1.2.3"),
|
||||
AllowPrivilegedContainers: types.BoolValue(true),
|
||||
|
||||
NodePools: []NodePool{
|
||||
{
|
||||
Name: types.StringValue("node"),
|
||||
MachineType: types.StringValue("B"),
|
||||
OSName: types.StringValue("os"),
|
||||
OSVersion: types.StringValue("os-ver"),
|
||||
Minimum: types.Int64Value(1),
|
||||
Maximum: types.Int64Value(5),
|
||||
MaxSurge: types.Int64Value(3),
|
||||
MaxUnavailable: types.Int64Null(),
|
||||
VolumeType: types.StringValue("type"),
|
||||
VolumeSize: types.Int64Value(3),
|
||||
Labels: types.MapValueMust(types.StringType, map[string]attr.Value{"k": types.StringValue("v")}),
|
||||
Taints: []Taint{
|
||||
{
|
||||
Effect: types.StringValue("effect"),
|
||||
Key: types.StringValue("key"),
|
||||
Value: types.StringValue("value"),
|
||||
},
|
||||
},
|
||||
CRI: types.StringValue("cri"),
|
||||
AvailabilityZones: types.ListValueMust(types.StringType, []attr.Value{types.StringValue("z1"), types.StringValue("z2")}),
|
||||
},
|
||||
},
|
||||
Maintenance: types.ObjectValueMust(maintenanceTypes, map[string]attr.Value{
|
||||
"enable_kubernetes_version_updates": types.BoolValue(true),
|
||||
"enable_machine_image_version_updates": types.BoolValue(true),
|
||||
"start": types.StringValue("03:04:05+06:00"),
|
||||
"end": types.StringValue("13:14:15Z"),
|
||||
}),
|
||||
Hibernations: []Hibernation{
|
||||
{
|
||||
Start: types.StringValue("1"),
|
||||
End: types.StringValue("2"),
|
||||
Timezone: types.StringValue("CET"),
|
||||
},
|
||||
},
|
||||
Extensions: &Extensions{
|
||||
Argus: &ArgusExtension{
|
||||
Enabled: types.BoolValue(true),
|
||||
ArgusInstanceId: types.StringValue("aid"),
|
||||
},
|
||||
ACL: &ACL{
|
||||
Enabled: types.BoolValue(true),
|
||||
AllowedCIDRs: types.ListValueMust(types.StringType, []attr.Value{
|
||||
types.StringValue("cidr1"),
|
||||
}),
|
||||
},
|
||||
},
|
||||
KubeConfig: types.StringNull(),
|
||||
},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"nil_response",
|
||||
nil,
|
||||
Cluster{},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_resource_id",
|
||||
&ske.ClusterResponse{},
|
||||
Cluster{},
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
state := &Cluster{
|
||||
ProjectId: tt.expected.ProjectId,
|
||||
}
|
||||
err := mapFields(context.Background(), tt.input, state)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
diff := cmp.Diff(state, &tt.expected)
|
||||
if diff != "" {
|
||||
t.Fatalf("Data does not match: %s", diff)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLatestMatchingVersion(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
availableVersions []ske.KubernetesVersion
|
||||
providedVersion *string
|
||||
expectedVersionUsed *string
|
||||
expectedHasDeprecatedVersion bool
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
"available_version",
|
||||
[]ske.KubernetesVersion{
|
||||
{
|
||||
Version: utils.Ptr("1.20.0"),
|
||||
State: utils.Ptr(VersionStateSupported),
|
||||
},
|
||||
{
|
||||
Version: utils.Ptr("1.20.1"),
|
||||
State: utils.Ptr(VersionStateSupported),
|
||||
},
|
||||
{
|
||||
Version: utils.Ptr("1.20.2"),
|
||||
State: utils.Ptr(VersionStateSupported),
|
||||
},
|
||||
{
|
||||
Version: utils.Ptr("1.19.0"),
|
||||
State: utils.Ptr(VersionStateSupported),
|
||||
},
|
||||
},
|
||||
utils.Ptr("1.20"),
|
||||
utils.Ptr("1.20.2"),
|
||||
false,
|
||||
true,
|
||||
},
|
||||
{
|
||||
"available_version_no_patch",
|
||||
[]ske.KubernetesVersion{
|
||||
{
|
||||
Version: utils.Ptr("1.20.0"),
|
||||
State: utils.Ptr(VersionStateSupported),
|
||||
},
|
||||
{
|
||||
Version: utils.Ptr("1.19.0"),
|
||||
State: utils.Ptr(VersionStateSupported),
|
||||
},
|
||||
},
|
||||
utils.Ptr("1.20"),
|
||||
utils.Ptr("1.20.0"),
|
||||
false,
|
||||
true,
|
||||
},
|
||||
{
|
||||
"deprecated_version",
|
||||
[]ske.KubernetesVersion{
|
||||
{
|
||||
Version: utils.Ptr("1.20.0"),
|
||||
State: utils.Ptr(VersionStateSupported),
|
||||
},
|
||||
{
|
||||
Version: utils.Ptr("1.19.0"),
|
||||
State: utils.Ptr(VersionStateDeprecated),
|
||||
},
|
||||
},
|
||||
utils.Ptr("1.19"),
|
||||
utils.Ptr("1.19.0"),
|
||||
true,
|
||||
true,
|
||||
},
|
||||
{
|
||||
"deprecated_version_not_selected",
|
||||
[]ske.KubernetesVersion{
|
||||
{
|
||||
Version: utils.Ptr("1.20.0"),
|
||||
State: utils.Ptr(VersionStateSupported),
|
||||
},
|
||||
{
|
||||
Version: utils.Ptr("1.19.0"),
|
||||
State: utils.Ptr(VersionStateDeprecated),
|
||||
},
|
||||
},
|
||||
utils.Ptr("1.20"),
|
||||
utils.Ptr("1.20.0"),
|
||||
false,
|
||||
true,
|
||||
},
|
||||
{
|
||||
"preview_version",
|
||||
[]ske.KubernetesVersion{
|
||||
{
|
||||
Version: utils.Ptr("1.20.0"),
|
||||
State: utils.Ptr(VersionStatePreview),
|
||||
},
|
||||
{
|
||||
Version: utils.Ptr("1.19.0"),
|
||||
State: utils.Ptr(VersionStateSupported),
|
||||
},
|
||||
},
|
||||
utils.Ptr("1.20"),
|
||||
utils.Ptr("1.20.0"),
|
||||
false,
|
||||
true,
|
||||
},
|
||||
{
|
||||
"no_matching_available_versions",
|
||||
[]ske.KubernetesVersion{
|
||||
{
|
||||
Version: utils.Ptr("1.20.0"),
|
||||
State: utils.Ptr(VersionStateSupported),
|
||||
},
|
||||
{
|
||||
Version: utils.Ptr("1.19.0"),
|
||||
State: utils.Ptr(VersionStateSupported),
|
||||
},
|
||||
},
|
||||
utils.Ptr("1.21"),
|
||||
nil,
|
||||
false,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"no_available_version",
|
||||
[]ske.KubernetesVersion{},
|
||||
utils.Ptr("1.20"),
|
||||
nil,
|
||||
false,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_available_version",
|
||||
nil,
|
||||
utils.Ptr("1.20"),
|
||||
nil,
|
||||
false,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"empty_provided_version",
|
||||
[]ske.KubernetesVersion{
|
||||
{
|
||||
Version: utils.Ptr("1.20.0"),
|
||||
State: utils.Ptr(VersionStateSupported),
|
||||
},
|
||||
{
|
||||
Version: utils.Ptr("1.19.0"),
|
||||
State: utils.Ptr(VersionStateSupported),
|
||||
},
|
||||
},
|
||||
utils.Ptr(""),
|
||||
nil,
|
||||
false,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"nil_provided_version",
|
||||
[]ske.KubernetesVersion{
|
||||
{
|
||||
Version: utils.Ptr("1.20.0"),
|
||||
State: utils.Ptr(VersionStateSupported),
|
||||
},
|
||||
{
|
||||
Version: utils.Ptr("1.19.0"),
|
||||
State: utils.Ptr(VersionStateSupported),
|
||||
},
|
||||
},
|
||||
nil,
|
||||
nil,
|
||||
false,
|
||||
false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
versionUsed, hasDeprecatedVersion, err := latestMatchingVersion(tt.availableVersions, tt.providedVersion)
|
||||
if !tt.isValid && err == nil {
|
||||
t.Fatalf("Should have failed")
|
||||
}
|
||||
if tt.isValid && err != nil {
|
||||
t.Fatalf("Should not have failed: %v", err)
|
||||
}
|
||||
if tt.isValid {
|
||||
if *versionUsed != *tt.expectedVersionUsed {
|
||||
t.Fatalf("Used version does not match: expecting %s, got %s", *tt.expectedVersionUsed, *versionUsed)
|
||||
}
|
||||
if tt.expectedHasDeprecatedVersion != hasDeprecatedVersion {
|
||||
t.Fatalf("hasDeprecatedVersion flag is wrong: expecting %t, got %t", tt.expectedHasDeprecatedVersion, hasDeprecatedVersion)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestGetMaintenanceTimes(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
startAPI string
|
||||
startTF *string
|
||||
endAPI string
|
||||
endTF *string
|
||||
isValid bool
|
||||
startExpected string
|
||||
endExpected string
|
||||
}{
|
||||
{
|
||||
description: "base",
|
||||
startAPI: "0001-02-03T04:05:06+07:08",
|
||||
endAPI: "0011-12-13T14:15:16+17:18",
|
||||
isValid: true,
|
||||
startExpected: "04:05:06+07:08",
|
||||
endExpected: "14:15:16+17:18",
|
||||
},
|
||||
{
|
||||
description: "base_utc",
|
||||
startAPI: "0001-02-03T04:05:06Z",
|
||||
endAPI: "0011-12-13T14:15:16Z",
|
||||
isValid: true,
|
||||
startExpected: "04:05:06Z",
|
||||
endExpected: "14:15:16Z",
|
||||
},
|
||||
{
|
||||
description: "api_wrong_format_1",
|
||||
startAPI: "T04:05:06+07:08",
|
||||
endAPI: "0011-12-13T14:15:16+17:18",
|
||||
isValid: false,
|
||||
},
|
||||
{
|
||||
description: "api_wrong_format_2",
|
||||
startAPI: "0001-02-03T04:05:06+07:08",
|
||||
endAPI: "14:15:16+17:18",
|
||||
isValid: false,
|
||||
},
|
||||
{
|
||||
description: "tf_state_filled_in_1",
|
||||
startAPI: "0001-02-03T04:05:06+07:08",
|
||||
startTF: utils.Ptr("04:05:06+07:08"),
|
||||
endAPI: "0011-12-13T14:15:16+17:18",
|
||||
endTF: utils.Ptr("14:15:16+17:18"),
|
||||
isValid: true,
|
||||
startExpected: "04:05:06+07:08",
|
||||
endExpected: "14:15:16+17:18",
|
||||
},
|
||||
{
|
||||
description: "tf_state_filled_in_2",
|
||||
startAPI: "0001-02-03T04:05:06Z",
|
||||
startTF: utils.Ptr("04:05:06+00:00"),
|
||||
endAPI: "0011-12-13T14:15:16Z",
|
||||
endTF: utils.Ptr("14:15:16+00:00"),
|
||||
isValid: true,
|
||||
startExpected: "04:05:06+00:00",
|
||||
endExpected: "14:15:16+00:00",
|
||||
},
|
||||
{
|
||||
description: "tf_state_filled_in_3",
|
||||
startAPI: "0001-02-03T04:05:06+00:00",
|
||||
startTF: utils.Ptr("04:05:06Z"),
|
||||
endAPI: "0011-12-13T14:15:16+00:00",
|
||||
endTF: utils.Ptr("14:15:16Z"),
|
||||
isValid: true,
|
||||
startExpected: "04:05:06Z",
|
||||
endExpected: "14:15:16Z",
|
||||
},
|
||||
{
|
||||
description: "tf_state_doesnt_match_1",
|
||||
startAPI: "0001-02-03T04:05:06+07:08",
|
||||
startTF: utils.Ptr("00:00:00+07:08"),
|
||||
endAPI: "0011-12-13T14:15:16+17:18",
|
||||
endTF: utils.Ptr("14:15:16+17:18"),
|
||||
isValid: false,
|
||||
},
|
||||
{
|
||||
description: "tf_state_doesnt_match_2",
|
||||
startAPI: "0001-02-03T04:05:06+07:08",
|
||||
startTF: utils.Ptr("04:05:06+07:08"),
|
||||
endAPI: "0011-12-13T14:15:16+17:18",
|
||||
endTF: utils.Ptr("00:00:00+17:18"),
|
||||
isValid: false,
|
||||
},
|
||||
{
|
||||
description: "tf_state_doesnt_match_3",
|
||||
startAPI: "0001-02-03T04:05:06+07:08",
|
||||
startTF: utils.Ptr("04:05:06Z"),
|
||||
endAPI: "0011-12-13T14:15:16+17:18",
|
||||
endTF: utils.Ptr("14:15:16+17:18"),
|
||||
isValid: false,
|
||||
},
|
||||
{
|
||||
description: "tf_state_doesnt_match_4",
|
||||
startAPI: "0001-02-03T04:05:06+07:08",
|
||||
startTF: utils.Ptr("04:05:06+07:08"),
|
||||
endAPI: "0011-12-13T14:15:16+17:18",
|
||||
endTF: utils.Ptr("14:15:16Z"),
|
||||
isValid: false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
apiResponse := &ske.ClusterResponse{
|
||||
Maintenance: &ske.Maintenance{
|
||||
TimeWindow: &ske.TimeWindow{
|
||||
Start: utils.Ptr(tt.startAPI),
|
||||
End: utils.Ptr(tt.endAPI),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
maintenanceValues := map[string]attr.Value{
|
||||
"enable_kubernetes_version_updates": types.BoolNull(),
|
||||
"enable_machine_image_version_updates": types.BoolNull(),
|
||||
"start": types.StringPointerValue(tt.startTF),
|
||||
"end": types.StringPointerValue(tt.endTF),
|
||||
}
|
||||
maintenanceObject, diags := types.ObjectValue(maintenanceTypes, maintenanceValues)
|
||||
if diags.HasError() {
|
||||
t.Fatalf("failed to create flavor: %v", core.DiagsToError(diags))
|
||||
}
|
||||
tfState := &Cluster{
|
||||
Maintenance: maintenanceObject,
|
||||
}
|
||||
|
||||
start, end, err := getMaintenanceTimes(context.Background(), apiResponse, tfState)
|
||||
|
||||
if err != nil {
|
||||
if tt.isValid {
|
||||
t.Errorf("getMaintenanceTimes failed on valid input: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !tt.isValid {
|
||||
t.Fatalf("getMaintenanceTimes didn't fail on invalid input")
|
||||
}
|
||||
if tt.startExpected != start {
|
||||
t.Errorf("extected start '%s', got '%s'", tt.startExpected, start)
|
||||
}
|
||||
if tt.endExpected != end {
|
||||
t.Errorf("extected end '%s', got '%s'", tt.endExpected, end)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckAllowPrivilegedContainers(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
kubernetesVersion *string
|
||||
allowPrivilegeContainers *bool
|
||||
isValid bool
|
||||
}{
|
||||
{
|
||||
description: "null_version_1",
|
||||
kubernetesVersion: nil,
|
||||
allowPrivilegeContainers: nil,
|
||||
isValid: false,
|
||||
},
|
||||
{
|
||||
description: "null_version_2",
|
||||
kubernetesVersion: nil,
|
||||
allowPrivilegeContainers: utils.Ptr(false),
|
||||
isValid: false,
|
||||
},
|
||||
{
|
||||
description: "flag_required_1",
|
||||
kubernetesVersion: utils.Ptr("0.999.999"),
|
||||
allowPrivilegeContainers: nil,
|
||||
isValid: false,
|
||||
},
|
||||
{
|
||||
description: "flag_required_2",
|
||||
kubernetesVersion: utils.Ptr("0.999.999"),
|
||||
allowPrivilegeContainers: utils.Ptr(false),
|
||||
isValid: true,
|
||||
},
|
||||
{
|
||||
description: "flag_required_3",
|
||||
kubernetesVersion: utils.Ptr("1.24.999"),
|
||||
allowPrivilegeContainers: nil,
|
||||
isValid: false,
|
||||
},
|
||||
{
|
||||
description: "flag_required_4",
|
||||
kubernetesVersion: utils.Ptr("1.24.999"),
|
||||
allowPrivilegeContainers: utils.Ptr(false),
|
||||
isValid: true,
|
||||
},
|
||||
{
|
||||
description: "flag_deprecated_1",
|
||||
kubernetesVersion: utils.Ptr("1.25"),
|
||||
allowPrivilegeContainers: nil,
|
||||
isValid: true,
|
||||
},
|
||||
{
|
||||
description: "flag_deprecated_2",
|
||||
kubernetesVersion: utils.Ptr("1.25"),
|
||||
allowPrivilegeContainers: utils.Ptr(false),
|
||||
isValid: false,
|
||||
},
|
||||
{
|
||||
description: "flag_deprecated_3",
|
||||
kubernetesVersion: utils.Ptr("2.0.0"),
|
||||
allowPrivilegeContainers: nil,
|
||||
isValid: true,
|
||||
},
|
||||
{
|
||||
description: "flag_deprecated_4",
|
||||
kubernetesVersion: utils.Ptr("2.0.0"),
|
||||
allowPrivilegeContainers: utils.Ptr(false),
|
||||
isValid: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.description, func(t *testing.T) {
|
||||
diags := checkAllowPrivilegedContainers(
|
||||
types.BoolPointerValue(tt.allowPrivilegeContainers),
|
||||
types.StringPointerValue(tt.kubernetesVersion),
|
||||
)
|
||||
|
||||
if tt.isValid && diags.HasError() {
|
||||
t.Errorf("checkAllowPrivilegedContainers failed on valid input: %v", core.DiagsToError(diags))
|
||||
}
|
||||
if !tt.isValid && !diags.HasError() {
|
||||
t.Errorf("checkAllowPrivilegedContainers didn't fail on valid input")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
118
stackit/internal/services/ske/project/datasource.go
Normal file
118
stackit/internal/services/ske/project/datasource.go
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
package ske
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/ske"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ datasource.DataSource = &projectDataSource{}
|
||||
)
|
||||
|
||||
// NewProjectDataSource is a helper function to simplify the provider implementation.
|
||||
func NewProjectDataSource() datasource.DataSource {
|
||||
return &projectDataSource{}
|
||||
}
|
||||
|
||||
// projectDataSource is the data source implementation.
|
||||
type projectDataSource struct {
|
||||
client *ske.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *projectDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_ske_project"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *projectDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *ske.APIClient
|
||||
var err error
|
||||
if providerData.SKECustomEndpoint != "" {
|
||||
apiClient, err = ske.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.SKECustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = ske.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "SKE client configured")
|
||||
}
|
||||
|
||||
// Schema defines the schema for the resource.
|
||||
func (r *projectDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: "Terraform's internal resource ID. It is structured as \"`project_id`\".",
|
||||
Computed: true,
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: "STACKIT Project ID in which the kubernetes project is enabled.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *projectDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.Config.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
|
||||
projectId := model.ProjectId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
_, err := r.client.GetProject(ctx, projectId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading project", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
model.Id = types.StringValue(projectId)
|
||||
model.ProjectId = types.StringValue(projectId)
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "SKE project read")
|
||||
}
|
||||
212
stackit/internal/services/ske/project/resource.go
Normal file
212
stackit/internal/services/ske/project/resource.go
Normal file
|
|
@ -0,0 +1,212 @@
|
|||
package ske
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
||||
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
|
||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||
"github.com/hashicorp/terraform-plugin-log/tflog"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/ske"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate"
|
||||
)
|
||||
|
||||
// Ensure the implementation satisfies the expected interfaces.
|
||||
var (
|
||||
_ resource.Resource = &projectResource{}
|
||||
_ resource.ResourceWithConfigure = &projectResource{}
|
||||
_ resource.ResourceWithImportState = &projectResource{}
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
Id types.String `tfsdk:"id"`
|
||||
ProjectId types.String `tfsdk:"project_id"`
|
||||
}
|
||||
|
||||
// NewProjectResource is a helper function to simplify the provider implementation.
|
||||
func NewProjectResource() resource.Resource {
|
||||
return &projectResource{}
|
||||
}
|
||||
|
||||
// projectResource is the resource implementation.
|
||||
type projectResource struct {
|
||||
client *ske.APIClient
|
||||
}
|
||||
|
||||
// Metadata returns the resource type name.
|
||||
func (r *projectResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
||||
resp.TypeName = req.ProviderTypeName + "_ske_project"
|
||||
}
|
||||
|
||||
// Configure adds the provider configured client to the resource.
|
||||
func (r *projectResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||
// Prevent panic if the provider has not been configured.
|
||||
if req.ProviderData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
providerData, ok := req.ProviderData.(core.ProviderData)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Expected configure type stackit.ProviderData, got %T", req.ProviderData))
|
||||
return
|
||||
}
|
||||
|
||||
var apiClient *ske.APIClient
|
||||
var err error
|
||||
if providerData.SKECustomEndpoint != "" {
|
||||
apiClient, err = ske.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithEndpoint(providerData.SKECustomEndpoint),
|
||||
)
|
||||
} else {
|
||||
apiClient, err = ske.NewAPIClient(
|
||||
config.WithCustomAuth(providerData.RoundTripper),
|
||||
config.WithRegion(providerData.Region),
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error configuring API client", fmt.Sprintf("Configuring client: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
r.client = apiClient
|
||||
tflog.Info(ctx, "SKE project client configured")
|
||||
}
|
||||
|
||||
// Schema returns the Terraform schema structure
|
||||
func (r *projectResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
||||
resp.Schema = schema.Schema{
|
||||
Attributes: map[string]schema.Attribute{
|
||||
"id": schema.StringAttribute{
|
||||
Description: "Terraform's internal resource ID. It is structured as \"`project_id`\".",
|
||||
Computed: true,
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.UseStateForUnknown(),
|
||||
},
|
||||
},
|
||||
"project_id": schema.StringAttribute{
|
||||
Description: "STACKIT Project ID in which the kubernetes project is enabled.",
|
||||
Required: true,
|
||||
Validators: []validator.String{
|
||||
validate.UUID(),
|
||||
validate.NoSeparator(),
|
||||
},
|
||||
PlanModifiers: []planmodifier.String{
|
||||
stringplanmodifier.RequiresReplace(),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates the resource and sets the initial Terraform state.
|
||||
func (r *projectResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
resp.Diagnostics.Append(req.Plan.Get(ctx, &model)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
_, err := r.client.CreateProject(ctx, projectId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating project", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
model.Id = types.StringValue(projectId)
|
||||
wr, err := ske.CreateProjectWaitHandler(ctx, r.client, projectId).SetTimeout(5 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating cluster", fmt.Sprintf("Project creation waiting: %v", err))
|
||||
return
|
||||
}
|
||||
_, ok := wr.(*ske.ProjectResponse)
|
||||
if !ok {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating cluster", fmt.Sprintf("Wait result conversion, got %+v", wr))
|
||||
return
|
||||
}
|
||||
diags := resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "SKE project created")
|
||||
}
|
||||
|
||||
// Read refreshes the Terraform state with the latest data.
|
||||
func (r *projectResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
diags := req.State.Get(ctx, &model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
_, err := r.client.GetProject(ctx, projectId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading project", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
model.Id = types.StringValue(projectId)
|
||||
model.ProjectId = types.StringValue(projectId)
|
||||
diags = resp.State.Set(ctx, model)
|
||||
resp.Diagnostics.Append(diags...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "SKE project read")
|
||||
}
|
||||
|
||||
// Update updates the resource and sets the updated Terraform state on success.
|
||||
func (r *projectResource) Update(ctx context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
// Update shouldn't be called
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating project", "Project can't be updated")
|
||||
}
|
||||
|
||||
// Delete deletes the resource and removes the Terraform state on success.
|
||||
func (r *projectResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
var model Model
|
||||
resp.Diagnostics.Append(req.State.Get(ctx, &model)...)
|
||||
if resp.Diagnostics.HasError() {
|
||||
return
|
||||
}
|
||||
projectId := model.ProjectId.ValueString()
|
||||
ctx = tflog.SetField(ctx, "project_id", projectId)
|
||||
|
||||
c := r.client
|
||||
_, err := c.DeleteProject(ctx, projectId).Execute()
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credential", fmt.Sprintf("Calling API: %v", err))
|
||||
return
|
||||
}
|
||||
_, err = ske.DeleteProjectWaitHandler(ctx, r.client, projectId).SetTimeout(10 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting credential", fmt.Sprintf("Project deletion waiting: %v", err))
|
||||
return
|
||||
}
|
||||
tflog.Info(ctx, "SKE project deleted")
|
||||
}
|
||||
|
||||
// ImportState imports a resource into the Terraform state on success.
|
||||
// The expected format of the resource import identifier is: project_id
|
||||
func (r *projectResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { // nolint:gocritic // function signature required by Terraform
|
||||
idParts := strings.Split(req.ID, core.Separator)
|
||||
if len(idParts) != 1 || idParts[0] == "" {
|
||||
core.LogAndAddError(ctx, &resp.Diagnostics,
|
||||
"Error importing project",
|
||||
fmt.Sprintf("Expected import identifier with format: [project_id] Got: %q", req.ID),
|
||||
)
|
||||
return
|
||||
}
|
||||
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("project_id"), idParts[0])...)
|
||||
tflog.Info(ctx, "SKE project state imported")
|
||||
}
|
||||
541
stackit/internal/services/ske/ske_acc_test.go
Normal file
541
stackit/internal/services/ske/ske_acc_test.go
Normal file
|
|
@ -0,0 +1,541 @@
|
|||
package ske_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform-plugin-testing/helper/acctest"
|
||||
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
|
||||
"github.com/hashicorp/terraform-plugin-testing/terraform"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/config"
|
||||
"github.com/stackitcloud/stackit-sdk-go/core/utils"
|
||||
"github.com/stackitcloud/stackit-sdk-go/services/ske"
|
||||
"github.com/stackitcloud/terraform-provider-stackit/stackit/internal/testutil"
|
||||
)
|
||||
|
||||
var projectResource = map[string]string{
|
||||
"project_id": testutil.ProjectId,
|
||||
}
|
||||
|
||||
var clusterResource = map[string]string{
|
||||
"project_id": testutil.ProjectId,
|
||||
"name": fmt.Sprintf("cl-%s", acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)),
|
||||
"name_min": fmt.Sprintf("cl-min-%s", acctest.RandStringFromCharSet(3, acctest.CharSetAlphaNum)),
|
||||
"kubernetes_version": "1.24",
|
||||
"kubernetes_version_used": "1.24.16",
|
||||
"kubernetes_version_new": "1.25",
|
||||
"kubernetes_version_used_new": "1.25.12",
|
||||
"allowPrivilegedContainers": "true",
|
||||
"nodepool_name": "np-acc-test",
|
||||
"nodepool_name_min": "np-acc-min-test",
|
||||
"nodepool_machine_type": "b1.2",
|
||||
"nodepool_os_version": "3510.2.5",
|
||||
"nodepool_os_version_min": "3510.2.5",
|
||||
"nodepool_os_name": "flatcar",
|
||||
"nodepool_minimum": "2",
|
||||
"nodepool_maximum": "3",
|
||||
"nodepool_max_surge": "1",
|
||||
"nodepool_max_unavailable": "1",
|
||||
"nodepool_volume_size": "20",
|
||||
"nodepool_volume_type": "storage_premium_perf0",
|
||||
"nodepool_zone": "eu01-3",
|
||||
"nodepool_cri": "containerd",
|
||||
"nodepool_label_key": "key",
|
||||
"nodepool_label_value": "value",
|
||||
"nodepool_taints_effect": "PreferNoSchedule",
|
||||
"nodepool_taints_key": "tkey",
|
||||
"nodepool_taints_value": "tvalue",
|
||||
"extensions_acl_enabled": "true",
|
||||
"extensions_acl_cidrs": "192.168.0.0/24",
|
||||
"extensions_argus_enabled": "false",
|
||||
"extensions_argus_instance_id": "aaaaaaaa-1111-2222-3333-444444444444", // A not-existing Argus ID let the creation time-out.
|
||||
"hibernations_start": "0 16 * * *",
|
||||
"hibernations_end": "0 18 * * *",
|
||||
"hibernations_timezone": "Europe/Berlin",
|
||||
"maintenance_enable_kubernetes_version_updates": "true",
|
||||
"maintenance_enable_machine_image_version_updates": "true",
|
||||
"maintenance_start": "01:23:45Z",
|
||||
"maintenance_end": "05:00:00+02:00",
|
||||
}
|
||||
|
||||
func getConfig(version string, apc *bool, maintenanceEnd *string) string {
|
||||
apcConfig := ""
|
||||
if apc != nil {
|
||||
if *apc {
|
||||
apcConfig = "allow_privileged_containers = true"
|
||||
} else {
|
||||
apcConfig = "allow_privileged_containers = false"
|
||||
}
|
||||
}
|
||||
maintenanceEndTF := clusterResource["maintenance_end"]
|
||||
if maintenanceEnd != nil {
|
||||
maintenanceEndTF = *maintenanceEnd
|
||||
}
|
||||
return fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
resource "stackit_ske_project" "project" {
|
||||
project_id = "%s"
|
||||
}
|
||||
|
||||
resource "stackit_ske_cluster" "cluster" {
|
||||
project_id = stackit_ske_project.project.project_id
|
||||
name = "%s"
|
||||
kubernetes_version = "%s"
|
||||
%s
|
||||
node_pools = [{
|
||||
name = "%s"
|
||||
machine_type = "%s"
|
||||
minimum = "%s"
|
||||
maximum = "%s"
|
||||
max_surge = "%s"
|
||||
max_unavailable = "%s"
|
||||
os_name = "%s"
|
||||
os_version = "%s"
|
||||
volume_size = "%s"
|
||||
volume_type = "%s"
|
||||
cri = "%s"
|
||||
availability_zones = ["%s"]
|
||||
labels = {
|
||||
%s = "%s"
|
||||
}
|
||||
taints = [{
|
||||
effect = "%s"
|
||||
key = "%s"
|
||||
value = "%s"
|
||||
}]
|
||||
}]
|
||||
extensions = {
|
||||
acl = {
|
||||
enabled = %s
|
||||
allowed_cidrs = ["%s"]
|
||||
}
|
||||
argus = {
|
||||
enabled = %s
|
||||
argus_instance_id = "%s"
|
||||
}
|
||||
}
|
||||
hibernations = [{
|
||||
start = "%s"
|
||||
end = "%s"
|
||||
timezone = "%s"
|
||||
}]
|
||||
maintenance = {
|
||||
enable_kubernetes_version_updates = %s
|
||||
enable_machine_image_version_updates = %s
|
||||
start = "%s"
|
||||
end = "%s"
|
||||
}
|
||||
}
|
||||
|
||||
resource "stackit_ske_cluster" "cluster_min" {
|
||||
project_id = stackit_ske_project.project.project_id
|
||||
name = "%s"
|
||||
kubernetes_version = "%s"
|
||||
node_pools = [{
|
||||
name = "%s"
|
||||
machine_type = "%s"
|
||||
os_version = "%s"
|
||||
minimum = "%s"
|
||||
maximum = "%s"
|
||||
availability_zones = ["%s"]
|
||||
}]
|
||||
}
|
||||
`,
|
||||
testutil.SKEProviderConfig(),
|
||||
projectResource["project_id"],
|
||||
clusterResource["name"],
|
||||
version,
|
||||
apcConfig,
|
||||
clusterResource["nodepool_name"],
|
||||
clusterResource["nodepool_machine_type"],
|
||||
clusterResource["nodepool_minimum"],
|
||||
clusterResource["nodepool_maximum"],
|
||||
clusterResource["nodepool_max_surge"],
|
||||
clusterResource["nodepool_max_unavailable"],
|
||||
clusterResource["nodepool_os_name"],
|
||||
clusterResource["nodepool_os_version"],
|
||||
clusterResource["nodepool_volume_size"],
|
||||
clusterResource["nodepool_volume_type"],
|
||||
clusterResource["nodepool_cri"],
|
||||
clusterResource["nodepool_zone"],
|
||||
clusterResource["nodepool_label_key"],
|
||||
clusterResource["nodepool_label_value"],
|
||||
clusterResource["nodepool_taints_effect"],
|
||||
clusterResource["nodepool_taints_key"],
|
||||
clusterResource["nodepool_taints_value"],
|
||||
clusterResource["extensions_acl_enabled"],
|
||||
clusterResource["extensions_acl_cidrs"],
|
||||
clusterResource["extensions_argus_enabled"],
|
||||
clusterResource["extensions_argus_instance_id"],
|
||||
clusterResource["hibernations_start"],
|
||||
clusterResource["hibernations_end"],
|
||||
clusterResource["hibernations_timezone"],
|
||||
clusterResource["maintenance_enable_kubernetes_version_updates"],
|
||||
clusterResource["maintenance_enable_machine_image_version_updates"],
|
||||
clusterResource["maintenance_start"],
|
||||
maintenanceEndTF,
|
||||
|
||||
// Minimal
|
||||
clusterResource["name_min"],
|
||||
clusterResource["kubernetes_version_new"],
|
||||
clusterResource["nodepool_name_min"],
|
||||
clusterResource["nodepool_machine_type"],
|
||||
clusterResource["nodepool_os_version_min"],
|
||||
clusterResource["nodepool_minimum"],
|
||||
clusterResource["nodepool_maximum"],
|
||||
clusterResource["nodepool_zone"],
|
||||
)
|
||||
}
|
||||
|
||||
func TestAccSKE(t *testing.T) {
|
||||
resource.ParallelTest(t, resource.TestCase{
|
||||
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
|
||||
CheckDestroy: testAccCheckSKEDestroy,
|
||||
Steps: []resource.TestStep{
|
||||
|
||||
// 1) Creation
|
||||
{
|
||||
Config: getConfig(clusterResource["kubernetes_version"], utils.Ptr(true), nil),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// project data
|
||||
resource.TestCheckResourceAttr("stackit_ske_project.project", "project_id", projectResource["project_id"]),
|
||||
// cluster data
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_ske_project.project", "project_id",
|
||||
"stackit_ske_cluster.cluster", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "name", clusterResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "kubernetes_version", clusterResource["kubernetes_version"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "kubernetes_version_used", clusterResource["kubernetes_version_used"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "allow_privileged_containers", clusterResource["allowPrivilegedContainers"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.name", clusterResource["nodepool_name"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.availability_zones.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.availability_zones.0", clusterResource["nodepool_zone"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.os_name", clusterResource["nodepool_os_name"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.os_version", clusterResource["nodepool_os_version"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.machine_type", clusterResource["nodepool_machine_type"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.minimum", clusterResource["nodepool_minimum"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.maximum", clusterResource["nodepool_maximum"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.max_surge", clusterResource["nodepool_max_surge"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.max_unavailable", clusterResource["nodepool_max_unavailable"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.volume_type", clusterResource["nodepool_volume_type"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.volume_size", clusterResource["nodepool_volume_size"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", fmt.Sprintf("node_pools.0.labels.%s", clusterResource["nodepool_label_key"]), clusterResource["nodepool_label_value"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.taints.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.taints.0.effect", clusterResource["nodepool_taints_effect"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.taints.0.key", clusterResource["nodepool_taints_key"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.taints.0.value", clusterResource["nodepool_taints_value"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.cri", clusterResource["nodepool_cri"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "extensions.acl.enabled", clusterResource["extensions_acl_enabled"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "extensions.acl.allowed_cidrs.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "extensions.acl.allowed_cidrs.0", clusterResource["extensions_acl_cidrs"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "extensions.argus.enabled", clusterResource["extensions_argus_enabled"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "extensions.argus.argus_instance_id", clusterResource["extensions_argus_instance_id"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "hibernations.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "hibernations.0.start", clusterResource["hibernations_start"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "hibernations.0.end", clusterResource["hibernations_end"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "hibernations.0.timezone", clusterResource["hibernations_timezone"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "maintenance.enable_kubernetes_version_updates", clusterResource["maintenance_enable_kubernetes_version_updates"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "maintenance.enable_machine_image_version_updates", clusterResource["maintenance_enable_machine_image_version_updates"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "maintenance.start", clusterResource["maintenance_start"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "maintenance.end", clusterResource["maintenance_end"]),
|
||||
|
||||
resource.TestCheckResourceAttrSet("stackit_ske_cluster.cluster", "kube_config"),
|
||||
|
||||
// Minimal cluster
|
||||
resource.TestCheckResourceAttrPair(
|
||||
"stackit_ske_project.project", "project_id",
|
||||
"stackit_ske_cluster.cluster_min", "project_id",
|
||||
),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster_min", "name", clusterResource["name_min"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster_min", "kubernetes_version", clusterResource["kubernetes_version_new"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster_min", "kubernetes_version_used", clusterResource["kubernetes_version_used_new"]),
|
||||
resource.TestCheckNoResourceAttr("stackit_ske_cluster.cluster_min", "allow_privileged_containers"),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster_min", "node_pools.0.name", clusterResource["nodepool_name_min"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster_min", "node_pools.0.availability_zones.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster_min", "node_pools.0.availability_zones.0", clusterResource["nodepool_zone"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_ske_cluster.cluster_min", "node_pools.0.os_name"),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster_min", "node_pools.0.os_version", clusterResource["nodepool_os_version_min"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster_min", "node_pools.0.machine_type", clusterResource["nodepool_machine_type"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster_min", "node_pools.0.minimum", clusterResource["nodepool_minimum"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster_min", "node_pools.0.maximum", clusterResource["nodepool_maximum"]),
|
||||
resource.TestCheckResourceAttrSet("stackit_ske_cluster.cluster_min", "node_pools.0.max_surge"),
|
||||
resource.TestCheckResourceAttrSet("stackit_ske_cluster.cluster_min", "node_pools.0.max_unavailable"),
|
||||
resource.TestCheckResourceAttrSet("stackit_ske_cluster.cluster_min", "node_pools.0.volume_type"),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.volume_size", clusterResource["nodepool_volume_size"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster_min", "node_pools.0.labels.%", "0"),
|
||||
resource.TestCheckNoResourceAttr("stackit_ske_cluster.cluster_min", "node_pools.0.taints"),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster_min", "node_pools.0.cri", clusterResource["nodepool_cri"]),
|
||||
resource.TestCheckNoResourceAttr("stackit_ske_cluster.cluster_min", "extensions"),
|
||||
resource.TestCheckNoResourceAttr("stackit_ske_cluster.cluster_min", "hibernations"),
|
||||
resource.TestCheckResourceAttrSet("stackit_ske_cluster.cluster_min", "maintenance.enable_kubernetes_version_updates"),
|
||||
resource.TestCheckResourceAttrSet("stackit_ske_cluster.cluster_min", "maintenance.enable_machine_image_version_updates"),
|
||||
resource.TestCheckResourceAttrSet("stackit_ske_cluster.cluster_min", "maintenance.start"),
|
||||
resource.TestCheckResourceAttrSet("stackit_ske_cluster.cluster_min", "maintenance.end"),
|
||||
resource.TestCheckResourceAttrSet("stackit_ske_cluster.cluster_min", "kube_config"),
|
||||
),
|
||||
},
|
||||
// 2) Data source
|
||||
{
|
||||
Config: fmt.Sprintf(`
|
||||
%s
|
||||
|
||||
data "stackit_ske_project" "project" {
|
||||
project_id = "%s"
|
||||
depends_on = [stackit_ske_project.project]
|
||||
}
|
||||
|
||||
data "stackit_ske_cluster" "cluster" {
|
||||
project_id = "%s"
|
||||
name = "%s"
|
||||
depends_on = [stackit_ske_cluster.cluster]
|
||||
}
|
||||
|
||||
data "stackit_ske_cluster" "cluster_min" {
|
||||
project_id = "%s"
|
||||
name = "%s"
|
||||
depends_on = [stackit_ske_cluster.cluster_min]
|
||||
}
|
||||
|
||||
`,
|
||||
getConfig(clusterResource["kubernetes_version"], utils.Ptr(true), nil),
|
||||
projectResource["project_id"],
|
||||
clusterResource["project_id"],
|
||||
clusterResource["name"],
|
||||
clusterResource["project_id"],
|
||||
clusterResource["name_min"],
|
||||
),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// project data
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_project.project", "id", projectResource["project_id"]),
|
||||
|
||||
// cluster data
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "id", fmt.Sprintf("%s,%s",
|
||||
clusterResource["project_id"],
|
||||
clusterResource["name"],
|
||||
)),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "project_id", clusterResource["project_id"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "name", clusterResource["name"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "kubernetes_version", clusterResource["kubernetes_version"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "kubernetes_version_used", clusterResource["kubernetes_version_used"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "allow_privileged_containers", clusterResource["allowPrivilegedContainers"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "node_pools.0.name", clusterResource["nodepool_name"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "node_pools.0.availability_zones.#", "1"),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "node_pools.0.availability_zones.0", clusterResource["nodepool_zone"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "node_pools.0.os_name", clusterResource["nodepool_os_name"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "node_pools.0.os_version", clusterResource["nodepool_os_version"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "node_pools.0.machine_type", clusterResource["nodepool_machine_type"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "node_pools.0.minimum", clusterResource["nodepool_minimum"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "node_pools.0.maximum", clusterResource["nodepool_maximum"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "node_pools.0.max_surge", clusterResource["nodepool_max_surge"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "node_pools.0.max_unavailable", clusterResource["nodepool_max_unavailable"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "node_pools.0.volume_type", clusterResource["nodepool_volume_type"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "node_pools.0.volume_size", clusterResource["nodepool_volume_size"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", fmt.Sprintf("node_pools.0.labels.%s", clusterResource["nodepool_label_key"]), clusterResource["nodepool_label_value"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "node_pools.0.taints.#", "1"),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "node_pools.0.taints.0.effect", clusterResource["nodepool_taints_effect"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "node_pools.0.taints.0.key", clusterResource["nodepool_taints_key"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "node_pools.0.taints.0.value", clusterResource["nodepool_taints_value"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "node_pools.0.cri", clusterResource["nodepool_cri"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "extensions.acl.enabled", clusterResource["extensions_acl_enabled"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "extensions.acl.allowed_cidrs.#", "1"),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "extensions.acl.allowed_cidrs.0", clusterResource["extensions_acl_cidrs"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "hibernations.#", "1"),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "hibernations.0.start", clusterResource["hibernations_start"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "hibernations.0.end", clusterResource["hibernations_end"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "hibernations.0.timezone", clusterResource["hibernations_timezone"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "hibernations.0.end", clusterResource["hibernations_end"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "maintenance.enable_kubernetes_version_updates", clusterResource["maintenance_enable_kubernetes_version_updates"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "maintenance.enable_machine_image_version_updates", clusterResource["maintenance_enable_machine_image_version_updates"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "maintenance.start", clusterResource["maintenance_start"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "maintenance.end", clusterResource["maintenance_end"]),
|
||||
|
||||
resource.TestCheckResourceAttrSet("data.stackit_ske_cluster.cluster", "kube_config"),
|
||||
|
||||
// Minimal cluster
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster_min", "name", clusterResource["name_min"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster_min", "kubernetes_version", clusterResource["kubernetes_version_new"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster_min", "kubernetes_version_used", clusterResource["kubernetes_version_used_new"]),
|
||||
resource.TestCheckNoResourceAttr("data.stackit_ske_cluster.cluster_min", "allow_privileged_containers"),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster_min", "node_pools.0.name", clusterResource["nodepool_name_min"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster_min", "node_pools.0.availability_zones.#", "1"),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster_min", "node_pools.0.availability_zones.0", clusterResource["nodepool_zone"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_ske_cluster.cluster_min", "node_pools.0.os_name"),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster_min", "node_pools.0.os_version", clusterResource["nodepool_os_version_min"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster_min", "node_pools.0.machine_type", clusterResource["nodepool_machine_type"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster_min", "node_pools.0.minimum", clusterResource["nodepool_minimum"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster_min", "node_pools.0.maximum", clusterResource["nodepool_maximum"]),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_ske_cluster.cluster_min", "node_pools.0.max_surge"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_ske_cluster.cluster_min", "node_pools.0.max_unavailable"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_ske_cluster.cluster_min", "node_pools.0.volume_type"),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster", "node_pools.0.volume_size", clusterResource["nodepool_volume_size"]),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster_min", "node_pools.0.labels.%", "0"),
|
||||
resource.TestCheckNoResourceAttr("data.stackit_ske_cluster.cluster_min", "node_pools.0.taints"),
|
||||
resource.TestCheckResourceAttr("data.stackit_ske_cluster.cluster_min", "node_pools.0.cri", clusterResource["nodepool_cri"]),
|
||||
resource.TestCheckNoResourceAttr("data.stackit_ske_cluster.cluster_min", "extensions"),
|
||||
resource.TestCheckNoResourceAttr("data.stackit_ske_cluster.cluster_min", "hibernations"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_ske_cluster.cluster_min", "maintenance.enable_kubernetes_version_updates"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_ske_cluster.cluster_min", "maintenance.enable_machine_image_version_updates"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_ske_cluster.cluster_min", "maintenance.start"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_ske_cluster.cluster_min", "maintenance.end"),
|
||||
resource.TestCheckResourceAttrSet("data.stackit_ske_cluster.cluster_min", "kube_config"),
|
||||
),
|
||||
},
|
||||
// 3) Import project
|
||||
{
|
||||
ResourceName: "stackit_ske_project.project",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
_, ok := s.RootModule().Resources["stackit_ske_project.project"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_ske_project.project")
|
||||
}
|
||||
return testutil.ProjectId, nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
},
|
||||
// 4) Import cluster
|
||||
{
|
||||
ResourceName: "stackit_ske_cluster.cluster",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_ske_cluster.cluster"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_ske_cluster.cluster")
|
||||
}
|
||||
_, ok = r.Primary.Attributes["project_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute project_id")
|
||||
}
|
||||
name, ok := r.Primary.Attributes["name"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute name")
|
||||
}
|
||||
return fmt.Sprintf("%s,%s", testutil.ProjectId, name), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
// The fields are not provided in the SKE API when disabled, although set actively.
|
||||
ImportStateVerifyIgnore: []string{"kube_config", "extensions.argus.%", "extensions.argus.argus_instance_id", "extensions.argus.enabled", "extensions.acl.enabled", "extensions.acl.allowed_cidrs", "extensions.acl.allowed_cidrs.#", "extensions.acl.%"},
|
||||
},
|
||||
// ) Import minimal cluster
|
||||
{
|
||||
ResourceName: "stackit_ske_cluster.cluster_min",
|
||||
ImportStateIdFunc: func(s *terraform.State) (string, error) {
|
||||
r, ok := s.RootModule().Resources["stackit_ske_cluster.cluster_min"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find resource stackit_ske_cluster.cluster_min")
|
||||
}
|
||||
_, ok = r.Primary.Attributes["project_id"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute project_id")
|
||||
}
|
||||
name, ok := r.Primary.Attributes["name"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("couldn't find attribute name")
|
||||
}
|
||||
return fmt.Sprintf("%s,%s", testutil.ProjectId, name), nil
|
||||
},
|
||||
ImportState: true,
|
||||
ImportStateVerify: true,
|
||||
ImportStateVerifyIgnore: []string{"kube_config"},
|
||||
},
|
||||
// 6) Update kubernetes version and maximum
|
||||
{
|
||||
Config: getConfig("1.25.12", nil, utils.Ptr("03:03:03+00:00")),
|
||||
Check: resource.ComposeAggregateTestCheckFunc(
|
||||
// cluster data
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "project_id", clusterResource["project_id"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "name", clusterResource["name"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "kubernetes_version", "1.25"),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "kubernetes_version_used", "1.25.12"),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.name", clusterResource["nodepool_name"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.availability_zones.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.availability_zones.0", clusterResource["nodepool_zone"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.os_name", clusterResource["nodepool_os_name"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.os_version", clusterResource["nodepool_os_version"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.machine_type", clusterResource["nodepool_machine_type"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.minimum", clusterResource["nodepool_minimum"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.maximum", clusterResource["nodepool_maximum"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.max_surge", clusterResource["nodepool_max_surge"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.max_unavailable", clusterResource["nodepool_max_unavailable"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.volume_type", clusterResource["nodepool_volume_type"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.volume_size", clusterResource["nodepool_volume_size"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", fmt.Sprintf("node_pools.0.labels.%s", clusterResource["nodepool_label_key"]), clusterResource["nodepool_label_value"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.taints.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.taints.0.effect", clusterResource["nodepool_taints_effect"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.taints.0.key", clusterResource["nodepool_taints_key"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.taints.0.value", clusterResource["nodepool_taints_value"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "node_pools.0.cri", clusterResource["nodepool_cri"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "extensions.acl.enabled", clusterResource["extensions_acl_enabled"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "extensions.acl.allowed_cidrs.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "extensions.acl.allowed_cidrs.0", clusterResource["extensions_acl_cidrs"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "extensions.argus.enabled", clusterResource["extensions_argus_enabled"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "extensions.argus.argus_instance_id", clusterResource["extensions_argus_instance_id"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "hibernations.#", "1"),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "hibernations.0.start", clusterResource["hibernations_start"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "hibernations.0.end", clusterResource["hibernations_end"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "hibernations.0.timezone", clusterResource["hibernations_timezone"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "maintenance.enable_kubernetes_version_updates", clusterResource["maintenance_enable_kubernetes_version_updates"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "maintenance.enable_machine_image_version_updates", clusterResource["maintenance_enable_machine_image_version_updates"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "maintenance.start", clusterResource["maintenance_start"]),
|
||||
resource.TestCheckResourceAttr("stackit_ske_cluster.cluster", "maintenance.end", "03:03:03+00:00"),
|
||||
|
||||
resource.TestCheckResourceAttrSet("stackit_ske_cluster.cluster", "kube_config"),
|
||||
),
|
||||
},
|
||||
// Deletion is done by the framework implicitly
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func testAccCheckSKEDestroy(s *terraform.State) error {
|
||||
ctx := context.Background()
|
||||
var client *ske.APIClient
|
||||
var err error
|
||||
if testutil.SKECustomEndpoint == "" {
|
||||
client, err = ske.NewAPIClient()
|
||||
} else {
|
||||
client, err = ske.NewAPIClient(
|
||||
config.WithEndpoint(testutil.SKECustomEndpoint),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating client: %w", err)
|
||||
}
|
||||
|
||||
projectsToDestroy := []string{}
|
||||
for _, rs := range s.RootModule().Resources {
|
||||
if rs.Type != "stackit_ske_project" {
|
||||
continue
|
||||
}
|
||||
projectsToDestroy = append(projectsToDestroy, rs.Primary.ID)
|
||||
}
|
||||
for _, projectId := range projectsToDestroy {
|
||||
_, err := client.GetProject(ctx, projectId).Execute()
|
||||
if err != nil {
|
||||
oapiErr, ok := err.(*ske.GenericOpenAPIError) //nolint:errorlint //complaining that error.As should be used to catch wrapped errors, but this error should not be wrapped
|
||||
if !ok {
|
||||
return fmt.Errorf("could not convert error to GenericOpenApiError in acc test destruction, %w", err)
|
||||
}
|
||||
if oapiErr.StatusCode() == http.StatusNotFound || oapiErr.StatusCode() == http.StatusForbidden {
|
||||
// Already gone
|
||||
continue
|
||||
}
|
||||
return fmt.Errorf("getting project: %w", err)
|
||||
}
|
||||
|
||||
_, err = client.DeleteProjectExecute(ctx, projectId)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying project %s during CheckDestroy: %w", projectId, err)
|
||||
}
|
||||
_, err = ske.DeleteProjectWaitHandler(ctx, client, projectId).SetTimeout(15 * time.Minute).WaitWithContext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("destroying project %s during CheckDestroy: waiting for deletion %w", projectId, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue