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,178 @@
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/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/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 {
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
}
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 {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error())
return
}
tflog.Info(ctx, "RabbitMQ zone client configured")
r.client = apiClient
}
// 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.",
"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", err.Error())
return
}
// Map response body to schema and populate Computed attribute values
err = mapFields(recordSetResp, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error())
return
}
// Set refreshed state
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
tflog.Info(ctx, "RabbitMQ credentials read")
}

View file

@ -0,0 +1,371 @@
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/conversion"
"github.com/stackitcloud/terraform-provider-stackit/stackit/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/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 = &rabbitMQCredentialsResource{}
_ resource.ResourceWithConfigure = &rabbitMQCredentialsResource{}
_ resource.ResourceWithImportState = &rabbitMQCredentialsResource{}
)
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 &rabbitMQCredentialsResource{}
}
// credentialsResource is the resource implementation.
type rabbitMQCredentialsResource struct {
client *rabbitmq.APIClient
}
// Metadata returns the resource type name.
func (r *rabbitMQCredentialsResource) 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 *rabbitMQCredentialsResource) 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 {
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 *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 {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error())
return
}
tflog.Info(ctx, "RabbitMQ zone client configured")
r.client = apiClient
}
// Schema defines the schema for the resource.
func (r *rabbitMQCredentialsResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
descriptions := map[string]string{
"main": "RabbitMQ credentials resource schema.",
"id": "Terraform's internal resource identifier.",
"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 *rabbitMQCredentialsResource) 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", got))
return
}
// Map response body to schema and populate Computed attribute values
err = mapFields(got, &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, "RabbitMQ credentials created")
}
// Read refreshes the Terraform state with the latest data.
func (r *rabbitMQCredentialsResource) 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", err.Error())
return
}
// Map response body to schema and populate Computed attribute values
err = mapFields(recordSetResp, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error())
return
}
// Set refreshed state
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
tflog.Info(ctx, "RabbitMQ credentials read")
}
// Update updates the resource and sets the updated Terraform state on success.
func (r *rabbitMQCredentialsResource) 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 *rabbitMQCredentialsResource) 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", err.Error())
}
_, 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 *rabbitMQCredentialsResource) 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,
"Unexpected Import Identifier",
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
}

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

View 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/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/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 {
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
}
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 {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error())
return
}
tflog.Info(ctx, "RabbitMQ zone client configured")
r.client = apiClient
}
// 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.",
"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,
},
"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 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()
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, "Unable to read instance", err.Error())
return
}
err = mapFields(instanceResp, &state)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Mapping fields", err.Error())
return
}
// Set refreshed state
diags = resp.State.Set(ctx, &state)
resp.Diagnostics.Append(diags...)
tflog.Info(ctx, "RabbitMQ instance read")
}

View file

