Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Outbound IP Registration to Azure SQL Using Azure Functions
[FunctionName("UpdateFirewallRulesHttpTrigger")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = "firewall/rules")]HttpRequestMessage req,
TraceWriter log)
{
...
log.Info($"Firewall rules on database servers in {resourceGroupName} are updating...");
...
var tasks = new List<Task>();
var servers = await azure.SqlServers
.ListByResourceGroupAsync(resourceGroupName)
.ConfigureAwait(false);
foreach (var server in servers)
{
var registeredIps = server.FirewallRules
.List()
.ToDictionary(p => p.Name, p => p.StartIPAddress);
var ipsToExclude = registeredIps.Where(p => !outboundIps.Contains(p.Value))
.Select(p => p.Key)
.ToList();
var IpsToInclude = outboundIps.Where(p => !registeredIps.ContainsValue(p))
.ToList();
var tasksToExclude = ipsToExclude.Select(ip => server.FirewallRules
.DeleteAsync(ip));
var tasksToInclude = IpsToInclude.Select(ip => server.FirewallRules
.Define($"webapp-{ip.Replace(".", "-")}")
.WithIPAddressRange(ip, ip)
.CreateAsync());
tasks.AddRange(tasksToExclude);
tasks.AddRange(tasksToInclude);
}
await Task.WhenAll(tasks).ConfigureAwait(false);
log.Info($"Firewall rules on database servers in {resourceGroupName} have been updated.");
return req.CreateResponse(HttpStatusCode.OK);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment