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,216 @@
package project
import (
"context"
"fmt"
"regexp"
"github.com/hashicorp/terraform-plugin-framework-validators/mapvalidator"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
"github.com/stackitcloud/terraform-provider-stackit/stackit/conversion"
"github.com/stackitcloud/terraform-provider-stackit/stackit/core"
"github.com/stackitcloud/terraform-provider-stackit/stackit/validate"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/stackit-sdk-go/core/config"
"github.com/stackitcloud/stackit-sdk-go/services/resourcemanager"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ datasource.DataSource = &projectDataSource{}
)
type ProjectData struct {
Id types.String `tfsdk:"id"` // needed by TF
ContainerId types.String `tfsdk:"container_id"`
ContainerParentId types.String `tfsdk:"parent_container_id"`
Name types.String `tfsdk:"name"`
Labels types.Map `tfsdk:"labels"`
}
// NewProjectDataSource is a helper function to simplify the provider implementation.
func NewProjectDataSource() datasource.DataSource {
return &projectDataSource{}
}
// projectDataSource is the data source implementation.
type projectDataSource struct {
client *resourcemanager.APIClient
}
// Metadata returns the data source type name.
func (d *projectDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_resourcemanager_project"
}
func (d *projectDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
// Prevent panic if the provider has not been configured.
if req.ProviderData == nil {
return
}
var apiClient *resourcemanager.APIClient
var err error
providerData, ok := req.ProviderData.(core.ProviderData)
if !ok {
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.ResourceManagerCustomEndpoint != "" {
apiClient, err = resourcemanager.NewAPIClient(
config.WithCustomAuth(providerData.RoundTripper),
config.WithServiceAccountEmail(providerData.ServiceAccountEmail),
config.WithEndpoint(providerData.ResourceManagerCustomEndpoint),
)
} else {
apiClient, err = resourcemanager.NewAPIClient(
config.WithCustomAuth(providerData.RoundTripper),
config.WithServiceAccountEmail(providerData.ServiceAccountEmail),
config.WithRegion(providerData.Region),
)
}
if err != nil {
resp.Diagnostics.AddError(
"Could not Configure API Client",
err.Error(),
)
return
}
tflog.Info(ctx, "Resource Manager project client configured")
d.client = apiClient
}
// Schema defines the schema for the data source.
func (d *projectDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
descriptions := map[string]string{
"main": "Resource Manager project data source schema.",
"id": "Terraform's internal unique identifier of the project, equivalent to the container ID",
"container_id": "Project container ID.",
"parent_container_id": "Parent container ID",
"name": "Project name.",
"labels": `Labels are key-value string pairs which can be attached to a resource container. A label key must match the regex [A-ZÄÜÖa-zäüöß0-9_-]{1,64}. A label value must match the regex ^$|[A-ZÄÜÖa-zäüöß0-9_-]{1,64}`,
}
resp.Schema = schema.Schema{
Description: descriptions["main"],
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: descriptions["id"],
Computed: true,
},
"container_id": schema.StringAttribute{
Description: descriptions["container_id"],
Required: true,
Validators: []validator.String{
validate.NoSeparator(),
},
},
"parent_container_id": schema.StringAttribute{
Description: descriptions["parent_container_id"],
Computed: true,
Validators: []validator.String{
validate.NoSeparator(),
},
},
"name": schema.StringAttribute{
Description: descriptions["name"],
Computed: true,
Validators: []validator.String{
stringvalidator.LengthAtLeast(1),
stringvalidator.LengthAtMost(63),
},
},
"labels": schema.MapAttribute{
Description: descriptions["labels"],
ElementType: types.StringType,
Computed: true,
Validators: []validator.Map{
mapvalidator.KeysAre(
stringvalidator.RegexMatches(
regexp.MustCompile(`[A-ZÄÜÖa-zäüöß0-9_-]{1,64}`),
"must match expression"),
),
mapvalidator.ValueStringsAre(
stringvalidator.RegexMatches(
regexp.MustCompile(`[A-ZÄÜÖa-zäüöß0-9_-]{1,64}`),
"must match expression"),
),
},
},
},
}
}
// Read refreshes the Terraform state with the latest data.
func (d *projectDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var state ProjectData
diags := req.Config.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
containerId := state.ContainerId.ValueString()
ctx = tflog.SetField(ctx, "project_id", containerId)
projectResp, err := d.client.GetProject(ctx, containerId).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Unable to Read Project", err.Error())
return
}
err = mapDataFields(ctx, projectResp, &state)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Mapping fields", err.Error())
return
}
diags = resp.State.Set(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Resource Manager project read")
}
func mapDataFields(ctx context.Context, projectResp *resourcemanager.ProjectResponseWithParents, model *ProjectData) (err error) {
if projectResp == nil {
return fmt.Errorf("response input is nil")
}
if model == nil {
return fmt.Errorf("model input is nil")
}
var containerId string
if model.ContainerId.ValueString() != "" {
containerId = model.ContainerId.ValueString()
} else if projectResp.ContainerId != nil {
containerId = *projectResp.ContainerId
} else {
return fmt.Errorf("container id not present")
}
var labels basetypes.MapValue
if projectResp.Labels != nil {
labels, err = conversion.ToTerraformStringMap(ctx, *projectResp.Labels)
if err != nil {
return fmt.Errorf("converting to StringValue map: %w", err)
}
} else {
labels = types.MapNull(types.StringType)
}
model.Id = types.StringValue(containerId)
model.ContainerId = types.StringValue(containerId)
model.ContainerParentId = types.StringPointerValue(projectResp.Parent.ContainerId)
model.Name = types.StringPointerValue(projectResp.Name)
model.Labels = labels
return nil
}

