Initial commit

This commit is contained in:
vicentepinto98 2023-09-07 11:34:45 +01:00
commit e4c8a6fbf4
186 changed files with 29501 additions and 0 deletions

View 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/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/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
}

View file

@ -0,0 +1,236 @@
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/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/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(_ 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 {
resp.Diagnostics.AddError("Unexpected Data Source Configure Type", fmt.Sprintf("Expected 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 {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error())
return
}
r.client = apiClient
}
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.",
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 {
resp.Diagnostics.AddError("Error creating credential", fmt.Sprintf("Calling API: %v", err))
return
}
err = mapFields(got.Credentials, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error())
return
}
diags = resp.State.Set(ctx, &model)
resp.Diagnostics.Append(diags...)
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 {
resp.Diagnostics.AddError("Error reading credential", fmt.Sprintf("Project id = %s, instance id = %s, username = %s: %v", projectId, instanceId, userName, err))
return
}
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
tflog.Info(ctx, "ARGUS credential read")
}
func (r *credentialResource) Update(_ context.Context, _ resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
// Update shouldn't be called
resp.Diagnostics.AddError("Error updating credentials", "credentials 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 {
resp.Diagnostics.AddError("Error deleting credential", "project id = "+projectId+", instance id = "+instanceId+", username = "+userName+", "+err.Error())
return
}
tflog.Info(ctx, "ARGUS credential deleted")
}

View 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)
}
}
})
}
}

View 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/stackitcloud/stackit-sdk-go/core/config"
"github.com/stackitcloud/stackit-sdk-go/services/argus"
"github.com/stackitcloud/terraform-provider-stackit/stackit/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/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(_ 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 {
resp.Diagnostics.AddError("Unexpected Data Source Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", 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 {
resp.Diagnostics.AddError(
"Could not Configure API Client",
err.Error(),
)
return
}
d.client = apiClient
}
// 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.",
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 state Model
diags := req.Config.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
projectId := state.ProjectId.ValueString()
instanceId := state.InstanceId.ValueString()
instanceResponse, err := d.client.GetInstance(ctx, instanceId, projectId).Execute()
if err != nil {
core.LogAndAddError(ctx, &diags, "Unable to read instance", err.Error())
return
}
err = mapFields(ctx, instanceResponse, &state)
if err != nil {
core.LogAndAddError(ctx, &diags, "Mapping fields", err.Error())
return
}
diags = resp.State.Set(ctx, state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
}

View file

@ -0,0 +1,558 @@
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/diag"
"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/stackitcloud/stackit-sdk-go/core/config"
"github.com/stackitcloud/stackit-sdk-go/services/argus"
"github.com/stackitcloud/terraform-provider-stackit/stackit/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/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(_ 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 {
resp.Diagnostics.AddError("Unexpected Resource Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", 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 {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error())
return
}
r.client = apiClient
}
// 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.",
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()
r.loadPlanId(ctx, &resp.Diagnostics, &model)
if diags.HasError() {
core.LogAndAddError(ctx, &diags, "Failed to load argus service plan", "plan "+model.PlanName.ValueString())
return
}
// Generate API request body from model
payload, err := toCreatePayload(&model)
if err != nil {
resp.Diagnostics.AddError("Error creating instance", fmt.Sprintf("Creating API payload: %v", err))
return
}
createResp, err := r.client.CreateInstance(ctx, projectId).CreateInstancePayload(*payload).Execute()
if err != nil {
resp.Diagnostics.AddError("Error creating instance", fmt.Sprintf("Calling API: %v", err))
return
}
instanceId := createResp.InstanceId
if instanceId == nil || *instanceId == "" {
resp.Diagnostics.AddError("Error creating instance", "API didn't return an instance id")
return
}
wr, err := argus.CreateInstanceWaitHandler(ctx, r.client, *instanceId, projectId).SetTimeout(20 * time.Minute).WaitWithContext(ctx)
if err != nil {
resp.Diagnostics.AddError("Error creating instance", fmt.Sprintf("Instance creation waiting: %v", err))
return
}
got, ok := wr.(*argus.InstanceResponse)
if !ok {
resp.Diagnostics.AddError("Error creating instance", fmt.Sprintf("Wait result conversion, got %+v", got))
return
}
// Map response body to schema and populate Computed attribute values
err = mapFields(ctx, got, &model)
if err != nil {
resp.Diagnostics.AddError("Error mapping fields", fmt.Sprintf("Project id %s, instance id %s: %v", projectId, *instanceId, err))
return
}
// Set state to fully populated data
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
}
// 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()
instanceResp, err := r.client.GetInstance(ctx, instanceId, projectId).Execute()
if err != nil {
resp.Diagnostics.AddError("Error reading instance", fmt.Sprintf("Project id = %s, instance id = %s: %v", projectId, instanceId, err))
return
}
// Map response body to schema and populate Computed attribute values
err = mapFields(ctx, instanceResp, &model)
if err != nil {
resp.Diagnostics.AddError("Error mapping fields", fmt.Sprintf("Project id %s, instance id %s: %v", projectId, instanceId, err))
return
}
// Set refreshed model
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
}
// 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()
r.loadPlanId(ctx, &resp.Diagnostics, &model)
if diags.HasError() {
core.LogAndAddError(ctx, &diags, "Failed to load argus service plan", "plan "+model.PlanName.ValueString())
return
}
// Generate API request body from model
payload, err := toUpdatePayload(&model)
if err != nil {
resp.Diagnostics.AddError("Error updating instance", fmt.Sprintf("Could not create API payload: %v", err))
return
}
// Update existing instance
_, err = r.client.UpdateInstance(ctx, instanceId, projectId).UpdateInstancePayload(*payload).Execute()
if err != nil {
resp.Diagnostics.AddError("Error updating instance", "project id = "+projectId+", instance Id = "+instanceId+", "+err.Error())
return
}
wr, err := argus.UpdateInstanceWaitHandler(ctx, r.client, instanceId, projectId).SetTimeout(20 * time.Minute).WaitWithContext(ctx)
if err != nil {
resp.Diagnostics.AddError("Error updating instance", fmt.Sprintf("Instance update waiting: %v", err))
return
}
got, ok := wr.(*argus.InstanceResponse)
if !ok {
resp.Diagnostics.AddError("Error updating instance", fmt.Sprintf("Wait result conversion, got %+v", got))
return
}
err = mapFields(ctx, got, &model)
if err != nil {
resp.Diagnostics.AddError("Error mapping fields in update", "project id = "+projectId+", instance Id = "+instanceId+", "+err.Error())
return
}
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
}
// 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 {
resp.Diagnostics.AddError("Error deleting instance", "project id = "+projectId+", instance Id = "+instanceId+", "+err.Error())
return
}
_, err = argus.DeleteInstanceWaitHandler(ctx, r.client, instanceId, projectId).SetTimeout(10 * time.Minute).WaitWithContext(ctx)
if err != nil {
resp.Diagnostics.AddError("Error deleting instance", fmt.Sprintf("Instance deletion waiting: %v", err))
return
}
}
// 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] == "" {
resp.Diagnostics.AddError(
"Unexpected Import Identifier",
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])...)
}
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, diags *diag.Diagnostics, model *Model) {
projectId := model.ProjectId.ValueString()
res, err := r.client.GetPlans(ctx, projectId).Execute()
if err != nil {
diags.AddError("Failed to list argus plans", err.Error())
return
}
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() == "" {
diags.AddError("Invalid plan_name", fmt.Sprintf("Couldn't find plan_name '%s', available names are:%s", planName, avl))
return
}
}

View 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
}

View file

@ -0,0 +1,221 @@
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/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/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(_ 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 {
resp.Diagnostics.AddError("Unexpected Data Source Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", 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 {
resp.Diagnostics.AddError(
"Could not Configure API Client",
err.Error(),
)
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.",
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, &diags, "Unable to read scrape config", err.Error())
return
}
err = mapFields(scResp.Data, &model)
if err != nil {
core.LogAndAddError(ctx, &diags, "Mapping fields", err.Error())
return
}
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
}

View file

@ -0,0 +1,676 @@
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/conversion"
"github.com/stackitcloud/terraform-provider-stackit/stackit/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/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(_ 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 {
resp.Diagnostics.AddError("Unexpected Resource Configure Type", fmt.Sprintf("Expected stackit.ProviderData, got %T. Please report this issue to the provider developers.", 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 {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error())
return
}
r.client = apiClient
}
// 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.",
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 {
resp.Diagnostics.AddError("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 {
resp.Diagnostics.AddError("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 {
resp.Diagnostics.AddError("Error creating scrape config", fmt.Sprintf("ScrapeConfig creation waiting: %v", err))
return
}
got, err := r.client.GetScrapeConfig(ctx, instanceId, scName, projectId).Execute()
if err != nil {
resp.Diagnostics.AddError("Error creating scrape config", fmt.Sprintf("ScrapeConfig creation waiting: %v", err))
return
}
err = mapFields(got.Data, &model)
if err != nil {
resp.Diagnostics.AddError("Error mapping fields", fmt.Sprintf("Project id %s, ScrapeConfig id %s: %v", projectId, scName, err))
return
}
// Set state to fully populated data
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
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 {
resp.Diagnostics.AddError("Error reading scrape config", fmt.Sprintf("Project id = %s, instance id = %s, scrape config name = %s: %v", projectId, instanceId, scName, err))
return
}
// Map response body to schema and populate Computed attribute values
err = mapFields(scResp.Data, &model)
if err != nil {
resp.Diagnostics.AddError("Error mapping fields", fmt.Sprintf("Project id = %s, instance id = %s, sc name = %s: %v", projectId, instanceId, scName, err))
return
}
// Set refreshed model
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
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 {
resp.Diagnostics.AddError("Error updating scrape config", fmt.Sprintf("Could not create API payload: %v", err))
return
}
_, err = r.client.UpdateScrapeConfig(ctx, instanceId, scName, projectId).UpdateScrapeConfigPayload(*payload).Execute()
if err != nil {
resp.Diagnostics.AddError("Error updating scrape config", fmt.Sprintf("Project id = %s, instance id = %s, scrape config name = %s: %v", projectId, instanceId, scName, 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 {
resp.Diagnostics.AddError("Error reading updated data", fmt.Sprintf("Project id %s, instance id %s, jo name %s: %v", projectId, instanceId, scName, err))
return
}
err = mapFields(scResp.Data, &model)
if err != nil {
resp.Diagnostics.AddError("Error mapping fields in update", "project id = "+projectId+", instance id = "+instanceId+", scrape config name = "+scName+", "+err.Error())
return
}
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
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 {
resp.Diagnostics.AddError("Error deleting scrape config", "project id = "+projectId+", instance id = "+instanceId+", scrape config name = "+scName+", "+err.Error())
return
}
_, err = argus.DeleteScrapeConfigWaitHandler(ctx, r.client, instanceId, scName, projectId).SetTimeout(1 * time.Minute).WaitWithContext(ctx)
if err != nil {
resp.Diagnostics.AddError("Error deleting scrape config", fmt.Sprintf("ScrapeConfig 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] == "" {
resp.Diagnostics.AddError(
"Unexpected Import Identifier",
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)
}
}

View 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)
}
}
})
}
}