Search code examples
unit-testingazure-devopsmocking

Azure Dev Ops | Unit Test | Not able to connect to SQL Database


I'm trying to add my unit test project back into our pipeline run in Azure Dev Ops.

This worked in the past, but we had to remove it for X reason.

I have everything working and the first 2 test run fine. On the 3rd test it has to connect our SQL database on Azure.

Here is the error:

System.Data.SqlClient.SqlException: Cannot open server 'Server' requested by the login. Client with IP address 'IP Address' is not allowed to access the server.  To enable access, use the Azure Management Portal or run sp_set_firewall_rule on the master database to create a firewall rule for this IP address or address range.  It may take up to five minutes for this change to take effect.
  Stack Trace:

I tried to add the first IP address on the error, but then the IP address changed (as Azure services do). Well then I followed this link, which we already have checked.

What else am I missing?


Solution

  • You can use Azure CLI to add starting your pipeline. You can use command az sql server firewall-rule

    You can get ip address running curl ifconfig.me

    Here you have allow.ps1 script

    $serverName = "<server name>"
    $resourceGroupName = "<resource group name>"
    $ruleName = "<rule name>"
    $globalIPAddress = curl ifconfig.me
    
    echo "Global IP Address of this site: $globalIPAddress"
    
    az sql server firewall create --firewall-rule-name $ruleName --server-name $serverName -g $resourceGroupName --start-ip-address $globalIPAddress --end-ip-address $globalIPAddress > $null
    az sql server firewall list --server-name $serverName -g $resourceGroupName -o table
    

    And here deny.ps1 whoch you can run at the end of the pipeline to remove ip from allow list

    $serverName = "<server name>"
    $resourceGroupName = "<resource group name>"
    $ruleName = "<rule name>"
    
    az sql server firewall delete --firewall-rule-name $ruleName --server-name $serverName -g $resourceGroupName > $null
    az sql server firewall list --server-name $serverName -g $resourceGroupName -o table