View file

@ -0,0 +1,434 @@
package project
import (
"context"
"fmt"
"regexp"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-framework-validators/mapvalidator"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
"github.com/stackitcloud/terraform-provider-stackit/stackit/conversion"
"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/hashicorp/terraform-plugin-log/tflog"
"github.com/stackitcloud/stackit-sdk-go/core/config"
"github.com/stackitcloud/stackit-sdk-go/services/resourcemanager"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = &projectResource{}
_ resource.ResourceWithConfigure = &projectResource{}
_ resource.ResourceWithImportState = &projectResource{}
)
const (
projectOwner = "project.owner"
)
type Model struct {
Id types.String `tfsdk:"id"` // needed by TF
ContainerId types.String `tfsdk:"container_id"`
ContainerParentId types.String `tfsdk:"parent_container_id"`
Name types.String `tfsdk:"name"`
Labels types.Map `tfsdk:"labels"`
OwnerEmail types.String `tfsdk:"owner_email"`
}
// NewProjectResource is a helper function to simplify the provider implementation.
func NewProjectResource() resource.Resource {
return &projectResource{}
}
// projectResource is the resource implementation.
type projectResource struct {
client *resourcemanager.APIClient
}
// Metadata returns the resource type name.
func (r *projectResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_resourcemanager_project"
}
// Configure adds the provider configured client to the resource.
func (r *projectResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
// Prevent panic if the provider has not been configured.
if req.ProviderData == nil {
return
}
providerData, ok := req.ProviderData.(core.ProviderData)
if !ok {
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 *resourcemanager.APIClient
var err error
if providerData.ResourceManagerCustomEndpoint != "" {
ctx = tflog.SetField(ctx, "resourcemanager_custom_endpoint", providerData.ResourceManagerCustomEndpoint)
apiClient, err = resourcemanager.NewAPIClient(
config.WithCustomAuth(providerData.RoundTripper),
config.WithServiceAccountEmail(providerData.ServiceAccountEmail),
config.WithEndpoint(providerData.ResourceManagerCustomEndpoint),
)
} else {
apiClient, err = resourcemanager.NewAPIClient(
config.WithCustomAuth(providerData.RoundTripper),
config.WithServiceAccountEmail(providerData.ServiceAccountEmail),
config.WithRegion(providerData.Region),
)
}
if err != nil {
resp.Diagnostics.AddError("Could not Configure API Client", err.Error())
return
}
tflog.Info(ctx, "Resource Manager project client configured")
r.client = apiClient
}
// Schema defines the schema for the resource.
func (r *projectResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
descriptions := map[string]string{
"main": "Resource Manager project resource schema.",
"id": "Terraform's internal unique identifier of the project, equivalent to the container ID",
"container_id": "Project container ID. Globally unique, user-friendly identifier.",
"parent_container_id": "Parent container ID",
"name": "Project name.",
"labels": "Labels are key-value string pairs which can be attached to a resource container. A label key must match the regex [A-ZÄÜÖa-zäüöß0-9_-]{1,64}. A label value must match the regex ^$|[A-ZÄÜÖa-zäüöß0-9_-]{1,64}",
"owner_email": "Email address of the owner of the project. This value is only considered during creation. Changing it afterwards will have no effect.",
}
resp.Schema = schema.Schema{
Description: descriptions["main"],
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: descriptions["id"],
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"container_id": schema.StringAttribute{
Description: descriptions["container_id"],
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
Validators: []validator.String{
validate.NoSeparator(),
},
},
"parent_container_id": schema.StringAttribute{
Description: descriptions["parent_container_id"],
Required: true,
Validators: []validator.String{
validate.NoSeparator(),
},
},
"name": schema.StringAttribute{
Description: descriptions["name"],
Required: true,
Validators: []validator.String{
stringvalidator.LengthAtLeast(1),
stringvalidator.LengthAtMost(63),
},
},
"labels": schema.MapAttribute{
Description: descriptions["labels"],
ElementType: types.StringType,
Optional: true,
Validators: []validator.Map{
mapvalidator.KeysAre(
stringvalidator.RegexMatches(
regexp.MustCompile(`[A-ZÄÜÖa-zäüöß0-9_-]{1,64}`),
"must match expression"),
),
mapvalidator.ValueStringsAre(
stringvalidator.RegexMatches(
regexp.MustCompile(`[A-ZÄÜÖa-zäüöß0-9_-]{1,64}`),
"must match expression"),
),
},
},
"owner_email": schema.StringAttribute{
Description: descriptions["owner_email"],
Required: true,
},
},
}
}
// Create creates the resource and sets the initial Terraform state.
func (r *projectResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform
var model Model
diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
containerId := model.ContainerId.ValueString()
ctx = tflog.SetField(ctx, "project_container_id", containerId)
serviceAccountEmail := r.client.GetConfig().ServiceAccountEmail
if serviceAccountEmail == "" {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating project", "The service account e-mail cannot be empty: set it in the provider configuration or through the STACKIT_SERVICE_ACCOUNT_EMAIL or in your credentials file (default filepath is ~/stackit/.credentials.json)")
return
}
// Generate API request body from model
payload, err := toCreatePayload(&model, serviceAccountEmail)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating project", fmt.Sprintf("Creating API payload: %v", err))
return
}
// Create new project
createResp, err := r.client.CreateProject(ctx).CreateProjectPayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating project", fmt.Sprintf("Calling API: %v", err))
return
}
respContainerId := *createResp.ContainerId
if respContainerId == "" {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating project", "API didn't return project id")
return
}
// If the request has not been processed yet and the containerId doesnt exist,
// the waiter will fail with authentication error, so wait some time before checking the creation
wr, err := resourcemanager.CreateProjectWaitHandler(ctx, r.client, respContainerId).SetSleepBeforeWait(1 * time.Minute).SetTimeout(10 * time.Minute).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating project", fmt.Sprintf("Instance creation waiting: %v", err))
return
}
got, ok := wr.(*resourcemanager.ProjectResponseWithParents)
if !ok {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating project", fmt.Sprintf("Wait result conversion, got %+v", wr))
return
}
// Map response body to schema and populate Computed attribute values
err = mapFields(ctx, 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, "Resource Manager project created")
}
// Read refreshes the Terraform state with the latest data.
func (r *projectResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform
var state = &Model{}
diags := req.State.Get(ctx, state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
containerId := state.ContainerId.ValueString()
ctx = tflog.SetField(ctx, "container_id", containerId)
projectResp, err := r.client.GetProject(ctx, containerId).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading project", err.Error())
return
}
// Map response body to schema and populate Computed attribute values
err = mapFields(ctx, projectResp, 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, "Resource Manager project read")
}
// Update updates the resource and sets the updated Terraform state on success.
func (r *projectResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform
// Retrieve values from plan
var model Model
diags := req.Plan.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
containerId := model.ContainerId.ValueString()
ctx = tflog.SetField(ctx, "container_id", containerId)
// Generate API request body from model
payload, err := toUpdatePayload(&model)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating project", fmt.Sprintf("Could not create API payload: %v", err))
return
}
// Update existing project
_, err = r.client.UpdateProject(ctx, containerId).UpdateProjectPayload(*payload).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating project", err.Error())
return
}
diags = resp.State.Set(ctx, &model)
resp.Diagnostics.Append(diags...)
tflog.Info(ctx, "Resource Manager project updated")
}
// Delete deletes the resource and removes the Terraform state on success.
func (r *projectResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform
// Retrieve values from state
var model Model
diags := req.State.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
containerId := model.ContainerId.ValueString()
ctx = tflog.SetField(ctx, "container_id", containerId)
// Delete existing project
err := r.client.DeleteProject(ctx, containerId).Execute()
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting project", err.Error())
return
}
_, err = resourcemanager.DeleteProjectWaitHandler(ctx, r.client, containerId).SetTimeout(10 * time.Minute).WaitWithContext(ctx)
if err != nil {
core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting project", fmt.Sprintf("Instance deletion waiting: %v", err))
return
}
tflog.Info(ctx, "Resource Manager project deleted")
}
// ImportState imports a resource into the Terraform state on success.
// The expected format of the resource import identifier is: container_id
func (r *projectResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
idParts := strings.Split(req.ID, core.Separator)
if len(idParts) != 1 || idParts[0] == "" {
resp.Diagnostics.AddError(
"Unexpected Import Identifier",
fmt.Sprintf("Expected import identifier with format: [container_id] Got: %q", req.ID),
)
return
}
ctx = tflog.SetField(ctx, "container_id", req.ID)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("container_id"), req.ID)...)
tflog.Info(ctx, "Resource Manager Project state imported")
}
func mapFields(ctx context.Context, projectResp *resourcemanager.ProjectResponseWithParents, model *Model) (err error) {
if projectResp == nil {
return fmt.Errorf("response input is nil")
}
if model == nil {
return fmt.Errorf("model input is nil")
}
var containerId string
if model.ContainerId.ValueString() != "" {
containerId = model.ContainerId.ValueString()
} else if projectResp.ContainerId != nil {
containerId = *projectResp.ContainerId
} else {
return fmt.Errorf("container id not present")
}
var labels basetypes.MapValue
if projectResp.Labels != nil && len(*projectResp.Labels) != 0 {
labels, err = conversion.ToTerraformStringMap(ctx, *projectResp.Labels)
if err != nil {
return fmt.Errorf("converting to StringValue map: %w", err)
}
} else {
labels = types.MapNull(types.StringType)
}
model.Id = types.StringValue(containerId)
model.ContainerId = types.StringValue(containerId)
if projectResp.Parent != nil {
model.ContainerParentId = types.StringPointerValue(projectResp.Parent.ContainerId)
} else {
model.ContainerParentId = types.StringNull()
}
model.Name = types.StringPointerValue(projectResp.Name)
model.Labels = labels
return nil
}
func toCreatePayload(model *Model, serviceAccountEmail string) (*resourcemanager.CreateProjectPayload, error) {
if model == nil {
return nil, fmt.Errorf("nil model")
}
owner := projectOwner
serviceAccountSubject := serviceAccountEmail
members := []resourcemanager.ProjectMember{
{
Subject: &serviceAccountSubject,
Role: &owner,
},
}
ownerSubject := model.OwnerEmail.ValueString()
if ownerSubject != "" && ownerSubject != serviceAccountSubject {
members = append(members,
resourcemanager.ProjectMember{
Subject: &ownerSubject,
Role: &owner,
})
}
modelLabels := model.Labels.Elements()
labels, err := conversion.ToOptStringMap(modelLabels)
if err != nil {
return nil, fmt.Errorf("converting to GO map: %w", err)
}
return &resourcemanager.CreateProjectPayload{
ContainerParentId: model.ContainerParentId.ValueStringPointer(),
Labels: labels,
Members: &members,
Name: model.Name.ValueStringPointer(),
}, nil
}
func toUpdatePayload(model *Model) (*resourcemanager.UpdateProjectPayload, error) {
if model == nil {
return nil, fmt.Errorf("nil model")
}
modelLabels := model.Labels.Elements()
labels, err := conversion.ToOptStringMap(modelLabels)
if err != nil {
return nil, fmt.Errorf("converting to GO map: %w", err)
}
return &resourcemanager.UpdateProjectPayload{
ContainerParentId: model.ContainerParentId.ValueStringPointer(),
Name: model.Name.ValueStringPointer(),
Labels: labels,
}, nil
}

