forked from Azure-Samples/azure-sdk-for-go-samples
/
vm.go
214 lines (185 loc) · 6.41 KB
/
vm.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package compute
import (
"context"
"fmt"
"io/ioutil"
"log"
"os"
"github.com/Azure-Samples/azure-sdk-for-go-samples/internal/config"
"github.com/Azure-Samples/azure-sdk-for-go-samples/internal/iam"
"github.com/Azure-Samples/azure-sdk-for-go-samples/network"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-07-01/compute"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/to"
)
func getVMClient() compute.VirtualMachinesClient {
vmClient := compute.NewVirtualMachinesClient(config.SubscriptionID())
a, _ := iam.GetResourceManagementAuthorizer()
vmClient.Authorizer = a
vmClient.AddToUserAgent(config.UserAgent())
return vmClient
}
func getVMExtensionsClient() compute.VirtualMachineExtensionsClient {
extClient := compute.NewVirtualMachineExtensionsClient(config.SubscriptionID())
a, _ := iam.GetResourceManagementAuthorizer()
extClient.Authorizer = a
extClient.AddToUserAgent(config.UserAgent())
return extClient
}
// CreateVM creates a new virtual machine with the specified name using the specified NIC.
// Username, password, and sshPublicKeyPath determine logon credentials.
func CreateVM(ctx context.Context, vmName, nicName, username, password, sshPublicKeyPath string) (vm compute.VirtualMachine, err error) {
// see the network samples for how to create and get a NIC resource
nic, _ := network.GetNic(ctx, nicName)
var sshKeyData string
if _, err = os.Stat(sshPublicKeyPath); err == nil {
sshBytes, err := ioutil.ReadFile(sshPublicKeyPath)
if err != nil {
log.Fatalf("failed to read SSH key data: %v", err)
}
sshKeyData = string(sshBytes)
} else {
sshKeyData = fakepubkey
}
vmClient := getVMClient()
future, err := vmClient.CreateOrUpdate(
ctx,
config.GroupName(),
vmName,
compute.VirtualMachine{
Location: to.StringPtr(config.Location()),
VirtualMachineProperties: &compute.VirtualMachineProperties{
HardwareProfile: &compute.HardwareProfile{
VMSize: compute.VirtualMachineSizeTypesBasicA0,
},
StorageProfile: &compute.StorageProfile{
ImageReference: &compute.ImageReference{
Publisher: to.StringPtr(publisher),
Offer: to.StringPtr(offer),
Sku: to.StringPtr(sku),
Version: to.StringPtr("latest"),
},
},
OsProfile: &compute.OSProfile{
ComputerName: to.StringPtr(vmName),
AdminUsername: to.StringPtr(username),
AdminPassword: to.StringPtr(password),
LinuxConfiguration: &compute.LinuxConfiguration{
SSH: &compute.SSHConfiguration{
PublicKeys: &[]compute.SSHPublicKey{
{
Path: to.StringPtr(
fmt.Sprintf("/home/%s/.ssh/authorized_keys",
username)),
KeyData: to.StringPtr(sshKeyData),
},
},
},
},
},
NetworkProfile: &compute.NetworkProfile{
NetworkInterfaces: &[]compute.NetworkInterfaceReference{
{
ID: nic.ID,
NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
Primary: to.BoolPtr(true),
},
},
},
},
},
},
)
if err != nil {
return vm, fmt.Errorf("cannot create vm: %v", err)
}
err = future.WaitForCompletionRef(ctx, vmClient.Client)
if err != nil {
return vm, fmt.Errorf("cannot get the vm create or update future response: %v", err)
}
return future.Result(vmClient)
}
// GetVM gets the specified VM info
func GetVM(ctx context.Context, vmName string) (compute.VirtualMachine, error) {
vmClient := getVMClient()
return vmClient.Get(ctx, config.GroupName(), vmName, compute.InstanceView)
}
// UpdateVM modifies the VM resource by getting it, updating it locally, and
// putting it back to the server.
func UpdateVM(ctx context.Context, vmName string, tags map[string]*string) (vm compute.VirtualMachine, err error) {
// get the VM resource
vm, err = GetVM(ctx, vmName)
if err != nil {
return
}
// update it
vm.Tags = tags
// PUT it back
vmClient := getVMClient()
future, err := vmClient.CreateOrUpdate(ctx, config.GroupName(), vmName, vm)
if err != nil {
return vm, fmt.Errorf("cannot update vm: %v", err)
}
err = future.WaitForCompletionRef(ctx, vmClient.Client)
if err != nil {
return vm, fmt.Errorf("cannot get the vm create or update future response: %v", err)
}
return future.Result(vmClient)
}
// DeallocateVM deallocates the selected VM
func DeallocateVM(ctx context.Context, vmName string) (osr autorest.Response, err error) {
vmClient := getVMClient()
future, err := vmClient.Deallocate(ctx, config.GroupName(), vmName)
if err != nil {
return osr, fmt.Errorf("cannot deallocate vm: %v", err)
}
err = future.WaitForCompletionRef(ctx, vmClient.Client)
if err != nil {
return osr, fmt.Errorf("cannot get the vm deallocate future response: %v", err)
}
return future.Result(vmClient)
}
// StartVM starts the selected VM
func StartVM(ctx context.Context, vmName string) (osr autorest.Response, err error) {
vmClient := getVMClient()
future, err := vmClient.Start(ctx, config.GroupName(), vmName)
if err != nil {
return osr, fmt.Errorf("cannot start vm: %v", err)
}
err = future.WaitForCompletionRef(ctx, vmClient.Client)
if err != nil {
return osr, fmt.Errorf("cannot get the vm start future response: %v", err)
}
return future.Result(vmClient)
}
// RestartVM restarts the selected VM
func RestartVM(ctx context.Context, vmName string) (osr autorest.Response, err error) {
vmClient := getVMClient()
future, err := vmClient.Restart(ctx, config.GroupName(), vmName)
if err != nil {
return osr, fmt.Errorf("cannot restart vm: %v", err)
}
err = future.WaitForCompletionRef(ctx, vmClient.Client)
if err != nil {
return osr, fmt.Errorf("cannot get the vm restart future response: %v", err)
}
return future.Result(vmClient)
}
// StopVM stops the selected VM
func StopVM(ctx context.Context, vmName string) (osr autorest.Response, err error) {
vmClient := getVMClient()
// skipShutdown parameter is optional, we are taking its default value here
future, err := vmClient.PowerOff(ctx, config.GroupName(), vmName, nil)
if err != nil {
return osr, fmt.Errorf("cannot power off vm: %v", err)
}
err = future.WaitForCompletionRef(ctx, vmClient.Client)
if err != nil {
return osr, fmt.Errorf("cannot get the vm power off future response: %v", err)
}
return future.Result(vmClient)
}