Friday, February 20, 2015

Set up in IaaS a Web Cluster (Ubuntu) in Azure using PowerShell

Infrastructure as a code in PowerShell:


###################Disclaimer########################################

# The script is provided ASIS. Feel free to modify as per your need #

#####################################################################

 

############################### USer Manual #####################

#The environment mentioned in the script has the followings:

#1. storage account: LRS

#2. Cloud Service (public url))

#3. Two VMS

#  3a. Picks up the latest stable Ubunutu images

#  3b. Sets up SSH on specific ports

#4. Availability Set

#5. Load balanced set for HTTP

#6. vnet and subnet

#7. assign static IP

#8. select default subscription and storage

#

#The script is idempotent...Run as many times you like...

#The script doesnt handle Transient Failures. Run multiple times as a workaround.

#

#Scripts prompts for:

#1. Set up an environment (*)

#2. Print Details of the environment

#3. Test High Availability of the environment

#4. Stop computation of the environment

#5. Tear Down the environment

#6. Perform all the above sequentially.

#(*) a web farm (2 web servies) in availability set, with load balanced set, in a cloud service, in a vnet, accessible over ssh.

############################### End USer Manual #####################

 

#####################Pre-requisite########

# 1. An Azure subscription

# 2. PowerShell

# 3. Putty or any SSH client

#####################End Pre-requisite########

clear screen

 

#global preference

#$ErrorActionPreference = "Stop"

$nl=[Environment]::NewLine

 

$bgcolor="Gray"

$fgcolor="Cyan"

 

###############################Set your variables##################################

# Set variables:

$prefixVariable='dp' #put in your initials

$cosVaraible='mycos' #put in company's initial

$workingDir='c:\dev\demo'

###############################(Optional) Set your variables##################################

$location = 'West US'

$adminname = 'MppUsWest1admin'

$adminpassword = 'MppUsWest1'

$ipaddressVnetRange='10.10.0.0/8'

$ipaddressSubNetRange='10.10.0.0/11'

$vm1IPAddress='10.10.0.2'

$vm2IPAddress='10.10.0.3'

$vm1SSHPublicPort='5001'

$vm2SSHPublicPort='5002'

$storageAccountType='Standard_LRS' #Standard_ZRS, Standard_GRS, Standard_RAGRS

###############################Set your variables##################################

 

$storageAccountName = "$prefixVariable$cosVaraible-test-storage"

$cloudsvcName = "$prefixVariable$cosVaraible-testapp-cs"

$vm1name = "$prefixVariable$cosVaraible-testapp-web-vm1"

$vm2name = "$prefixVariable$cosVaraible-testapp-web-vm2"

$vnetname = "$prefixVariable$cosVaraible-mycostest-vnet"     

$subnetname = "$prefixVariable$cosVaraible-testapp-web-subnet"

$cloudappFQDN='.cloudapp.net'

$availabilitySetName="$prefixVariable$cosVaraible-myapptest-web-as"

$bkpFilePrefix="bkp$prefixVariable$cosVaraible"

$wipFilePrefix = "wip$prefixVariable$cosVaraible"

 

#vnet config string

$vnetString='<VirtualNetworkSite name="variable-vnetname" Location="variable-location">

        <AddressSpace>

          <AddressPrefix>variable-ipaddressvnetrange</AddressPrefix>

        </AddressSpace>

        <Subnets>

          <Subnet name="variable-subnetname">

            <AddressPrefix>variable-ipaddresssubnetrange</AddressPrefix>

          </Subnet>

        </Subnets>

      </VirtualNetworkSite>';

$vnetString=$vnetString -replace "variable-vnetname", "$vnetname"

$vnetString=$vnetString -replace "variable-subnetname", "$subnetname"

$vnetString=$vnetString -replace "variable-ipaddressvnetrange", "$ipaddressVnetRange"

$vnetString=$vnetString -replace "variable-ipaddresssubnetrange", "$ipaddressSubNetRange"

$vnetString=$vnetString -replace "variable-location", "$location"

 

$vnetSampleString = '<?xml version="1.0" encoding="utf-8"?>

<NetworkConfiguration xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/ServiceHosting/2011/07/NetworkConfiguration">

  <VirtualNetworkConfiguration>

    <Dns />

    <VirtualNetworkSites>

      <VirtualNetworkSite name="dpmycos-mycostest-vnet" Location="West US">

        <AddressSpace>

          <AddressPrefix>10.10.0.0/8</AddressPrefix>

        </AddressSpace>

        <Subnets>

          <Subnet name="dpmycos-testapp-web-subnet">

            <AddressPrefix>10.10.0.0/11</AddressPrefix>

          </Subnet>

        </Subnets>

      </VirtualNetworkSite>

    </VirtualNetworkSites>

  </VirtualNetworkConfiguration>

</NetworkConfiguration>'

 

 

###################Display message########################

function Display-Message ($message, $message2) {

    Display-Message_NoLineBreak $message, $message2

    $nl

}

function Display-ErrorMessage ($myError) {

    Write-Host "Error: $myError" -BackgroundColor Red -ForegroundColor $fgcolor

    #Show-ErrorDetails

    $Error.Clear();

    $nl

}

function Display-Message_NoLineBreak ($message, $message2) {

    if ($message2 -ne $null) {

        Write-Host $message $message2 -BackgroundColor DarkBlue -ForegroundColor $fgcolor

    } else {

        Write-Host $message $message2 -BackgroundColor $bgcolor -ForegroundColor $fgcolor

    }

}

####################End of Display message################

 

################Show Error Details#########################

function Show-ErrorDetails {

    param (

        $ErrorRecord = $Error[0]

       )

 

    $ErrorRecord | Format-List * -Force

    $ErrorRecord.InvocationInfo | Format-List *

    $Exception = $ErrorRecord.Exception

    for ($depth=0; $Exception -ne $null; $depth++)

    {

        "$depth" * 80

        $Exception | Format-List -Force *

        $Exception = $Exception.InnerException

    }

}

################end of Show-ErrorDetails###################

 

#################create VM##########################