View file

@ -0,0 +1,278 @@
package project
import (
"context"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/stackitcloud/stackit-sdk-go/core/utils"
"github.com/stackitcloud/stackit-sdk-go/services/resourcemanager"
"github.com/stackitcloud/terraform-provider-stackit/stackit/conversion"
)
func TestMapFields(t *testing.T) {
tests := []struct {
description string
input *resourcemanager.ProjectResponseWithParents
expected Model
expectedLabels *map[string]string
isValid bool
}{
{
"default_ok",
&resourcemanager.ProjectResponseWithParents{
ContainerId: utils.Ptr("cid"),
},
Model{
Id: types.StringValue("cid"),
ContainerId: types.StringValue("cid"),
ContainerParentId: types.StringNull(),
Name: types.StringNull(),
},
nil,
true,
},
{
"values_ok",
&resourcemanager.ProjectResponseWithParents{
ContainerId: utils.Ptr("cid"),
Labels: &map[string]string{
"label1": "ref1",
"label2": "ref2",
},
Parent: &resourcemanager.Parent{
ContainerId: utils.Ptr("pid"),
},
Name: utils.Ptr("name"),
},
Model{
Id: types.StringValue("cid"),
ContainerId: types.StringValue("cid"),
ContainerParentId: types.StringValue("pid"),
Name: types.StringValue("name"),
},
&map[string]string{
"label1": "ref1",
"label2": "ref2",
},
true,
},
{
"response_nil_fail",
nil,
Model{},
nil,
false,
},
{
"no_resource_id",
&resourcemanager.ProjectResponseWithParents{},
Model{},
nil,
false,
},
}
for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) {
if tt.expectedLabels == nil {
tt.expected.Labels = types.MapNull(types.StringType)
} else {
convertedLabels, err := conversion.ToTerraformStringMap(context.Background(), *tt.expectedLabels)
if err != nil {
t.Fatalf("Error converting to terraform string map: %v", err)
}
tt.expected.Labels = convertedLabels
}
state := &Model{
ContainerId: tt.expected.ContainerId,
}
err := mapFields(context.Background(), tt.input, state)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}
if tt.isValid && err != nil {
t.Fatalf("Should not have failed: %v", err)
}
if tt.isValid {
diff := cmp.Diff(state, &tt.expected)
if diff != "" {
t.Fatalf("Data does not match: %s", diff)
}
}
})
}
}
func TestToCreatePayload(t *testing.T) {
tests := []struct {
description string
input *Model
inputLabels *map[string]string
expected *resourcemanager.CreateProjectPayload
isValid bool
}{
{
"default_ok",
&Model{},
nil,
&resourcemanager.CreateProjectPayload{
ContainerParentId: nil,
Labels: nil,
Members: &[]resourcemanager.ProjectMember{
{
Role: utils.Ptr(projectOwner),
Subject: utils.Ptr("service_account_email"),
},
},
Name: nil,
},
true,
},
{
"mapping_with_conversions_ok",
&Model{
ContainerParentId: types.StringValue("pid"),
Name: types.StringValue("name"),
OwnerEmail: types.StringValue("owner_email"),
},
&map[string]string{
"label1": "1",
"label2": "2",
},
&resourcemanager.CreateProjectPayload{
ContainerParentId: utils.Ptr("pid"),
Labels: &map[string]string{
"label1": "1",
"label2": "2",
},
Members: &[]resourcemanager.ProjectMember{
{
Role: utils.Ptr(projectOwner),
Subject: utils.Ptr("service_account_email"),
},
{
Role: utils.Ptr(projectOwner),
Subject: utils.Ptr("owner_email"),
},
},
Name: utils.Ptr("name"),
},
true,
},
{
"nil_model",
nil,
nil,
nil,
false,
},
}
for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) {
if tt.input != nil {
if tt.inputLabels == nil {
tt.input.Labels = types.MapNull(types.StringType)
} else {
convertedLabels, err := conversion.ToTerraformStringMap(context.Background(), *tt.inputLabels)
if err != nil {
t.Fatalf("Error converting to terraform string map: %v", err)
}
tt.input.Labels = convertedLabels
}
}
output, err := toCreatePayload(tt.input, "service_account_email")
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}
if tt.isValid && err != nil {
t.Fatalf("Should not have failed: %v", err)
}
if tt.isValid {
diff := cmp.Diff(output, tt.expected)
if diff != "" {
t.Fatalf("Data does not match: %s", diff)
}
}
})
}
}
func TestToUpdatePayload(t *testing.T) {
tests := []struct {
description string
input *Model
inputLabels *map[string]string
expected *resourcemanager.UpdateProjectPayload
isValid bool
}{
{
"default_ok",
&Model{},
nil,
&resourcemanager.UpdateProjectPayload{
ContainerParentId: nil,
Labels: nil,
Name: nil,
},
true,
},
{
"mapping_with_conversions_ok",
&Model{
ContainerParentId: types.StringValue("pid"),
Name: types.StringValue("name"),
OwnerEmail: types.StringValue("owner_email"),
},
&map[string]string{
"label1": "1",
"label2": "2",
},
&resourcemanager.UpdateProjectPayload{
ContainerParentId: utils.Ptr("pid"),
Labels: &map[string]string{
"label1": "1",
"label2": "2",
},
Name: utils.Ptr("name"),
},
true,
},
{
"nil_model",
nil,
nil,
nil,
false,
},
}
for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) {
if tt.input != nil {
if tt.inputLabels == nil {
tt.input.Labels = types.MapNull(types.StringType)
} else {
convertedLabels, err := conversion.ToTerraformStringMap(context.Background(), *tt.inputLabels)
if err != nil {
t.Fatalf("Error converting to terraform string map: %v", err)
}
tt.input.Labels = convertedLabels
}
}
output, err := toUpdatePayload(tt.input)
if !tt.isValid && err == nil {
t.Fatalf("Should have failed")
}
if tt.isValid && err != nil {
t.Fatalf("Should not have failed: %v", err)
}
if tt.isValid {
diff := cmp.Diff(output, tt.expected)
if diff != "" {
t.Fatalf("Data does not match: %s", diff)
}
}
})
}
}

View file

@ -0,0 +1,170 @@
package resourcemanager_test
import (
"context"
"fmt"
"testing"
"github.com/hashicorp/terraform-plugin-testing/helper/acctest"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/terraform"
"github.com/stackitcloud/stackit-sdk-go/core/config"
"github.com/stackitcloud/stackit-sdk-go/core/utils"
"github.com/stackitcloud/stackit-sdk-go/services/resourcemanager"
"github.com/stackitcloud/terraform-provider-stackit/stackit/testutil"
)
// Project resource data
var projectResource = map[string]string{
"name": fmt.Sprintf("acc-pj-%s", acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)),
"parent_container_id": testutil.TestProjectParentContainerID,
"billing_reference": "TEST-REF",
"new_label": "a-label",
}
func resourceConfig(name, label string) string {
return fmt.Sprintf(`
%s
resource "stackit_resourcemanager_project" "project" {
parent_container_id = "%s"
name = "%s"
labels = {
"billing_reference" = "%s"
%s
}
owner_email = "%s"
}
`,
testutil.ResourceManagerProviderConfig(),
projectResource["parent_container_id"],
name,
projectResource["billing_reference"],
label,
testutil.TestProjectServiceAccountEmail,
)
}
func TestAccResourceManagerResource(t *testing.T) {
resource.Test(t, resource.TestCase{
ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories,
CheckDestroy: testAccCheckResourceManagerDestroy,
Steps: []resource.TestStep{
// Creation
{
Config: resourceConfig(projectResource["name"], ""),
Check: resource.ComposeAggregateTestCheckFunc(
// Project data
resource.TestCheckResourceAttrSet("stackit_resourcemanager_project.project", "container_id"),
resource.TestCheckResourceAttr("stackit_resourcemanager_project.project", "name", projectResource["name"]),
resource.TestCheckResourceAttr("stackit_resourcemanager_project.project", "parent_container_id", projectResource["parent_container_id"]),
resource.TestCheckResourceAttr("stackit_resourcemanager_project.project", "labels.%", "1"),
resource.TestCheckResourceAttr("stackit_resourcemanager_project.project", "labels.billing_reference", projectResource["billing_reference"]),
),
},
// Data source
{
Config: fmt.Sprintf(`
%s
data "stackit_resourcemanager_project" "project" {
container_id = stackit_resourcemanager_project.project.container_id
}`,
resourceConfig(projectResource["name"], ""),
),
Check: resource.ComposeAggregateTestCheckFunc(
// Project data
resource.TestCheckResourceAttrSet("data.stackit_resourcemanager_project.project", "id"),
resource.TestCheckResourceAttrSet("data.stackit_resourcemanager_project.project", "container_id"),
resource.TestCheckResourceAttr("data.stackit_resourcemanager_project.project", "name", projectResource["name"]),
resource.TestCheckResourceAttrSet("data.stackit_resourcemanager_project.project", "parent_container_id"),
resource.TestCheckResourceAttr("data.stackit_resourcemanager_project.project", "labels.%", "1"),
resource.TestCheckResourceAttr("data.stackit_resourcemanager_project.project", "labels.billing_reference", projectResource["billing_reference"]),
resource.TestCheckResourceAttrPair("data.stackit_resourcemanager_project.project", "project_id",
"stackit_resourcemanager_project.project", "project_id"),
),
},
// Import
{
ResourceName: "stackit_resourcemanager_project.project",
ImportStateIdFunc: func(s *terraform.State) (string, error) {
r, ok := s.RootModule().Resources["stackit_resourcemanager_project.project"]
if !ok {
return "", fmt.Errorf("couldn't find resource stackit_resourcemanager_project.project")
}
containerId, ok := r.Primary.Attributes["container_id"]
if !ok {
return "", fmt.Errorf("couldn't find attribute container_id")
}
return containerId, nil
},
ImportState: true,
ImportStateVerify: true,
// The owner_email attributes don't exist in the
// API, therefore there is no value for it during import.
ImportStateVerifyIgnore: []string{"owner_email"},
},
// Update
{
Config: resourceConfig(fmt.Sprintf("%s-new", projectResource["name"]), "new_label='a-label'"),
Check: resource.ComposeAggregateTestCheckFunc(
// Project data
resource.TestCheckResourceAttrSet("stackit_resourcemanager_project.project", "container_id"),
resource.TestCheckResourceAttr("stackit_resourcemanager_project.project", "name", fmt.Sprintf("%s-new", projectResource["name"])),
resource.TestCheckResourceAttr("stackit_resourcemanager_project.project", "parent_container_id", projectResource["parent_container_id"]),
resource.TestCheckResourceAttr("stackit_resourcemanager_project.project", "labels.%", "2"),
resource.TestCheckResourceAttr("stackit_resourcemanager_project.project", "labels.billing_reference", projectResource["billing_reference"]),
resource.TestCheckResourceAttr("stackit_resourcemanager_project.project", "labels.new_label", projectResource["new_label"]),
),
},
// Deletion is done by the framework implicitly
},
})
}
func testAccCheckResourceManagerDestroy(s *terraform.State) error {
ctx := context.Background()
var client *resourcemanager.APIClient
var err error
if testutil.ResourceManagerCustomEndpoint == "" {
client, err = resourcemanager.NewAPIClient()
} else {
client, err = resourcemanager.NewAPIClient(
config.WithEndpoint(testutil.ResourceManagerCustomEndpoint),
)
}
if err != nil {
return fmt.Errorf("creating client: %w", err)
}
projectsToDestroy := []string{}
for _, rs := range s.RootModule().Resources {
if rs.Type != "stackit_resourcemanager_project" {
continue
}
// project terraform ID: "[container_id]"
containerId := rs.Primary.ID
projectsToDestroy = append(projectsToDestroy, containerId)
}
projectsResp, err := client.GetProjects(ctx).ContainerParentId(projectResource["parent_container_id"]).Execute()
if err != nil {
return fmt.Errorf("getting projectsResp: %w", err)
}
items := *projectsResp.Items
for i := range items {
if utils.Contains(projectsToDestroy, *items[i].ContainerId) {
err := client.DeleteProjectExecute(ctx, *items[i].ContainerId)
if err != nil {
return fmt.Errorf("destroying project %s during CheckDestroy: %w", *items[i].ContainerId, err)
}
_, err = resourcemanager.DeleteProjectWaitHandler(ctx, client, *items[i].ContainerId).WaitWithContext(ctx)
if err != nil {
return fmt.Errorf("destroying project %s during CheckDestroy: waiting for deletion %w", *items[i].ContainerId, err)
}
}
}
return nil
}