TFRun.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
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
#Add paging
<# AVAILABLE
Apply a Run
    POST /runs/:run_id/actions/apply
#>


function Get-TFRun {
    <#
    .SYNOPSIS
    Get workspace runs.
 
    Run cmdlet to list all runs for a given workspace. Use the CURRENT switch for the current run.
    or
    Get properties of a specify a Run ID.
 
    Specify the SERVER, APITOKEN and ORG within the cmdlet or use Set-Terraform to store them globally.
    APIToken can be generated at https://<TFE>/app/settings/tokens
 
    .DESCRIPTION
    List Runs in a Workspace
        GET /workspaces/:workspace_id/runs
 
    Get run details
        GET /runs/:run_id
 
    .LINK
    https://www.terraform.io/docs/cloud/api/run.html
    #>


    [CmdletBinding()]
    Param
    (
        [Parameter(Position=0,Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName,ParameterSetName='Wks')]
        [string]$Name,

        [Parameter(ParameterSetName='Wks')]
        [switch]$Current,

        [Parameter(Position=1,Mandatory,ParameterSetName='Run')]
        [Alias('id')]
        [string]$RunId,

        [string]$Server = $Terraform.Server,

        [string]$APIToken = $Terraform.Token,

        [string]$Org = $Terraform.Org
    )

    PROCESS {
        
        if (!$Server -or !$APIToken) {Write-Warning "Missing Server and APIToken, use Set-Terraform"; Continue}

        $Headers = @{
            Authorization = "Bearer $APIToken"
            'Content-Type' = 'application/vnd.api+json'
        }

        if ($PSCmdlet.ParameterSetName -eq 'Wks') {

            $WorkspaceId = (Get-TFWorkspace -Server $Server -APIToken $APIToken -Name $Name).id
            Write-Verbose "Workspace $Name; WorkspaceId $WorkspaceId"
            if (!$WorkspaceId) {Continue}

            $Uri = "https://$Server/api/v2/workspaces/$WorkspaceId/runs"
            
        } elseif ($PSCmdlet.ParameterSetName -eq 'Run') {

            $Uri = "https://$Server/api/v2/runs/$RunId"
        
        }

        try {

            $Results = (Invoke-RestMethod -Uri $Uri -Headers $Headers -Method Get).data

            foreach ($Result in $Results) {
                $Run = ($Result).Attributes
                $Run.PSObject.TypeNames.Insert(0,'Terraform.TFRun')
                $Run | Add-Member -NotePropertyName id -NotePropertyValue $Result.id
                
                if ($Name) {
                    $Run | Add-Member -NotePropertyName name -NotePropertyValue $Name
                }

                $Run

                if ($Current) {break} #exit loop after first output
            }

        } catch {
            Write-Warning "Unable to get run : $($_.Exception.Message) : Line $($_.InvocationInfo.ScriptLineNumber)"
            Continue
        }
    }
}

function Set-TFRun {
    <#
    .SYNOPSIS
    Set an ACTION for a specific Run.
 
    Specify any of the following Actions: DISCARD, CANCEL, FORCE-CANCEL, FORCE-EXECUTE
 
    Specify the SERVER, APITOKEN and ORG within the cmdlet or use Set-Terraform to store them globally.
    APIToken can be generated at https://<TFE>/app/settings/tokens
 
    .DESCRIPTION
    Discard a Run
        POST /runs/:run_id/actions/discard
 
    Cancel a Run
        POST /runs/:run_id/actions/cancel
 
    Forcefully cancel a run
        POST /runs/:run_id/actions/force-cancel
 
    Forcefully execute a run
        POST /runs/:run_id/actions/force-execute
 
    .LINK
    https://www.terraform.io/docs/cloud/api/run.html
    #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact='High')]
    Param
    (
        [Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
        [ValidatePattern('^run-')]
        [Alias('id')]
        [string]$RunId,

        [Parameter(Mandatory)]
        [ValidateSet('discard','cancel','force-cancel','force-execute')]
        [string]$Action,

        [string]$Server = $Terraform.Server,

        [string]$APIToken = $Terraform.Token,

        [string]$Org = $Terraform.Org
    )

    PROCESS {
        
        if (!$Server -or !$APIToken) {Write-Warning "Missing Server and APIToken, use Set-Terraform"; Continue}

        $Uri = "https://$Server/api/v2/runs/$RunId/actions/$Action"
        $Headers = @{
            Authorization = "Bearer $APIToken"
            'Content-Type' = 'application/vnd.api+json'
        }

        try {

            if ($PSCmdlet.ShouldProcess("$RunId : $Action")) {
                Invoke-RestMethod -Uri $Uri -Headers $Headers -Method Post | Out-Null
            }

        } catch {
            Write-Warning "Unable to $Action on $RunId : $($_.Exception.Message) : Line $($_.InvocationInfo.ScriptLineNumber)"
            Continue
        }
    }
}

function Start-TFRun {
    <#
    .SYNOPSIS
    Create a run for a workspace.
 
    Specify the SERVER, APITOKEN and ORG within the cmdlet or use Set-Terraform to store them globally.
    APIToken can be generated at https://<TFE>/app/settings/tokens
 
    .DESCRIPTION
    Create a Run
        POST /runs
 
    .LINK
    https://www.terraform.io/docs/cloud/api/run.html
    #>


    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
        [string]$Name,

        [string]$Message = 'Queued from PowerShell',

        [string]$Server = $Terraform.Server,

        [string]$APIToken = $Terraform.Token,

        [string]$Org = $Terraform.Org
    )

    PROCESS {
        
        if (!$Server -or !$APIToken) {Write-Warning "Missing Server and APIToken, use Set-Terraform"; Continue}

        $Uri = "https://$Server/api/v2/runs"
        $Headers = @{
            Authorization = "Bearer $APIToken"
            'Content-Type' = 'application/vnd.api+json'
        }

        try {

            $WorkspaceId = (Get-TFWorkspace -Server $Server -APIToken $APIToken -Name $Name).id
            Write-Verbose "Workspace $Name; WorkspaceId $WorkspaceId"
            if (!$WorkspaceId) {Continue}

            $Data = [PSCustomObject]@{
                attributes = [PSCustomObject]@{
                    message = $Message
                }
                relationships = @{workspace=@{data=@{id=$WorkspaceId}}}
            }

            $Body = @{data=$Data} | ConvertTo-Json -Depth 5
            Write-Verbose "$Body"

            Invoke-RestMethod -Uri $Uri -Headers $Headers -Body $Body -Method Post | Out-Null

        } catch {
            Write-Warning "Unable to get run : $($_.Exception.Message) : Line $($_.InvocationInfo.ScriptLineNumber)"
            Continue
        }
    }
}

Set-Alias gtfr Get-TFRun
Set-Alias stfr Set-TFRun
Set-Alias satfr Start-TFRun