Don Chambers
Don Chambers

Reputation: 4309

How do I use an azure private endpoint from a script called by a bicep?

I have a bicep that creates an Azure SQL with a private endpoint. Then I use this resource Microsoft.Resources/deploymentScripts@2020-10-01, to run a PowerShell script that connects to Azure Sql.

It fails because it is trying to use the public endpoint. How do I force this to use the private endpoint?

I get this error: Exception calling "Open" with "0" argument(s):

"Reason: An instance-specific error occurred while establishing a connection to SQL Server. Connection was denied since Deny Public Network Access is set to Yes (https://docs.microsoft.com/azure/azure-sql/database/connectivity-settings#deny-public-network-access). To connect to this server, use the Private Endpoint from inside your virtual network (https://docs.microsoft.com/azure/sql-database/sql-database-private-endpoint-overview#how-to-set-up-private-link-for-azure-sql-database)."

Upvotes: 0

Views: 610

Answers (1)

Jahnavi
Jahnavi

Reputation: 8058

  1. Run Test-NetConnection to return detailed connection information, including the time it takes to establish the connection Or you can use the Resolve-DnsName Powershell command to query the DNS name server of the private endpoint.

  2. Change the connection string in your PowerShell script to include the private endpoint URL. By referring to MSDoc, I've created a private endpoint for SQL database, added the below deployment script in script content block and was able to deploy it successfully.

resource runPowerShellInline 'Microsoft.Resources/deploymentScripts@2020-10-01' = {
....
properties: {
 scriptContent: '''
      $serverName = sqlServerName
      $database = databaseName
      $privateEndpointURL = "sqlServerName.privatelink.database.windows.net"
      $connString = "Server=$privateEndpointURL;Database=databaseName;User Id=sqlAdministratorLogin;Password=sqlAdministratorLoginPassword;"
      $SQLconnection = New-Object System.Data.SqlClient.SqlConnection
      $SQLconnection.ConnectionString = $connString
      $SQLconnection.Open()
   '''
  }
}
    

Deployment:

az deployment group create --resource-group "Jahnavi" --template-file script.bicep

Portal View deployment:

enter image description here

If still the issue persists, Check the PowerShell script is running in the context of the virtual network. If you run the deployment script from an Azure VM on the same virtual network as your Azure SQL Database's private endpoint, it should work as expected.

Upvotes: 0

Related Questions