My Profile Photo Title

Thoughts about DevOps and automation from a Windows guy


SQL Server Installation with DSC feature image

SQL Server Installation with DSC

If you’re looking for an example of a SQL Server Installation with DSC then read below.

I’m been playing a lot with DSC lately and specifically with the xSQLServerSetup resource in the xSQLServer module found in the DSC resource kit. In my tests I ran into the same bug detailed here on TechNet:

https://social.technet.microsoft.com/Forums/en-US/c31314f4-e440-424f-a52e-c8c6e2bf703b/powershell-dsc-xsqlserver-xsqlserversetup-error?forum=ITCG

The specific error is:

MSFT_xSQLServerSetup failed to execute Set-TargetResource functionality with error message: Set-TargetResouce failed.

I found that SQL was successfully being installed but the Local Configuration Manager was left in a weird state so I used this opportunity to build my own SQL installation module as an exercise for myself. This is in part based on another DSC module by Colin Dembovsky found here. This is not intended to replace all the functionality in the xSQLServer module and I expect I will use the xSQLServerSetup resource for production use once it is fully baked. All this module will do is install SQL Server using some basic settings. It will NOT modify or uninstall SQL if you change your DSC configuration after the fact. I had no need for that capability but feel free to extend this if you like.

DSC Configuration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
$computerName = "sql01"
$installCreds = Get-Credential
$saCreds = Get-Credential

$ConfigData = @{   
    AllNodes = @(        
        @{     
            NodeName = "*"
            PSDscAllowPlainTextPassword = $true
        }
        @{
            NodeName = $computerName
            Credentials = $creds
            SQLInstanceName = "MSSQLSERVER"
            SQLFeatures = "SQLENGINE, IS, CONN, BC, SDK, BOL, SSMS, ADV_SSMS"
            SQLSecurityMode = "SQL"
            SQLISOSourcePath = "<<PATH TO SQL ISO>>"
            SACredentials = $saCreds
        }
    )  
}

Configuration SQLInstallTest {
    param ()

    Import-DscResource -ModuleName cSQLInstaller

    Node $AllNodes.NodeName {          
        cscSQLInstaller InstallSQL {
            Name = "BaseSQLInstall"
            Ensure = "Present"
            SQLISOSourcePath = $Node.SQLISOSourcePath
            SetupCredentials = $Node.Credentials
            SecurityMode = $Node.SQLSecurityMode
            SAPwd = $Node.SACredentials
        }
    }
}

Custom SQL Install Resource

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
function Get-TargetResource {
  [CmdletBinding()]
  [OutputType([System.Collections.Hashtable])]
  param (
    [parameter(Mandatory = $true)]
    [System.String]
    $Name,

    [parameter(Mandatory = $true)]
    [ValidateSet("Present","Absent")]
    [System.String]
    $Ensure,

    [parameter(Mandatory = $true)]
    [System.String]
    $SQLISOSourcePath,

    [parameter(Mandatory = $true)]
    [System.Management.Automation.PSCredential]
    $SetupCredentials,

    [parameter(Mandatory = $true)]
    [ValidateSet("SQL","Windows")]
    [System.String]
    $SecurityMode
  )

  # Get SQL instances
  $sqlInstances = gwmi win32_service -computerName localhost | ? { $_.Name -match "mssql*" -and $_.PathName -match "sqlservr.exe" } | % { $_.Caption }
  $res = $sqlInstances -ne $null -and $sqlInstances -gt 0
  $vals = @{
    Installed = $res;
    InstanceCount = $sqlInstances.count
  }
  $vals
}


