Public/Set-BuildSecrets.ps1

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
function Set-BuildSecrets {
        <#
    .SYNOPSIS
        Sets all secrets stored in a specific key vault as environment variables.
    .DESCRIPTION
        Sets all secrets stored in a specific key vault as environment variables. The user has to login to azure first using "Login-AzureRMAccount"
    .PARAMETER KeyVaultName
        The name of the key vault containing the environment
    .PARAMETER SubscriptionID
            Allows the user to specify a subscription id if required. if not specified, the default subscription will be used.
    .PARAMETER UseSecureString
        If specified the securestring version of the secrets will be stored in the environment.
    .EXAMPLE
        Set-BuildEnvironment -KeyVaultName "MyVault" -ResourceGroupName "MyResourceGroup"
    #>
    
    
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [String]$KeyVaultName,
        [Parameter(Mandatory=$false)]
        [String]$SubscriptionID,
        [Parameter(Mandatory=$false)]
        [Switch]$UseSecureString
    )
    

    Begin {
        
    }
    Process {

        try {         
                     
            # This would set all secrets of a vault as environment variables.
            $Secrets = Get-AzureKeyVaultSecret -VaultName $KeyVaultName | Where-Object -Property Tags -In $Tag | Select-Object -ExpandProperty Name           
                       
            foreach ($Secret in $Secrets) {  
        
                # We get the secret from azure key vault
                $SecretValue = Get-AzureKeyVaultSecret -VaultName $KeyVaultName -Name $Secret

               if ($UseSecureString) {
                    # Set Environment Variable using secure string
                    New-Item -Path Env:$Secret -Value $SecretValue.SecretValue -Force
               } else {
                    # Set Environment Variable using clear text
                    New-Item -Path Env:$Secret -Value $SecretValue.SecretValueText -Force
               }    

            }

             # Store the secret names of the environment which is being loaded.
             $Script:BuildEnvironment += $KeyVaultName

        } Catch {              
            Throw "$($_.Exception.Message)"
        }
  
    }
    End {
    
    }

}