Debian Codegraph @

ansible_collections/lowlydba/sqlserver/plugins/modules/spn.ps1

raw
1 #!powershell
2 # -*- coding: utf-8 -*-
3
4 # (c) 2022, John McCall (@lowlydba)
5 # (c) 2021, Sudhir Koduri (@kodurisudhir)
6 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 #AnsibleRequires -CSharpUtil Ansible.Basic
9 #AnsibleRequires -PowerShell ansible_collections.lowlydba.sqlserver.plugins.module_utils._SqlServerUtils
10 #Requires -Modules @{ ModuleName="dbatools"; ModuleVersion="2.0.0" }
11
12 $ErrorActionPreference = "Stop"
13
14 $spec = @{
15 supports_check_mode = $true
16 options = @{
17 computer_username = @{ type = 'str'; required = $false }
18 computer_password = @{ type = 'str'; required = $false; no_log = $true; }
19 computer = @{ type = 'str'; required = $true }
20 service_account = @{ type = 'str'; required = $true; }
21 state = @{ type = 'str'; required = $false; default = 'present'; choices = @('present', 'absent') }
22 }
23 required_together = @(
24 , @('computer_username', 'computer_password')
25 )
26 }
27 $module = [Ansible.Basic.AnsibleModule]::Create($args, $spec)
28 if ($null -ne $module.Params.computer_username) {
29 [securestring]$secPassword = ConvertTo-SecureString $Module.Params.computer_password -AsPlainText -Force
30 [pscredential]$computerCredential = New-Object System.Management.Automation.PSCredential ($Module.Params.computer_username, $secPassword)
31 }
32 $computer = $module.Params.computer
33 $serviceAccount = $module.Params.service_account
34 $serviceClass = "MSSQLSvc"
35 $spn = "$serviceClass/$computer"
36 $state = $module.Params.state
37 $checkMode = $module.CheckMode
38 $module.Result.changed = $false
39 $PSDefaultParameterValues = @{ "*:EnableException" = $true; "*:Confirm" = $false; "*:WhatIf" = $checkMode }
40
41 try {
42 $existingSPN = Get-DbaSpn -ComputerName $computer -Credential $computerCredential -AccountName $serviceAccount | Where-Object spn -eq $spn
43
44 if ($state -eq "present") {
45 if ($null -ne $existingSPN) {
46 # SPNs can only be added and removed, not modified
47 $module.ExitJson()
48 }
49 elseif ($null -eq $existingSPN) {
50 $output = Set-DbaSpn -SPN $spn -ServiceAccount $serviceAccount -Credential $computerCredential
51 $module.Result.changed = $true
52 }
53 }
54 elseif ($state -eq "absent") {
55 if ($null -ne $existingSPN) {
56 $output = Remove-DbaSpn -SPN $spn -ServiceAccount $serviceAccount -Credential $computerCredential
57 $module.Result.changed = $true
58 }
59 }
60
61 if ($output) {
62 $resultData = ConvertTo-SerializableObject -InputObject $output
63 $module.Result.data = $resultData
64 }
65 $module.ExitJson()
66 }
67 catch {
68 $module.FailJson("Configuring SPN failed: $($_.Exception.Message)", $_)
69 }