Skip to content

Commit 49efad5

Browse files
author
William Lam
committed
vSphere GOSC w/cloud-init using vSphere REST API
1 parent 2e9236a commit 49efad5

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
$cloudinit_metadata_file = "metadata-ubuntu.json"
2+
$vcenter = "fill-me-in"
3+
$vcenter_username = "fill-me-in"
4+
$vcenter_password = "fill-me-in"
5+
$vm_id = "fill-me-in"
6+
$vm_dns_server = "fill-me-in"
7+
$vm_dns_domain = "fill-me-in"
8+
$debug = $false
9+
10+
### DO NOT EDIT BEYOND HERE ###
11+
12+
$metadata = Get-Content -Raw ${cloudinit_metadata_file}
13+
$escaped_metadata = (($metadata | ConvertFrom-Json)|ConvertTo-Json -Depth 12 -Compress)
14+
15+
$pair = "${vcenter_username}:${vcenter_password}"
16+
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
17+
$base64 = [System.Convert]::ToBase64String($bytes)
18+
19+
$results = Invoke-WebRequest -Uri "https://${vcenter}/api/session" -Method POST -Headers @{"Authorization"="Basic $base64"}
20+
if($results.StatusCode -ne 201) {
21+
Write-Host -ForegroundColor Red "Failed to login to vCenter Serve, please verify your credentials are correct"
22+
break
23+
}
24+
$vmware_session_id = $results.content.replace('"','')
25+
26+
$userdata = @'
27+
#cloud-config
28+
runcmd:
29+
- hostnamectl set-hostname cloud-init-configured.primp-industries.local
30+
'@
31+
32+
$payload = [ordered]@{
33+
"spec" = [ordered]@{
34+
"configuration_spec" = [ordered]@{
35+
"cloud_config" = [ordered]@{
36+
"cloudinit" = [ordered]@{
37+
"metadata" = $escaped_metadata;
38+
"userdata" = $userdata;
39+
};
40+
"type" = "CLOUDINIT";
41+
};
42+
};
43+
"global_DNS_settings" = @{
44+
"dns_servers" = @(${vm_dns_server});
45+
"dns_suffix_list" = @(${vm_dns_domain});
46+
};
47+
"interfaces" = @(@{
48+
"adapter" = @{
49+
"ipv4" = [ordered]@{
50+
"type" = "STATIC";
51+
};
52+
};
53+
});
54+
}
55+
}
56+
57+
$body = $payload | ConvertTo-Json -depth 12
58+
59+
if($debug) {$body}
60+
61+
$results = Invoke-WebRequest -Uri "https://${vcenter}/api/vcenter/vm/${vm_id}/guest/customization" -Method PUT -Headers @{"vmware-api-session-id"=$vmware_session_id;"Content-Type"="application/json"} -Body $body
62+
if($results.StatusCode -ne 204) {
63+
Write-Host -ForegroundColor Red "Failed apply GuestOS Customization Spec"
64+
break
65+
} else {
66+
Write-Host -ForegroundColor Green "Successfully applied GuestOS Cloud-Init Customization Spec to ${vm_id}"
67+
}

0 commit comments

Comments
 (0)