[Sample of Apr 13rd] How to add firewall rules programmatically in Windows Azure

 

Homepage image
Sample of the Day RSS Feed

Sample Download: https://code.msdn.microsoft.com/CSAzureAddFirewallRules-352de4ed

One of the common asks from developers is the ability to add firewall rules to Windows Azure Compute instances. Startup tasks in Windows Azure can help you add firewall rules. This sample code will add few sample firewall rules to Azure VM's.

The sample is written by Microsoft Escalation Engineer - Narahari Dogiparthi.

imageYou can find more code samples that demonstrate the most typical programming scenarios by using Microsoft All-In-One Code Framework Sample Browser or Sample Browser Visual Studio extension. They give you the flexibility to search samples, download samples on demand, manage the downloaded samples in a centralized place, and automatically be notified about sample updates. If it is the first time that you hear about Microsoft All-In-One Code Framework, please watch the introduction video on Microsoft Showcase, or read the introduction on our homepage https://1code.codeplex.com/.

 

Introduction

One of the common asks from developers is the ability to add firewall rules to Windows Azure Compute instances. Startup tasks in Windows Azure can help you add firewall rules.  This sample code will add few sample firewall rules to Azure VM's.

 

Building the Sample

This sample can be run as-is without making any changes to it.

 

Running the Sample

Open the sample on the machine where VS 2010, Windows Azure SDK 1.6 are installed
 
Right click on the cloud service project i.e. CSAzureAddFirewallRules and choose Publish
 
Follow the steps in publish Wizard and choose subscription details, deployment slots, etc. and enable remote desktop for all roles
 
After successful publish, login to Azure VM and verify that 3 inbound firewall rules are added. You can use “Windows Firewall With Advanced Security” program to verify the firewall rules.

 

Using the Code

1) Create firewallrules.cmd file with below code:
 
netsh advfirewall firewall add rule name="ICMPv6" dir=in action=allow enable=yes protocol=icmpv6
netsh advfirewall firewall add rule name="Windows Remote Management (HTTP-In)" dir=in action=allow service=any enable=yes profile=any localport=5985 protocol=tcp
netsh advfirewall firewall add rule name="Allowing Interal Service Traffic"  dir=in action=allow localport=444 protocol=tcp
 
2) Add the firewallrules.cmd file to Web Role / Worker role as required.
 
3) Configure below file properties for addreg.cmd file , so that it will be copied to bin directory.
 
Build Action : Content
Copy To Output Directory : Copy Always
 
4) Finally, define startup task in ServiceDefinition.csdef file by adding following block of configuration under <Webrole> / <WorkerRole> tag

<Startup> <Task commandLine="firewallrules.cmd" executionContext="elevated" taskType="simple"> </Task> </Startup>

5) Deploy the application to cloud.