function Set-TargetResource {
  [CmdletBinding()]
  param (
    [parameter(Mandatory = $true)]
    [System.String]
    $Name,

    [parameter(Mandatory = $true)]
    [ValidateSet("Present","Absent")]
    [System.String]
    $Ensure,

    [System.String]
    $Features = "SQLENGINE,IS,CONN,BC,SDK,BOL,SSMS,ADV_SSMS",

    [System.String]
    $InstanceName = "MSSQLSERVER",

    [System.String]
    $InstanceDir = "D:\MSSQL",

    [System.String]
    $SQLCollation = "Latin1_General_100_CI_AS_KS_WS_SC",

    [System.String]
    $SQLUserDBDir = "D:\MSSQL\Data",

    [System.String]
    $SQLUserDBLogDir = "L:\MSSQL\Data",

    [System.String]
    $SQLTempDBDir = "T:\MSSQL\Data",

    [System.String]
    $SQLTempDBLogDir = "V:\MSSQL\Data",

    [System.String]
    $SQLBackupDir = "D:\MSSQL\Backups",

    [parameter(Mandatory = $true)]
    [System.String]
    $SQLISOSourcePath,

    [parameter(Mandatory = $true)]
    [System.Management.Automation.PSCredential]
    $SetupCredentials,

    [parameter(Mandatory = $true)]
    [ValidateSet("SQL","Windows")]
    [System.String]
    $SecurityMode,

    [System.Management.Automation.PSCredential]
    $SAPwd,

    [System.Management.Automation.PSCredential]
    $SQLSvcAccount,

    [System.Management.Automation.PSCredential]
    $AgtSvcAccount
  )

  if ($Ensure -eq "Present") {
    #region Copy and mount ISO
    $localISOPath = (Join-Path -Path $env:SystemDrive -ChildPath "Temp")
    Write-Verbose "Copying SQL ISO locally"                
    $localISOFullPath = Copy-Item -Path $SQLISOSourcePath -Destination $localISOPath -Force -PassThru

    Write-Verbose "Mounting SQL ISO file"
    $setupDriveLetter = (Mount-DiskImage -ImagePath $localISOFullPath -PassThru | Get-Volume).DriveLetter + ":"
    if ($setupDriveLetter -eq $null) {
      throw "Could not mount SQL install iso"
    }
    Write-Verbose "Drive letter for ISO is: $setupDriveLetter"
    #endregion

    #region Build install arguments
    $arguments = " /Quiet=`"True`" /IAcceptSQLServerLicenseTerms=`"True`" /Enu=`"True`" /UpdateEnabled=`"True`" /UpdateSource=`"MU`" /ErrorReporting=`"False`" /Action=`"Install`""
    $arguments += " /Help=`"False`" /IndicateProgress=`"False`" /x86=`"False`" /InstallSharedDir=`"C:\Program Files\Microsoft SQL Server`" /InstallSharedWoWDir=`"C:\Program Files (x86)\Microsoft SQL Server`" "
    $arguments += " /InstanceName=`"$InstanceName`" "
    $arguments += " /Features=`"" + $Features + "`" /SQMReporting=`"False`" /InstanceID=`"MSSQLSERVER`" /SQLCollation=`"$SQLCollation`" "

    # SQLSvcAccount
    if($PSBoundParameters.ContainsKey("SQLSvcAccount")) {
      if($SQLSvcAccount.UserName -eq "SYSTEM") {
        $arguments += " /SQLSVCACCOUNT=`"NT AUTHORITY\SYSTEM`""
      } else {
        $arguments += " /SQLSVCACCOUNT=`"" + $SQLSvcAccount.UserName + "`""
        $arguments += " /SQLSVCPASSWORD=`"" + $SQLSvcAccount.GetNetworkCredential().Password + "`""
      }
    }

    # AgtSvcAccount
    if($PSBoundParameters.ContainsKey("AgtSvcAccount")) {
      if($AgtSvcAccount.UserName -eq "SYSTEM") {
        $arguments += " /AGTSVCACCOUNT=`"NT AUTHORITY\SYSTEM`" "
      } else {
        $arguments += " /AGTSVCACCOUNT=`"" + $AgtSvcAccount.UserName + "`""
        $arguments += " /AGTSVCPASSWORD=`"" + $AgtSvcAccount.GetNetworkCredential().Password + "`""
      }
    }
    $arguments += " /AGTSVCSTARTUPTYPE=Automatic "

    # SQLSysAdminAccounts
    $arguments += " /SQLSysAdminAccounts=`"" + $SetupCredentials.UserName + "`""
    if($PSBoundParameters.ContainsKey("SQLSysAdminAccounts")) {
      foreach($AdminAccount in $SQLSysAdminAccounts) {
        $arguments += " `"$AdminAccount`""
      }
    }

    # SAPwd
    if($SecurityMode -eq "SQL") {
      $arguments += " /SecurityMode=`"SQL`" "
      $arguments += " /SAPwd=" + "'" + $SAPwd.GetNetworkCredential().Password + "'"
    }        
    #endregion

    #region Run the installer using arguments
    Write-Verbose  $arguments
    $cmd = "$setupDriveLetter\Setup.exe " + $arguments
    Write-Verbose "Running SQL Install - check %programfiles%\Microsoft SQL Server\120\Setup Bootstrap\Log\ for logs..."
    Invoke-Expression $cmd | Write-Verbose
    #endregion

    #region Finish
    Write-Verbose "Dismounting SQL ISO"
    Dismount-DiskImage -ImagePath $localISOFullPath
    Write-Verbose "Removing install files"
    Remove-Item $localISOFullPath -Force
    #endregion
  }
}


function Test-TargetResource {
  [CmdletBinding()]
  [OutputType([System.Boolean])]
  param (
    [parameter(Mandatory = $true)]
    [System.String]
    $Name,

    [parameter(Mandatory = $true)]
    [ValidateSet("Present","Absent")]
    [System.String]
    $Ensure,

    [System.String]
    $Features = "SQLENGINE,IS,CONN,BC,SDK,BOL,SSMS,ADV_SSMS",

    [System.String]
    $InstanceName = "MSSQLSERVER",

    [System.String]
    $InstanceDir = "D:\MSSQL",

    [System.String]
    $SQLCollation = "Latin1_General_100_CI_AS_KS_WS_SC",

    [System.String]
    $SQLUserDBDir = "D:\MSSQL\Data",

    [System.String]
    $SQLUserDBLogDir = "L:\MSSQL\Data",

    [System.String]
    $SQLTempDBDir = "T:\MSSQL\Data",

    [System.String]
    $SQLTempDBLogDir = "V:\MSSQL\Data",

    [System.String]
    $SQLBackupDir = "D:\MSSQL\Backups",

    [parameter(Mandatory = $true)]
    [System.String]
    $SQLISOSourcePath,

    [parameter(Mandatory = $true)]
    [System.Management.Automation.PSCredential]
    $SetupCredentials,

    [parameter(Mandatory = $true)]
    [ValidateSet("SQL","Windows")]
    [System.String]
    $SecurityMode,

    [System.Management.Automation.PSCredential]
    $SAPwd,

    [System.Management.Automation.PSCredential]
    $SQLSvcAccount,

    [System.Management.Automation.PSCredential]
    $AgtSvcAccount
  )

  $sqlInstances = gwmi win32_service -computerName localhost | ? { $_.Name -match "mssql*" -and $_.PathName -match "sqlservr.exe" } | % { $_.Caption }
  $res = $sqlInstances -ne $null -and $sqlInstances -gt 0
  if ($res) {
    Write-Verbose "SQL Server is already installed"
  } else {
    Write-Verbose "SQL Server is not installed"
  }
  $res
}


Export-ModuleMember -Function *-TargetResource

Cheers,

Brandon

Sharing is caring