Setting IPRestrictions in a Windows Azure Cloud App Deployment

posted in
To set IP Restrictions in Windows Azure, you have to do 2 things, create an azure startup task in your service configuration (.cscg file), and a cmd file that runs it.

Create a Service Configuration Startup Task to run a startup command
      <Task commandLine="startup\ip-restrictions.cmd" executionContext="elevated">
          <Variable name="EMULATED">
            <RoleInstanceValue xpath="/RoleEnvironment/Deployment/@emulated" />
          <Variable name="RESTRICTIP">
            <RoleInstanceValue xpath="/RoleEnvironment/CurrentInstance/ConfigurationSettings/ConfigurationSetting[@name='RestrictIp']/@value"/>

Create a startup command 

This startup command checks the "RESTRICTIP" variable so that you can have different deployments that you can set whether or not to restrict IPs by (beta, test, production, etc).  It also bypasses this if you are running the Azure Emulator.

This installs the IP Restriction Windows Role, unlocks the IIS Config, and sets the appropriate IP Restrictions (put your IP in place of

if "%RESTRICTIP%"=="false" goto :EOF
if "%EMULATED%"=="true" goto :EOF

powershell Install-WindowsFeature Web-IP-Security
%windir%\system32\inetsrv\AppCmd.exe unlock config -section:system.webServer/security/ipSecurity
%windir%\system32\inetsrv\AppCmd.exe set config -section:system.webServer/security/ipSecurity /~ /commit:apphost
%windir%\system32\inetsrv\AppCmd.exe set config -section:system.webServer/security/ipSecurity /allowUnlisted:false /commit:apphost
%windir%\system32\inetsrv\AppCmd.exe set config -section:system.webServer/security/ipSecurity /+"[ipAddress='',allowed='True']" /commit:apphost

This particular solution will not work well if you are trying to have IP restrictions on your staging deployment, and not your production deployment, since the startup command only runs on a deploy, and you will likely just swap VIPs to go from staging to production.
Find a problem or mistake? File a bug or better yet, submit a pull request
Copyright © 2010 - 2022 - Doug Tarr