-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUpdateGroupMembership.ps1
542 lines (499 loc) · 15.6 KB
/
UpdateGroupMembership.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
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
<#
.SYNOPSIS
Replace group memberships on Jira Cloud
.DESCRIPTION
Reads CSV file containing columns:
GroupName - Name of user group. Surround with double quotes if it has comma.
UserEmail - Pipe-delimited list of emails of users to be added to user group.
Prefix email with - to indicate removal.
Specify a single hash "#" to delete all members. The rest of the line is ignored.
CSV comment is NOT supported.
e.g.
GroupName,UserEmail
Group1,*
This removes all members from Group1.
e.g.
GroupName,UserEmail
Group1,#
Group1,user1@example.com|user2@example.com
This removes all members from Group1, then adds user1 and user2.
e.g.
GroupName,UserEmail
Group1,user1@example.com|-user2@example.com
This adds user1 and removes user2.
site-admins group is not supported for safety reasons. If encountered it will be ignored.
.PARAMETER LogFile
Path to log file. If not specified, result will be written to stdout.
.PARAMETER Trace
Switch. Enable trace. If specified, each action will be written to stdout.
.PARAMETER NoMemberList
Switch. Supress printing members of user groups processed.
.PARAMETER SkipConfirm
Switch. Skip confirmation if defined. By default each action will prompt for confirmation.
.PARAMETER Domain
Jira Cloud domain.
.PARAMETER Email
Email to authentication with Jira. The account must be in site-admins group.
.PARAMETER Token
REST API token generated by Jira.
See: https://support.atlassian.com/atlassian-account/docs/manage-api-tokens-for-your-atlassian-account/
.PARAMETER Csv
Path to CSV file containing columns:
GroupName, UserEmail
#>
Param (
[Parameter()]
[switch] $NoMemberList,
[Parameter()]
[string] $LogFile,
[Parameter()]
[switch] $Trace,
[Parameter()]
[switch] $SkipConfirm,
[Parameter()]
[string] $Domain = $(Read-Host -prompt "Enter Jira Cloud domain, e.g. kcwong.atlassian.net"),
[Parameter()]
[string] $Email = $(Read-Host -prompt "Enter site admin email, e.g. kc.wong@igsl-group.com"),
[Parameter()]
[SecureString] $Token = $(Read-Host -AsSecureString -prompt "Enter API token"),
[Parameter()]
[ValidateScript({
if (Test-Path -PathType Leaf $_) {
$true
} else {
throw "Please provide valid CSV path"
}
})]
[string] $Csv = $(Read-Host -prompt "Enter CSV path")
)
class RestException : Exception {
RestException($Message) : base($Message) {
}
}
# Call Invoke-WebRequest without throwing exception on 4xx/5xx
function WebRequest {
param (
[string] $Uri,
[string] $Method,
[hashtable] $Headers,
[object] $Body
)
$Response = $null
try {
$script:ProgressPreference = 'SilentlyContinue' # Subsequent calls do not display UI.
$Response = Invoke-WebRequest -Method $Method -Header $Headers -Uri $Uri -Body $Body
} catch {
$Response = @{}
$Response.StatusCode = $_.Exception.Response.StatusCode.value__
$Response.content = $_.Exception.Message
} finally {
$script:ProgressPreference = 'Continue' # Subsequent calls do display UI.
}
$Response
}
function AddAuthHeader {
param (
[hashtable] $Headers,
[string] $Email,
[string] $Token
)
$Auth = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($Email + ":" + $Token))
$Headers.Authorization = "Basic " + $Auth
}
function GetAccountId {
param (
[string] $Email
)
$Uri = "https://" + $Domain + "/rest/api/3/user/search"
$Parameters = @{
query = $Email
}
$Response = WebRequest -Method "GET" -Header $Headers -Uri $Uri -Body $Parameters
if ($Response.StatusCode -ne 200) {
throw [RestException]::new("Unable to retrieve account ID for email $Email, response code: " + $Response.StatusCode)
}
$Json = $Response.content | ConvertFrom-Json
$Count = 0
foreach ($Item in $Json) {
# Only process accountType = atlassian
if ($Item.accountType -eq "atlassian") {
$AccountId = $Item.accountId
$Count = $Count + 1
}
}
if ($Count -eq 1) {
$AccountId
} else {
throw [RestException]::new("Unable to locate distinct user for $Email, matches found: " + $Count)
}
}
function GetGroupId {
param (
[string] $GroupName
)
$Uri = "https://" + $Domain + "/rest/api/3/groups/picker"
$Parameters = @{
query = $GroupName
}
$Response = WebRequest -Method "GET" -Header $Headers -Uri $Uri -Body $Parameters
if ($Response.StatusCode -ne 200) {
throw [RestException]::new("Unable to retrieve group ID for $GroupName, response code: " + $Response.StatusCode)
}
$Json = $Response.content | ConvertFrom-Json
if ($Json.total -ne 1) {
throw [RestException]::new("Unable to locate distinct group for $GroupName, matches found: " + $Json.total)
}
$GroupId = $Json.groups[0].groupId
$GroupId
}
function IsGroupMember {
param (
[string] $GroupId,
[string] $AccountId
)
$Members = GetGroupMembers $GroupId
foreach ($Member in $Members) {
if ($AccountId -eq $Member.accountId) {
$true
}
}
$false
}
function GetGroupMembers {
param (
[string] $GroupId
)
$Uri = "https://" + $Domain + "/rest/api/3/group/member"
$Parameters = @{
groupId = $GroupId;
maxResults = 500
}
$Response = WebRequest -Method "GET" -Header $Headers -Uri $Uri -Body $Parameters
if ($Response.StatusCode -ne 200) {
throw [RestException]::new("Unable to retrieve group members for $GroupName, response code: " + $Response.StatusCode)
}
$Json = $Response.content | ConvertFrom-Json
$GroupMembers = [System.Collections.ArrayList]::new()
foreach ($Member in $Json.values) {
$Item = @{
accountId = $Member.accountId;
email = $Member.emailAddress;
displayName = $Member.displayName
}
[void] $GroupMembers.Add($Item)
}
$GroupMembers
}
function DeleteGroupMember {
param (
[string] $GroupId,
[string] $AccountId
)
# Invoke-WebRequest does not support -Body for -Method "DELETE"
# So we have to add query string to URI instead
$Uri = "https://" + $Domain + "/rest/api/3/group/user?groupId=" + [uri]::EscapeDataString($GroupId) + "&accountId=" + [uri]::EscapeDataString($AccountId)
$Response = WebRequest -Method "DELETE" -Header $Headers -Uri $Uri
if ($Response.StatusCode -ne 200) {
throw [RestException]::new("Unable to remove $AccountId from $GroupId, response code: " + $Response.StatusCode)
}
}
function AddGroupMember {
param (
[string] $GroupId,
[string] $AccountId
)
$Uri = "https://" + $Domain + "/rest/api/3/group/user?groupId=" + [uri]::EscapeDataString($GroupId)
$Body = "{`"accountId`": `"" + $AccountId + "`"}"
$Response = WebRequest -Method "POST" -Header $Headers -Uri $Uri -Body $Body
if ($Response.StatusCode -ne 201) {
throw [RestException]::new("Unable to add $AccountId to $GroupId, response code: " + $Response.StatusCode)
}
}
enum ResultType {
OK
ERR
WARN
}
function CreateResult {
param (
[int] $LineNo,
[string] $UserEmail,
[string] $Action,
[ResultType] $Result,
[string] $ErrorMessage
)
$Obj = New-Object -TypeName PSObject
$Obj | Add-Member -Name "LineNo" -MemberType NoteProperty -Value ($LineNo + 1)
$Obj | Add-Member -Name "Email" -MemberType NoteProperty -Value $UserEmail
$Obj | Add-Member -Name "Action" -MemberType NoteProperty -Value $Action
$Obj | Add-Member -Name "Result" -MemberType NoteProperty -Value $Result
$Obj | Add-Member -Name "Message" -MemberType NoteProperty -Value $ErrorMessage
$script:ActionTotal++
switch ($Result) {
([ResultType]::OK) {
$script:ActionSuccess++
break
}
([ResultType]::ERR) {
$script:ActionError++
break
}
([ResultType]::WARN) {
$script:ActionWarning++
break
}
}
$Obj
}
function AddResult {
param (
[hashtable] $Result,
[string] $GroupName,
[PSObject] $Item
)
if (-not $Result."$GroupName") {
$Result."$GroupName" = [System.Collections.ArrayList]::new()
}
if ($Item) {
[void] $Result."$GroupName".Add($Item)
if ($Trace) {
$Msg = "[TRACE] Line: " + $Item.LineNo + " " + $Item.Action + " " + $Item.Email + ": " + $Item.Result + " " + $Item.Message
Write-Output "$Msg"
}
}
}
function WriteLog {
param (
[string] $Message
)
Write-Output $Message
if ($LogFile) {
Add-Content -Path $LogFile -Value $Message
}
}
function GetConfirm {
param (
[string] $Message
)
if ($SkipConfirm) {
$true
} else {
if ($ConfirmAll) {
$true
} else {
$Confirmation = Read-Host "$Message ([Y]es/[N]o/[A]ll)?"
if ($Confirmation -eq 'y') {
$true
} elseif ($Confirmation -eq 'a') {
$script:ConfirmAll = $true
$true
} else {
$false
}
}
}
}
# Main body
$StartTime = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$ConfirmAll = $false
$IgnoreGroup = "site-admins"
# Action counters
$ActionTotal = 0
$ActionSuccess = 0
$ActionError = 0
$ActionWarning = 0
# Parse CSV
$Data = Import-Csv -Path $Csv
# Progress counter
# Note: If there's only 1 line of data, .Count will be null.
if ($Data.Count) {
$Total = $Data.Count
} elseif ($Data) {
$Total = 1
} else {
$Total = 0
}
# Result data
# Key: Group name
# Value: Array of PSObject of results
$Result = @{}
# Headers
$Headers = @{
"Content-Type" = "application/json"
}
$PlainToken = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Token))
AddAuthHeader $Headers $Email $PlainToken
# Get self account ID
try {
$AccountId = GetAccountId $Email
} catch [RestException] {
Write-Error "Unable to find account ID for $Email, please double check -Email and -Token parameters"
Write-Error $PSItem.toString()
Exit
}
# For all rows, add users
Write-Progress -Id 1 -Activity "0/${Total}" -PercentComplete 0
$LineNo = 0
foreach($Line in $Data) {
$GroupName = $Line.GroupName
AddResult $Result $GroupName
$LineNo = $LineNo + 1
Write-Progress -Id 1 -Activity "Processing line ${LineNo}/${Total}" -PercentComplete ((($LineNo - 1) / $Total) * 100)
if ($IgnoreGroup -eq $GroupName) {
$R = CreateResult $LineNo "--" "--" ([ResultType]::WARN) "$IgnoreGroup group is ignored for safety reasons"
AddResult $Result $GroupName $R
} else {
try {
# Find group ID
$GroupId = GetGroupId $GroupName
if ($Line.UserEmail.Substring(0, 1) -eq "#") {
$Action = "Clear"
# Clear all users
try {
$GroupMembers = GetGroupMembers $GroupId
if ($GroupMembers) {
foreach ($Member in $GroupMembers) {
# Remove user
# Email may be unavailable due to privacy settings
if ($Member.email) {
$Name = $Member.displayName + " (" + $Member.email + ")"
} else {
$Name = $Member.displayName + " (email not available)"
}
if (GetConfirm "Clear $Name from group $GroupName") {
try {
DeleteGroupMember $GroupId $Member.accountId
$R = CreateResult $LineNo $Name $Action ([ResultType]::OK) ""
AddResult $Result $GroupName $R
} catch [RestException] {
$R = CreateResult $LineNo $Name $Action ([ResultType]::ERR) $PSItem.toString()
AddResult $Result $GroupName $R
}
} else {
$R = CreateResult $LineNo $Name $Action ([ResultType]::WARN) "Rejected by user"
AddResult $Result $GroupName $R
}
}
} else {
$R = CreateResult $LineNo "" $Action ([ResultType]::OK) "No members to remove"
AddResult $Result $GroupName $R
}
} catch [RestException] {
$R = CreateResult $LineNo "" $Action ([ResultType]::ERR) "Group member list cannot be found: $PSItem"
AddResult $Result $GroupName $R
}
} else {
$Items = [regex]::split($Line.UserEmail, "\|")
foreach ($Item in $Items) {
$Action = "Add"
$UserEmail = $Item
if ($Item.Substring(0, 1) -eq "-") {
$Add = $false
$Action = "Remove"
$UserEmail = $Item.Substring(1)
}
# Get User ID
try {
$UserId = GetAccountId $UserEmail
$IsMember = IsGroupMember $GroupId $UserId
if ($Action -eq "Add") {
if ($IsMember) {
$R = CreateResult $LineNo $UserEmail $Action ([ResultType]::WARN) "Already a member"
AddResult $Result $GroupName $R
} else {
# Add user
if (GetConfirm "Add $UserEmail to group $GroupName") {
try {
AddGroupMember $GroupId $UserId
$R = CreateResult $LineNo $UserEmail $Action ([ResultType]::OK) ""
AddResult $Result $GroupName $R
} catch [RestException] {
$R = CreateResult $LineNo $UserEmail $Action ([ResultType]::ERR) $PSItem.toString()
AddResult $Result $GroupName $R
}
} else {
$R = CreateResult $LineNo $UserEmail $Action ([ResultType]::WARN) "Rejected by user"
AddResult $Result $GroupName $R
}
}
} elseif ($Action -eq "Remove") {
if ($IsMember) {
# Remove user
if (GetConfirm "Remove $UserEmail from group $GroupName") {
try {
DeleteGroupMember $GroupId $UserId
$R = CreateResult $LineNo $UserEmail $Action ([ResultType]::OK) ""
AddResult $Result $GroupName $R
} catch [RestException] {
$R = CreateResult $LineNo $UserEmail $Action ([ResultType]::ERR) $PSItem.toString()
AddResult $Result $GroupName $R
}
} else {
$R = CreateResult $LineNo $UserEmail $Action ([ResultType]::WARN) "Rejected by user"
AddResult $Result $GroupName $R
}
} else {
$R = CreateResult $LineNo $UserEmail $Action ([ResultType]::WARN) "Not a member"
AddResult $Result $GroupName $R
}
}
} catch [RestException] {
$R = CreateResult $LineNo $UserEmail $Action ([ResultType]::ERR) "Account ID cannot be found: $PSItem"
AddResult $Result $GroupName $R
}
}
}
} catch [RestException] {
$R = CreateResult $LineNo "--" "--" ([ResultType]::ERR) "Group ID cannot be found: $PSItem"
AddResult $Result $GroupName $R
}
}
}
Write-Progress -Id 1 -Activity "${Total}/${Total}" -Completed -PercentComplete 100
WriteLog "Update User Group Membership"
WriteLog "============================"
WriteLog "Date/Time: ${StartTime}"
WriteLog "Domain: ${Domain}"
WriteLog "Email: ${Email}"
WriteLog "CSV File: ${Csv}"
WriteLog "`n"
WriteLog "Total no. of actions: ${ActionTotal}"
WriteLog "No. of successes : ${ActionSuccess}"
WriteLog "No. of warnings : ${ActionWarning}"
WriteLog "No. of errors : ${ActionError}"
WriteLog "`n"
foreach ($Item in $Result.GetEnumerator() | Sort-Object -property:Key) {
$Name = $Item.Key
WriteLog "Group: $Name"
WriteLog "================================================================================"
if ($LogFile) {
$Item.Value | Format-Table -Wrap | Out-File -Append -FilePath $LogFile
}
$Item.Value | Format-Table -Wrap
if (-not $NoMemberList) {
WriteLog "Current Members"
WriteLog "---------------"
try {
$GroupId = GetGroupId $Item.Key
try {
$GroupMembers = GetGroupMembers $GroupId
$Count = 0
foreach ($Member in $GroupMembers) {
if ($Member.email) {
$Name = $Member.displayName + " (" + $Member.email + ")"
} else {
$Name = $Member.displayName + " (email not available)"
}
WriteLog $Name
$Count = $Count + 1
}
WriteLog "Member Count: $Count"
} catch [RestException] {
WriteLog "Failed to list members: $PSItem"
}
} catch [RestException] {
WriteLog "Group ID cannot be found: $PSItem"
}
}
WriteLog "================================================================================`n"
}