Skip to content

Instantly share code, notes, and snippets.

@zachbonham
Last active December 11, 2015 07:48
Show Gist options
  • Save zachbonham/4568276 to your computer and use it in GitHub Desktop.
Save zachbonham/4568276 to your computer and use it in GitHub Desktop.
Internal PowerShell DSL for VM template descriptions. A Hyper-V, or Azure, provider would actually instantiate from metadata (see bottom).
set-psdebug -strict
# bleh
#
$global:boxes = @{}
<#
Here we are defining an internal PowerShell DSL for creating 'boxes'.
#>
function box()
{
param([string]$name, [scriptblock]$block)
BEGIN
{
$script:basebox = $null
$script:cpu = 1
$script:memory = "1GB"
$script:windowsRoles = $null
}
PROCESS
{
write-host "PROCESS"
function basebox($basebox)
{
$script:basebox = $basebox
}
function cpu($cpu)
{
$script:cpu = $cpu
}
function memory([string]$memory)
{
$script:memory = $memory
}
function windowsRoles($windowsRoles)
{
$script:windowsRoles = $windowsRoles
}
}
END
{
write-host "END"
# this will actually execute all the variable assignment
# in the brackets (scriptblock) below.
#
# box "mybox" {
# cpu 4
# memory 2GB
#}
invoke-command $block
$box = new-object object
<#
are we defining a new box based on an existing box?
#>
if ( $script:basebox -ne $null )
{
$box = $global:boxes[$script:basebox]
}
else
{
add-member -inputobject $box -memberType NoteProperty -force -name "name" -value $name
add-member -inputobject $box -memberType NoteProperty -force -name "cpu" -value $script:cpu
add-member -inputobject $box -memberType NoteProperty -force -name "memory" -value $script:memory
add-member -inputobject $box -memberType NoteProperty -force -name "windowsRoles" -value $script:windowsRoles
}
write-debug "adding box $($box.name)"
$global:boxes[$box.name] = $box
$box
}
}
# create a box from an existing template
#
function new-box($name, $from)
{
write-debug "new-box ($name, $from)"
box $name {
basebox $from
}
}
<#
this would actually be defined in something like
wserver2012small.box
wserver2012standard.box
and kept in source control.
Very simple definitions here - there would probably be many more attributes to configure.
The 'box' PowerShell API would allow us to do something like:
#>
box "Windows Server 2012 Small" {
cpu 2
memory 1GB
windowsRoles "ServerCore", "AppServer", "WebServer"
} | out-null
box "Windows Server 2012 Standard" {
cpu 4
memory 4GB
windowsRoles "ServerCore", "AppServer", "WebServer"
} | out-null
<#
load the box API into our current session
we can also update our PSProfile to include this on each load
#>
. .\box
# now create a list of servers based upon a template
#
$servers = "Web01", "Web02", "Web03"
$servers | % { new-box $_ -from "Windows Server 2012 Standard" }
# Maybe.. :)
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment