summaryrefslogtreecommitdiffstats
path: root/ansible_collections/lowlydba/sqlserver/plugins/modules/database.ps1
blob: dc030946c6199e33d91e6dbc541412eb1071be83 (plain)
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
249
250
251
252
253
254
#!powershell
# -*- coding: utf-8 -*-

# (c) 2022, John McCall (@lowlydba)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

#AnsibleRequires -CSharpUtil Ansible.Basic
#AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
#Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="2.0.0" }

$ErrorActionPreference = "Stop"

$spec = @{
    supports_check_mode = $true
    options = @{
        database = @{type = 'str'; required = $true }
        recovery_model = @{type = 'str'; required = $false; choices = @('Full', 'Simple', 'BulkLogged') }
        data_file_path = @{type = 'str'; required = $false }
        log_file_path = @{type = 'str'; required = $false }
        owner = @{type = 'str'; required = $false; }
        maxdop = @{type = 'int'; required = $false; }
        secondary_maxdop = @{type = 'int'; required = $false; }
        compatibility = @{type = 'str'; required = $false; }
        rcsi = @{type = 'bool'; required = $false; }
        only_accessible = @{type = 'bool'; default = 'true' }
        state = @{type = 'str'; required = $false; default = 'present'; choices = @('present', 'absent') }
    }
}

$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-LowlyDbaSqlServerAuthSpec))
$sqlInstance, $sqlCredential = Get-SqlCredential -Module $module
$database = $module.Params.database
$recoveryModel = $module.Params.recovery_model
$dataFilePath = $module.Params.data_file_path
$logFilePath = $module.Params.log_file_path
$owner = $module.Params.owner
$compatibility = $module.Params.compatibility
[nullable[bool]]$rcsiEnabled = $module.Params.rcsi
[nullable[bool]]$onlyAccessible = $module.Params.only_accessible
[nullable[int]]$maxDop = $module.Params.maxdop
[nullable[int]]$secondaryMaxDop = $module.Params.secondary_maxdop
$state = $module.Params.state
$checkMode = $module.CheckMode