function Create-VM ($sshport, $vmname, $ubuntuImageName, $adminpassword, $adminname, $subnetname, $vmIPAddress, $cloudsvcName, $vnetname, $location) {

    Display-Message_NoLineBreak "Going to create vm:"

    Display-Message_NoLineBreak "vmname: $vmname"

    Display-Message_NoLineBreak "ubuntuImageName: $ubuntuImageName"

    Display-Message_NoLineBreak "adminpassword: $adminpassword"

    Display-Message_NoLineBreak "adminname: $adminname"

    Display-Message_NoLineBreak "subnetname: $subnetname"

    Display-Message_NoLineBreak "vmIPAddress: $vmIPAddress"

    Display-Message_NoLineBreak "cloudsvcName: $cloudsvcName"

    Display-Message_NoLineBreak "vnetname: $vnetname"

    Display-Message_NoLineBreak "location: $location"

    Display-Message_NoLineBreak "sshport: $sshport"

    Pause

    $vmObject=New-AzureVMConfig -Name "$vmname" -InstanceSize "Small" -ImageName "$ubuntuImageName" |`

                Add-AzureProvisioningConfig -Linux -Password "$adminpassword" -LinuxUser "$adminname" -NoSSHEndPoint|`

                Set-AzureSubnet -SubnetNames "$subnetname" |`

                Set-AzureStaticVNetIP -IPAddress "$vmIPAddress" |`

                Add-AzureEndpoint -LocalPort 22 -Name SSH -Protocol tcp -PublicPort "$sshport" | `

                New-AzureVM –ServiceName "$cloudsvcName" -WaitForBoot -VNetName "$vnetname" -Location "$location"

    return $vmObject

}

#################end of create VM###################

 

#################display usage of Ubuntu###########

function Display-UbuntuMessage () {

    Display-Message_NoLineBreak 'After you connect to Ubuntu'

    Display-Message_NoLineBreak '1. Accept the cert'

    Display-Message_NoLineBreak '2. login'

    Display-Message_NoLineBreak '3. sudo su -'

    Display-Message_NoLineBreak '4. apt-get install apache2'

    Display-Message_NoLineBreak '4a. Answer Y when prompted to continue'

    Display-Message_NoLineBreak '5. ps -ef | grep apache'

    Display-Message_NoLineBreak '6 echo `hostname` >> /var/www/index.html'

    Display-Message_NoLineBreak '7. curl localhost'

    Display-Message_NoLineBreak '8. validate some html content is displayed'

}

#################end display usage of Ubuntu###########

 

##################Collect User Response################

function Collect-UserResponse ($message) {

    Display-ErrorMessage $message

    Read-Host 'Press <Enter> to continue or Ctrl+C to Abort'

}

##################end of Collecting User Response######

 

##################collect latest Ubuntu image##########

function Collect-UbuntuImage() {

    Display-Message "Going to collect the latest Ubuntu Stock Image Name..."

    $latestUbuntuImage=Get-AzureVMImage | Select-Object *  | Where-Object {$_.ImageName -like "*Ubuntu*LTS*"} | Where-Object {$_.ImageName -notlike "*Daily*"} |  Sort-Object {$_.PublishedDate} -Descending | Select-Object -First 1

    $ubuntuImageName=$latestUbuntuImage.ImageName

    Display-Message "Going to use the following Ubunut Stock Image: $ubuntuImageName"

    return $ubuntuImageName

}

##################end of collect latest Ubuntu image###

 

##################handle vm creation workflow#########

function Handle-VMCreateWorkFlow ($sshport, $vmname, $ubuntuImageName, $adminpassword, $adminname, $subnetname, $vmIPAddress, $cloudsvcName, $vnetname, $location) {

    try

    {

        $isError=$false

        $vmObject=Get-AzureVM -ServiceName $cloudsvcName -Name $vmname

        if (($vmObject) -ne $null) {

            Collect-UserResponse "$vmname alread exists!!!"

            $isError = $true

        }

 

        if (!$isError) {

            $vmObject=Create-VM $sshport $vmname $ubuntuImageName $adminpassword $adminname $subnetname $vmIPAddress $cloudsvcName $vnetname $location

 

            Display-Message "$vmname created: $vmObject"

            Display-Message "Connect to Host:$cloudsvcName$cloudappFQDN on Port $sshport using $adminname/$adminpassword in Putty"

            Display-UbuntuMessage

            Read-Host 'Press <Enter> to continue....'

        }

        return $vmObject

    }

    catch

    {

        Display-ErrorMessage $Error

        Collect-UserResponse "Error in creating $vmname...."

    }

}

##################end of handle vm creation workflow###

 

##################handle Availability Set workflow##########

function Handle-AvailabilitySetCreateWorkFlow ($vmName) {

    $vmObject=Get-AzureVM -ServiceName $cloudsvcName -Name $vmName

    $vmAvailabilitySetName=$vmObject.AvailabilitySetName

    if ($vmAvailabilitySetName -eq $null) {

        Display-Message "Going to create availability set $availabilitySetName and attach VM $vmObject"

        Set-AzureAvailabilitySet -AvailabilitySetName $availabilitySetName -VM $vmObject | Update-AzureVM

        Display-Message "Availability set $availabilitySetName for VM $vmObject is all set."

    } else {

        Collect-UserResponse "$vmName is already all set with Avaialbility Set!!!"

    }

 

}

##################end of handle Availability Set Workflow###

 

##########set vm Http end point#############

function Handle-HttpVMEndPoint ($vmName) {

    $vmObject=get-azurevm -ServiceName $cloudsvcName -Name $vmname

    $vmEP=Get-AzureEndpoint -VM $vmObject -Name HttpIn

    if ($vmEP -eq $null) {

        Display-Message "Going to set HttpIn port 80 on $vmName"

        #Add-AzureEndpoint -LocalPort 80 -Name HttpIn -Protocol tcp -VM $vmObject -PublicPort 80| Update-AzureVM

        Add-AzureEndpoint -DefaultProbe -LBSetName HttpLBSet -LocalPort 80 -Name HttpIn -Protocol tcp -VM $vmObject -PublicPort 80 | Update-AzureVM

        Display-Message "HttpIn port 80 set on $vmName"

    } else {

        Collect-UserResponse "$vmName with HttpIn(Port 80) already exposed!!!"

    }

}

##########end set vm Http end point#########

 

####################Prompt for a folder to be selected#########

function Pick-Working-Folder($message='Select a folder (work folder)', $path = "c:\") { 

    $object = New-Object -comObject Shell.Application  

     

    $folder = $object.BrowseForFolder(0, $message, 0, $path) 

    #if ($folder -ne $null) { 

    #    $folder.self.Path 

    #} 

    return $folder.self.Path

}

####################end Prompt for a folder to be selected#########

 

#####################Handle V-Net Creation#########################

function Handle-VNet-Create ()

{

    #Display-Message "(Sample)Full contnet of a vnet config file only with one VNet: $vnetSampleString"

    Display-Message "NEw Vnet congiguration snippet: $vnetString"

 

    #prompt for Working directory

    $workingDirExist=Test-Path $workingDir

    if (!$workingDirExist) {

        $workingDir=Pick-Working-Folder

    }

    Display-Message "Working directory: $workingDir"

    $timestamp=Get-Date -Format 'yyyy-MM-dd-HH-mm-s'

    #$timestamp='xyz'

    $exportFileName="$workingDir\$bkpFilePrefix$timestamp.xml"

    $wipFileName="$workingDir\$wipFilePrefix$timestamp.xml"

    #download current vnet config file and save it with a date and timestamp

    Display-Message "Going to download the current vnet configuration..."

    Get-AzureVNetConfig -ExportToFile $exportFileName

    Display-Message "Existing vnet configuration saved on $exportFileName."

    copy $exportFileName $wipFileName

 

    #check to see if the config already exists

    $createVnet = $false

    $vnetConfigFileText=$null

 

    $wipFileNameExist=Test-Path $wipFileName

    $wipFileContent=Get-Content $wipFileName

    $oneVNetExists=Get-Content $wipFileName | Select-String "<VirtualNetworkSites>"

    $vnetAlreadyExists=Get-Content $wipFileName | Select-String $vnetname

    $whatblock=$null

    if (!$wipFileNameExist -or $wipFileContent.Length -eq 0){

        $whatblock="file doesn't exist"

        #no file exists

            $vnetConfigFileText='<?xml version="1.0" encoding="utf-8"?>

        <NetworkConfiguration xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/ServiceHosting/2011/07/NetworkConfiguration">

          <VirtualNetworkConfiguration>

            <Dns />

            <VirtualNetworkSites>'

            $vnetConfigFileText="$vnetConfigFileText

            $vnetString"

            $vnetConfigFileText="$vnetConfigFileText   

            </VirtualNetworkSites>

          </VirtualNetworkConfiguration>

        </NetworkConfiguration>"

    } elseif ($oneVNetExists -eq $null) {

        $whatblock="No wrapper exist"

        #if only the wrapper exists; a variant of if file nothing exists

        $vnetStringToAdd="<VirtualNetworkSites>

            $vnetString

            </VirtualNetworkSites>

            </VirtualNetworkConfiguration>

        "

        $vnetConfigFileText = [IO.File]::ReadAllText($wipFileName)

        $vnetConfigFileText=$vnetConfigFileText -replace " </VirtualNetworkConfiguration>", "$vnetStringToAdd"

    } elseif($vnetAlreadyExists -eq $null) {

        $whatblock="add only $vnetname"

        #edit the file and add the vnet config string

        $vnetStringToAdd="$vnetString

            </VirtualNetworkSites>"

        $vnetConfigFileText = [IO.File]::ReadAllText($wipFileName)

        $vnetConfigFileText=$vnetConfigFileText -replace "</VirtualNetworkSites>", "$vnetStringToAdd"

 

    }

 

    if ($whatblock -ne $null -or $whatblock.Length -ne 0) {

        Display-Message "Final content of vnet confir file: $vnetConfigFileText"

        Set-Content $wipFileName $vnetConfigFileText

 

        #set vnet and subnect

        Display-Message "Going to set the network config for $vnetname $subnetname..."

        Set-AzureVNetConfig -ConfigurationPath $wipFileName

        Display-Message "$vnetname with $subnetname is all set now."

    } else {

        Collect-UserResponse "VNet $vnetname already exists!!!"

    }

    Display-Message "End of Vnet creation function."

}

#####################End Handle V-Net Creation#########################

 

#####################Handle V-Net Removal#########################

function Handle-VNet-Remove ()

{

    #download current vnet file

    $timestamp=Get-Date -Format 'yyyy-MM-dd-HH-mm-s'

    #$timestamp='xyz'

    $exportFileName="$workingDir\$bkpFilePrefix$timestamp.xml"

    $wipFileName="$workingDir\$wipFilePrefix$timestamp.xml"

    #download current vnet config file and save it with a date and timestamp

    Display-Message "Going to download the current vnet configuration..."

    Get-AzureVNetConfig -ExportToFile $exportFileName

    Display-Message "Existing vnet configuration saved on $exportFileName."

    copy $exportFileName $wipFileName

    $wipFileContent=Get-Content $wipFileName

    #edit and remove the config string

    $vnetConfigFileText = [IO.File]::ReadAllText($wipFileName)

    Display-Message "vnetString: $vnetString"

    Pause

 

    [xml]$vnetConfigNodes = Get-Content $exportFileName

    $vns=$vnetConfigNodes.NetworkConfiguration.VirtualNetworkConfiguration.VirtualNetworkSites.VirtualNetworkSite

    foreach ($var in $vns) { if ($var.name -eq "$vnetname") {$vnetConfigNodes.NetworkConfiguration.VirtualNetworkConfiguration.VirtualNetworkSites.RemoveChild($var)}}

    $vnetConfigNodes.Save($wipFileName)

   

    #set vnet

    Display-Message "Going to remove the network config for $vnetname $subnetname..."

    Set-AzureVNetConfig -ConfigurationPath $wipFileName

    Display-Message "$vnetname with $subnetname is removed now."

 

    Display-Message "End of Vnet removal"

}

#####################End Handle V-Net Removal#########################

 

###############setup environment############

function Setup-Environment () {

    try

    {

        #check if storage account exist

        $isError = $false

        if ((Test-AzureName -Storage $storageAccountName)) {

            Collect-UserResponse "Storage Account already exists!!!"

            $isError = $true

        }

 

        if (!$isError) {

            #create storage account

            Display-Message "Going to create storage account... $storageAccountName"

            $myStorageAccount=New-AzureStorageAccount -StorageAccountName $storageAccountName -Location $location -Type $storageAccountType

            Display-Message "Storage Account created: " $myStorageAccount.OperationStatus

        }

 

        #set default subscription and the storage account

        Display-Message "Going to set the default Subscription"

        Set-AzureSubscription -SubscriptionName $subscriptionName -CurrentStorageAccountName $storageAccountName

        Display-Message "Default Subscription and Storage Account set"

        #print the subscription

        Display-Message "Going to print azure subscription."

        Get-AzureSubscription

        Pause

 

        #Handle V-Net creation

        Handle-VNet-Create

 

 

        #check if cloud service already exists

        if ((Test-AzureName -Service $cloudsvcName)) {

            Collect-UserResponse "Cloud Service already exists!!!"

            $isError = $true

        }

 

        if (!$isError) {

            #create a cloud service

            Display-Message "Going to create the cloud service $cloudsvcName..."

            New-AzureService -Location $location -ServiceName $cloudsvcName -Description "$cloudsvcName Test"

            Display-Message "Cloud service $cloudsvcName created."

        }

 

        #collect the latest Ubuntu image

        Display-Message "Going to collect the latest Ubuntu Stock Image Name..."

        $latestUbuntuImage=Get-AzureVMImage | Select-Object *  | Where-Object {$_.ImageName -like "*Ubuntu*LTS*"} | Where-Object {$_.ImageName -notlike "*Daily*"} |  Sort-Object {$_.PublishedDate} -Descending | Select-Object -First 1

        $ubuntuImageName=$latestUbuntuImage.ImageName

        Display-Message "Going to use the following Ubunut Stock Image: $ubuntuImageName"

        #$ubuntuImageName=Collect-UbuntuImage

        #Display-Message "ubuntuImageName: $ubuntuImageName"

        Pause

 

        #create VM1

        $vm1=Handle-VMCreateWorkFlow $vm1SSHPublicPort $vm1name $ubuntuImageName $adminpassword $adminname $subnetname $vm1IPAddress $cloudsvcName $vnetname $location

 

        #create VM2

        $vm2=Handle-VMCreateWorkFlow $vm2SSHPublicPort $vm2name $ubuntuImageName $adminpassword $adminname $subnetname $vm2IPAddress $cloudsvcName $vnetname $location

 

        #create/set availability set for vm1

        Handle-AvailabilitySetCreateWorkFlow $vm1name

        #create/set availability set for vm2

        Handle-AvailabilitySetCreateWorkFlow $vm2name

 

        #set HTTP End point for VM1

        Handle-HttpVMEndPoint $vm1name

        #set HTTP End point for VM2

        Handle-HttpVMEndPoint $vm2name

    }

    catch

    {

        Display-ErrorMessage $Error

    }

    Display-Message "End of module Setup-Environment."

}

###############end up setup environment############

 

###############Test module#####################

function Test-Environment() {

    try {

        #Get VM1

        $vm1=Get-AzureVM -ServiceName $cloudsvcName -Name $vm1name

        if ($vm1.instanceStatus -ne "ReadyRole") {

            $vmInstanceStatus=$vm1.instanceStatus

            Display-Message "Current Status of $vm1name is $vmInstanceStatus. Thus starting the vm..."

            Start-AzureVM -ServiceName $cloudsvcName -Name $vm1name

            Display-Message "$vm1name started."

        }

        #Get VM2

        $vm2=Get-AzureVM -ServiceName $cloudsvcName -Name $vm2name

        if ($vm2.instanceStatus -ne "ReadyRole") {

            $vmInstanceStatus=$vm2.instanceStatus

            Display-Message "Current Status of $vm2name is $vmInstanceStatus. Thus starting the vm..."

            Start-AzureVM -ServiceName $cloudsvcName -Name $vm2name

            Display-Message "$vm2name started."

        }

 

        #open browser

        Display-Message "Going to Launch IE and browse to http://$cloudsvcName$cloudappFQDN?v=123..."

        $ie = new-object -comobject "InternetExplorer.Application" 

        $ie.visible = $true 

        $ie.navigate("http://$cloudsvcName$cloudappFQDN\?v=123")

        Display-Message "Browser launched to http://$cloudsvcName$cloudappFQDN?v=123..."

        $useresponseVMUsed=Read-Host 'Select which VM do you see: vm1(1) vm2(2) followed by <Enter> [default vm1(1)]'

        if ($useresponseVMUsed -eq $null -or $useresponseVMUsed.Length -eq 0) {

            $useresponseVMUsed="1"

        }

        $vmtostop=$vm1name

        if ($useresponseVMUsed -eq "2") {

            $vmtostop=$vm2name

        }

        Display-Message "Going to stop $vmtostop..."

        Stop-AzureVM -ServiceName $cloudsvcName -Name $vmtostop

        Display-Message "$vmtostop stopped."

 

        Display-Message "Refresh the page again in the Browser"

    }

    catch

    {

        Display-ErrorMessage $Error

    }

    Display-Message "End of module Test-Environment."

}

###############end of Test module#####################

 

################stop vm module###########################

function Stop-Environment() {

    Display-Message "Going to stop the VMs..."

    Stop-AzureVM -ServiceName $cloudsvcName -Name * -Force

    Display-Message "All VMs for the $cloudsvcName stopped."

    Display-Message "End of module Stop-Environment."

}

################end stop vm module#######################

 

################tear down the setup##########################

function Tear-Environment() {

    #remove VMs

    Display-Message "Going to remove $vm1name..."

    Remove-AzureVM -ServiceName $cloudsvcName $vm1name -DeleteVHD -Verbose

    Display-Message "Removed $vm1name."

    Pause

    Display-Message "Going to remove $vm2name..."

    Remove-AzureVM -ServiceName $cloudsvcName $vm2name -DeleteVHD -Verbose

    Display-Message "Removed $vm2name."

    Pause

    #remove storage account

    Display-Message "Going to remove storage account $storageAccountName..."

    Remove-AzureStorageAccount -StorageAccountName $storageAccountName -Verbose

    Display-Message "Removed $storageAccountName."

    Pause

    #remove cloud service

    Display-Message "Going to remove Cloud Service $cloudsvcName..."

    Remove-AzureService -ServiceName $cloudsvcName -Force -Verbose

    Display-Message "Removed $storageAccountName."

    Pause

 

    #remove VNet

    Handle-VNet-Remove

    Pause

    Display-Message "End of module TearDown-Environment."

}

################end tear down the setup######################

 

################print Environment####################

function Print-Environment() {

    Display-Message_NoLineBreak "Storage Account Name:" $storageAccountName

    Display-Message_NoLineBreak "Default Subscription:" $subscriptionName

    Display-Message_NoLineBreak "Cloud Service/Public dns name: $cloudsvcName$cloudappFQDN"

    Display-Message_NoLineBreak "VM1 SSH access $cloudsvcName$cloudappFQDN : $vm1SSHPublicPort"

    Display-Message_NoLineBreak "VM2 SSH access $cloudsvcName$cloudappFQDN : $vm2SSHPublicPort"

    Display-Message_NoLineBreak "VM1 name: $vm1name"

    Display-Message_NoLineBreak "VM2 name: $vm2name"

    Display-Message_NoLineBreak "Availability Set name: $availabilitySetName"

    Display-Message_NoLineBreak "Vnet name: $vnetname"

    Display-Message_NoLineBreak "Subnet name: $subnetname"

    Display-Message "End of module Print-Environment."

}

################end print Environment####################

 

 

 

#add your account

Display-Message "Going to add account..."

Add-AzureAccount

Display-Message "Added account."

 

 

#ensure that you are in service management mode

Display-Message "Going to switch to service management mode..."

Switch-AzureMode -Name AzureServiceManagement

Display-Message "Switched to service management mode."

 

 

###########Find default subscription##########

$subscriptionName = ""

foreach ($sub in Get-AzureSubscription)

{

    if ($sub.IsDefault -eq "True")

    {

        $subscriptionName = $sub.SubscriptionName

    }

}

Display-Message "Default Subscription:" $subscriptionName

Pause

################################

 

 

#cleanse the storage account name

$storageAccountName = [Regex]::Replace($storageAccountName.ToLower(), '[^(a-z0-9)]', '')

Display-Message "Storage Account Name:" $storageAccountName

 

#modularize it.

$collectModule=Read-Host 'Select Setup(1), Print (2), Test(3), Stop VMs (4), Tear Down (5), or All (6) followed by <Enter> [default All(6)]'

if ($collectModule -eq $null -or $collectModule.Length -eq 0) {

    $collectModule="6"

}

Display-Message "You have selected $collectModule"

 

$confirmStatus=Read-Host 'Are you sure you want to continue Yes(1)/No(2) followed by <Enter> [default No(2)]'

if ($confirmStatus -eq $null -or $confirmStatus.Length -eq 0) {

    $confirmStatus="2"

}

 

if ($confirmStatus -eq "2") {

    Display-Message "Good Bye!!!"

    break;

}

 

switch($collectModule) {

    1 {Setup-Environment

        break

    }

    2 {Print-Environment

        break

    }

    3 {Test-Environment

        break

    }

    4 {Stop-Environment

        break

    }

    5 {Tear-Environment

        break

    }

    6 {

        Setup-Environment

        Print-Environment

        Pause

        Test-Environment

        Pause

        Stop-Environment

        Pause

        Tear-Environment

        break

    }

    default {"Invalid module"}
}

No comments:

Post a Comment