Sunday, March 15, 2015

Azure VM Deployment script




  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
<#
.SYNOPSIS
This script will evalute you current version of powershell, and deploy Windows VMs with Antimalware. 
.Description

.NOTES
    File Name : DeployAzureVM
    Author    : Drew the horrid, drew@gui.us 

#>

#Import Azure Powershell
Import-Module "C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\ServiceManagement\azure\azure.psd1"

#Write installed Azure PoSh module version
Write-Host ""
Write-host "Checking Azure Powershell Version.."
Write-Host ""
Write-Host "Your Installed Azure Powershell Version is: " -NoNewline; Write-Host -ForegroundColor "Yellow" (Get-Module -Name azure).version.tostring()

#Code block to check online version
$web=(Invoke-Webrequest -Uri "http://github.com/Azure/azure-powershell/releases" -MaximumRedirection 1).links | where {$_.outertext -like "Windows Standalone"}
    Write-Host "Lastest version online is:                  " -NoNewline;Write-Host -ForegroundColor "Yellow" ($web[0].href.Split("/")[4].trim("azure-powershell.").trim(".msi"))
    Write-Host ""
    Write-Host "MSI Direct Download Link: " -NoNewline;Write-Host -ForegroundColor Yellow $web[0].href
    Write-Host "Reference: https://github.com/Azure/azure-powershell/releases"
    Write-Host ""
    
#Get Subscription info
Write-Host "Checking Subscription:";$AZsub=Get-AzureSubscription -Current
Write-Host ""

#Check if currentstorageaccount is defined
If ($AZsub.CurrentStorageAccountName -eq $null) {Write-Warning "Storage Account is not defined";Write-Host ""
    Write-Host "Please enter the target storage account name";Write-Host "Note: target storage account must be in the same region as the target cloud servicename"
    Write-Host ""
    $AZSubStorage=Read-Host "Storage account name (all lowercase) "
    Set-AzureSubscription -SubscriptionName $AZsub.SubscriptionName -CurrentStorageAccountName $AZSubStorage}
    Write-Host ""

#confirmation 
$AZsub=Get-AzureSubscription -Current
    Write-Host ""
    Write-host "Current Subscription Name: " -NoNewline; Write-Host $AZsub.SubscriptionName -ForegroundColor Yellow
    Write-host "Current Storage Account: " -NoNewline; Write-Host $AZsub.CurrentStorageAccountName -ForegroundColor Yellow
    Write-Host ""

#Get service account
Write-Host "Please enter" -NoNewline;Write-Host -ForegroundColor Yellow " Cloud Service Account Name" -NoNewline;$servicename=Read-Host " "
    Write-host ""

#Check Service Account
If ((Get-AzureService $servicename) -eq $null) {New-AzureService -Servicename $Servicename -location (Get-AzureStorageAccount $AZsub.currentstorageaccountname).Geoprimarylocation -verbose}

# Get-VM Images and filter Windows Server 2012 R2
$VMImages=Get-AzureVMImage |Where-Object {($_.PublisherName -like "Microsoft*" -and $_.ImageFamily -like 'Windows Server 2012 R2 Datacenter') }
    Write-Host "Image we will use: " -NoNewline;Write-Host $VMImages[1].Label -ForegroundColor Magenta;`
    Write-Host "Image Published Date: " -NoNewline;Write-Host $VMImages[1].PublishedDate -ForegroundColor Magenta;`
    
#Get Credentials that defined in the deployment
$Cred=Get-Credential -Message "Please enter the Username and Password for this deployment"
    Write-Host ""
    Write-Host "Default VM naming scheme is " -NoNewline;Write-Host -ForegroundColor Yellow "thing"; Write-Host "Example: thing1, thing2, thing3, etc.."
    $thingname = 'thing'; if (($result = Read-Host "Press enter to accept default computername scheme 'thingX' or enter a new one: ") -eq '') {$thingname} else {$thingname=$result}
    Write-Host ""
    [int]$ManyVMs=Read-Host "How Many VMs do you want created:  " 

#Recipe ready, cooking the request         
Write-host -ForegroundColor Yellow "cooking your request" 
Write-Host ""
Write-Host -ForegroundColor Magenta "Azure tip: local redudant storage costs less than geo replicated storage (geo is default)"
    
