cAzureKeyVault.psm1

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
enum Ensure {
    Absent
    Present
}

<#
    This resource retrieves an Azure Key Vault secret and saves it to a specified file
#>


[DscResource()]
class AzureKeyVaultSecret {

    <#
        Key Vault secret name to retrieve
    #>

    [DscProperty(Key)]
    [string] $SecretName

    <#
        Whether or not to Base64 decode the contents before serializing to a file
    #>

    [DscProperty()]
    [bool] $Base64Decode = $false

    <#
        Fully qualified path to the file that is expected to be present or absent.
    #>

    [DscProperty(Mandatory)]
    [string] $Path

    <#
        Key Vault secret name to retrieve
    #>

    [DscProperty(Mandatory)]
    [string] $VaultName

    [DscProperty(Mandatory)]
    [Ensure] $Ensure

    <#
        Azure Resource Manager account credentials with GET access to the Key Vault
    #>

    [DscProperty(Mandatory)]
    [PSCredential] $Credential

    <#
        Azure Resource Manager account tenant Id used for logging in
    #>

    [DscProperty(Mandatory)]
    [string] $TenantId
  
    [DscProperty(NotConfigurable)]
    [Nullable[datetime]] $CreationTime

    [DscProperty(NotConfigurable)]
    [string] $FileSize

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")]
    [void] Set() {
        $this.VerifyModuleDependencies()
        $fileExists = $this.TestFilePath($this.Path)
        if ($this.Ensure -eq [Ensure]::Present) {
            if (-not $fileExists) {
                try {
                    LoginAzureRmAccount -Credential $this.Credential -TenantId $this.TenantId
                    $keyVaultSecret = GetAzureKeyVaultSecret -VaultName $this.VaultName -Name $this.SecretName
                    if ($this.Base64Decode) {
                        $bytes = [System.Convert]::FromBase64String($keyVaultSecret.SecretValueText)
                        [System.IO.File]::WriteAllBytes($this.Path, $bytes)
                    }
                    else {
                        # Encrypt the secret value. Note that this must be decrypted using the same PsDscRunAsCredential used in this step.
                        Set-Content -Path $this.Path -Value (ConvertTo-SecureString $keyVaultSecret.SecretValueText -AsPlainText -Force | ConvertFrom-SecureString)
                    }
                }
                catch {
                    if ($this.TestFilePath($this.Path)) {
                        Remove-Item -LiteralPath $this.Path -Force
                    }
                    throw $_
                }
            }
        }
        else {
            if ($fileExists) {
                Write-Verbose -Message "Deleting the file $($this.Path)"
                Remove-Item -LiteralPath $this.Path -Force
            }
        }
    }

    [bool] Test() {
        $present = $this.TestFilePath($this.Path)
        if ($this.Ensure -eq [Ensure]::Present) {
            return $present
        }
        else {
            return -not $present
        }
    }

    [AzureKeyVaultSecret] Get() {
        $present = $this.TestFilePath($this.Path)

        if ($present) {
            $file = Get-ChildItem -LiteralPath $this.Path
            $this.CreationTime = $file.CreationTime
            $this.FileSize = $file.Length
            $this.Ensure = [Ensure]::Present
        }
        else {
            $this.CreationTime = $null
            $this.FileSize = $null
            $this.Ensure = [Ensure]::Absent
        }

        return $this 
    }

    <#
        .SYNOPSIS
            Helper function to check if file exists
 
        .PARAMETER location
            Fully qualified path to file
    #>

    [bool] TestFilePath([string] $location) {
        $present = $true
        $item = Get-ChildItem -LiteralPath $location -ErrorAction Ignore
        if ($item -eq $null) {
            $present = $false
        }
        elseif ($item.PSProvider.Name -ne "FileSystem") {
            throw "Path $($location) is not a file path."
        }
        elseif ($item.PSIsContainer) {
            throw "Path $($location) is a directory path."
        }

        return $present
    }

    <#
        .SYNOPSIS
            Helper function to validate dependent modules exist
    #>

    [void] VerifyModuleDependencies() {
        $dependentModules = @(
            "AzureRM.Profile", 
            "AzureRM.KeyVault")
        $this.VerifyModuleDependencies($dependentModules)
    }
        
    [void] VerifyModuleDependencies([string[]]$dependentModules) {
        $dependentModules | % {
            if (-not(Get-Module -Name $_ -ListAvailable -Refresh)) {
                $exception = New-Object System.InvalidOperationException "Please ensure that the $_ Powershell module is installed"
                $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, "ModuleNotFound", ObjectNotFound, $null
                throw $errorRecord
            }
        }
    }

}

Function LoginAzureRmAccount([PSCredential]$Credential, [string]$TenantId) {
    Login-AzureRmAccount -ServicePrincipal -Credential $Credential -TenantId $TenantId
}

Function GetAzureKeyVaultSecret([string]$VaultName, [string]$Name) {
    return Get-AzureKeyVaultSecret -VaultName $VaultName -Name $Name
}