Public/SDK Wrappers/Invoke-VSDeploy.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
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
function Invoke-VSDeploy {
    <#
    .SYNOPSIS
    Creates a change set then executes it
    
    .DESCRIPTION
    Invokes a change set in CloudFormation. If the stack name already exists, it updates that stack. If it does not, it creates a new stack.
    
    .PARAMETER TemplateBody
    A JSON or YAML string containing the template body.
    
    .PARAMETER TemplateFile
    The path to the local file containing the template.
    
    .PARAMETER StackName
    The name of the AWS CloudFormation stack you're deploying to. If you specify an existing stack, the command updates the stack. If you specify a new stack, the command creates it.
    
    .PARAMETER Parameters
    A hashtable of key-value parameters that specify input parameters for your stack template. If you're updating a stack and you don't specify a parameter, the command uses the stack's existing value. For new stacks, you must specify parameters that don't have a default value.
    
    .PARAMETER Capabilities
    A list of capabilities that you must specify before AWS Cloudformation can create certain stacks. Some stack templates might include resources that can affect permissions in your AWS account, for example, by creating new AWS Identity and Access Management (IAM) users. For those stacks, you must explicitly acknowledge their capabilities by specifying this parameter. The only valid values are CAPABILITY_IAM and CAPABILITY_NAMED_IAM. If you have IAM resources, you can specify either capability. If you have IAM resources with custom names, you must specify CAPABILITY_NAMED_IAM
    
    .PARAMETER DoNotExecute
    Indicates whether to execute the change set. Specify this flag if you want to view your stack changes before executing the change set. The command creates an AWS CloudFormation change set and then exits without executing the change set. After you view the change set, execute it to implement your changes.
    
    .PARAMETER RoleARN
    The Amazon Resource Name (ARN) of an AWS Identity and Access Management (IAM) role that AWS CloudFormation assumes when executing the change set.
    
    .PARAMETER NotificationARNs
    Amazon Simple Notification Service topic Amazon Resource Names (ARNs) that AWS CloudFormation associates with the stack.
    
    .PARAMETER ProfileName
    The name of the configuration profile to deploy the stack with. Defaults to $env:AWS_PROFILE, if set.
    
    .FUNCTIONALITY
    Vaporshell
    #>

    [cmdletbinding(DefaultParameterSetName = "TemplateFile")]
    Param
    (
        [parameter(Mandatory = $true,Position = 0,ParameterSetName = "TemplateBody",ValueFromPipeline = $true)]
        [String]
        $TemplateBody,
        [parameter(Mandatory = $true,Position = 0,ParameterSetName = "TemplateFile")]
        [ValidateScript({
                Test-Path $_
            })]
        [String]
        $TemplateFile,
        [parameter(Mandatory = $true,Position = 1)]
        [String]
        $StackName,
        [parameter(Mandatory = $false)]
        [ValidateScript( {
                $allowedTypes = "System.Management.Automation.PSCustomObject","Amazon.CloudFormation.Model.Parameter","System.Collections.Hashtable"
                if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
                    $true
                }
                else {
                    $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
                }
            })]
        [Alias("ParameterOverrides")]
        $Parameters,
        [parameter(Mandatory = $false)]
        [ValidateSet("CAPABILITY_IAM","CAPABILITY_NAMED_IAM")]
        [String[]]
        $Capabilities,
        [parameter(Mandatory = $false)]
        [Alias("NoExecuteChangeSet")]
        [Switch]
        $DoNotExecute,
        [parameter(Mandatory = $false)]
        [System.String]
        $RoleARN,
        [parameter(Mandatory = $false)]
        [System.String[]]
        $NotificationARNs,
        [parameter(Mandatory = $false)]
        [Switch]
        $Watch,
        [parameter(Mandatory = $false)]
        [String]
        $ProfileName = $env:AWS_PROFILE
    )
    Begin {
        $changeSetParams = @{}
        $prof = @{}
        if ($ProfileName -and ($PSBoundParameters.Keys -notcontains "ProfileName")) {
            $PSBoundParameters["ProfileName"] = $ProfileName
        }
        if ($ProfileName) {
            $prof["ProfileName"] = $ProfileName
        }
    }
    Process {
        if ($PSCmdlet.ParameterSetName -eq "TemplateFile") {
            Write-Verbose "Getting TemplateBody from TemplateFile path"
            $templateFilePath = (Resolve-Path $TemplateFile).Path
            $TemplateBody = [System.IO.File]::ReadAllText($templateFilePath)
        }
        $changeSetParams["TemplateBody"] = $TemplateBody
        $changeSetParams["ChangeSetName"] = "$($StackName)-$(Get-Date -Format "yyyyMMdd-HHmmss")"
        foreach ($key in $PSBoundParameters.Keys) {
            if ((Get-Command New-VSChangeSet).Parameters.Keys -contains $key -and $key -ne "Verbose") {
                $changeSetParams[$key] = $PSBoundParameters[$key]
            }
        }
        try {
            Write-Verbose "Creating change set as UPDATE"
            $changeSet = New-VSChangeSet @changeSetParams -Verbose:$false
            Write-Verbose "Change Set type 'UPDATE' created"
        }
        catch {
            try {
                $changeSet = New-VSChangeSet @changeSetParams -ChangeSetType CREATE -Verbose:$false
                Write-Verbose "Change Set type 'CREATE' created"
            }
            catch {
                $PSCmdlet.ThrowTerminatingError($_)
            }
        }
        $changeSetDetails = Get-VSChangeSet -Description -ChangeSetName $changeSet.Id -StackName $changeSet.StackId @prof -Verbose:$false
        if ($DoNotExecute) {
            return $changeSetDetails
        }
        else {
            $i=0
            Write-Verbose "Waiting for change set to be available to execute"
            do {
                $i++
                Start-Sleep 1
                $changeSetDetails = Get-VSChangeSet -Description -ChangeSetName $changeSet.Id -StackName $changeSet.StackId -Verbose:$false @prof
            }
            until ($changeSetDetails.ExecutionStatus.Value -eq "AVAILABLE" -or $changeSetDetails.Status.Value -eq "FAILED" -or $i -ge 60)
            if ($changeSetDetails.Status.Value -eq "FAILED") {
                Write-Warning "Change Set FAILED! Reason: $($changeSetDetails.StatusReason)"
            }
            elseif ($i -ge 60) {
                Write-Warning "Change Set is not showing as available to execute after 60 seconds! Returning details"
                return $changeSetDetails
            }
            else {
                Write-Verbose "Executing Change Set after $i seconds"
                try {
                    $execution = Invoke-VSChangeSetExecution -ChangeSetName $changeSetDetails.ChangeSetId -StackName $changeSetDetails.StackId @prof
                    if ($Watch) {
                        Write-Verbose "Watching deployment!"
                        Watch-Stack -StackName $StackName
                    }
                    else {
                        return $changeSetDetails | Select-Object *,@{N="ExecutionResponse";E={$execution}}
                    }
                }
                catch {
                    $PSCmdlet.ThrowTerminatingError($_)
                }
            }
        }
    }
}