Search code examples
sql-serverpowershellvagrantsqlcmd

Unable to connect to database using SqlCmd in a Vagrant provision script


I am using Vagrant to create a reproducible environment for work. In my vagrantfile I have the following:

config.vm.provision :shell, path: "./dependencies.ps1"

config.vm.provision :shell, reboot: true

config.vm.provision :shell, path: "./sql.ps1"

dependencies.ps1 runs the following:

choco install sql-server-express -o -ia "'/IACCEPTSQLSERVERLICENSETERMS /Q /ACTION=install /INSTANCEID=MSSQLSERVER /INSTANCENAME=MSSQLSERVER /UPDATEENABLED=FALSE'" -y

sql.ps1 at this stage has the following (just to test if I can connect):

SqlCmd -E -S LOCALDEV -Q "SELECT name FROM master.sys.databases"

The result is:

Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible

When SSMS is installed on the guest it connects with no issues using the server name LocalDev. Likewise, running the sql.ps1 script when I am logged in also works. This makes sense, the SQL Server instance is set to use Windows authentication, and as a logged in user I have the appropriate permissions. However this doesn't help with my vagrantfile, which needs to configure everything required for work out of the box (no pun intended).

I have tried various combinations of possible server names including localhost, localhost,1433, LocalDev\MSSQLSERVER, LocalDev\MSSQLSERVER, 1433 and so on but to no avail.

Any advice much appreciated.


Solution

  • After the scripted install of SQL Server I had:

    config.vm.provision :shell, reboot: true
    

    in my VagrantFile. The solution to the problem above was to briefly sleep after the reboot before attempting to connect to SQL Server. ie.

    Start-Sleep -Seconds 90
    Invoke-Sqlcmd -ServerInstance "LOCALHOST\MSSQLSERVER,1433" -Query "RESTORE DATABASE...
    

    The script ran straight after the reboot and, at that point in time, SQL Server wasn't available.