Skip to content

VM import #36

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Apr 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@ name: Tests
# This GitHub action runs your tests for each pull request and push.
# Optionally, you can turn it on using a schedule for regular testing.
on:
pull_request:
paths-ignore:
- 'README.md'
push:
paths-ignore:
- 'README.md'
Expand Down
34 changes: 34 additions & 0 deletions docs/resources/vm.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,23 @@ resource "hypercore_vm" "myvm" {
}
}

resource "hypercore_vm" "import-from-smb" {
group = "my-group"
name = "imported-vm"
description = "some description"

vcpu = 4
memory = 4096 # MiB

import = {
server = "10.5.11.39"
username = ";administrator"
password = "***"
path = "/cidata"
file_name = "example-template.xml"
}
}

output "vm_uuid" {
value = hypercore_vm.myvm.id
}
Expand All @@ -63,6 +80,7 @@ output "vm_uuid" {
- `clone` (Object) Clone options if the VM is being created as a clone. The `source_vm_uuid` is the UUID of the VM used for cloning, <br>`user_data` and `meta_data` are used for the cloud init data. (see [below for nested schema](#nestedatt--clone))
- `description` (String) Description of this VM
- `group` (String) Group/tag to create this VM in
- `import` (Attributes) Options for importing a VM through a SMB server or some other HTTP location. <br>Use server, username, password for SMB or http_uri for some other HTTP location. Parameters path and file_name are always **required** (see [below for nested schema](#nestedatt--import))
- `memory` (Number) Memory (RAM) size in `MiB`: If the cloned VM was already created <br>and it's memory was modified, the cloned VM will be rebooted (either gracefully or forcefully)
- `snapshot_schedule_uuid` (String) UUID of the snapshot schedule to create automatic snapshots
- `vcpu` (Number) Number of CPUs on this VM. If the cloned VM was already created and it's <br>`VCPU` was modified, the cloned VM will be rebooted (either gracefully or forcefully)
Expand All @@ -89,3 +107,19 @@ Optional:
- `meta_data` (String)
- `source_vm_uuid` (String)
- `user_data` (String)


<a id="nestedatt--import"></a>
### Nested Schema for `import`

Required:

- `file_name` (String)
- `path` (String)

Optional:

- `http_uri` (String)
- `password` (String, Sensitive)
- `server` (String)
- `username` (String)
17 changes: 17 additions & 0 deletions examples/resources/hypercore_vm/resource.tf
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,23 @@ resource "hypercore_vm" "myvm" {
}
}

resource "hypercore_vm" "import-from-smb" {
group = "my-group"
name = "imported-vm"
description = "some description"

vcpu = 4
memory = 4096 # MiB

import = {
server = "10.5.11.39"
username = ";administrator"
password = "***"
path = "/cidata"
file_name = "example-template.xml"
}
}

output "vm_uuid" {
value = hypercore_vm.myvm.id
}
196 changes: 150 additions & 46 deletions internal/provider/hypercore_vm_resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,22 @@ type HypercoreVMResourceModel struct {
Description types.String `tfsdk:"description"`
VCPU types.Int32 `tfsdk:"vcpu"`
Memory types.Int64 `tfsdk:"memory"`
Import *ImportModel `tfsdk:"import"`
SnapshotScheduleUUID types.String `tfsdk:"snapshot_schedule_uuid"`
Clone CloneModel `tfsdk:"clone"`
Clone *CloneModel `tfsdk:"clone"`
AffinityStrategy AffinityStrategyModel `tfsdk:"affinity_strategy"`
Id types.String `tfsdk:"id"`
}

type ImportModel struct {
HTTPUri types.String `tfsdk:"http_uri"`
Server types.String `tfsdk:"server"`
Username types.String `tfsdk:"username"`
Password types.String `tfsdk:"password"`
Path types.String `tfsdk:"path"`
FileName types.String `tfsdk:"file_name"`
}

type CloneModel struct {
SourceVMUUID types.String `tfsdk:"source_vm_uuid"`
UserData types.String `tfsdk:"user_data"`
Expand Down Expand Up @@ -99,6 +109,32 @@ func (r *HypercoreVMResource) Schema(ctx context.Context, req resource.SchemaReq
MarkdownDescription: "UUID of the snapshot schedule to create automatic snapshots",
Optional: true,
},
"import": schema.SingleNestedAttribute{
MarkdownDescription: "Options for importing a VM through a SMB server or some other HTTP location. <br>" +
"Use server, username, password for SMB or http_uri for some other HTTP location. Parameters path and file_name are always **required**",
Optional: true,
Attributes: map[string]schema.Attribute{
"http_uri": schema.StringAttribute{
Optional: true,
},
"server": schema.StringAttribute{
Optional: true,
},
"username": schema.StringAttribute{
Optional: true,
},
"password": schema.StringAttribute{
Optional: true,
Sensitive: true,
},
"path": schema.StringAttribute{
Required: true,
},
"file_name": schema.StringAttribute{
Required: true,
},
},
},
"clone": schema.ObjectAttribute{
MarkdownDescription: "" +
"Clone options if the VM is being created as a clone. The `source_vm_uuid` is the UUID of the VM used for cloning, <br>" +
Expand Down Expand Up @@ -166,16 +202,121 @@ func (r *HypercoreVMResource) Configure(ctx context.Context, req resource.Config
r.client = restClient
}

func getVMStruct(data *HypercoreVMResourceModel, vmDescription *string, vmTags *[]string) *utils.VM {
// Gets VM structure from Utils.VM, sends parameters based on which VM create logic is being called
sourceVMUUID, userData, metaData := "", "", ""
if data.Clone != nil {
sourceVMUUID = data.Clone.SourceVMUUID.ValueString()
userData = data.Clone.UserData.ValueString()
metaData = data.Clone.MetaData.ValueString()
}
vmStruct := utils.GetVMStruct(
data.Name.ValueString(),
sourceVMUUID,
userData,
metaData,
vmDescription,
vmTags,
data.VCPU.ValueInt32Pointer(),
data.Memory.ValueInt64Pointer(),
data.SnapshotScheduleUUID.ValueStringPointer(),
nil,
data.AffinityStrategy.StrictAffinity.ValueBool(),
data.AffinityStrategy.PreferredNodeUUID.ValueString(),
data.AffinityStrategy.BackupNodeUUID.ValueString(),
)
return vmStruct
}

func validateParameters(data *HypercoreVMResourceModel) (*string, *[]string) {
var tags *[]string
var description *string

if data.Group.ValueString() == "" {
tags = nil
} else {
t := []string{data.Group.ValueString()}
tags = &t
}

if data.Description.ValueString() == "" {
description = nil
} else {
description = data.Description.ValueStringPointer()
}
return description, tags
}
func isHTTPImport(data *HypercoreVMResourceModel) bool {
// Check if HTTP URI is being used for VM import
httpUri := data.Import.HTTPUri.ValueString()
return httpUri != ""
}
func isSMBImport(data *HypercoreVMResourceModel) bool {
smbServer := data.Import.Server.ValueString()
smbUsername := data.Import.Username.ValueString()
smbPassword := data.Import.Password.ValueString()

return smbServer != "" || smbUsername != "" || smbPassword != ""
}

func (r *HypercoreVMResource) handleCloneLogic(data *HypercoreVMResourceModel, ctx context.Context, vmNew *utils.VM) {
changed, msg := vmNew.Clone(*r.client, ctx)
tflog.Info(ctx, fmt.Sprintf("Changed: %t, Message: %s\n", changed, msg))
// Clone will retain setting from original VM so we call SetVMParams to change those settings based on user input before we save state
changed, vmWasRebooted, vmDiff := vmNew.SetVMParams(*r.client, ctx)
data.Id = types.StringValue(vmNew.UUID)
tflog.Info(ctx, fmt.Sprintf("Changed: %t, Was VM Rebooted: %t, Diff: %v", changed, vmWasRebooted, vmDiff))
}
func (r *HypercoreVMResource) handleImportFromSMBLogic(data *HypercoreVMResourceModel, ctx context.Context, resp *resource.CreateResponse, vmNew *utils.VM, path string, fileName string) {
smbServer, smbUsername, smbPassword := data.Import.Server.ValueString(), data.Import.Username.ValueString(), data.Import.Password.ValueString()
errorDiagnostic := utils.ValidateSMB(smbServer, smbUsername, smbPassword)
if errorDiagnostic != nil {
resp.Diagnostics.AddError(errorDiagnostic.Summary(), errorDiagnostic.Detail())
return
}
smbSource := utils.BuildImportSource(smbUsername, smbPassword, smbServer, path, fileName, "", true)
vmNew.Import(*r.client, smbSource, ctx)
// Import will retain setting from original VM so we call SetVMParams to change those settings based on user input before we save state
changed, vmWasRebooted, vmDiff := vmNew.SetVMParams(*r.client, ctx)
data.Id = types.StringValue(vmNew.UUID)
tflog.Info(ctx, fmt.Sprintf("Changed: %t, Was VM Rebooted: %t, Diff: %v", changed, vmWasRebooted, vmDiff))
}
func (r *HypercoreVMResource) handleImportFromURILogic(data *HypercoreVMResourceModel, ctx context.Context, resp *resource.CreateResponse, vmNew *utils.VM, path string, fileName string) {
httpUri := data.Import.HTTPUri.ValueString()
errorDiagnostic := utils.ValidateHTTP(httpUri, path)
if errorDiagnostic != nil {
resp.Diagnostics.AddError(errorDiagnostic.Summary(), errorDiagnostic.Detail())
return
}
httpSource := utils.BuildImportSource("", "", "", path, fileName, httpUri, false)
vmNew.Import(*r.client, httpSource, ctx)
// Import will retain setting from original VM so we call SetVMParams to change those settings based on user input before we save state
changed, vmWasRebooted, vmDiff := vmNew.SetVMParams(*r.client, ctx)
data.Id = types.StringValue(vmNew.UUID)
tflog.Info(ctx, fmt.Sprintf("Changed: %t, Was VM Rebooted: %t, Diff: %v", changed, vmWasRebooted, vmDiff))
}
func (r *HypercoreVMResource) doCreateLogic(data *HypercoreVMResourceModel, ctx context.Context, resp *resource.CreateResponse, description *string, tags *[]string) {
vmNew := getVMStruct(data, description, tags)
// Chose which VM create logic we're going with (clone or import)
if data.Clone != nil {
r.handleCloneLogic(data, ctx, vmNew)
} else if data.Import != nil {
path := data.Import.Path.ValueString()
fileName := data.Import.FileName.ValueString()
if isHTTPImport(data) && !isSMBImport(data) {
r.handleImportFromURILogic(data, ctx, resp, vmNew, path, fileName)
} else if isSMBImport(data) && !isHTTPImport(data) {
r.handleImportFromSMBLogic(data, ctx, resp, vmNew, path, fileName)
}
}
}

func (r *HypercoreVMResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
tflog.Info(ctx, "TTRT HypercoreVMResource CREATE")
var data HypercoreVMResourceModel
// var readData HypercoreVMResourceModel

// Read Terraform plan data into the model
resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
// resp.State.Get(ctx, &readData)
//
// tflog.Debug(ctx, fmt.Sprintf("STATE IS: %v\n", readData.Disks))

if r.client == nil {
resp.Diagnostics.AddError(
Expand All @@ -190,48 +331,11 @@ func (r *HypercoreVMResource) Create(ctx context.Context, req resource.CreateReq
return
}

var tags *[]string
var description *string

if data.Group.ValueString() == "" {
tags = nil
} else {
tags = &[]string{data.Group.ValueString()}
}

if data.Description.ValueString() == "" {
description = nil
} else {
description = data.Description.ValueStringPointer()
}

tflog.Info(ctx, fmt.Sprintf("TTRT Create: name=%s, source_uuid=%s", data.Name.ValueString(), data.Clone.SourceVMUUID.ValueString()))

vmClone, _ := utils.NewVM(
data.Name.ValueString(),
data.Clone.SourceVMUUID.ValueString(),
data.Clone.UserData.ValueString(),
data.Clone.MetaData.ValueString(),
description,
tags,
data.VCPU.ValueInt32Pointer(),
data.Memory.ValueInt64Pointer(),
data.SnapshotScheduleUUID.ValueStringPointer(),
nil,
data.AffinityStrategy.StrictAffinity.ValueBool(),
data.AffinityStrategy.PreferredNodeUUID.ValueString(),
data.AffinityStrategy.BackupNodeUUID.ValueString(),
)
changed, msg := vmClone.Create(*r.client, ctx)
tflog.Info(ctx, fmt.Sprintf("Changed: %t, Message: %s\n", changed, msg))

// General parametrization
// set: description, group, vcpu, memory, power_state
changed, vmWasRebooted, vmDiff := vmClone.SetVMParams(*r.client, ctx)
tflog.Info(ctx, fmt.Sprintf("Changed: %t, Was VM Rebooted: %t, Diff: %v", changed, vmWasRebooted, vmDiff))
// Validate parameters TODO: Add other inputs here from schema if validation is needed
description, tags := validateParameters(&data)

// save into the Terraform state.
data.Id = types.StringValue(vmClone.UUID)
// Right now handles import or clone TODO: Add other VM create options here
r.doCreateLogic(&data, ctx, resp, description, tags)

// Write logs using the tflog package
// Documentation: https://terraform.io/plugin/log
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,18 @@ import (
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
)

var requested_power_state string = "stop" // "started"
// UUID of VM with name "testtf_src"
// var testtf_src_uuid string = "27af8248-88ee-4420-85d7-78b735415064" // https://172.31.6.11
var testtf_src_uuid string = "ff36479e-06bb-4141-bad5-0097c8c1a4a6" // https://10.5.11.205

func TestAccHypercoreVMResource(t *testing.T) {
func TestAccHypercoreVMResourceClone(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
Steps: []resource.TestStep{
// Create and Read testing
{
Config: testAccHypercoreVMResourceConfig("testtf-vm", testtf_src_uuid),
Config: testAccHypercoreVMResourceCloneConfig("testtf-vm", testtf_src_uuid),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr("hypercore_vm.test", "description", "testtf-vm-description"),
resource.TestCheckResourceAttr("hypercore_vm.test", "memory", "4096"),
Expand Down Expand Up @@ -64,7 +63,7 @@ func TestAccHypercoreVMResource(t *testing.T) {
*/
// Update and Read testing
{
Config: testAccHypercoreVMResourceConfig("testtf-vm", testtf_src_uuid),
Config: testAccHypercoreVMResourceCloneConfig("testtf-vm", testtf_src_uuid),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr("hypercore_vm.test", "name", "testtf-vm"),
resource.TestCheckResourceAttr("hypercore_vm.test", "description", "testtf-vm-description"),
Expand All @@ -79,7 +78,7 @@ func TestAccHypercoreVMResource(t *testing.T) {
})
}

func testAccHypercoreVMResourceConfig(vm_name string, source_vm_uuid string) string {
func testAccHypercoreVMResourceCloneConfig(vm_name string, source_vm_uuid string) string {
return fmt.Sprintf(`
resource "hypercore_vm" "test" {
name = %[1]q
Expand Down
Loading
Loading