@ -0,0 +1,637 @@
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/diag"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/objectplanmodifier"
"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/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/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"`
OrganizationGuid types.String `tfsdk:"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 {
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 *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 {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error())
return
}
tflog.Info(ctx, "rabbitmq zone client configured")
r.client = apiClient
}
// 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.",
"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,
Validators: []validator.String{
stringvalidator.LengthAtLeast(1),
},
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
},
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.Object{
objectplanmodifier.UseStateForUnknown(),
},
},
"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,
},
"organization_guid": 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
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)
r.loadPlanId(ctx, &resp.Diagnostics, &model)
if diags.HasError() {
core.LogAndAddError(ctx, &diags, "Failed to load RabbitMQ service plan", "plan "+model.PlanName.ValueString())
return
}
var parameters = &parametersModel{}
if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) {
diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{})
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
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", got))
return
}
// Map response body to schema and populate Computed attribute values
err = mapFields(got, &model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error())
return
}
// Set state to fully populated data
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
tflog.Info(ctx, "rabbitmq instance created")
}
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
}
// 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 state Model
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
projectId := state.ProjectId.ValueString()
instanceId := state.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 instances", err.Error())
return
}
// Map response body to schema and populate Computed attribute values
err = mapFields(instanceResp, &state)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error mapping fields", err.Error())
return
}
// Set refreshed state
diags = resp.State.Set(ctx, state)
resp.Diagnostics.Append(diags...)
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)
r.loadPlanId(ctx, &resp.Diagnostics, &model)
if diags.HasError() {
core.LogAndAddError(ctx, &diags, "Failed to load RabbitMQ service plan", "plan "+model.PlanName.ValueString())
return
}
var parameters = &parametersModel{}
if !(model.Parameters.IsNull() || model.Parameters.IsUnknown()) {
diags = model.Parameters.As(ctx, parameters, basetypes.ObjectAsOptions{})
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
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("Could not create 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 := 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", got))
return
}
// Map response body to schema and populate Computed attribute values
err = mapFields(got, &model)
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...)
tflog.Info(ctx, "rabbitmq instance updated")
}
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
}
// 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
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", err.Error())
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] == "" {
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])...)
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.OrganizationGuid = types.StringPointerValue(instance.OrganizationGuid)
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, diags *diag.Diagnostics, model *Model) {
projectId := model.ProjectId.ValueString()
res, err := r.client.GetOfferings(ctx, projectId).Execute()
if err != nil {
diags.AddError("Failed to list RabbitMQ offerings", err.Error())
return
}
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
}
availablePlanNames = fmt.Sprintf("%s\n- %s", availablePlanNames, *plan.Name)
}
}
if !isValidVersion {
diags.AddError("Invalid version", fmt.Sprintf("Couldn't find version '%s', available versions are:%s", version, availableVersions))
return
}
diags.AddError("Invalid plan_name", fmt.Sprintf("Couldn't find plan_name '%s' for version %s, available names are:%s", planName, version, availablePlanNames))
}

View 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(),
OrganizationGuid: 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"),
OrganizationGuid: 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"),
OrganizationGuid: 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{},
&parametersModel{},
&rabbitmq.CreateInstancePayload{
Parameters: &rabbitmq.InstanceParameters{},
},
true,
},
{
"simple_values",
&Model{
Name: types.StringValue("name"),
PlanId: types.StringValue("plan"),
},
&parametersModel{
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(""),
},
&parametersModel{
SgwAcl: types.StringNull(),
},
&rabbitmq.CreateInstancePayload{
InstanceName: utils.Ptr(""),
Parameters: &rabbitmq.InstanceParameters{
SgwAcl: nil,
},
PlanId: utils.Ptr(""),
},
true,
},
{
"nil_model",
nil,
&parametersModel{},
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{},
&parametersModel{},
&rabbitmq.UpdateInstancePayload{
Parameters: &rabbitmq.InstanceParameters{},
},
true,
},
{
"simple_values",
&Model{
PlanId: types.StringValue("plan"),
},
&parametersModel{
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(""),
},
&parametersModel{
SgwAcl: types.StringNull(),
},
&rabbitmq.UpdateInstancePayload{
Parameters: &rabbitmq.InstanceParameters{
SgwAcl: nil,
},
PlanId: utils.Ptr(""),
},
true,
},
{
"nil_model",
nil,
&parametersModel{},
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)
}
}
})
}
}

View file

@ -0,0 +1,286 @@
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/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/testutil"
)
// Instance resource data
var instanceResource = map[string]string{
"project_id": testutil.ProjectId,
"name": testutil.ResourceNameWithDateTime("rabbitmq"),
"plan_id": "7e1f8394-5dd5-40b1-8608-16b4344eb51b",
"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_id = "%s"
parameters = {
%s
metrics_frequency = "%s"
}
}
%s
`,
testutil.RabbitMQProviderConfig(),
instanceResource["project_id"],
instanceResource["name"],
instanceResource["plan_id"],
aclsLine,
instanceResource["metrics_frequency"],
resourceConfigCredentials(),
)
}
func resourceConfigWithUpdate() string {
return fmt.Sprintf(`
%s
resource "stackit_rabbitmq_instance" "instance" {
project_id = "%s"
name = "%s"
plan_id = "%s"
parameters = {
sgw_acl = "%s"
}
}
%s
`,
testutil.RabbitMQProviderConfig(),
instanceResource["project_id"],
instanceResource["name"],
instanceResource["plan_id"],
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", "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", "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
}