-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
vmscaleset.go
321 lines (289 loc) · 9.96 KB
/
vmscaleset.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package azuretasks
import (
"context"
"encoding/base64"
"fmt"
"strings"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2020-06-01/compute"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/klog/v2"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/cloudup/azure"
)
// SubnetID contains the resource ID/names required to construct a subnet ID.
type SubnetID struct {
SubscriptionID string
ResourceGroupName string
VirtualNetworkName string
SubnetName string
}
// String returns the subnet ID in the path format.
func (s *SubnetID) String() string {
return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/virtualNetworks/%s/subnets/%s",
s.SubscriptionID,
s.ResourceGroupName,
s.VirtualNetworkName,
s.SubnetName)
}
// ParseSubnetID parses a given subnet ID string and returns a SubnetID.
func ParseSubnetID(s string) (*SubnetID, error) {
l := strings.Split(s, "/")
if len(l) != 11 {
return nil, fmt.Errorf("malformed format of subnet ID: %s, %d", s, len(l))
}
return &SubnetID{
SubscriptionID: l[2],
ResourceGroupName: l[4],
VirtualNetworkName: l[8],
SubnetName: l[10],
}, nil
}
//go:generate fitask -type=VMScaleSet
// VMScaleSet is an Azure VM Scale Set.
type VMScaleSet struct {
Name *string
Lifecycle *fi.Lifecycle
ResourceGroup *ResourceGroup
VirtualNetwork *VirtualNetwork
Subnet *Subnet
StorageProfile *VMScaleSetStorageProfile
// RequirePublicIP is set to true when VMs require public IPs.
RequirePublicIP *bool
// SKUName specifies the SKU of of the VM Scale Set
SKUName *string
// Capacity specifies the number of virtual machines the VM Scale Set.
Capacity *int64
// ComputerNamePrefix is the prefix of each VM name of the form <prefix><base-36-instance-id>.
// See https://docs.microsoft.com/en-us/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-instance-ids.
ComputerNamePrefix *string
// AdmnUser specifies the name of the administrative account.
AdminUser *string
SSHPublicKey *string
// CustomData is the user data configuration
CustomData fi.Resource
Tags map[string]*string
PrincipalID *string
}
// VMScaleSetStorageProfile wraps *compute.VirtualMachineScaleSetStorageProfile
// and implements fi.HasDependencies.
//
// If we don't implement the interface and directly use
// compute.VirtualMachineScaleSetStorageProfile in VMScaleSet, the
// topological sort on VMScaleSet will fail as StorageProfile doesn't
// implement a proper interface.
type VMScaleSetStorageProfile struct {
*compute.VirtualMachineScaleSetStorageProfile
}
var _ fi.HasDependencies = &VMScaleSetStorageProfile{}
// GetDependencies returns a slice of tasks on which the tasks depends on.
func (p *VMScaleSetStorageProfile) GetDependencies(tasks map[string]fi.Task) []fi.Task {
return nil
}
var _ fi.Task = &VMScaleSet{}
var _ fi.CompareWithID = &VMScaleSet{}
// CompareWithID returns the Name of the VM Scale Set.
func (s *VMScaleSet) CompareWithID() *string {
return s.Name
}
// Find discovers the VMScaleSet in the cloud provider.
func (s *VMScaleSet) Find(c *fi.Context) (*VMScaleSet, error) {
cloud := c.Cloud.(azure.AzureCloud)
l, err := cloud.VMScaleSet().List(context.TODO(), *s.ResourceGroup.Name)
if err != nil {
return nil, err
}
var found *compute.VirtualMachineScaleSet
for _, v := range l {
if *v.Name == *s.Name {
found = &v
break
}
}
if found == nil {
return nil, nil
}
profile := found.VirtualMachineProfile
nwConfigs := *profile.NetworkProfile.NetworkInterfaceConfigurations
if len(nwConfigs) != 1 {
return nil, fmt.Errorf("unexpected number of network configs found for VM ScaleSet %s: %d", *s.Name, len(nwConfigs))
}
nwConfig := nwConfigs[0]
ipConfigs := *nwConfig.VirtualMachineScaleSetNetworkConfigurationProperties.IPConfigurations
if len(ipConfigs) != 1 {
return nil, fmt.Errorf("unexpected number of IP configs found for VM ScaleSet %s: %d", *s.Name, len(ipConfigs))
}
ipConfig := ipConfigs[0]
subnetID, err := ParseSubnetID(*ipConfig.Subnet.ID)
if err != nil {
return nil, fmt.Errorf("failed to parse subnet ID %s", *ipConfig.Subnet.ID)
}
osProfile := profile.OsProfile
sshKeys := *osProfile.LinuxConfiguration.SSH.PublicKeys
if len(sshKeys) != 1 {
return nil, fmt.Errorf("unexpected number of SSH keys found for VM ScaleSet %s: %d", *s.Name, len(sshKeys))
}
// TODO(kenji): Do not check custom data as Azure doesn't
// populate (https://github.com/Azure/azure-cli/issues/5866).
// Find a way to work around this.
return &VMScaleSet{
Name: s.Name,
Lifecycle: s.Lifecycle,
ResourceGroup: &ResourceGroup{
Name: s.ResourceGroup.Name,
},
VirtualNetwork: &VirtualNetwork{
Name: to.StringPtr(subnetID.VirtualNetworkName),
},
Subnet: &Subnet{
Name: to.StringPtr(subnetID.SubnetName),
},
StorageProfile: &VMScaleSetStorageProfile{
VirtualMachineScaleSetStorageProfile: profile.StorageProfile,
},
RequirePublicIP: to.BoolPtr(ipConfig.PublicIPAddressConfiguration != nil),
SKUName: found.Sku.Name,
Capacity: found.Sku.Capacity,
ComputerNamePrefix: osProfile.ComputerNamePrefix,
AdminUser: osProfile.AdminUsername,
SSHPublicKey: sshKeys[0].KeyData,
Tags: found.Tags,
PrincipalID: found.Identity.PrincipalID,
}, nil
}
// Run implements fi.Task.Run.
func (s *VMScaleSet) Run(c *fi.Context) error {
c.Cloud.(azure.AzureCloud).AddClusterTags(s.Tags)
return fi.DefaultDeltaRunMethod(s, c)
}
// CheckChanges returns an error if a change is not allowed.
func (s *VMScaleSet) CheckChanges(a, e, changes *VMScaleSet) error {
if a == nil {
// Check if required fields are set when a new resource is created.
if e.Name == nil {
return fi.RequiredField("Name")
}
return nil
}
// Check if unchangeable fields won't be changed.
if changes.Name != nil {
return fi.CannotChangeField("Name")
}
return nil
}
// RenderAzure creates or updates a VM Scale Set.
func (s *VMScaleSet) RenderAzure(t *azure.AzureAPITarget, a, e, changes *VMScaleSet) error {
if a == nil {
klog.Infof("Creating a new VM Scale Set with name: %s", fi.StringValue(e.Name))
} else {
klog.Infof("Updating a VM Scale Set with name: %s", fi.StringValue(e.Name))
}
name := *e.Name
var customData *string
if e.CustomData != nil {
d, err := fi.ResourceAsBytes(e.CustomData)
if err != nil {
return fmt.Errorf("error rendering CustomData: %s", err)
}
customData = to.StringPtr(base64.StdEncoding.EncodeToString(d))
}
osProfile := &compute.VirtualMachineScaleSetOSProfile{
ComputerNamePrefix: e.ComputerNamePrefix,
AdminUsername: e.AdminUser,
CustomData: customData,
LinuxConfiguration: &compute.LinuxConfiguration{
SSH: &compute.SSHConfiguration{
PublicKeys: &[]compute.SSHPublicKey{
{
Path: to.StringPtr(fmt.Sprintf("/home/%s/.ssh/authorized_keys", *e.AdminUser)),
KeyData: to.StringPtr(*e.SSHPublicKey),
},
},
},
DisablePasswordAuthentication: to.BoolPtr(true),
},
}
subnetID := SubnetID{
SubscriptionID: t.Cloud.SubscriptionID(),
ResourceGroupName: *e.ResourceGroup.Name,
VirtualNetworkName: *e.VirtualNetwork.Name,
SubnetName: *e.Subnet.Name,
}
ipConfigProperties := &compute.VirtualMachineScaleSetIPConfigurationProperties{
Subnet: &compute.APIEntityReference{
ID: to.StringPtr(subnetID.String()),
},
Primary: to.BoolPtr(true),
PrivateIPAddressVersion: compute.IPv4,
}
if *e.RequirePublicIP {
ipConfigProperties.PublicIPAddressConfiguration = &compute.VirtualMachineScaleSetPublicIPAddressConfiguration{
Name: to.StringPtr(name + "-publicipconfig"),
VirtualMachineScaleSetPublicIPAddressConfigurationProperties: &compute.VirtualMachineScaleSetPublicIPAddressConfigurationProperties{
PublicIPAddressVersion: compute.IPv4,
},
}
}
networkConfig := compute.VirtualMachineScaleSetNetworkConfiguration{
Name: to.StringPtr(name + "-netconfig"),
VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{
Primary: to.BoolPtr(true),
EnableIPForwarding: to.BoolPtr(true),
IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{
{
Name: to.StringPtr(name + "-ipconfig"),
VirtualMachineScaleSetIPConfigurationProperties: ipConfigProperties,
},
},
},
}
vmss := compute.VirtualMachineScaleSet{
Location: to.StringPtr(t.Cloud.Region()),
Sku: &compute.Sku{
Name: e.SKUName,
Capacity: e.Capacity,
},
VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{
UpgradePolicy: &compute.UpgradePolicy{
Mode: compute.UpgradeModeManual,
},
VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{
OsProfile: osProfile,
StorageProfile: e.StorageProfile.VirtualMachineScaleSetStorageProfile,
NetworkProfile: &compute.VirtualMachineScaleSetNetworkProfile{
NetworkInterfaceConfigurations: &[]compute.VirtualMachineScaleSetNetworkConfiguration{
networkConfig,
},
},
},
},
// Assign a system-assigned managed identity so that
// Azure creates an identity for VMs and provision
// its credentials on the VMs.
Identity: &compute.VirtualMachineScaleSetIdentity{
Type: compute.ResourceIdentityTypeSystemAssigned,
},
Tags: e.Tags,
}
result, err := t.Cloud.VMScaleSet().CreateOrUpdate(
context.TODO(),
*e.ResourceGroup.Name,
name,
vmss)
if err != nil {
return err
}
e.PrincipalID = result.Identity.PrincipalID
return nil
}