try {
    # Get database status
    try {
        $server = Connect-DbaInstance -SqlInstance $sqlInstance -SqlCredential $sqlCredential
        $getDatabaseSplat = @{
            SqlInstance = $sqlInstance
            SqlCredential = $sqlCredential
            Database = $database
            OnlyAccessible = $onlyAccessible
            ExcludeSystem = $true
            EnableException = $true
        }
        $existingDatabase = Get-DbaDatabase @getDatabaseSplat
        $output = $existingDatabase
    }
    catch {
        $module.FailJson("Error checking database status.", $_.Exception.Message)
    }

    if ($state -eq "absent") {
        if ($null -ne $existingDatabase) {
            try {
                $droppedDatabase = $existingDatabase | Remove-DbaDatabase -WhatIf:$checkMode -EnableException -Confirm:$false
                if ($droppedDatabase.Status -eq "Dropped") {
                    $module.Result.changed = $true
                }
                elseif ($droppedDatabase.Status -ne "Dropped") {
                    $module.FailJson("Database [$database] was not dropped. " + $droppedDatabase.Status)
                }
            }
            catch {
                $module.FailJson("An exception occurred while trying to drop database [$database].", $_)
            }
        }
        $module.ExitJson()
    }
    elseif ($state -eq "present") {
        # Create database
        if ($null -eq $existingDatabase) {
            try {
                $newDbParams = @{
                    SqlInstance = $sqlInstance
                    SqlCredential = $sqlCredential
                    Database = $database
                    WhatIf = $checkMode
                    EnableException = $true
                }
                if ($null -ne $dataFilePath) {
                    $newDbParams.Add("DataFilePath", $dataFilePath)
                }
                if ($null -ne $logFilePath) {
                    $newDbParams.Add("LogFilePath", $logFilePath)
                }
                if ($null -ne $owner) {
                    $newDbParams.Add("Owner", $owner)
                }
                $output = New-DbaDatabase @newDbParams
                $module.Result.changed = $true
            }
            catch {
                $module.FailJson("Creating database [$database] failed.", $_)
            }
        }
        # Set Owner
        elseif ($null -ne $owner) {
            try {
                if ($existingDatabase.Owner -ne $owner) {
                    $setDbParams = @{
                        SqlInstance = $sqlInstance
                        SqlCredential = $sqlCredential
                        Database = $database
                        TargetLogin = $owner
                        WhatIf = $checkMode
                        EnableException = $true
                    }
                    $null = Set-DbaDbOwner @setDbParams
                    $output = Get-DbaDatabase @getDatabaseSplat
                    $module.Result.changed = $true
                }
            }
            catch {
                $module.FailJson("Setting database owner for [$database] failed.", $_)
            }
        }

        # Add non-standard fields to output
        if ($null -ne $output) {
            # Secondary MaxDop
            [int]$existingSecondaryMaxDop = $server.Databases[$database].SecondaryMaxDop
            $output | Add-Member -MemberType NoteProperty -Name "SecondaryMaxDop" -Value $existingSecondaryMaxDop
            $output.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames.Add("SecondaryMaxDop")

            # MaxDop (exists, but is not in default display)
            $existingMaxDop = $server.Databases[$database].MaxDop
            $output.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames.Add("MaxDop")

            # RCSI
            $existingRCSI = $server.Databases[$database].IsReadCommittedSnapshotOn
            $output | Add-Member -MemberType NoteProperty -Name "RCSI" -Value $existingRCSI
            $output.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames.Add("RCSI")
        }

        # Recovery Model
        if ($null -ne $recoveryModel) {
            try {
                if ($recoveryModel -ne $output.RecoveryModel) {
                    $recoveryModelSplat = @{
                        SqlInstance = $sqlInstance
                        SqlCredential = $sqlCredential
                        Database = $database
                        RecoveryModel = $recoveryModel
                        WhatIf = $checkMode
                        EnableException = $true
                        Confirm = $false
                    }
                    $null = Set-DbaDbRecoveryModel @recoveryModelSplat
                    $output.RecoveryModel = $recoveryModel
                    $module.Result.changed = $true
                }
            }
            catch {
                $module.FailJson("Setting recovery model for [$database] failed.", $_)
            }
        }

        # Compatibility Mode
        if ($null -ne $compatibility) {
            try {
                $existingCompatibility = $output.Compatibility
                if ($compatibility -ne $existingCompatibility) {
                    $compatSplat = @{
                        SqlInstance = $sqlInstance
                        SqlCredential = $sqlCredential
                        Database = $database
                        Compatibility = $compatibility
                        WhatIf = $checkMode
                        EnableException = $true
                    }
                    $null = Set-DbaDbCompatibility @compatSplat
                    $output.Compatibility = $compatibility
                    $module.Result.changed = $true
                }
            }
            catch {
                $module.FailJson("Setting Compatibility for [$database] failed.", $_)
            }
        }

        # RCSI
        if ($null -ne $rcsiEnabled) {
            try {
                if ($rcsiEnabled -ne $existingRCSI) {
                    if (-not $checkMode) {
                        $server.Databases[$database].IsReadCommittedSnapshotOn = $rcsiEnabled
                        $server.Databases[$database].Alter()
                        $output.RCSI = $rcsiEnabled
                    }
                    $module.Result.changed = $true
                }
            }
            catch {
                $module.FailJson("Setting Read Commmitted Snapshot Isolation for [$database] failed.", $_)
            }
        }

        # Configure MAXDOPs
        ## Database Scoped MaxDop
        if ($null -ne $MaxDop) {
            try {
                if ($MaxDop -ne $existingMaxDop) {
                    if (-not $checkMode) {
                        $server.Databases[$database].MaxDop = $maxDop
                        $server.Databases[$database].Alter()
                        $output.MaxDop = $MaxDOP
                    }
                    $module.Result.changed = $true
                }
            }
            catch {
                $module.FailJson("Setting MAXDOP for [$database] failed.", $_)
            }
        }

        ## Secondary Mode MaxDop
        if ($null -ne $secondaryMaxDOP) {
            try {
                if ($secondaryMaxDop -ne $existingSecondaryMaxDop) {
                    if (-not $checkMode) {
                        $server.Databases[$database].MaxDopForSecondary = $secondaryMaxDOP
                        $server.Databases[$database].Alter()
                        $output.SecondaryMaxDop = $secondaryMaxDop
                    }
                    $module.Result.changed = $true
                }
            }
            catch {
                $module.FailJson("Setting MaxDop for secondary mode failed.", $_)
            }
        }
    }

    if ($null -ne $output) {
        $resultData = ConvertTo-SerializableObject -InputObject $output
        $module.Result.data = $resultData
    }
    $module.ExitJson()
}
catch {
    $module.FailJson("Configuring database failed: $($_.Exception.Message)", $_)
}