-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUpdateGroup.ps1
303 lines (269 loc) · 7.83 KB
/
UpdateGroup.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
<#
.SYNOPSIS
Create/delete user groups on Jira Cloud
.DESCRIPTION
Create or delete user groups.
GroupFile parameter is processed first, followed by CreateGroup then DeleteGroup.
site-admins group is ignored for safety reason.
.PARAMETER SkipConfirm
Switch. If specified, will not prompt for deleting groups.
.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 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 CreateGroup
Optional. Comma-delimited user group names to be created.
.PARAMETER DeleteGroup
Optional. Comma-delimited user group names to be deleted.
.PARAMETER GroupFile
Optional. Path to file containing group names. One group name per line. Prefix with "-" to delete a group, otherwise group is created.
#>
Param (
[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()]
[string[]] $CreateGroup,
[Parameter()]
[string[]] $DeleteGroup,
[Parameter()]
[ValidateScript({
if ($_) {
if (Test-Path -PathType Leaf $_) {
$true
} else {
throw "Please provide valid path"
}
} else {
$true
}
})]
[string] $GroupFile
)
class RestException : Exception {
RestException($Message) : base($Message) {
}
}
function AddAuthHeader {
param (
[hashtable] $Headers,
[string] $Email,
[string] $Token
)
$Auth = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($Email + ":" + $Token))
$Headers.Authorization = "Basic " + $Auth
}
# 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 GetGroupId {
param (
[string] $GroupName
)
$Uri = "https://" + $Domain + "/rest/api/3/groups/picker"
$Parameters = @{
query = $GroupName
}
$Response = WebRequest -Uri $Uri -Method "GET" -Headers $Headers -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 CreateGroup {
param (
[string] $GroupName
)
$Uri = "https://" + $Domain + "/rest/api/3/group"
$Body = "{`"name`": `"$GroupName`"}"
$Response = WebRequest -Method "POST" -Header $Headers -Uri $Uri -Body $Body
if ($Response.StatusCode -eq 400) {
throw [RestException]::new("Group $GroupName already exists")
} elseif ($Response.StatusCode -ne 201) {
throw [RestException]::new("Unable to create group $GroupName, response code: " + $Response.StatusCode)
}
$Json = $Response.content | ConvertFrom-Json
$GroupId = $Json.groupId
$GroupId
}
function DeleteGroup {
param (
[string] $GroupName
)
$GroupId = GetGroupId $GroupName
$Uri = "https://" + $Domain + "/rest/api/3/group?groupId=" + [uri]::EscapeDataString($GroupId)
$Response = WebRequest -Method "DELETE" -Header $Headers -Uri $Uri
if ($Response.StatusCode -eq 404) {
throw [RestException]::new("Group $GroupName does not exist")
} elseif ($Response.StatusCode -ne 200) {
throw [RestException]::new("Unable to delete group $GroupName, response code: " + $Response.StatusCode)
}
}
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
$GroupsToAdd = 0
$GroupsAdded = 0
$GroupsToDelete = 0
$GroupsDeleted = 0
# Headers
$Headers = @{
"Content-Type" = "application/json"
}
$PlainToken = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Token))
AddAuthHeader $Headers $Email $PlainToken
# For all rows
WriteLog "Update User Group"
WriteLog "================="
WriteLog "Date/Time: ${StartTime}"
WriteLog "Domain: ${Domain}"
WriteLog "Email: ${Email}"
WriteLog "CSV File: ${GroupFile}"
WriteLog "CreateGroup: $CreateGroup"
WriteLog "DeleteGroup: $DeleteGroup"
WriteLog "`n"
# Parse CSV
if ($GroupFile) {
$Data = Import-Csv -Header 'GroupName' -Path $GroupFile
if ($Data.Count) {
$Total = $Data.Count
} elseif ($Data) {
$Total = 1
} else {
$Total = 0
}
Write-Progress -Id 1 -Activity "0/${Total}" -PercentComplete 0
$LineNo = 0
foreach($Line in $Data) {
$LineNo = $LineNo + 1
Write-Progress -Id 1 -Activity "Processing line ${LineNo}/${Total}" -PercentComplete ((($LineNo - 1) / $Total) * 100)
# Default is to create
$Action = "Create"
$GroupName = $Line.GroupName
if ($Line.GroupName.Substring(0, 1) -eq "-") {
# Delete group
$Action = "Delete"
$GroupName = $Line.GroupName.Substring(1)
}
if ($Action -eq "Create") {
try {
$GroupsToAdd++
$GroupId = CreateGroup $GroupName
WriteLog "Group $GroupName created, group ID: $GroupId"
$GroupsAdded++
} catch [RestException] {
WriteLog "Failed to create group ${GroupName}: $PSItem"
}
} else {
try {
$GroupsToDelete++
DeleteGroup $GroupName
WriteLog "Group $GroupName deleted"
$GroupsDeleted++
} catch [RestException] {
WriteLog "Failed to delete group ${GroupName}: $PSItem"
}
}
}
Write-Progress -Id 1 -Activity "${Total}/${Total}" -Completed -PercentComplete 100
}
if ($CreateGroup) {
foreach ($GroupName in $CreateGroup.split(',')) {
try {
$GroupsToAdd++
$GroupId = CreateGroup $GroupName
WriteLog "Group $GroupName created, group ID: $GroupId"
$GroupsAdded++
} catch [RestException] {
WriteLog "Failed to create group ${GroupName}: $PSItem"
}
}
}
if ($DeleteGroup) {
foreach ($GroupName in $DeleteGroup.split(',')) {
try {
$GroupsToDelete++
DeleteGroup $GroupName
WriteLog "Group $GroupName deleted"
$GroupsDeleted++
} catch [RestException] {
WriteLog "Failed to delete group ${GroupName}: $PSItem"
}
}
}
WriteLog "`n"
WriteLog "Create Groups: ${GroupsAdded}/${GroupsToAdd}"
WriteLog "Delete Groups: ${GroupsDeleted}/${GroupsToDelete}"
WriteLog "`n"