diff --git a/docs/resources/org_psk.md b/docs/resources/org_psk.md new file mode 100644 index 00000000..fe9692e4 --- /dev/null +++ b/docs/resources/org_psk.md @@ -0,0 +1,55 @@ +--- +page_title: "mist_org_psk Resource - terraform-provider-mist" +subcategory: "Wi-Fi Assurance" +description: |- + This data source provides the list of Org PSKs. +--- + +# mist_org_psk (Resource) + +This data source provides the list of Org PSKs. + + +## Example Usage + +```terraform +resource "mist_org_psk" "psk_one" { + org_id = mist_org.terraform_test.id + name = "JNP-FR-PAR" + passphrase = "secretone" + ssid = mist_org_wlan.wlan_one.ssid + usage = "multi" +} +``` + + +## Schema + +### Required + +- `name` (String) +- `org_id` (String) +- `passphrase` (String, Sensitive) passphrase of the PSK (8-63 character or 64 in hex) +- `ssid` (String) SSID this PSK should be applicable to + +### Optional + +- `email` (String) email to send psk expiring notifications to +- `expire_time` (Number) Expire time for this PSK key (epoch time in seconds). Default `null` (as no expiration) +- `expiry_notification_time` (Number) Number of days before psk is expired. Used as to when to start sending reminder notification when the psk is about to expire +- `mac` (String) if `usage`==`single`, the mac that this PSK ties to, empty if `auto-binding` +- `macs` (List of String) if `usage`==`macs`, this list contains N number of client mac addresses or mac patterns(11:22:*) or both. This list is capped at 5000 +- `max_usage` (Number) For Org PSK Only. Max concurrent users for this PSK key. Default is 0 (unlimited) +- `note` (String) +- `notify_expiry` (Boolean) If set to true, reminder notification will be sent when psk is about to expire +- `notify_on_create_or_edit` (Boolean) If set to true, notification will be sent when psk is created or edited +- `old_passphrase` (String, Sensitive) previous passphrase of the PSK if it has been rotated +- `role` (String) +- `usage` (String) enum: `macs`, `multi`, `single` +- `vlan_id` (String) + +### Read-Only + +- `id` (String) PSK ID + + diff --git a/examples/data-sources/mist_org_psks/example.tf b/examples/data-sources/mist_org_psks/example.tf new file mode 100644 index 00000000..49037deb --- /dev/null +++ b/examples/data-sources/mist_org_psks/example.tf @@ -0,0 +1,4 @@ +data "mist_org_psks" "psks_vip" { + org_id = "15fca2ac-b1a6-47cc-9953-cc6906281550" + role = "vip" +} diff --git a/examples/resources/mist_org_psk/import.sh b/examples/resources/mist_org_psk/import.sh new file mode 100644 index 00000000..034ddf18 --- /dev/null +++ b/examples/resources/mist_org_psk/import.sh @@ -0,0 +1,12 @@ +# Gateway cluster can be imported by specifying the org_id and the psk_id +terraform import mist_org_psk.psk_one 17b46405-3a6d-4715-8bb4-6bb6d06f316a.d3c42998-9012-4859-9743-6b9bee475309 +``` + + +In Terraform v1.5.0 and later, use an import block to import `mist_org_psk` with `id`=`{org_id}.{psk_id}`: + +```tf +import { + to = mist_org_psk.psk_one + id = "17b46405-3a6d-4715-8bb4-6bb6d06f316a.d3c42998-9012-4859-9743-6b9bee475309" +} diff --git a/examples/resources/mist_org_psk/resource.tf b/examples/resources/mist_org_psk/resource.tf new file mode 100644 index 00000000..95134df4 --- /dev/null +++ b/examples/resources/mist_org_psk/resource.tf @@ -0,0 +1,7 @@ +resource "mist_org_psk" "psk_one" { + org_id = mist_org.terraform_test.id + name = "JNP-FR-PAR" + passphrase = "secretone" + ssid = mist_org_wlan.wlan_one.ssid + usage = "multi" +} \ No newline at end of file diff --git a/internal/provider/org_psk_resource.go b/internal/provider/org_psk_resource.go new file mode 100644 index 00000000..62c5e96d --- /dev/null +++ b/internal/provider/org_psk_resource.go @@ -0,0 +1,290 @@ +package provider + +import ( + "context" + "fmt" + "strings" + + "github.com/tmunzer/mistapi-go/mistapi" + + "github.com/Juniper/terraform-provider-mist/internal/resource_org_psk" + + "github.com/google/uuid" + "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-log/tflog" +) + +var ( + _ resource.Resource = &orgPskResource{} + _ resource.ResourceWithConfigure = &orgPskResource{} + _ resource.ResourceWithImportState = &orgPskResource{} +) + +func NewOrgPsk() resource.Resource { + return &orgPskResource{} +} + +type orgPskResource struct { + client mistapi.ClientInterface +} + +func (r *orgPskResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { + tflog.Info(ctx, "Configuring Mist Psk client") + if req.ProviderData == nil { + return + } + + client, ok := req.ProviderData.(mistapi.ClientInterface) + if !ok { + resp.Diagnostics.AddError( + "Unexpected Data Source Configure Type", + fmt.Sprintf("Expected *mistapigo.APIClient, got: %T. Please report this issue to the provider developers.", req.ProviderData), + ) + return + } + + r.client = client +} +func (r *orgPskResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_org_psk" +} + +func (r *orgPskResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + MarkdownDescription: docCategoryWlan + "This data source provides the list of Org PSKs.", + Attributes: resource_org_psk.OrgPskResourceSchema(ctx).Attributes, + } +} + +func (r *orgPskResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + tflog.Info(ctx, "Starting Psk Create") + var plan, state resource_org_psk.OrgPskModel + + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + orgId, err := uuid.Parse(plan.OrgId.ValueString()) + if err != nil { + resp.Diagnostics.AddError( + "Invalid \"org_id\" value for \"org_psk\" resource", + fmt.Sprintf("Could not parse the UUID \"%s\": %s", plan.OrgId.ValueString(), err.Error()), + ) + return + } + + psk, diags := resource_org_psk.TerraformToSdk(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + var upsert bool = false + data, err := r.client.OrgsPsks().CreateOrgPsk(ctx, orgId, &upsert, &psk) + if err != nil { + resp.Diagnostics.AddError( + "Error creating Psk", + "Could not create Psk, unexpected error: "+err.Error(), + ) + return + } + + state, diags = resource_org_psk.SdkToTerraform(ctx, &data.Data) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + diags = resp.State.Set(ctx, state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + +} + +func (r *orgPskResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var state resource_org_psk.OrgPskModel + + diags := resp.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + orgId, err := uuid.Parse(state.OrgId.ValueString()) + if err != nil { + resp.Diagnostics.AddError( + "Invalid \"org_id\" value for \"org_psk\" resource", + fmt.Sprintf("Could not parse the UUID \"%s\": %s", state.OrgId.ValueString(), err.Error()), + ) + return + } + pskId, err := uuid.Parse(state.Id.ValueString()) + if err != nil { + resp.Diagnostics.AddError( + "Invalid \"id\" value for \"org_psk\" resource", + fmt.Sprintf("Could not parse the UUID \"%s\": %s", state.Id.ValueString(), err.Error()), + ) + return + } + + tflog.Info(ctx, "Starting Psk Read: psk_id "+state.Id.ValueString()) + httpr, err := r.client.OrgsPsks().GetOrgPsk(ctx, orgId, pskId) + if httpr.Response.StatusCode == 404 { + resp.State.RemoveResource(ctx) + return + } else if err != nil { + resp.Diagnostics.AddError( + "Error getting Psk", + "Could not get Psk, unexpected error: "+err.Error(), + ) + return + } + state, diags = resource_org_psk.SdkToTerraform(ctx, &httpr.Data) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + diags = resp.State.Set(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } +} + +func (r *orgPskResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var state, plan resource_org_psk.OrgPskModel + tflog.Info(ctx, "Starting Psk Update") + + diags := resp.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + diags = req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + psk, diags := resource_org_psk.TerraformToSdk(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + orgId, err := uuid.Parse(state.OrgId.ValueString()) + if err != nil { + resp.Diagnostics.AddError( + "Invalid \"org_id\" value for \"org_psk\" resource", + fmt.Sprintf("Could not parse the UUID \"%s\": %s", state.OrgId.ValueString(), err.Error()), + ) + return + } + pskId, err := uuid.Parse(state.Id.ValueString()) + if err != nil { + resp.Diagnostics.AddError( + "Invalid \"id\" value for \"org_psk\" resource", + fmt.Sprintf("Could not parse the UUID \"%s\": %s", state.Id.ValueString(), err.Error()), + ) + return + } + + tflog.Info(ctx, "Starting Psk Update for Psk "+state.Id.ValueString()) + data, err := r.client.OrgsPsks(). + UpdateOrgPsk(ctx, orgId, pskId, &psk) + if err != nil { + resp.Diagnostics.AddError( + "Error updating Psk", + "Could not update Psk, unexpected error: "+err.Error(), + ) + return + } + + state, diags = resource_org_psk.SdkToTerraform(ctx, &data.Data) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + diags = resp.State.Set(ctx, state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + +} + +func (r *orgPskResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var state resource_org_psk.OrgPskModel + + diags := resp.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + orgId, err := uuid.Parse(state.OrgId.ValueString()) + if err != nil { + resp.Diagnostics.AddError( + "Invalid \"org_id\" value for \"org_psk\" resource", + fmt.Sprintf("Could not parse the UUID \"%s\": %s", state.OrgId.ValueString(), err.Error()), + ) + return + } + pskId, err := uuid.Parse(state.Id.ValueString()) + if err != nil { + resp.Diagnostics.AddError( + "Invalid \"id\" value for \"org_psk\" resource", + fmt.Sprintf("Could not parse the UUID \"%s\": %s", state.Id.ValueString(), err.Error()), + ) + return + } + + tflog.Info(ctx, "Starting Psk Delete: psk_id "+state.Id.ValueString()) + httpr, err := r.client.OrgsPsks().DeleteOrgPsk(ctx, orgId, pskId) + if httpr.StatusCode != 404 && err != nil { + resp.Diagnostics.AddError( + "Error deleting Psk", + "Could not delete Psk, unexpected error: "+err.Error(), + ) + return + } +} + +func (r *orgPskResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + + importIds := strings.Split(req.ID, ".") + if len(importIds) != 2 { + resp.Diagnostics.AddError( + "Invalid \"id\" value for \"org_psk\" resource", + "import \"id\" format must be \"{org_id}.{psk_id}\"", + ) + return + } + _, err := uuid.Parse(importIds[0]) + if err != nil { + resp.Diagnostics.AddError( + "Invalid \"org_id\" value for \"org_psk\" resource", + fmt.Sprintf("Could not parse the UUID \"%s\": %s. Import \"id\" format must be \"{org_id}.{psk_id}\"", importIds[0], err.Error()), + ) + return + } + resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("org_id"), importIds[0])...) + + _, err = uuid.Parse(importIds[1]) + if err != nil { + resp.Diagnostics.AddError( + "Invalid \"id\" value for \"org_psk\" resource", + fmt.Sprintf("Could not parse the UUID \"%s\": %s. Import \"id\" format must be \"{org_id}.{psk_id}\"", importIds[1], err.Error()), + ) + return + } + resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), importIds[1])...) +} diff --git a/internal/provider/org_psks_data_source.go b/internal/provider/org_psks_data_source.go new file mode 100644 index 00000000..3e2075ef --- /dev/null +++ b/internal/provider/org_psks_data_source.go @@ -0,0 +1,101 @@ +package provider + +import ( + "context" + "fmt" + + "github.com/tmunzer/mistapi-go/mistapi" + + "github.com/tmunzer/mistapi-go/mistapi/models" + + "github.com/Juniper/terraform-provider-mist/internal/datasource_org_psks" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-log/tflog" +) + +var _ datasource.DataSource = (*orgPsksDataSource)(nil) + +func NewOrgPsksDataSource() datasource.DataSource { + return &orgPsksDataSource{} +} + +type orgPsksDataSource struct { + client mistapi.ClientInterface +} + +func (d *orgPsksDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { + tflog.Info(ctx, "Configuring Mist Org Psks Datasource client") + if req.ProviderData == nil { + return + } + + client, ok := req.ProviderData.(mistapi.ClientInterface) + if !ok { + resp.Diagnostics.AddError( + "Unexpected Data Source Configure Type", + fmt.Sprintf("Expected *mistapigo.APIClient, got: %T. Please report this issue to the provider developers.", req.ProviderData), + ) + return + } + + d.client = client +} +func (d *orgPsksDataSource) Metadata(ctx context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_org_psks" +} + +func (d *orgPsksDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + MarkdownDescription: docCategoryWan + "This data source provides the list of WAN Assurance Psks." + + "The Psks are used in the `service_policies` from the Gateway configuration and Gateway templates ", + Attributes: datasource_org_psks.OrgPsksDataSourceSchema(ctx).Attributes, + } +} + +func (d *orgPsksDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { + var ds datasource_org_psks.OrgPsksModel + resp.Diagnostics.Append(req.Config.Get(ctx, &ds)...) + + if resp.Diagnostics.HasError() { + return + } + + orgId, err := uuid.Parse(ds.OrgId.ValueString()) + if err != nil { + resp.Diagnostics.AddError( + "Invalid \"org_id\" value for \"org_psks\" data_source", + "Could parse the UUID: "+err.Error(), + ) + return + } + + var name *string = ds.Name.ValueStringPointer() + var limit *int = models.ToPointer(1000) + var page *int + var ssid *string = ds.Ssid.ValueStringPointer() + var role *string = ds.Role.ValueStringPointer() + + data, err := d.client.OrgsPsks().ListOrgPsks(ctx, orgId, name, ssid, role, page, limit) + if err != nil { + resp.Diagnostics.AddError( + "Error getting AP Stats", + "Could not get AP Stats, unexpected error: "+err.Error(), + ) + return + } + + deviceApStat, diags := datasource_org_psks.SdkToTerraform(ctx, data.Data) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + if err := resp.State.SetAttribute(ctx, path.Root("org_psks"), deviceApStat); err != nil { + resp.Diagnostics.Append(err...) + return + } +} diff --git a/internal/resource_org_psk/org_psk_resource_gen.go b/internal/resource_org_psk/org_psk_resource_gen.go new file mode 100644 index 00000000..78606afb --- /dev/null +++ b/internal/resource_org_psk/org_psk_resource_gen.go @@ -0,0 +1,161 @@ +// Code generated by terraform-plugin-framework-generator DO NOT EDIT. + +package resource_org_psk + +import ( + "context" + "github.com/Juniper/terraform-provider-mist/internal/validators" + "github.com/hashicorp/terraform-plugin-framework-validators/listvalidator" + "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/int64default" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + + "github.com/hashicorp/terraform-plugin-framework/resource/schema" +) + +func OrgPskResourceSchema(ctx context.Context) schema.Schema { + return schema.Schema{ + Attributes: map[string]schema.Attribute{ + "email": schema.StringAttribute{ + Optional: true, + Description: "email to send psk expiring notifications to", + MarkdownDescription: "email to send psk expiring notifications to", + }, + "expire_time": schema.Int64Attribute{ + Optional: true, + Computed: true, + Description: "Expire time for this PSK key (epoch time in seconds). Default `null` (as no expiration)", + MarkdownDescription: "Expire time for this PSK key (epoch time in seconds). Default `null` (as no expiration)", + Default: int64default.StaticInt64(0), + }, + "expiry_notification_time": schema.Int64Attribute{ + Optional: true, + Description: "Number of days before psk is expired. Used as to when to start sending reminder notification when the psk is about to expire", + MarkdownDescription: "Number of days before psk is expired. Used as to when to start sending reminder notification when the psk is about to expire", + }, + "id": schema.StringAttribute{ + Computed: true, + Description: "PSK ID", + MarkdownDescription: "PSK ID", + }, + "mac": schema.StringAttribute{ + Optional: true, + Description: "if `usage`==`single`, the mac that this PSK ties to, empty if `auto-binding`", + MarkdownDescription: "if `usage`==`single`, the mac that this PSK ties to, empty if `auto-binding`", + Validators: []validator.String{ + mistvalidator.AllowedWhenValueIs(path.MatchRelative().AtParent().AtName("usage"), types.StringValue("single")), mistvalidator.ParseMac(), + }, + }, + "macs": schema.ListAttribute{ + ElementType: types.StringType, + Optional: true, + Description: "if `usage`==`macs`, this list contains N number of client mac addresses or mac patterns(11:22:*) or both. This list is capped at 5000", + MarkdownDescription: "if `usage`==`macs`, this list contains N number of client mac addresses or mac patterns(11:22:*) or both. This list is capped at 5000", + Validators: []validator.List{ + listvalidator.SizeAtMost(5000), + mistvalidator.AllowedWhenValueIs(path.MatchRelative().AtParent().AtName("usage"), + types.StringValue("macs")), + }, + }, + "max_usage": schema.Int64Attribute{ + Optional: true, + Computed: true, + Description: "For Org PSK Only. Max concurrent users for this PSK key. Default is 0 (unlimited)", + MarkdownDescription: "For Org PSK Only. Max concurrent users for this PSK key. Default is 0 (unlimited)", + Default: int64default.StaticInt64(0), + }, + "name": schema.StringAttribute{ + Required: true, + }, + "note": schema.StringAttribute{ + Optional: true, + }, + "notify_expiry": schema.BoolAttribute{ + Optional: true, + Computed: true, + Description: "If set to true, reminder notification will be sent when psk is about to expire", + MarkdownDescription: "If set to true, reminder notification will be sent when psk is about to expire", + Default: booldefault.StaticBool(false), + }, + "notify_on_create_or_edit": schema.BoolAttribute{ + Optional: true, + Description: "If set to true, notification will be sent when psk is created or edited", + MarkdownDescription: "If set to true, notification will be sent when psk is created or edited", + }, + "old_passphrase": schema.StringAttribute{ + Optional: true, + Sensitive: true, + Description: "previous passphrase of the PSK if it has been rotated", + MarkdownDescription: "previous passphrase of the PSK if it has been rotated", + }, + "org_id": schema.StringAttribute{ + Required: true, + }, + "passphrase": schema.StringAttribute{ + Required: true, + Sensitive: true, + Description: "passphrase of the PSK (8-63 character or 64 in hex)", + MarkdownDescription: "passphrase of the PSK (8-63 character or 64 in hex)", + Validators: []validator.String{ + stringvalidator.LengthBetween(8, 64), + }, + }, + "role": schema.StringAttribute{ + Optional: true, + Validators: []validator.String{ + stringvalidator.LengthBetween(0, 32), + }, + }, + "ssid": schema.StringAttribute{ + Required: true, + Description: "SSID this PSK should be applicable to", + MarkdownDescription: "SSID this PSK should be applicable to", + }, + "usage": schema.StringAttribute{ + Optional: true, + Computed: true, + Description: "enum: `macs`, `multi`, `single`", + MarkdownDescription: "enum: `macs`, `multi`, `single`", + Validators: []validator.String{ + stringvalidator.OneOf( + "macs", + "multi", + "single", + ), + }, + Default: stringdefault.StaticString("multi"), + }, + "vlan_id": schema.StringAttribute{ + Optional: true, + Validators: []validator.String{ + stringvalidator.Any(mistvalidator.ParseInt(1, 4094), mistvalidator.ParseVar()), + }, + }, + }, + } +} + +type OrgPskModel struct { + Email types.String `tfsdk:"email"` + ExpireTime types.Int64 `tfsdk:"expire_time"` + ExpiryNotificationTime types.Int64 `tfsdk:"expiry_notification_time"` + Id types.String `tfsdk:"id"` + Mac types.String `tfsdk:"mac"` + Macs types.List `tfsdk:"macs"` + MaxUsage types.Int64 `tfsdk:"max_usage"` + Name types.String `tfsdk:"name"` + Note types.String `tfsdk:"note"` + NotifyExpiry types.Bool `tfsdk:"notify_expiry"` + NotifyOnCreateOrEdit types.Bool `tfsdk:"notify_on_create_or_edit"` + OldPassphrase types.String `tfsdk:"old_passphrase"` + OrgId types.String `tfsdk:"org_id"` + Passphrase types.String `tfsdk:"passphrase"` + Role types.String `tfsdk:"role"` + Ssid types.String `tfsdk:"ssid"` + Usage types.String `tfsdk:"usage"` + VlanId types.String `tfsdk:"vlan_id"` +} diff --git a/internal/resource_org_psk/sdk_to_terraform.go b/internal/resource_org_psk/sdk_to_terraform.go new file mode 100644 index 00000000..08481fc7 --- /dev/null +++ b/internal/resource_org_psk/sdk_to_terraform.go @@ -0,0 +1,112 @@ +package resource_org_psk + +import ( + "context" + + "github.com/tmunzer/mistapi-go/mistapi/models" + + mist_transform "github.com/Juniper/terraform-provider-mist/internal/commons/utils" + + "github.com/hashicorp/terraform-plugin-framework/diag" + "github.com/hashicorp/terraform-plugin-framework/types" +) + +func SdkToTerraform(ctx context.Context, d *models.Psk) (OrgPskModel, diag.Diagnostics) { + var state OrgPskModel + var diags diag.Diagnostics + + var email types.String + var expire_time types.Int64 + var expiry_notification_time types.Int64 + var id types.String + var mac types.String + var macs types.List = types.ListNull(types.StringType) + var max_usage types.Int64 + var name types.String + var note types.String + var notify_expiry types.Bool + var notify_on_create_or_edit types.Bool + var old_passphrase types.String + var org_id types.String + var passphrase types.String + var role types.String + var ssid types.String + var usage types.String + var vlan_id types.String + + if d.Email != nil { + email = types.StringValue(*d.Email) + } + if d.ExpireTime.Value() != nil { + expire_time = types.Int64Value(int64(*d.ExpireTime.Value())) + } + if d.ExpiryNotificationTime != nil { + expiry_notification_time = types.Int64Value(int64(*d.ExpiryNotificationTime)) + } + if d.Id != nil { + id = types.StringValue(d.Id.String()) + } + if d.Mac != nil { + mac = types.StringValue(*d.Mac) + } + if d.Macs != nil { + macs = mist_transform.ListOfStringSdkToTerraform(ctx, d.Macs) + } + if d.MaxUsage != nil { + max_usage = types.Int64Value(int64(*d.MaxUsage)) + } + + name = types.StringValue(d.Name) + + if d.Note != nil { + note = types.StringValue(*d.Note) + } + if d.NotifyExpiry != nil { + notify_expiry = types.BoolValue(*d.NotifyExpiry) + } + if d.NotifyOnCreateOrEdit != nil { + notify_on_create_or_edit = types.BoolValue(*d.NotifyOnCreateOrEdit) + } + if d.OldPassphrase != nil { + old_passphrase = types.StringValue(*d.OldPassphrase) + } + if d.OrgId != nil { + org_id = types.StringValue(d.OrgId.String()) + } + + passphrase = types.StringValue(d.Passphrase) + + if d.Role != nil { + role = types.StringValue(*d.Role) + } + + ssid = types.StringValue(d.Ssid) + + usage = types.StringValue(string(*d.Usage)) + + if d.VlanId != nil { + vlan_id = types.StringValue(d.VlanId.String()) + } + + state.Email = email + state.ExpireTime = expire_time + state.ExpiryNotificationTime = expiry_notification_time + state.Id = id + state.Mac = mac + state.Macs = macs + state.MaxUsage = max_usage + state.Name = name + state.Note = note + state.NotifyExpiry = notify_expiry + state.NotifyOnCreateOrEdit = notify_on_create_or_edit + state.OldPassphrase = old_passphrase + state.Passphrase = passphrase + state.OrgId = org_id + state.Role = role + state.Ssid = ssid + state.Usage = usage + state.VlanId = vlan_id + + return state, diags + +} diff --git a/internal/resource_org_psk/terraform_to_sdk.go b/internal/resource_org_psk/terraform_to_sdk.go new file mode 100644 index 00000000..cd237232 --- /dev/null +++ b/internal/resource_org_psk/terraform_to_sdk.go @@ -0,0 +1,113 @@ +package resource_org_psk + +import ( + "context" + + "github.com/tmunzer/mistapi-go/mistapi/models" + + mist_transform "github.com/Juniper/terraform-provider-mist/internal/commons/utils" + + "github.com/hashicorp/terraform-plugin-framework/diag" +) + +func TerraformToSdk(ctx context.Context, plan *OrgPskModel) (models.Psk, diag.Diagnostics) { + var diags diag.Diagnostics + data := models.Psk{} + unset := make(map[string]interface{}) + + if !plan.Email.IsNull() && !plan.Email.IsUnknown() { + data.Email = plan.Email.ValueStringPointer() + } else { + unset["-email"] = "" + } + + if !plan.ExpireTime.IsNull() && !plan.ExpireTime.IsUnknown() { + data.ExpireTime = models.NewOptional(models.ToPointer(int(plan.ExpireTime.ValueInt64()))) + } else { + unset["-expire_time"] = "" + } + + if !plan.ExpiryNotificationTime.IsNull() && !plan.ExpiryNotificationTime.IsUnknown() { + data.ExpiryNotificationTime = models.ToPointer(int(plan.ExpiryNotificationTime.ValueInt64())) + } else { + unset["-expiry_notification_time"] = "" + } + + if !plan.Mac.IsNull() && !plan.Mac.IsUnknown() { + data.Mac = plan.Mac.ValueStringPointer() + } else { + unset["-mac"] = "" + } + + if !plan.Macs.IsNull() && !plan.Macs.IsUnknown() { + data.Macs = mist_transform.ListOfStringTerraformToSdk(ctx, plan.Macs) + } else { + unset["-macs"] = "" + } + + if !plan.MaxUsage.IsNull() && !plan.MaxUsage.IsUnknown() { + data.MaxUsage = models.ToPointer(int(plan.MaxUsage.ValueInt64())) + } else { + unset["-max_usage"] = "" + } + + data.Name = plan.Name.String() + + if !plan.Note.IsNull() && !plan.Note.IsUnknown() { + data.Note = plan.Note.ValueStringPointer() + } else { + unset["-note"] = "" + } + + if !plan.NotifyExpiry.IsNull() && !plan.NotifyExpiry.IsUnknown() { + data.NotifyExpiry = plan.NotifyExpiry.ValueBoolPointer() + } else { + unset["-notify_expiry"] = "" + } + + if !plan.NotifyOnCreateOrEdit.IsNull() && !plan.NotifyOnCreateOrEdit.IsUnknown() { + data.NotifyOnCreateOrEdit = plan.NotifyOnCreateOrEdit.ValueBoolPointer() + } else { + unset["-notify_on_create_or_edit"] = "" + } + + if !plan.OldPassphrase.IsNull() && !plan.OldPassphrase.IsUnknown() { + data.OldPassphrase = plan.OldPassphrase.ValueStringPointer() + } else { + unset["-old_passphrase"] = "" + } + + if !plan.Passphrase.IsNull() && !plan.Passphrase.IsUnknown() { + data.Passphrase = plan.Passphrase.ValueString() + } else { + unset["-passphrase"] = "" + } + + if !plan.Role.IsNull() && !plan.Role.IsUnknown() { + data.Role = plan.Role.ValueStringPointer() + } else { + unset["-role"] = "" + } + + if !plan.Ssid.IsNull() && !plan.Ssid.IsUnknown() { + data.Ssid = plan.Ssid.ValueString() + } else { + unset["-ssid"] = "" + } + + if !plan.Usage.IsNull() && !plan.Usage.IsUnknown() { + data.Usage = models.ToPointer(models.PskUsageEnum(plan.Usage.ValueString())) + } else { + unset["-usage"] = "" + } + + if !plan.VlanId.IsNull() && !plan.VlanId.IsUnknown() { + data.VlanId = models.ToPointer(models.PskVlanIdContainer.FromString(plan.VlanId.ValueString())) + } else { + unset["-vlan_id"] = "" + } + + data.AdditionalProperties = unset + + return data, diags +}