Use TeamCity and PowerShell to Automate Windows Azure Deployments
Join the DZone community and get the full member experience.
Join For Freehi guys,
introduction
we will cover:
- overview to configure multiple build projects on teamcity
- configure one of the build projects to deploy to the azure cloud
- automated deployments to the azure cloud for web and worker roles
- leverage the msbuild target templates to automate generation of azure package files
- alternative solution of generating the azure package files
- using configuration transformations to manage settings e.g. uat, dev, production
a colleague of mine tatham oddie and i are currently use teamcity to automatically deploy our azure/mvc3/neo4j based project to the azure cloud. lets see how this can be done with relative ease and is fully automated. the focus here will be based on powershell scripts which are using the cerebrata command scriplets, which can be found here: http://www.cerebrata.com/products/azuremanagementcmdlets/default.aspx
the powershell script included here will automatically undeploy and redploy you azure service and will even wait until all the services are in the ready state.
i will leave you to checking those commandlets out, and they worth every penny spent.
now lets check how we get the deployment working.
the basic idea is that you have a continuous integration build configured on the build server in teamcity, then what you do is configure the ci build to generate artifacts, which are basically the output from the build that can be used by another build project e.g. you can take the artifacts for the ci build and then run functional tests or integration tests builds that run totally separate from the ci build. the idea here is, your functional and integration will never interfere with the ci build and the unit tests. thus keeping ci builds fast and efficient.
prerequisites on build server
- teamcity professional version 6.5.1
- cloud subscription certificate with private key is imported into the user certificate store for the team city service account
- cerebrata cmdlets
teamcity -continuous integration build project
ok, so, lets do a quick check at my ci build that spits out the azure packages.
as we can see above, the ci build creates an artifact called azurepackage.
the way we generate these artifacts is very easy. in the settings for the ci build project we setup the artifacts path.
e.g. myprojectmyproject.azurebin%buildconfiguration%publish => azurepackage
so, we will look at the build steps to configure.
as we can see below, we just say where the msbuild is run from and then where the unit tests dll’s are.
cool, now we need to setup the artifacts and configuration.
we just mention we want a release build.
ok, now we need to tell our azure deployment project to have a dependency on the ci project we configured above.
team city – uat deployment build project
so lets now go check out the uat deployment project.
this project will have dependencies on the ci build and then we will configure all the build parameters so it can connect to your azure storage and service for automatic deployments. once we done here, we will have a look at the powershell script that we use to automatically deploy to the cloud, the script supports un-deploying existing deployment slots before deploying a new one with retry attempts.
ok, lets check the following for the uat deployment project.
the above screenshot is the command that executes the powershell script, the parameters (%whatever%) will resolve from build parameters in step 6 of the screen shot above.
here is the command for copy/paste friendless. of course if you using some other database then you do not need the neo4j stuff.
-azureaccountname “%azureaccountname%” -azureservicename “%azureservicename%” -azuredeploymentslot “%azuredeploymentslot%” -azureaccountkey “%azureaccountkey%” -azuresubscriptionid “%azuresubscriptionid%” -azurecertificatethumbprint “%azurecertificatethumbprint%” -packagesource “%azurepackagedependencypath%myproject.azure.cspkg” -configsource “%azurepackagedependencypath%%configfilename%” -deploymentname “%build.number%-%build.vcs.number%” -neo4jblobname “%neo4jblobname%” -neo4jzippedbinaryfilehttpsource “%neo4jzippedbinaryfilehttpsource%” |
this is the input for a deploy-package.cmd file, which is in our source repository.
now, we also need to tell the deployment project to use the artifact from our ci project. so we setup an artifact dependencies as show below in the dependencies section. also, notice how we use a wildcard, so get all files from azurepackage (azurepackage/**). this will be the cspackage files.
notice above, that i have a snapshot dependency, this is forcing the uat deployment to use the same source code that the ci build project is using.
so, the parameters are as follows.
powershell deployment scripts
the deployment scripts consist of three files and remember i assumed you installed the cerebrata management command scriptlets.
ok, so lets look at the deploy-package.cmd file, i would like to pay my gratitude to jason stangroome( http://blog.codeassassin.com ) for this,
jason wrote: “this tiny proxy script just writes a temporary powershell script containing all the arguments you’re trying to pass to let powershell interpret them and avoid getting them messed up by the win32 native command line parser.”
@echo off setlocal set tempscript=%temp%\%~n0.%random%.ps1 echo $erroractionpreference="stop" >"%tempscript%" echo ^& "%~dpn0.ps1" %* >>"%tempscript%" powershell.exe -command "& \"%tempscript%\"" set errlvl=%errorlevel% del "%tempscript%" exit /b %errlvl%
ok, and now here is the powershell code, deployment-package.ps1. i will leave you to read what it does. in summary.
it demonstrates.
- un-deploying a service deployment slot
- deploying a service deployment slot
- using the certificate store to retrieve the certificate for service connections via a cert thumbprint – users cert store under the service account that teamcity runs on.
- uploading blobs
- downloading blobs
- waiting until the new deployment is in a ready state
#requires -version 2.0 param ( [parameter(mandatory=$true)] [string]$azureaccountname, [parameter(mandatory=$true)] [string]$azureservicename, [parameter(mandatory=$true)] [string]$azuredeploymentslot, [parameter(mandatory=$true)] [string]$azureaccountkey, [parameter(mandatory=$true)] [string]$azuresubscriptionid, [parameter(mandatory=$true)] [string]$azurecertificatethumbprint, [parameter(mandatory=$true)] [string]$packagesource, [parameter(mandatory=$true)] [string]$configsource, [parameter(mandatory=$true)] [string]$deploymentname, [parameter(mandatory=$true)] [string]$neo4jzippedbinaryfilehttpsource, [parameter(mandatory=$true)] [string]$neo4jblobname ) $erroractionpreference = "stop" if ((get-pssnapin -registered -name azuremanagementcmdletssnapin -erroraction silentlycontinue) -eq $null) { throw "azuremanagementcmdletssnapin missing. install them from https://www.cerebrata.com/products/azuremanagementcmdlets/download.aspx" } add-pssnapin azuremanagementcmdletssnapin -erroraction silentlycontinue function addblobcontainerifnotexists ($blobcontainername) { write-verbose "finding blob container $blobcontainername" $containers = get-blobcontainer -accountname $azureaccountname -accountkey $azureaccountkey $deploymentscontainer = $containers | where-object { $_.blobcontainername -eq $blobcontainername } if ($deploymentscontainer -eq $null) { write-verbose "container $blobcontainername doesn't exist, creating it" new-blobcontainer $blobcontainername -accountname $azureaccountname -accountkey $azureaccountkey } else { write-verbose "found blob container $blobcontainername" } } function uploadblobifnotexists{param ([string]$container, [string]$blobname, [string]$filesource) write-verbose "finding blob $container\$blobname" $blob = get-blob -blobcontainername $container -blobprefix $blobname -accountname $azureaccountname -accountkey $azureaccountkey if ($blob -eq $null) { write-verbose "uploading blob $blobname to $container/$blobname" import-file -file $filesource -blobname $blobname -blobcontainername $container -accountname $azureaccountname -accountkey $azureaccountkey } else { write-verbose "found blob $container\$blobname" } } function checkifdeploymentisdeleted { $trieselapsed = 0 $maximumretries = 10 $waitinterval = [system.timespan]::fromseconds(30) do { $trieselapsed+=1 [system.threading.thread]::sleep($waitinterval) write-verbose "checking if deployment is deleted, current retry is $trieselapsed/$maximumretries" $deploymentinstance = get-deployment ` -servicename $azureservicename ` -slot $azuredeploymentslot ` -subscriptionid $azuresubscriptionid ` -certificate $certificate ` -erroraction silentlycontinue if($deploymentinstance -eq $null) { write-verbose "deployment is now deleted" break } if($trieselapsed -ge $maximumretries) { throw "checking if deployment deleted has been running longer than 5 minutes, it seems the delployment is not deleting, giving up this step." } } while($trieselapsed -le $maximumretries) } function waituntilallroleinstancesareready { $trieselapsed = 0 $maximumretries = 60 $waitinterval = [system.timespan]::fromseconds(60) do { $trieselapsed+=1 [system.threading.thread]::sleep($waitinterval) write-verbose "checking if all role instances are ready, current retry is $trieselapsed/$maximumretries" $roleinstances = get-roleinstancestatus ` -servicename $azureservicename ` -slot $azuredeploymentslot ` -subscriptionid $azuresubscriptionid ` -certificate $certificate ` -erroraction silentlycontinue $roleinstancesthatarenotready = $roleinstances | where-object { $_.instancestatus -ne "ready" } if ($roleinstances -ne $null -and $roleinstancesthatarenotready -eq $null) { write-verbose "all role instances are now ready" break } if ($trieselapsed -ge $maximumretries) { throw "checking if all roles instances are ready for more than one hour, giving up..." } } while($trieselapsed -le $maximumretries) } function downloadneo4jbinaryzipfileanduploadtoblobstorageifnotexists{param ([string]$blobcontainername, [string]$blobname, [string]$httpsourcefile) write-verbose "finding blob $blobcontainername\$blobname" $blobs = get-blob -blobcontainername $blobcontainername -listall -accountname $azureaccountname -accountkey $azureaccountkey $blob = $blobs | findstr $blobname if ($blob -eq $null) { write-verbose "neo4j binary does not exist in blob storage. " write-verbose "downloading file $httpsourcefile..." $temporaryneo4jfile = [system.io.path]::gettempfilename() $webclient = new-object -typename system.net.webclient $webclient.downloadfile($httpsourcefile, $temporaryneo4jfile) uploadblobifnotexists $blobcontainername $blobname $temporaryneo4jfile } } write-verbose "retrieving management certificate" $certificate = get-childitem -path "cert:\currentuser\my\$azurecertificatethumbprint" -erroraction silentlycontinue if ($certificate -eq $null) { throw "couldn't find the azure management certificate in the store" } if (-not $certificate.hasprivatekey) { throw "the private key for the azure management certificate is not available in the certificate store" } write-verbose "deleting deployment" remove-deployment ` -servicename $azureservicename ` -slot $azuredeploymentslot ` -subscriptionid $azuresubscriptionid ` -certificate $certificate ` -erroraction silentlycontinue write-verbose "sent delete deployment async, will check back later to see if it is deleted" $deploymentscontainername = "deployments" $neo4jcontainername = "neo4j" addblobcontainerifnotexists $deploymentscontainername addblobcontainerifnotexists $neo4jcontainername $deploymentblobname = "$deploymentname.cspkg" downloadneo4jbinaryzipfileanduploadtoblobstorageifnotexists $neo4jcontainername $neo4jblobname $neo4jzippedbinaryfilehttpsource write-verbose "azure service information:" write-verbose "service name: $azureservicename" write-verbose "slot: $azuredeploymentslot" write-verbose "package location: $packagesource" write-verbose "config file location: $configsource" write-verbose "label: $deploymentname" write-verbose "deploymentname: $deploymentname" write-verbose "subscriptionid: $azuresubscriptionid" write-verbose "certificate: $certificate" checkifdeploymentisdeleted write-verbose "starting deployment" new-deployment ` -servicename $azureservicename ` -slot $azuredeploymentslot ` -packagelocation $packagesource ` -configfilelocation $configsource ` -label $deploymentname ` -deploymentname $deploymentname ` -subscriptionid $azuresubscriptionid ` -certificate $certificate waituntilallroleinstancesareready write-verbose "completed deployment"
automating cloud package file without using cspack and csrun explicitly
we will need to edit the cloud project file so that visual studio can create the cloud package files , as it will then automatically run the cspackage for you which can be consumed by the artifacts and hence other build projects. this allows us to bake functionality into the msbuild process to generate the package files without the need for explicitly using cspack.exe and csrun.exe. resulting in less scripts, else you would need a separate powershell script just to package the cloud project files.
below are the changes for the . ccproj file of the cloud project. notice the condition is that we generate these package files only if the build is outside of visual studio, so this is nice to keep it from not always creating the packages to keep our development experience build process short. so for the condition below to work, you will need to build the project from the command line using msbuild.
here is the config entries for the project file.
<propertygroup> <cloudextensionsdir condition=" '$(cloudextensionsdir)' == '' ">$(msbuildextensionspath)\microsoft\cloud service\1.0\visual studio 10.0\</cloudextensionsdir> </propertygroup> <import project="$(cloudextensionsdir)microsoft.cloudservice.targets" /> <import project="$(msbuildextensionspath)\microsoft\visualstudio\v10.0\web\microsoft.web.publishing.targets" /> <target name="azuredeploy" aftertargets="build" dependsontargets="corepublish" condition="'$(buildinginsidevisualstudio)'!='true'"> </target>
e.g.
c:\windows\microsoft.net\framework64\v4.0.30319\msbuild.exe myproject.sln /p:configuration=release
configuration transformations
you can also leverage configuration transformations so that you can have configurations for each environment. this is discussed here:
http://blog.alexlambert.com/2010/05/using-visual-studio-configuration.html
however, in a nutshell, you can have something like this in place, this means you can then have separate deployment config files, e.g.
serviceconfiguration.cscfg
serviceconfiguration.uat.cscfg
serviceconfiguration.prod..cscfg
just use the following config in the .ccproj file.
<target name="validateservicefiles" inputs="@(environmentconfiguration);@(environmentconfiguration->'%(baseconfiguration)')" outputs="@(environmentconfiguration->'%(identity).transformed.cscfg')"> <message text="validateservicefiles: transforming %(environmentconfiguration.baseconfiguration) to %(environmentconfiguration.identity).tmp via %(environmentconfiguration.identity)" /> <transformxml source="%(environmentconfiguration.baseconfiguration)" transform="%(environmentconfiguration.identity)" destination="%(environmentconfiguration.identity).tmp" /> <message text="validateservicefiles: transformation complete; starting validation" /> <validateservicefiles servicedefinitionfile="@(servicedefinition)" serviceconfigurationfile="%(environmentconfiguration.identity).tmp" /> <message text="validateservicefiles: validation complete; renaming temporary file" /> <move sourcefiles="%(environmentconfiguration.identity).tmp" destinationfiles="%(environmentconfiguration.identity).transformed.cscfg" /> </target> <target name="movetransformedenvironmentconfigurationxml" aftertargets="afterpackagecomputeservice" inputs="@(environmentconfiguration->'%(identity).transformed.cscfg')" outputs="@(environmentconfiguration->'$(outdir)publish\%(filename).cscfg')"> <move sourcefiles="@(environmentconfiguration->'%(identity).transformed.cscfg')" destinationfiles="@(environmentconfiguration->'$(outdir)publish\%(filename).cscfg')" /> </target>
here is a sample serviceconfiguration.uat.config that will then leverage the transformations. note the transformation for the web and worker roles sections. our worker role is neo4jserverhost and the web is just called web.
<?xml version="1.0"?> <sc:serviceconfiguration xmlns:sc="http://schemas.microsoft.com/servicehosting/2008/10/serviceconfiguration" xmlns:xdt="http://schemas.microsoft.com/xml-document-transform"> <sc:role name="neo4jserverhost" xdt:locator="match(name)"> <sc:configurationsettings> <sc:setting xdt:transform="replace" xdt:locator="match(name)" name="microsoft.windowsazure.plugins.diagnostics.connectionstring" value="defaultendpointsprotocol=https;accountname=myprojectname;accountkey=myaccountkey"/> <sc:setting xdt:transform="replace" xdt:locator="match(name)" name="storage connection string" value="defaultendpointsprotocol=https;accountname=myprojectname;accountkey=myaccountkey"/> <sc:setting xdt:transform="replace" xdt:locator="match(name)" name="drive connection string" value="defaultendpointsprotocol=http;accountname=myprojectname;accountkey=myaccountkey"/> <sc:setting xdt:transform="replace" xdt:locator="match(name)" name="neo4j dbdrive override path" value=""/> <sc:setting xdt:transform="replace" xdt:locator="match(name)" name="uniqueidsynchronizationstoreconnectionstring" value="defaultendpointsprotocol=https;accountname=myprojectname;accountkey=myaccountkey"/> </sc:configurationsettings> </sc:role> <sc:role name="web" xdt:locator="match(name)"> <sc:configurationsettings> <sc:setting xdt:transform="replace" xdt:locator="match(name)" name="microsoft.windowsazure.plugins.diagnostics.connectionstring" value="defaultendpointsprotocol=https;accountname=myprojectname;accountkey=myaccountkey"/> <sc:setting xdt:transform="replace" xdt:locator="match(name)" name="uniqueidsynchronizationstoreconnectionstring" value="defaultendpointsprotocol=https;accountname=myprojectname;accountkey=myaccountkey"/> </sc:configurationsettings> </sc:role> </sc:serviceconfiguration>
manually executing the script for testing
prerequisites:
- you will need to install the cerebrata azure management cmdlets from: https://www.cerebrata.com/products/azuremanagementcmdlets/download.aspx
- if you are running 64 bit version, you will need to follow the readme file instructions contained with the azuremanagementcmdlets, as it requires manual copying of files. if you followed the default install, this readme will be in c:\program files\cerebrata\azure management cmdlets\readme.pdf
- you will need to install the certificate and private key (which must be marked as exportable) to your user certificate store. this file will have an extension of .pfx. use the certificate management snap-in, for user account store. the certificate should be installed in the personal folder.
- once the certificate is installed, you should note the certificate thumbprint, as this is used as one of the parameters when executing the powershell script. ensure you remove all the spaces from the thumbprint when using it in the script !
1) first up, you’ll need to make your own ”myproject.azure.cspkg” file. to do this, run this:
c:\windows\microsoft.net\framework64\v4.0.30319\msbuild.exe myproject.sln /p:configuration=release
(adjust paths as required.)
you’ll now find a package waiting for you at ”c:\code\myproject\myproject\myproject.azure\bin\release\publish\myproject.azure.cspkg”.
2) make sure you have the required management certificate installed on your machine (including the private key).
3) now you’re ready to run the deployment script.
it requires quite a lot of parameters. the easiest way to find them is just to copy them from the last output log on teamcity.
you will need to manually execute is deploy-package.ps1.
the deploy-package.ps1 file has input parameters that need to be supplied. below is the list of parameters and description.
note: these values can change in the future, so ensure you do not rely on this example below.
azureaccountname: the windows azure account name e.g. myprojectuat
azureservicename: the windows azure service name e.g. myprojectuat
azuredeploymentslot: production or staging e.g. production
azureaccountkey: the azure account key: e.g. youraccountkey==
azuresubscriptionid:*the azure subscription id e.g. yourazuresubscriptionid
azurecertificatethumbprint: the certificate thumbprint you note down when importing the pfx file e.g. yourcertificatethumbprintwithnowhitespaces
packagesource: location of the .cspkg file e.g. c:\code\myproject\myproject.azure\bin\release\publish\myproject.azure.cspkg
configsource: location of the azure configuration files .cscfg e.g. c:\code\myproject\myproject\myproject.azure\bin\release\publish\serviceconfiguration.uat.cscfg
deploymentname: this can be a friendly name of the deployment e.g. local-uat-deploy-test
neo4jblobname: the name of the blob file containing the neo4j binaries in zip format e.g. neo4j-community-1.4.m04-windows.zip
neo4jzippedbinaryfilehttpsource: the http location of the neo4j zipped binary files e.g. https://mydownloads.com/mydownloads/neo4j-community-1.4.m04-windows.zip?dl=1
-verbose: you can use an additional parameter to get verbose output which is useful when developing and testing the script, just append -verbose to the end of the command.
below is an example executed on my machine, this will be different on your machine, so use it as a guideline only:
<code title=sample deployment execution>
.\deploy-package.ps1 -azureaccountname myprojectuat `
-azureservicename myprojectuat `
-azuredeploymentslot production `
-azureaccountkey youraccountkey== `
-azuresubscriptionid yoursubscriptionid `
-azurecertificatethumbprint yourcertificatethumbprint `
-packagesource “c:\code\myproject\myproject\myproject.azure\bin\release\publish\myproject.azure.cspkg” `
-configsource “c:\code\myproject\myproject\myproject.azure\bin\release\publish\serviceconfiguration.uat.cscfg” `
-deploymentname local-uat-deploy-test -neo4jblobname neo4j-community-1.4.1-windows.zip `
-neo4jzippedbinaryfilehttpsource https://mydownloads.com/mydownloads/neo4j-community-1.4.1-windows.zip?dl=1 -verbose
</code>
note: when running the powershell command and the 64bit version of the scripts, ensure you running the powershell version that you fixed in the readme file from cerebrata, do not rely on the default shortcut links in the start menu!
summary
well, i hope this will help you automating azure deployments to the cloud, this a great way to keep uat happy with agile deployments to meet the goals of every sprint.
if you do not like the way we generate the package files above, you can choose to use csrun and cspack explicitly, i have prepared this script already, below is the code for you to use.
#requires -version 2.0 param ( [parameter(mandatory=$false)] [string]$artifactdownloadlocation ) $erroractionpreference = "stop" $installpath= join-path $artifactdownloadlocation "..\azurepackage" $azuretoolspackagesdkpath="c:\program files\windows azure sdk\v1.4\bin\cspack.exe" $azuretoolsdeploysdkpath="c:\program files\windows azure sdk\v1.4\bin\csrun.exe" $csdefinitionfile="..\..\neo4j.azure.server\servicedefinition.csdef" $csconfigurationfile="..\..\neo4j.azure.server\serviceconfiguration.cscfg" $webrolepropertiesfile = ".\webroleproperties.txt" $workerrolepropertiesfile=".\workerroleproperties.txt" $csoutputpackage="$installpath\neo4j.azure.server.csx" $serviceconfigurationfile = "$installpath\serviceconfiguration.cscfg" $webrolename="web" $webrolebinaryfolder="..\..\web" $workerrolename="neo4jserverhost" $workerrolebinaryfolder="..\..\neo4jserverhost\bin\debug" $workerroleentrypointdll="neo4j.azure.server.dll" function startazure{ "starting azure development fabric" & $azuretoolsdeploysdkpath /devfabric:start & $azuretoolsdeploysdkpath /devstore:start } function stopazure{ "shutting down development fabric" & $azuretoolsdeploysdkpath /devfabric:shutdown & $azuretoolsdeploysdkpath /devstore:shutdown } #example: cspack neo4j.azure.server\servicedefinition.csdef /out:.\neo4j.azure.server.csx /role:$webrolename;$webrolename /sites:$webrolename;$webrolename;.\$webrolename /role:neo4jserverhost;neo4jserverhost\bin\debug;neo4j.azure.server.dll /copyonly /rolepropertiesfile:$webrolename;webroleproperties.txt /rolepropertiesfile:$workerrolename;workerroleproperties.txt function packageazure() { "packaging the azure web and worker role." & $azuretoolspackagesdkpath $csdefinitionfile /out:$csoutputpackage /role:$webrolename";"$webrolebinaryfolder /sites:$webrolename";"$webrolename";"$webrolebinaryfolder /role:$workerrolename";"$workerrolebinaryfolder";"$workerroleentrypointdll /copyonly /rolepropertiesfile:$webrolename";"$webrolepropertiesfile /rolepropertiesfile:$workerrolename";"$workerrolepropertiesfile if (-not $?) { throw "the packaging process returned an error code." } } function copyserviceconfigurationfile() { "copying service configuration file." copy $csconfigurationfile $serviceconfigurationfile } #example: csrun /run:.\neo4j.azure.server.csx;.\neo4j.azure.server\serviceconfiguration.cscfg /launchbrowser function deployazure{param ([string] $azurecsxpath, [string] $azureconfigpath) "deploying the package" & $azuretoolsdeploysdkpath $csoutputpackage $serviceconfigurationfile if (-not $?) { throw "the deployment process returned an error code." } } write-host "beginning deploy and configuration at" (get-date) packageazure stopazure startazure copyserviceconfigurationfile deployazure '$csoutputpackage' '$serviceconfigurationfile' # give it 60s to boot up neo4j [system.threading.thread]::sleep(60000) # hit the homepage to make sure it's warmed up (new-object system.net.webclient).downloadstring("http://localhost:8080") | out-null write-host "completed deploy and configuration at" (get-date)
note, if using .net 4.0 which i am sure you all are, you will need to provide the text files for web role and worker role with these entries.
workerroleproperties.txt
targetframeworkversion=v4.0
entrypoint=neo4j.azure.server.dll
webroleproperties.txt
targetframeworkversion=v4.0
thanks to tatham oddie for contributing and coming up with such great ideas for our builds.
cheers
romiko
Opinions expressed by DZone contributors are their own.
Comments