#Deployment engine code block
1..$ManyVMs |% {$VMName = "$thingname$_"
    New-AzureVMConfig -Name $VMName -InstanceSize "Medium" -ImageName $vmimages[1].ImageName |Add-AzureProvisioningConfig -Windows -AdminUsername $cred.UserName -Password $Cred.GetNetworkCredential().password -TimeZone "Central Standard Time" -Verbose |Add-AzureDataDisk -CreateNew -DiskSizeInGB '15' -DiskLabel "disk 1" -LUN '0' |New-AzureVM -servicename $ServiceName -verbose
        
    # Install Antimalware 
    Write-host "Installing IaaS AntiMalware on $VMName" -ForegroundColor Yellow

        # Create Json String for Azure IaaS Antimalware 
        $JsonString="{ 'AntimalwareEnabled': true }"
                
        # Deploy Antimalware    
        Get-AzureVM -Name $VMName -ServiceName $ServiceName  | Set-AzureVMExtension -Publisher Microsoft.Azure.Security -ExtensionName IaaSAntimalware -Version 1.* -PublicConfiguration $JsonString |Update-AzureVM  
        
               }

#Function to access Virtual Machines

Function Enter-AZSession ($VMRM){
 if ($VMRM.status -ne "ReadyRole") {Write-Error "VM Status is not ReadyRole";break}
else {
Write-Host Connecting to hostname: "  -ForeGroundColor Yellow -nonewline; $($VMRM.VM.RoleName)
Enter-PSSession -ConnectionUri ($VMRM|Get-AzureWinRMUri) -Credential (Get-Credential) -SessionOption (New-PSSessionOption -SkipCACheck:$true)}}
Write-Host ""
Write-host "If you would like to PS remote into your machines, enter the following"
Write-host -ForegroundColor Magenta "$VMS=Get-AzureVM" 
Write-Host "$VMS" -ForegroundColor Magenta
Write-Host "starting from the top, index number is zero '0', you can PS remote into a VM by entering the following command (0 being the first VM)" 
Write-Host -ForegroundColor Magenta 'Enter-AZSession $VMS[0]' 

Sunday, March 1, 2015

Azure Virtual Machines (VMS) Powershell Remote (WinRM), function that skips the CA validation. 


Function Enter-AZSession ($VMRM){ if ($VMRM.status -ne "ReadyRole") {Write-Error "VM Status is not ReadyRole";break} else { Write-Host “Connecting to hostname: " -ForeGroundColor Yellow -NoNewLine; $($VMRM.VM.RoleName) Enter-PSSession -ConnectionUri ($VMRM|Get-AzureWinRMUri) -Credential (Get-Credential) -SessionOption (New-PSSessionOption -SkipCACheck:$true)} }

#powershell
#azure
#iaas
#virtual machines
#remote
#powershell
#winrm
#CA
#PSSession
#VM

Saturday, September 6, 2014

Azure, Chocolatey and Powershell.. this provision a full VM including IISl WebServer, NET-Framework-Features, chocolatley, google chrome, 7zip, notepad ++.. Hands free/no user interaction

<#

.SYNOPSIS

Chocolatey, Azure and Powershell

.Description

Azure SandBoxing

.NOTES

File Name : DeployFun.PS1

Author : Drew the horrid

 

 

This Script will do the following

- Pull Virtual Network Name and Append the name to the Deployment

- Parse the VM library for Windows Server 2012 R2 Datacenter and select the latest patched version

- Attach a 15GB data disk

- Install Azure Microsoft Antimalware Service

- Download the VM Certificate and install the certificate in your machine\root ca (hence you have to run as admin)

- Remote execute and install WebServer, NET-Framework-Features, chocolatley, google chrome, 7zip, notepad ++

a small VM and install Azure the Microsoft Antimaleware Extension as well as chocolatey, Chrome, 7Zip)

 

.Pending things

- Create logic to list storage accounts and let the user pick

- Create list of services and let the user pick (have to figure out region/vnet thing)

- Get-AzureVNET if not there .. don't bind Vnet in AzureVM build

- Prompt for DC name and CA name

- need a delay check that vm is up before invoke-command

 

 

#>

 

 

 

 

 

# Subscription Block

Get-AzureSubscription | Remove-AzureSubscription

 

Import-AzurePublishSettingsFile .\filenameHERE

 

# Bind Variable for storage account (must have a storage account provisioned for PS Azure VM deployments)

$Sub=Get-AzureSubscription

Set-AzureSubscription -SubscriptionName $sub.SubscriptionName -CurrentStorageAccountName NAMEHERE

 

# Get-Vnet name '#' this block if you don't have a vnet

[xml]$Vnet=(Get-AzureVNetConfig).XMLConfiguration

$Vnetname= $vnet.GetElementsByTagName('VirtualNetworkSites').Virtualnetworksite.name

 

# Get-VM Images and filter Windows Server 2012 R2

$VMImages=Get-AzureVMImage |Where-Object {($_.PublisherName -ilike "Microsoft*" -and $_.ImageFamily -ilike 'Windows Server 2012 R2 Datacenter') }

 

# Variables for Deployment

$ServiceName="Drew"

$VMName="DC1"

 

# Get Credentials

$Cred=Get-Credential -Message "Username and Password for this deployment"

 

# Deployment Engine **IMPORTANT: Remove -vnetname and $VnetName if you do not have VNET configured

New-AzureVMConfig -Name $VMName -InstanceSize "Small" -ImageName $vmimages[1].ImageName |Add-AzureProvisioningConfig -Windows -AdminUsername $cred.UserName -Password

 

$Cred.GetNetworkCredential().password -TimeZone "Central Standard Time" -Verbose |Add-AzureDataDisk -CreateNew -DiskSizeInGB 15 -DiskLabel "disk 1" -LUN 0 |New-AzureVM -

 

servicename $ServiceName -VNetName $Vnetname -Verbose

 

 

# Get the VM

$vm = Get-AzureVM ServiceName $ServiceName -Name $VMName

 

# Add Microsoft Antimalware Agent to the Virtual Machine

Set-AzureVMExtension -Publisher Microsoft.Azure.Security -ExtensionName IaaSAntimalware -Version 1.* -VM $vm.VM

Update-AzureVM -Name $VMName -ServiceName $Servicename -VM $vm.VM

 

# Get the VM Certificate and add it our machine's trusted root ca so we can remote into it

 

$winRMCert =(Get-AzureVM -ServiceName $ServiceName -name $VMname| select -ExpandProperty vm).DefaultWinRMCertificateThumbprint

$AzureX509cert = Get-AzureCertificate -ServiceName $Servicename -Thumbprint $winRMCert -ThumbprintAlgorithm sha1

$certTempFile = [IO.Path]::GetTempFileName()

$AzureX509cert.Data | Out-File $certTempFile

$CertToImport = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $certTempFile

$store = New-Object System.Security.Cryptography.X509Certificates.X509Store "Root", "LocalMachine"

$store.Certificates.Count

$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)

$store.Add($CertToImport)

$store.Close()

write-Host ("Cleanup cert file- "+[System.DateTime]::Now.ToString("hh:mm:ss"))

Remove-Item $certTempFile

 

# Get DNS and PORT for remoting

# Get DNS name and remove http formatting

$VMDNSNAME=(($vm.dnsname).Remove(0,7)).replace("/","")

# Get PS endpoint

$endpoints=$VM |Get-AzureEndpoint

 

### Code to Enter Remote Session on the VM

# Enter-PSSession -ComputerName $VMDNSNAME -Port $endpoints[1].port -Credential $cred -UseSSL

 

## Code to wait until PSRemote Port starts

for($retry = 0; $retry -le 5; $retry++)

{

try

{

$session = New-PSSession -ComputerName $VMDNSNAME -Credential $cred -Port $endpoints[1].port -UseSSL

if ($session -ne $null)

{

break

}

Write-Output "Unable to create a PowerShell session . . . sleeping and trying again in 30 seconds."

Start-Sleep -Seconds 30

}

catch

{

Write-Output "Unable to create a PowerShell session . . . sleeping and trying again in 30 seconds."

Start-Sleep -Seconds 30

}

}

 

# Install IIS, .NET, Choc, Google Chrome, 7Zip, Notepad++

 

 

Invoke-Command -ComputerName $VMDNSNAME -Port $endpoints[1].port -Credential $cred -UseSSL -ScriptBlock {install-WindowsFeature -Name Web-Server -

 

IncludeManagementTools;install-windowsfeature -name NET-Framework-Features;iex ((new-object net.webclient).DownloadString("http://chocolatey.org/install.ps1"));cinst

 

googlechrome;cinst 7zip;cinst notepadplusplus}