Merge pull request #2 from vmware/master

sync
This commit is contained in:
Wouter Kursten
2018-04-07 09:19:25 +02:00
committed by GitHub
10 changed files with 691 additions and 16 deletions

View File

@@ -5101,7 +5101,7 @@ function Get-HVPoolStorageObject {
$storageObject.Datastores = Get-HVDatastore -DatastoreInfoList $datastoreList -DatastoreNames $datastores -DsStorageOvercommit $StorageOvercommit
if ($useSeparateDatastoresReplicaAndOSDisks) {
$storageObject.ViewComposerStorageSettings.UseSeparateDatastoresReplicaAndOSDisks = $UseSeparateDatastoresReplicaAndOSDisks
$storageObject.ViewComposerStorageSettings.ReplicaDiskDatastore = ($datastoreInfoList | Where-Object { ($_.datastoredata.name -eq $replicaDiskDatastore) -or ($_.datastoredata.path -eq $replicaDiskDatastore)}).id
$storageObject.ViewComposerStorageSettings.ReplicaDiskDatastore = ($datastoreList | Where-Object { ($_.datastoredata.name -eq $replicaDiskDatastore) -or ($_.datastoredata.path -eq $replicaDiskDatastore)}).id
}
}
if ($storageObject.Datastores.Count -eq 0) {
@@ -8220,13 +8220,12 @@ function Remove-HVEntitlement {
$confirmFlag = Get-HVConfirmFlag -keys $PsBoundParameters.Keys
$AndFilter = @()
$results = $null
$userInfo = Get-UserInfo -UserName $User
$UserOrGroupName = $userInfo.Name
$Domain = $userInfo.Domain
$nameFilter = Get-HVQueryFilter 'base.name' -Eq $UserOrGroupName
$doaminFilter = Get-HVQueryFilter 'base.domain' -Eq $Domain
$IsGroup = ($Type -eq 'Group')
$groupFilter = Get-HVQueryFilter 'base.group' -Eq $IsGroup
if ($User) {
$userInfo = Get-UserInfo -UserName $User
$AndFilter += Get-HVQueryFilter 'base.loginName' -Eq $userInfo.Name
$AndFilter += Get-HVQueryFilter 'base.domain' -Eq $userInfo.Domain
}
$AndFilter += Get-HVQueryFilter 'base.group' -Eq ($Type -eq 'Group')
[VMware.Hv.UserEntitlementId[]] $userEntitlements = $null
if ($ResourceName) {
$info = $services.PodFederation.PodFederation_get()
@@ -8242,10 +8241,15 @@ function Remove-HVEntitlement {
$results = Get-HVQueryResult -EntityType EntitledUserOrGroupLocalSummaryView -Filter $filters -HvServer $HvServer
if ($results) {
foreach ($result in $Results) {
$userEntitlements = $result.localData.desktopUserEntitlements
Write-Host $userEntitlements.Length " desktopUserEntitlement(s) will be removed for UserOrGroup " $user
$deleteResources = @()
for ($i = 0; $i -lt $result.localdata.desktops.length; $i++) {
if ($ResourceObjs.Id.id -eq $result.localdata.Desktops[$i].id) {
$deleteResources += $result.localdata.DesktopUserEntitlements[$i]
}
}
Write-Host $deleteResources.Length " desktopUserEntitlement(s) will be removed for UserOrGroup " $user
if (!$confirmFlag -OR $pscmdlet.ShouldProcess($User)) {
$services.UserEntitlement.UserEntitlement_DeleteUserEntitlements($userEntitlements)
$services.UserEntitlement.UserEntitlement_DeleteUserEntitlements($deleteResources)
}
}
}
@@ -8347,10 +8351,15 @@ function Remove-HVEntitlement {
$results = Get-HVQueryResult -EntityType EntitledUserOrGroupGlobalSummaryView -Filter $AndFilter -HvServer $HvServer
if ($results) {
foreach ($result in $Results) {
$userEntitlements = $result.globalData.globalUserEntitlements
Write-Host $userEntitlements.Length " GlobalEntitlement(s) will be removed for UserOrGroup " $user
$deleteResources = @()
for ($i = 0; $i -lt $result.globalData.globalEntitlements.length; $i++) {
if ($ResourceObjs.Id.id -eq $result.globalData.globalEntitlements[$i].id) {
$deleteResources += $result.globalData.globalUserEntitlements[$i]
}
}
Write-Host $deleteResources.Length " GlobalEntitlement(s) will be removed for UserOrGroup " $user
if (!$confirmFlag -OR $pscmdlet.ShouldProcess($User)) {
$services.UserEntitlement.UserEntitlement_DeleteUserEntitlements($userEntitlements)
$services.UserEntitlement.UserEntitlement_DeleteUserEntitlements($deleteResources)
}
}
@@ -8447,6 +8456,11 @@ PARAMETER Key
[Parameter(Mandatory = $false)]
$Value,
[Parameter(Mandatory = $false)]
[ValidatePattern("^.+?[@\\].+?$")]
[string]
$User,
[Parameter(Mandatory = $false)]
$HvServer = $null
)
@@ -8474,6 +8488,11 @@ PARAMETER Key
$machineList.add($macineObj.id, $macineObj.base.Name)
}
}
if ($machineList.count -eq 0) {
Write-Error "Machine $machineName not found - try fqdn"
[System.gc]::collect()
return
}
} elseif ($PSCmdlet.MyInvocation.ExpectingInput -or $Machine) {
foreach ($item in $machine) {
if (($item.GetType().name -eq 'MachineNamesView') -or ($item.GetType().name -eq 'MachineInfo')) {
@@ -8491,6 +8510,22 @@ PARAMETER Key
} elseif ($key -or $value) {
Write-Error "Both key:[$key] and value:[$value] needs to be specified"
}
if ($User) {
$userInfo = Get-UserInfo -UserName $User
$UserOrGroupName = $userInfo.Name
$Domain = $userInfo.Domain
$filter1 = Get-HVQueryFilter 'base.name' -Eq $UserOrGroupName
$filter2 = Get-HVQueryFilter 'base.domain' -Eq $Domain
$filter3 = Get-HVQueryFilter 'base.group' -Eq $false
$andFilter = Get-HVQueryFilter -And -Filters @($filter1, $filter2, $filter3)
$results = Get-HVQueryResult -EntityType ADUserOrGroupSummaryView -Filter $andFilter -HvServer $HvServer
if ($results.length -ne 1) {
Write-Host "Unable to find specific user with given search parameters"
[System.gc]::collect()
return
}
$updates += Get-MapEntry -key 'base.user' -value $results[0].id
}
if ($Maintenance) {
if ($Maintenance -eq 'ENTER_MAINTENANCE_MODE') {

Binary file not shown.

View File

@@ -654,7 +654,7 @@ Function Get-VMCFirewallRule {
.DESCRIPTION
Removes VMC Firewall Rule given Rule Id
.EXAMPLE
Import-VMCFirewallRule -OrgName <Org Name> -SDDCName <SDDC Name> -GatewayType <MGW or CGW> -RuleId <Rule Id>
Remove-VMCFirewallRule -OrgName <Org Name> -SDDCName <SDDC Name> -GatewayType <MGW or CGW> -RuleId <Rule Id>
#>
param(
[Parameter(Mandatory=$false)][String]$SDDCName,
@@ -688,5 +688,171 @@ Function Get-VMCFirewallRule {
$firewallService.delete($orgId,$sddcId,$EdgeId,$RuleId)
}
Function Get-VMCLogicalNetwork {
<#
.NOTES
===========================================================================
Created by: Kyle Ruddy
Date: 03/06/2018
Organization: VMware
Blog: https://thatcouldbeaproblem.com
Twitter: @kmruddy
===========================================================================
Export-ModuleMember -Function 'Get-VMCCommand', 'Connect-VMCVIServer', 'Get-VMCOrg', 'Get-VMCSDDC', 'Get-VMCTask', 'Get-VMCSDDCDefaultCredential', 'Get-VMCSDDCPublicIP', 'Get-VMCVMHost', 'Get-VMCSDDCVersion', 'Get-VMCFirewallRule', 'Export-VMCFirewallRule', 'Import-VMCFirewallRule', 'Remove-VMCFirewallRule'
.SYNOPSIS
Retruns VMC Logical Networks for a given SDDC
.DESCRIPTION
Retruns VMC Logical Networks for a given SDDC
.EXAMPLE
Get-VMCLogicalNetwork -OrgName <Org Name> -SDDCName <SDDC Name>
.EXAMPLE
Get-VMCLogicalNetwork -OrgName <Org Name> -SDDCName <SDDC Name> -LogicalNetworkName <Logical Network Name>
#>
param(
[Parameter(Mandatory=$true)][String]$SDDCName,
[Parameter(Mandatory=$true)][String]$OrgName,
[Parameter(Mandatory=$false)][String]$LogicalNetworkName
)
$orgId = (Get-VMCOrg -Name $OrgName).Id
$sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id
if(-not $orgId) {
Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input"
break
}
if(-not $sddcId) {
Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input"
break
}
$logicalNetworkService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.logical
$logicalNetworks = ($logicalNetworkService.get_0($orgId, $sddcId)).data | Sort-Object -Property id
if($LogicalNetworkName) {
$logicalNetworks = $logicalNetworks | Where-Object {$_.Name -eq $LogicalNetworkName}
}
$results = @()
foreach ($logicalNetwork in $logicalNetworks) {
$tmp = [pscustomobject] @{
ID = $logicalNetwork.id;
Name = $logicalNetwork.name;
SubnetMask = $logicalNetwork.subnets.address_groups.prefix_length;
Gateway = $logicalNetwork.subnets.address_groups.primary_address;
DHCPipRange = $logicalNetwork.dhcp_configs.ip_pools.ip_range;
DHCPdomain = $logicalNetwork.dhcp_configs.ip_pools.domain_name;
CGatewayID = $logicalNetwork.cgw_id;
CGateway = $logicalNetwork.cgw_name;
}
$results+=$tmp
}
$results
}
Function Remove-VMCLogicalNetwork {
<#
.NOTES
===========================================================================
Created by: Kyle Ruddy
Date: 03/06/2018
Organization: VMware
Blog: https://thatcouldbeaproblem.com
Twitter: @kmruddy
===========================================================================
.SYNOPSIS
Removes Logical Network given ID
.DESCRIPTION
Removes Logical Network given ID
.EXAMPLE
Remove-VMCLogicalNetwork -OrgName <Org Name> -SDDCName <SDDC Name> -LogicalNetworkName <LogicalNetwork Name>
#>
[cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')]
param(
[Parameter(Mandatory=$true)][String]$SDDCName,
[Parameter(Mandatory=$true)][String]$OrgName,
[Parameter(Mandatory=$true)][String]$LogicalNetworkName
)
if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break }
$orgId = (Get-VMCOrg -Name $OrgName).Id
$sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id
$lsId = (Get-VMCLogicalNetwork -OrgName $OrgName -SDDCName $SDDCName -LogicalNetworkName $LogicalNetworkName).Id
if(-not $orgId) {
Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input"
break
}
if(-not $sddcId) {
Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input"
break
}
if(-not $lsId) {
Write-Host -ForegroundColor red "Unable to find SDDC $LogicalNetworkName, please verify input"
break
}
$logicalNetworkService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.logical
$logicalNetworkService.delete($orgId,$sddcId,$lsId)
}
Function New-VMCLogicalNetwork {
<#
.NOTES
===========================================================================
Created by: Kyle Ruddy
Date: 03/06/2018
Organization: VMware
Blog: https://thatcouldbeaproblem.com
Twitter: @kmruddy
===========================================================================
.SYNOPSIS
Creates a new Logical Network
.DESCRIPTION
Creates a new Logical Network
.EXAMPLE
New-VMCLogicalNetwork -OrgName <Org Name> -SDDCName <SDDC Name> -LogicalNetworkName <LogicalNetwork Name> -SubnetMask <Subnet Mask Prefix> -Gateway <Gateway IP Address>
#>
[cmdletbinding(SupportsShouldProcess = $true,ConfirmImpact='High')]
param(
[Parameter(Mandatory=$true)][String]$SDDCName,
[Parameter(Mandatory=$true)][String]$OrgName,
[Parameter(Mandatory=$true)][String]$LogicalNetworkName,
[Parameter(Mandatory=$true)][String]$SubnetMask,
[Parameter(Mandatory=$true)][String]$Gateway
)
if (-not $global:DefaultVMCServers) { Write-error "No VMC Connection found, please use the Connect-VMC to connect"; break }
$orgId = (Get-VMCOrg -Name $OrgName).Id
$sddcId = (Get-VMCSDDC -Name $SDDCName -Org $OrgName).Id
if(-not $orgId) {
Write-Host -ForegroundColor red "Unable to find Org $OrgName, please verify input"
break
}
if(-not $sddcId) {
Write-Host -ForegroundColor red "Unable to find SDDC $SDDCName, please verify input"
break
}
$logicalNetworkService = Get-VmcService com.vmware.vmc.orgs.sddcs.networks.logical
$logicalNetworkSpec = $logicalNetworkService.Help.create.sddc_network.Create()
$logicalNetworkSpec.name = $LogicalNetworkName
$logicalNetworkSpec.cgw_id = "edge-2"
$logicalNetworkSpec.cgw_name = "SDDC-CGW-1"
$logicalNetworkAddressGroupSpec = $logicalNetworkService.Help.create.sddc_network.subnets.address_groups.Element.Create()
$logicalNetworkAddressGroupSpec.prefix_length = $SubnetMask
$logicalNetworkAddressGroupSpec.primary_address = $Gateway
$logicalNetworkSpec.subnets.address_groups.Add($logicalNetworkAddressGroupSpec) | Out-Null
$logicalNetworkService.create($orgId, $sddcId, $logicalNetworkSpec)
Get-VMCLogicalNetwork -OrgName $OrgName -SDDCName $SDDCName -LogicalNetworkName $LogicalNetworkName
}
Export-ModuleMember -Function 'Get-VMCCommand', 'Connect-VMCVIServer', 'Get-VMCOrg', 'Get-VMCSDDC', 'Get-VMCTask', 'Get-VMCSDDCDefaultCredential', 'Get-VMCSDDCPublicIP', 'Get-VMCVMHost', 'Get-VMCSDDCVersion', 'Get-VMCFirewallRule', 'Export-VMCFirewallRule', 'Import-VMCFirewallRule', 'Remove-VMCFirewallRule', 'Get-VMCLogicalNetwork', 'Remove-VMCLogicalNetwork', 'New-VMCLogicalNetwork'

View File

@@ -0,0 +1,110 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>VMware Cloud on AWS VM Request-O-Matic</title><!-- Get a pretty style sheet -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div align="center"><img src="vmc-sticker.png" width="200"></div>
<h2 align="center">VM Request-O-Matic</h2>
<div class="container-fluid">
<div class="row">
<div class="col-xs-12 col-sm-6 col-sm-push-3">
<p>Use this form to create a new VM on VMware Cloud on AWS</p>
<form id="vmForm" name="vmForm">
<div class="form-group">
<label for="username">Your Name</label> <input class="form-control" id="username" name="username" placeholder="Bob Bobber" required="" type="tel">
</div>
<div class="form-group">
<label for="emailaddress">Email Address</label> <input class="form-control" id="emailaddress" name="emailaddress" placeholder="Bob@bobber.com" required="" type="tel">
</div>
<div class="form-group">
<label for="vmtype">VM Type</label> <select class="form-control" id="vmtype" name="vmtype" required="">
<option selected value="40ff3b8c-f6c7-4aa3-8db8-bb631e16ffae">
Windows 10 Desktop (4 CPU, 4GB RAM, 25GB HDD)
</option>
<option value="37561477-a8c2-4aed-9fce-1bb38557c2b0">
Windows Server 2016 (8 CPU, 12GB RAM, 100GB HDD)
</option>
<option value="40ff3b8c-f6c7-4aa3-8db8-bb631e16ffae">
Ubuntu Desktop (4 CPU, 4GB RAM, 25GB HDD)
</option>
<option value="575fbc82-fb0f-4c1f-95c3-3b0fb0613b82">
Ubuntu Server (8 CPU, 12GB RAM, 100GB HDD)
</option>
</select>
</div><button class="btn btn-default" type="submit">Create a VM!</button>
</form>
</div>
<div class="hidden alert alert-success" id="success" role="alert">
<br>
<br>
Success! Your VM was created successfully, check your email for login instructions.
</div>
<div class="hidden alert alert-danger" id="error" role="alert">
<br>
<br>
Dang. Something went wrong, check your email for next steps.
</div>
</div>
</div><!-- get the AWS Javascript library -->
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.98.0.min.js">
</script>
<script>
// set up Amazon Cognito (create a federated identity pool)
// https://us-west-2.console.aws.amazon.com/cognito/create
// Initialize the Amazon Cognito credentials provider
AWS.config.region = 'us-west-2'; // Region
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'us-west-2:e93c4c86-240d-4966-86ef-e56cf60ba468',
});
function invokeLambda( e ){
<!-- pull the variables out of the form -->
var username = document.getElementById('username'),
emailaddress = document.getElementById('emailaddress');
var selectid = document.getElementById("vmtype");
var selectedvm = selectid.options[selectid.selectedIndex].value;
// create JSON object for parameters for invoking Lambda function
var lambdaParams = {
FunctionName : 'vm-request-o-matic',
InvocationType : 'RequestResponse',
LogType : 'None',
Payload: JSON.stringify({
username: username.value,
emailaddress: emailaddress.value,
vmtype: selectedvm})
};
// create variable to hold data returned by the Lambda function
var lambdaResults;
var lambda = new AWS.Lambda({region: 'us-west-2', apiVersion: '2015-03-31'});
e.preventDefault();
lambda.invoke(lambdaParams, function(error, data) {
if (error) {
prompt(error);
} else {
lambdaResults = JSON.parse(data.Payload);
prompt(lambdaResults);
}
});
};
document.getElementById('vmForm').addEventListener('submit', invokeLambda);
</script>
</body>
</html>

View File

@@ -0,0 +1,22 @@
This is a simple 'serverless application' that allows you to create a VM in
an SDDC on VMware Cloud on AWS using a few cool tools including: Lambda,
Cognito, S3, and VMware Cloud on AWS.
Matt Dreyer
August 16, 2017
To make this work you need to do the following:
1. Make sure that the vCenter in your SDDC is publicly accessible, or painfully configure Lambda
to run in an VPC and NAT to a specific IP address (which requires even more IAM roles for VPC access).
2. Create a working VM, and then Clone it to an OVF template in Content Library
3. Use the vCenter API browser to discover the UUID of the your OVF template
4. Update the HTML in index.html to match the UUID(s) of the VMs you wish to deploy
5. Create a new Lambda function and upload vm-request-form.zip as your code
6. Create a new Cognito "Federated Identity" for "anonymous access"
7. Update the javascript in index.html to match your new Cognito role
8. Create an S3 bucket and configure it for Webhosting
9. Upload index.html and vmc-sticker.png into your bucket
10. Muck with IAM until Lambda and Cognito get along together
(required Cognito role permissions are AWSLambdaExecute and AWSLambdaRole)

View File

@@ -0,0 +1,193 @@
"""
Basic Tests against the Skyscraper API
VMC API documentation available at https://vmc.vmware.com/swagger/index.html#/
CSP API documentation is available at https://saas.csp.vmware.com/csp/gateway/api-docs
vCenter API documentation is available at https://code.vmware.com/apis/191/vsphere-automation
Matt Dreyer
August 15, 2017
You can install python 3.6 from https://www.python.org/downloads/windows/
You can install the dependent python packages locally (handy for Lambda) with:
pip install requests -t . --upgrade
pip install simplejson -t . --upgrade
pip install certifi -t . --upgrade
pip install pyvim -t . --upgrade
pip install datetime -t . --upgrade
"""
import requests #need this for Get/Post/Delete
import simplejson as json #need this for JSON
import datetime #need this for a time stamp
# To use this script you need to create an OAuth Refresh token for your Org
# You can generate an OAuth Refresh Token using the tool at vmc.vmware.com
# https://console.cloud.vmware.com/csp/gateway/portal/#/user/tokens
strAccessKey = "your key goes here"
#where are our service end points
strProdURL = "https://vmc.vmware.com"
strCSPProdURL = "https://console.cloud.vmware.com"
slackURL = "https://hooks.slack.com/services/T6Mrrrrr/B6TSrrrrr/RUldlEzzeY0Dy3drrrrrr"
#make a datestamp
rightnow = str(datetime.datetime.now())
rightnow = rightnow.split(".")[0] #get rid of miliseconds
def getAccessToken(myKey):
params = {'refresh_token': myKey}
headers = {'Content-Type': 'application/json'}
response = requests.post('https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/authorize', params=params, headers=headers)
json_response = response.json()
access_token = json_response['access_token']
# debug only
# print(response.status_code)
# print(response.json())
return access_token
#-------------------- Figure out which Org we are in
def getTenantID(sessiontoken):
myHeader = {'csp-auth-token' : sessiontoken}
response = requests.get( strProdURL + '/vmc/api/orgs', headers=myHeader)
# debug only
# print(response.status_code)
# print(response.json())
# parse the response to grab our tenant id
jsonResponse = response.json()
strTenant = str(jsonResponse[0]['id'])
return(strTenant)
#---------------Login to vCenter and get an API token
# this will only work if the MGW firewall rules are configured appropriately
def vCenterLogin(sddcID, tenantid, sessiontoken):
#Get the vCenter details from VMC
myHeader = {'csp-auth-token' : sessiontoken}
myURL = strProdURL + "/vmc/api/orgs/" + tenantid + "/sddcs/" + sddcID
response = requests.get(myURL, headers=myHeader)
jsonResponse = response.json()
vCenterURL = jsonResponse['resource_config']['vc_ip']
vCenterUsername = jsonResponse['resource_config']['cloud_username']
vCenterPassword = jsonResponse['resource_config']['cloud_password']
#Now get an API token from vcenter
myURL = vCenterURL + "rest/com/vmware/cis/session"
response = requests.post(myURL, auth=(vCenterUsername,vCenterPassword))
token = response.json()['value']
vCenterAuthHeader = {'vmware-api-session-id':token}
return(vCenterURL, vCenterAuthHeader)
#------------ Get vCenter inventory and post to slack
def getSDDCInventory(sddcID, tenantid, sessiontoken):
#first we need to get an authentication token from vCenter
vCenterURL, vCenterAuthHeader = vCenterLogin(sddcID, tenantid, sessiontoken)
#now let's get a VM count
# for all vms use this : myURL = vCenterURL + "rest/vcenter/vm"
# for management vms use this: myURL = vCenterURL + "rest/vcenter/vm?filter.resource_pools=resgroup-54"
# for workload vms use this: myURL = vCenterURL + "rest/vcenter/vm?filter.resource_pools=resgroup-55"
myURL = vCenterURL + "rest/vcenter/vm"
response = requests.get(myURL, headers=vCenterAuthHeader)
#deal with vAPI wrapping
vms = response.json()['value']
poweredon = []
poweredoff = []
for i in vms:
if i['power_state'] == "POWERED_ON":
poweredon.append(i['name'])
else:
poweredoff.append(i['name'])
vm_on = len(poweredon)
vm_off = len(poweredoff)
#next let's figure out how much space we have left on the datastore
myURL = vCenterURL + "rest/vcenter/datastore"
response = requests.get(myURL, headers=vCenterAuthHeader)
#grab the workload datastore
datastore = response.json()['value'][1]
ds_total = int(datastore['capacity'])
ds_free = int(datastore['free_space'])
usage = int((ds_free / ds_total) * 100)
freeTB = ( ds_free / 1024 / 1024 / 1024 / 1024)
jsonSlackMessage = {'text': \
"SDDC Inventory Report\n" + \
"\t " + str(vm_on) + " Virtual Machines Running\n" + \
"\t " + str(vm_off) + " Virtual Machines Powered Off\n" + \
"\t " + str(usage) + "% Datastore Capacity Remaining (" + str(int(freeTB)) + " TB)"}
postSlack(slackURL, jsonSlackMessage)
return()
#------------------ Post something to Slack
# Slack API info can be found at https://api.slack.com/incoming-webhooks
# https://api.slack.com/tutorials/slack-apps-hello-world
# Need to create a new App using the Slack API App Builder -- it only needs to do one thing - catch a webhook
def postSlack(slackURL, slackJSONData):
slackData = json.dumps(slackJSONData)
myHeader = {'Content-Type': 'application/json'}
response = requests.post(slackURL, slackData, headers=myHeader)
if response.status_code != 200:
raise ValueError(
'Request to slack returned an error %s, the response is:\n%s'
% (response.status_code, response.text)
)
return
#--------------------------------------------
#---------------- Main ----------------------
#--------------------------------------------
def lambda_handler(event, context):
sddcID = " your id goes here"
tenantID = "your tenant goes here"
#Get our access token
sessiontoken = getAccessToken(strAccessKey)
#get the inventory and dump it to
getSDDCInventory(sddcID, tenantID, sessiontoken)
return
#testing only
#lambda_handler(0, 0)

View File

@@ -0,0 +1,50 @@
<#
.NOTES
===========================================================================
Created by: Alan Renouf
Date: March 27, 2018
Organization: VMware
Blog: virtu-al.net
Twitter: @alanrenouf
===========================================================================
.DESCRIPTION
This will allow you to create multiple workloads in the correct locations on VMware Cloud on AWS.
.Example
$vCenter = "vcenter.sddc-52-53-75-20.vmc.vmware.com"
$vCenterUser = "cloudadmin@vmc.local"
$vCenterPassword = 'VMware1!'
$ResourcePool = "Compute-ResourcePool"
$Datastore = "WorkloadDatastore"
$DestinationFolder = "Workloads"
$Template = "Gold_Linux_Template"
$VMNamePrefix = "NEWVM"
$NumofVMs = 100
$RunASync = $true #Set this to $True to create the VMs and not wait for the result before starting the next one
#>
# ------------- VARIABLES SECTION - EDIT THE VARIABLES BELOW -------------
$vCenter = "vcenter.sddc-123456789.vmc.vmware.com"
$vCenterUser = "cloudadmin@vmc.local"
$vCenterPassword = '123456789'
$ResourcePool = "Compute-ResourcePool"
$Datastore = "WorkloadDatastore"
$DestinationFolder = "Workloads"
$Template = "Gold_Linux_Template"
$VMNamePrefix = "NEWVM"
$NumofVMs = 100
$RunASync = $true
# ------------- END VARIABLES - DO NOT EDIT BELOW THIS LINE -------------
# Connect to VMC vCenter Server
$VCConn = Connect-VIServer -Server $vCenter -User $vCenterUser -Password $vCenterPassword
1..$NumofVMs | Foreach-Object {
Write-Host "Creating $VMNamePrefix$($_)"
if ($RunASync){
New-VM -Name "$VMNamePrefix$($_)" -Template $Template -ResourcePool $ResourcePool -Datastore $datastore -Location $DestinationFolder -RunAsync
} Else {
New-VM -Name "$VMNamePrefix$($_)" -Template $Template -ResourcePool $ResourcePool -Datastore $datastore -Location $DestinationFolder
}
}

View File

@@ -0,0 +1,99 @@
<#
.NOTES
===========================================================================
Created by: Brian Graf
Date: January 8, 2018
Organization: VMware
Blog: brianjgraf.com
Twitter: @vBrianGraf
===========================================================================
.DESCRIPTION
This will allow you to vMotion workloads from your on-premises environment to VMware Cloud on AWS.
.NOTES
PLEASE NOTE THAT THIS REQUIRES L2 Stretch Network between your on-prem environment and VMC. Without the Layer2 VPN, vMotion will not work.
.Example
# ------------- VARIABLES SECTION - EDIT THE VARIABLES BELOW -------------
$destinationvCenter = "vcenter.sddc-52-53-75-20.vmc.vmware.com"
$destinationvCenterUser = "clouduser@cloud.local"
$destinationvCenterPassword = 'VMware1!'
$DestinationResourcePool = "Compute-ResourcePool"
$DestinationPortGroup = "L2-Stretch-Network"
$DestinationDatastore = "WorkloadDatastore"
$DestinationFolder = "Workloads"
$SourcevCenter = "vcsa-tmm-02.utah.lab" # This is your on-prem vCenter
$SourcevCenterUser = "administrator@vsphere.local"
$SourcevCenterPassword = "VMware1!"
# This is an easy way to select which VMs will vMotion up to VMC. The Asterisk
# acts as a wildcard
$VMs = "BG_Ubuntu_*"
#>
# ------------- VARIABLES SECTION - EDIT THE VARIABLES BELOW -------------
$destinationvCenter = "" # This is your VMware Cloud on AWS SDDC
$destinationvCenterUser = ""
$destinationvCenterPassword = ''
$DestinationResourcePool = "" # Name of the resource pool where the VM will be migrated to
$DestinationPortGroup = "" # Portgroup name that the VM will be connected to
$DestinationDatastore = "" # Name of the vSAN datastore
$DestinationFolder = "" # VM folder where the VM will reside
$SourcevCenter = "" # This is your on-prem vCenter
$SourcevCenterUser = ""
$SourcevCenterPassword = ""
# This is an easy way to select which VMs will vMotion up to VMC.
$VMs = ""
# ------------- END VARIABLES - DO NOT EDIT BELOW THIS LINE -------------
# Connect to VMC Server
$destVCConn = Connect-VIServer -Server $destinationvCenter -User $destinationvCenterUser -Password $destinationvCenterPassword
# Connect to On-Prem Server
$sourceVCConn = connect-viserver $SourcevCenter -User $SourcevCenterUser -Password $SourcevCenterPassword
# Start numbering for status updates
$i = 1
# Count total VMs selected to move
$CountVMstoMove = (Get-VM $VMs -Server $sourceVCConn).Count
# For each VM Get the necessary information for the migration
foreach ($VM in (get-VM $VMs -Server $sourceVCConn)) {
# Get the network adapter information
$networkAdapter = Get-NetworkAdapter -VM $vm -Server $sourceVCConn
# Get the destination resource pool
$destination = Get-Resourcepool $DestinationResourcePool -Server $destVCConn
# Get the destination portgroup
$destinationPortGroup = Get-VDPortgroup -Name $DestinationPortGroup -Server $destVCConn
# Get the destination datastore
$destinationDatastore = Get-Datastore $DestinationDatastore -Server $destVCConn
# Get the destination folder
$folder = get-folder $DestinationFolder -server $destVCConn
# Write updates as each VM is being migrated
Write-host "($i of $CountVMsToMove) Moving " -NoNewline
Write-host "$($VM.name) " -NoNewline -ForegroundColor Yellow
Write-host "from " -NoNewline
Write-host "($SourcevCenter) " -NoNewline -ForegroundColor Yellow
Write-host "to " -NoNewline
Write-host "($DestinationvCenter) " -ForegroundColor Yellow
# The actual vMotion command along with a measurement to time the duration of the vMotion
$Duration = Measure-Command {Move-VM -VM $vm -Destination $destination -NetworkAdapter $networkAdapter -PortGroup $destinationPortGroup -Datastore $destinationDatastore -InventoryLocation $folder | Out-Null}
# Write the completion string
Write-host " ($i of $CountVMsToMove) Move of $($VM.name) Completed in ($Duration) Minutes!" -ForegroundColor Green
# Increase our integer by one and move on
$i++
}