Skip to content

Instantly share code, notes, and snippets.

@jnahelou
Created December 29, 2017 16:45
Show Gist options
  • Save jnahelou/1ad31134e0d2cf72106b1150db6563f7 to your computer and use it in GitHub Desktop.
Save jnahelou/1ad31134e0d2cf72106b1150db6563f7 to your computer and use it in GitHub Desktop.
Draft anti-affinity
package main
import (
"context"
"fmt"
"log"
"net/url"
"github.com/vmware/govmomi"
"github.com/vmware/govmomi/find"
"github.com/vmware/govmomi/vim25/types"
)
type Config struct {
User string
Password string
VSphereServer string
InsecureFlag bool
Debug bool
DebugPath string
DebugPathRun string
}
const defaultAPITimeout = 600
func boolPtr(b bool) *bool {
return &b
}
func main() {
c := Config{User: "CHANGEME", Password: "CHANGEME", VSphereServer: "CHANGEME", InsecureFlag: true, Debug: true, DebugPath: "", DebugPathRun: ""}
dc := "CHANGEME"
u, err := url.Parse("https://" + c.VSphereServer + "/sdk")
if err != nil {
log.Fatalf("Error parse url: %s", err)
}
u.User = url.UserPassword(c.User, c.Password)
if err != nil {
log.Fatalf("Error setting up client debug: %s", err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
vimClient, err := govmomi.NewClient(ctx, u, c.InsecureFlag)
if err != nil {
log.Fatalf("Error setting up client: %s", err)
}
log.Printf("[INFO] VMWare vSphere Client configured for URL: %s", c.VSphereServer)
finder := find.NewFinder(vimClient.Client, true)
dcid, err := finder.Datacenter(context.TODO(), dc)
if err != nil {
log.Fatalf("Unable to find datacenter : %v", err)
}
id := dcid.Reference().Value
fmt.Printf("%v", id)
finder.SetDatacenter(dcid)
clusters, err := finder.ClusterComputeResourceList(context.TODO(), "CHANGEME")
if err != nil {
log.Fatalf("Unable to find cluster : %v", err)
}
cid := clusters[0].Reference().Value
fmt.Printf("%v", cid)
cluster := clusters[0]
vms, err := finder.VirtualMachineList(ctx, "CHANGEME*")
if err != nil {
log.Fatalf("Virtual machines errors: %s", err)
return
}
fmt.Printf("%v", vms)
var refVMs []types.ManagedObjectReference
for _, vm := range vms {
ref := types.ManagedObjectReference{
Type: "VirtualMachine",
Value: vm.Reference().Value,
}
refVMs = append(refVMs, ref)
}
var ruleSpecs []types.ClusterRuleSpec
aaRule := &types.ClusterAntiAffinityRuleSpec{}
aaRule.Name = "test"
aaRule.Mandatory = boolPtr(false)
aaRule.Enabled = boolPtr(true)
aaRule.Vm = refVMs
spec := types.ClusterRuleSpec{}
spec.Operation = types.ArrayUpdateOperationAdd
spec.Info = aaRule
ruleSpecs = append(ruleSpecs, spec)
clusterSpec := &types.ClusterConfigSpecEx{RulesSpec: ruleSpecs}
task, err := cluster.Reconfigure(context.TODO(), clusterSpec, true)
if err != nil {
log.Fatalf("%v", err)
}
fmt.Print("waiting for cluster reconfig...")
err = task.Wait(context.TODO())
fmt.Println("completed")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment