-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSet-GitHubVariable.ps1
More file actions
559 lines (453 loc) · 21.6 KB
/
Copy pathSet-GitHubVariable.ps1
File metadata and controls
559 lines (453 loc) · 21.6 KB
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
function Set-GitHubVariable
{
<#
.SYNOPSIS
Creates or updates a GitHub configuration variable at an explicit repository, environment, or organization scope.
.DESCRIPTION
Creates or updates a GitHub configuration variable. Scope selection is always explicit through
the required -Scope parameter.
Repository scope can omit -Repository and use the current Git repository's origin remote.
Environment and organization scopes require their matching target parameters.
The function prefers the GitHub CLI-backed API transport when `gh` is available and falls
back to direct REST API requests otherwise. Existing variables are updated only when -Force
is used, unless the current value already matches the requested value.
The function supports:
- Repository, environment, and organization variables via -Scope
- Organization visibility and selected repository targeting
- -WhatIf/-Confirm through ShouldProcess
- Secure PAT input via -Token with fallback to GH_TOKEN
- Exponential backoff retries for transient failures
.PARAMETER Name
The GitHub variable name.
Configuration variable names:
- Can contain only letters, numbers, and underscores
- Cannot start with a number
- Cannot start with the GITHUB_ prefix
- Are case-insensitive when referenced by GitHub
.PARAMETER Value
The variable value to store.
Variables are stored as plain text rather than as encrypted secrets, so use
Set-GitHubSecret for sensitive values.
GitHub configuration variables are intended for non-secret configuration that GitHub Actions
workflows can reference with `${{ vars.NAME }}`. At repository and organization scope,
GitHub also makes variables available to Dependabot where GitHub supports that behavior.
Empty string values are allowed.
.PARAMETER Scope
The GitHub variable scope. Valid values are Repository, Environment, and Organization.
Meanings:
- Repository: a repository-level variable for one repository
- Environment: an environment-level variable for one deployment environment in a repository
- Organization: an organization-level variable that can be shared with repositories
Companion parameter rules:
- Repository: use -Scope Repository; -Repository is optional
- Environment: use -Scope Environment; -Repository and -Environment are required
- Organization: use -Scope Organization; -Organization is required
.PARAMETER Repository
The target repository in OWNER/REPO or HOST/OWNER/REPO format.
Supported with -Scope Repository and -Scope Environment.
Repository variables are available within the specified repository. Environment variables
belong to a specific environment in the specified repository.
When -Scope Repository is used and -Repository is omitted, the function tries to resolve the
current Git repository's origin remote. If that cannot be determined, specify -Repository
explicitly.
Examples:
- octo-org/service-api
- github.example.com/platform/service-api
.PARAMETER Environment
The deployment environment name for environment variables.
Supported only with -Scope Environment and requires -Repository.
Environment variables belong to a single named environment within the repository and are
intended for jobs that reference that environment.
GitHub environment names:
- Are not case sensitive
- May not exceed 255 characters
- Must be unique within the repository
GitHub REST endpoints require environment names to be URL-encoded. This function handles
that automatically, so names containing spaces or `/` are supported.
.PARAMETER Organization
The target organization for organization variables.
Supported only with -Scope Organization.
Organization variables can be shared with repositories in the organization according to the
access policy set by -Visibility and -SelectedRepository.
.PARAMETER Visibility
Organization variable visibility. Valid values are all, private, and selected.
Supported only with -Scope Organization.
Meanings:
- all: every repository in the organization can use the variable
- private: only private repositories in the organization can use the variable
- selected: only repositories listed in -SelectedRepository can use the variable
When -SelectedRepository is used and -Visibility is omitted, visibility is treated as
selected. When a new organization variable is created without any explicit access settings,
the function uses GitHub's default private visibility.
When you update an existing organization variable without -Visibility or
-SelectedRepository, the function preserves the variable's current access policy.
.PARAMETER SelectedRepository
The repositories that can access an organization variable.
Supported only with -Scope Organization.
This is the repository allow-list used when an organization variable has selected visibility.
If you provide -SelectedRepository and omit -Visibility, the function treats the access
policy as selected.
Bare repository names such as 'app1' are resolved relative to -Organization for REST API
fallback. OWNER/REPO format also works.
.PARAMETER Force
Overwrites an existing variable when the current value differs.
If the existing value already matches the requested value, the function returns Unchanged
and does not require -Force.
Result behavior:
- Existing variable + same value: Unchanged
- Existing variable + different value + no -Force: Skipped
- Existing variable + different value + -Force: Updated
- Missing variable: Created
.PARAMETER Token
Optional GitHub personal access token as a SecureString.
If supplied, the token is used only for the outbound `gh` or REST request and is never
written to command output.
When omitted, the function checks the environment variable named by
-TokenEnvironmentVariableName. If the GitHub CLI is installed, its existing authenticated
session can also be used when no token is supplied. If `gh` is not available and the
function falls back to REST, a token or token environment variable is required.
.PARAMETER TokenEnvironmentVariableName
The environment variable name to check for a GitHub token when -Token is not supplied.
Defaults to GH_TOKEN.
This environment variable is read only when -Token is not supplied. It is used for `gh`
authentication and REST fallback.
.EXAMPLE
PS > Set-GitHubVariable -Name 'DOTNET_VERSION' -Value '8.0.x' -Scope Repository
Creates a repository variable for the current Git repository.
.EXAMPLE
PS > Set-GitHubVariable -Name 'DEPLOY_RING' -Value 'production' -Scope Environment -Repository 'octo-org/service-api' -Environment 'Production'
Creates an environment variable for the Production deployment environment.
.EXAMPLE
PS > Set-GitHubVariable -Name 'REGION' -Value 'us-east-1' -Scope Organization -Organization 'octo-org' -Visibility selected -SelectedRepository 'app1', 'app2'
Creates an organization variable that is visible only to selected repositories.
.EXAMPLE
PS > Set-GitHubVariable -Name 'FEATURE_FLAG' -Value 'enabled' -Scope Organization -Organization 'octo-org'
Creates an organization variable that defaults to GitHub's private visibility.
.EXAMPLE
PS > Set-GitHubVariable -Name 'FEATURE_FLAG' -Value 'enabled' -Scope Organization -Organization 'octo-org' -Force
Overwrites an existing organization variable.
.EXAMPLE
PS > $token = ConvertTo-SecureString $env:GITHUB_ADMIN_TOKEN -AsPlainText -Force
PS > Set-GitHubVariable -Name 'BUILD_CONFIGURATION' -Value 'Release' -Scope Repository -Repository 'octo-org/service-api' -Token $token -WhatIf
Shows what would happen without modifying the variable.
.EXAMPLE
PS > Set-GitHubVariable -Name 'PACKAGE_SOURCE' -Value 'internal' -Scope Organization -Organization 'octo-org' -TokenEnvironmentVariableName 'GITHUB_ADMIN_TOKEN'
Reads the GitHub token from a non-default environment variable.
.OUTPUTS
GitHub.VariableSetResult
Returns a summary object with status, target scope, transport used, and whether the variable
changed.
.NOTES
-Scope is required for all GitHub helper functions in this module family.
Variables prefer the GitHub CLI-backed transport and fall back to direct REST API requests.
Organization variables default to private visibility when they are created without explicit
visibility settings.
.LINK
https://cli.github.com/manual/gh_variable_set
.LINK
https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/Developer/Set-GitHubVariable.ps1
#>
[CmdletBinding(SupportsShouldProcess)]
[OutputType([PSCustomObject])]
param(
[Parameter(Mandatory, Position = 0)]
[ValidateNotNullOrEmpty()]
[ValidateScript({
if ($_ -match '^(?i:GITHUB_)')
{
throw "GitHub variable names cannot start with the 'GITHUB_' prefix."
}
if ($_ -notmatch '^(?![0-9])[A-Za-z0-9_]+$')
{
throw 'GitHub variable names may only contain letters, numbers, or underscores, and cannot start with a number.'
}
$true
})]
[String]$Name,
[Parameter(Mandatory)]
[AllowEmptyString()]
[String]$Value,
[Parameter(Mandatory)]
[ValidateSet('Repository', 'Environment', 'Organization')]
[String]$Scope,
[Parameter()]
[String]$Repository,
[Parameter()]
[ValidateScript({
if ([string]::IsNullOrWhiteSpace($_))
{
throw 'GitHub environment names cannot be empty or whitespace.'
}
if ($_.Length -gt 255)
{
throw 'GitHub environment names may not exceed 255 characters.'
}
$true
})]
[String]$Environment,
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$Organization,
[Parameter()]
[ValidateSet('all', 'private', 'selected')]
[String]$Visibility,
[Parameter()]
[String[]]$SelectedRepository,
[Parameter()]
[Switch]$Force,
[Parameter()]
[SecureString]$Token,
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$TokenEnvironmentVariableName = 'GH_TOKEN'
)
begin
{
function Import-GitHubConfigurationHelpersIfNeeded
{
if (-not (Get-Variable -Name 'PwshProfileGitHubConfigurationHelpers' -Scope Script -ErrorAction SilentlyContinue))
{
$dependencyDirectory = Join-Path -Path $PSScriptRoot -ChildPath 'Private'
$dependencyPath = Join-Path -Path $dependencyDirectory -ChildPath 'GitHubConfigurationHelpers.ps1'
$dependencyPath = [System.IO.Path]::GetFullPath($dependencyPath)
if (-not (Test-Path -LiteralPath $dependencyPath -PathType Leaf))
{
throw "Required dependency could not be found. Expected location: $dependencyPath"
}
try
{
. $dependencyPath
Write-Verbose "Loaded GitHub configuration helpers from: $dependencyPath"
}
catch
{
throw "Failed to load GitHub configuration helpers from '$dependencyPath': $($_.Exception.Message)"
}
}
}
Import-GitHubConfigurationHelpersIfNeeded
$helpers = $script:PwshProfileGitHubConfigurationHelpers
$maxRetryCount = $helpers.DefaultRetryCount
$initialRetryDelaySeconds = $helpers.DefaultInitialRetryDelaySeconds
$resolvedScope = $Scope
switch ($resolvedScope)
{
'Repository'
{
if ($PSBoundParameters.ContainsKey('Environment'))
{
throw 'Use -Scope Environment when specifying -Environment.'
}
if ($PSBoundParameters.ContainsKey('Organization'))
{
throw 'Use -Scope Organization when specifying -Organization.'
}
}
'Environment'
{
if (-not $PSBoundParameters.ContainsKey('Repository'))
{
throw '-Scope Environment requires -Repository.'
}
if (-not $PSBoundParameters.ContainsKey('Environment'))
{
throw '-Scope Environment requires -Environment.'
}
if ($PSBoundParameters.ContainsKey('Organization'))
{
throw '-Scope Environment does not support -Organization.'
}
}
'Organization'
{
if (-not $PSBoundParameters.ContainsKey('Organization'))
{
throw '-Scope Organization requires -Organization.'
}
if ($PSBoundParameters.ContainsKey('Repository'))
{
throw '-Scope Organization does not support -Repository.'
}
if ($PSBoundParameters.ContainsKey('Environment'))
{
throw '-Scope Organization does not support -Environment.'
}
}
}
if ($SelectedRepository -and $resolvedScope -ne 'Organization')
{
throw '-SelectedRepository is supported only for -Scope Organization.'
}
if ($Visibility -and $resolvedScope -ne 'Organization')
{
throw '-Visibility is supported only for -Scope Organization.'
}
if ($Visibility -eq 'selected' -and -not $SelectedRepository)
{
throw "Visibility 'selected' requires -SelectedRepository."
}
if ($PSBoundParameters.ContainsKey('SelectedRepository') -and $Visibility -and $Visibility -ne 'selected')
{
throw "-SelectedRepository requires '-Visibility selected'. Specify '-Visibility selected' or omit -Visibility."
}
if ($PSBoundParameters.ContainsKey('SelectedRepository'))
{
$normalizeSelectedRepositoriesParams = @{
Repositories = $SelectedRepository
Organization = $Organization
RequireOwnerRepoFormat = $false
}
$SelectedRepository = & $helpers.NormalizeSelectedRepositories @normalizeSelectedRepositoriesParams
}
$getVariableContextParams = @{
Scope = $resolvedScope
Repository = $Repository
Environment = $Environment
Organization = $Organization
}
$variableContext = & $helpers.GetVariableContext @getVariableContextParams
$transport = & $helpers.ResolveTransport
$resolveAuthContextParams = @{
Token = $Token
TokenEnvironmentVariableName = $TokenEnvironmentVariableName
RequireToken = ($transport.Name -ne 'GhCli')
}
$authContext = & $helpers.ResolveAuthContext @resolveAuthContextParams
$variablePath = & $helpers.GetSingleItemPath -CollectionPath $variableContext.CollectionPath -Name $Name
$tryGetGitHubResourceParams = @{
Path = $variablePath
BaseUri = $variableContext.ApiBaseUri
Transport = $transport
AuthContext = $authContext
MaxRetryCount = $maxRetryCount
InitialRetryDelaySeconds = $initialRetryDelaySeconds
Activity = "Get GitHub variable $Name"
}
$existingVariable = & $helpers.TryGetGitHubResource @tryGetGitHubResourceParams
}
process
{
if ($existingVariable.Found -and "$($existingVariable.Resource.value)" -eq $Value)
{
return & $helpers.NewOperationResult -TypeName 'GitHub.VariableSetResult' -Properties @{
Name = $Name
Scope = $variableContext.Scope
Target = $variableContext.DisplayTarget
Status = 'Unchanged'
Changed = $false
AlreadyExists = $true
UsedForce = $false
Transport = $transport.Name
Authentication = $authContext.Source
Message = "Variable '$Name' already has the requested value."
}
}
if ($existingVariable.Found -and -not $Force)
{
return & $helpers.NewOperationResult -TypeName 'GitHub.VariableSetResult' -Properties @{
Name = $Name
Scope = $variableContext.Scope
Target = $variableContext.DisplayTarget
Status = 'Skipped'
Changed = $false
AlreadyExists = $true
UsedForce = $false
Transport = $transport.Name
Authentication = $authContext.Source
Message = "Variable '$Name' already exists for $($variableContext.DisplayTarget). Use -Force to overwrite it."
}
}
$action = if ($existingVariable.Found) { 'Update GitHub variable' } else { 'Create GitHub variable' }
if (-not $PSCmdlet.ShouldProcess("$($variableContext.DisplayTarget) :: $Name", $action))
{
return & $helpers.NewOperationResult -TypeName 'GitHub.VariableSetResult' -Properties @{
Name = $Name
Scope = $variableContext.Scope
Target = $variableContext.DisplayTarget
Status = 'WhatIf'
Changed = $false
AlreadyExists = $existingVariable.Found
UsedForce = $Force.IsPresent
Transport = $transport.Name
Authentication = $authContext.Source
Message = "$action skipped by WhatIf."
}
}
try
{
$body = @{
name = $Name
value = $Value
}
if ($variableContext.Scope -eq 'Organization')
{
$shouldIncludeVisibility = $Visibility -or $SelectedRepository -or -not $existingVariable.Found
if ($shouldIncludeVisibility)
{
$body['visibility'] = if ($Visibility)
{
$Visibility
}
elseif ($SelectedRepository)
{
'selected'
}
else
{
'private'
}
}
if ($SelectedRepository)
{
$resolveSelectedRepositoryIdsParams = @{
Repositories = $SelectedRepository
Organization = $Organization
Transport = $transport
AuthContext = $authContext
MaxRetryCount = $maxRetryCount
InitialRetryDelaySeconds = $initialRetryDelaySeconds
}
$body['selected_repository_ids'] = & $helpers.ResolveSelectedRepositoryIds @resolveSelectedRepositoryIdsParams
}
}
$method = if ($existingVariable.Found) { 'PATCH' } else { 'POST' }
$path = if ($existingVariable.Found) { $variablePath } else { $variableContext.CollectionPath }
$invokeGitHubRequestParams = @{
Method = $method
BaseUri = $variableContext.ApiBaseUri
Path = $path
Transport = $transport
AuthContext = $authContext
Body = $body
MaxRetryCount = $maxRetryCount
InitialRetryDelaySeconds = $initialRetryDelaySeconds
Activity = "$action $Name"
SensitiveValues = @()
}
$null = & $helpers.InvokeGitHubRequest @invokeGitHubRequestParams
return & $helpers.NewOperationResult -TypeName 'GitHub.VariableSetResult' -Properties @{
Name = $Name
Scope = $variableContext.Scope
Target = $variableContext.DisplayTarget
Status = if ($existingVariable.Found) { 'Updated' } else { 'Created' }
Changed = $true
AlreadyExists = $existingVariable.Found
UsedForce = $Force.IsPresent
Transport = $transport.Name
Authentication = $authContext.Source
Message = if ($existingVariable.Found) { "Variable '$Name' was updated." } else { "Variable '$Name' was created." }
}
}
catch
{
$getFriendlyErrorMessageParams = @{
Operation = 'set variable'
Name = $Name
Target = $variableContext.DisplayTarget
Exception = $_.Exception
}
$friendlyMessage = & $helpers.GetFriendlyErrorMessage @getFriendlyErrorMessageParams
throw $friendlyMessage
}
}
}