posh-awsp.psm1

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
function Get-AWSConfigFile {
  <#
    .SYNOPSIS
      Returns the name of the file to use for AWS CLI configuration profiles.

    .DESCRIPTION
      If there is a value in the AWS_CONFIG_FILE environment variable, returns
      that value. Otherwise, returns the default config file location.

    .LINK
      https://www.github.com/jonscheiding/posh-awsprofile

    .LINK
      https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html
  #>


  [string]$AwsConfigFile = $Env:AWS_CONFIG_FILE

  if([string]::IsNullOrEmpty($AwsConfigFile)) {
    #
    # If the environment variable is not configured, calculate
    # the default location as documented in the AWS CLI docs.
    #
    $AwsHome = $Env:HOME

    if($null -eq $AwsHome) {
      $AwsHome = $Env:HOMEDRIVE + $Env:HOMEPATH
    }

    if($null -eq $AwsHome) {
      Write-Error "Could not determine user's home directory."
      return $null
    }

    [string]$AwsHomeDefault = Join-Path $Home ".aws"
    $AwsConfigFile = Join-Path $AwsHomeDefault "config"
  }

  return $AwsConfigFile
}

function Get-AWSCurrentProfile {
  <#
    .SYNOPSIS
      Returns the currently set AWS CLI profile, or "default" if none has been specified.

    .DESCRIPTION
      This returns the value of the AWS_PROFILE environment variable. If the variable is
      not set, it will return "default".

      If the variable is set to a value that does not exist as a configured AWS CLI profile,
      a warning will be displayed.

    .PARAMETER Quiet
      Suppress informational output.

    .LINK
      https://www.github.com/jonscheiding/posh-awsprofile
  #>


  Param(
    [Parameter()]
    [switch] $Quiet
  )

  $ProfileItem = (Get-Item -ErrorAction Ignore Env:AWS_PROFILE)
  if($null -eq $ProfileItem) {
    if(!$Quiet) { Write-Host "No profile selected; 'default' will be used." }

    $ProfileName = "default"
  } else {
    $ProfileName = $ProfileItem.Value
  }

  Test-AWSProfile -ProfileName $ProfileName | Out-Null

  return $ProfileName
}

function Set-AWSCurrentProfile {
  <#
    .SYNOPSIS
      Sets the AWS CLI profile to the provided value, or clears it if $null is passed.

    .DESCRIPTION
      This manipulates the value of the AWS_PROFILE environment variable. If the provided
      value does not exist as a configured AWS CLI profile, a warning will be displayed.

    .PARAMETER ProfileName
      Set the profile to this value.

    .PARAMETER Clear
      Clear the selected profile.

    .PARAMETER Persist
      Save the updated profile into the user's environment variables so that it persists
      across PowerShell restarts.

    .PARAMETER Quiet
      Suppress informational output.

    .LINK
      https://www.github.com/jonscheiding/posh-awsprofile
  #>


  Param(
    [Parameter(Mandatory=$true, Position=0, ParameterSetName='Set-Profile')]
    [string]$ProfileName,
    [Parameter(Mandatory=$true, ParameterSetName='Clear-Profile')]
    [switch]$Clear,
    [Parameter()]
    [switch]$Persist,
    [Parameter()]
    [switch] $Quiet
  )

  Write-Host ''

  switch($PSCmdlet.ParameterSetName) {
    "Clear-Profile" {
      $ProfileName = $null
      if(!$Quiet) { Write-Host "Clearing profile setting for current session." }
      Remove-Item -ErrorAction Ignore Env:AWS_PROFILE
    }
    "Set-Profile" {
      Test-AWSProfile -ProfileName $ProfileName | Out-Null
      if(!$Quiet) { Write-Host "Setting profile for current session to '$ProfileName'." }
      Set-Item Env:AWS_PROFILE $ProfileName
    }
  }

  if(!$Persist) {
    if(!$Quiet) { Write-Host "To change the profile setting for future sessions, run this command with the -Persist argument." }
    return
  }

  if(!(Test-IsWindows)) {
    Write-Warning "The -Persist argument is not supported on non-Windows platforms."
    return
  }

  if(!$Quiet) { Write-Host "Updating user environment variable to change profile setting for future sessions." }
  [System.Environment]::SetEnvironmentVariable(
    "AWS_PROFILE", $ProfileName,
    [System.EnvironmentVariableTarget]::User)
}

function Get-AWSAvailableProfiles {
  <#
    .SYNOPSIS
      Displays the list of available AWS CLI profiles.

    .DESCRIPTION
      Shows the list of profiles found in the AWS CLI config file, as returned
      by Get-AWSConfigFile. If that file does not exist, a warning is displayed.

    .LINK
      https://www.github.com/jonscheiding/posh-awsprofile
  #>


  $AwsConfigFile = Get-AWSConfigFile
  if ($null -eq $AwsConfigFile) {
    Write-Error "Cannot find AWS config file"
    return $null
  }

  if(!(Test-Path $AwsConfigFile -PathType Leaf)) {
    Write-Warning "AWS CLI config file $AwsConfigFile doesn't exist. Run 'aws configure' to create it."
    return @()
  }

  $NoSection = "NoSection"

  $IniFile = [ordered]@{}
  switch -regex -file $AwsConfigFile
  {
    "^\[(.+)\]$" # Section
    {
      $Section = $matches[1] -Replace 'profile ',''
      $IniFile[$Section] = @{}
      $CommentCount = 0
    }

    "^(;.*)$" # Comment
    {
      if (!($Section))
      {
          $Section = $NoSection
          $IniFile[$Section] = @{}
      }
      $Value = $matches[1]
      $CommentCount = $CommentCount + 1
      $Name = "Comment" + $CommentCount
      $IniFile[$Section][$Name] = $Value
    }

    "(.+?)\s*=\s*(.*)" # Key
    {
      if (!($Section))
      {
          $Section = $NoSection
          $IniFile[$Section] = @{}
      }
      $Name,$Value = $matches[1..2]
      $IniFile[$Section][$Name] = $Value
    }
  }

  $AwsProfiles = @()
  foreach ($ProfileName in $IniFile.Keys) {
    $AwsProfiles += @{ Name = $ProfileName; Region = $IniFile[$ProfileName]['region']}
  }

  return $AwsProfiles
}

function Test-AWSProfile {
  <#
    .SYNOPSIS
      Checks the validity of the provided AWS CLI profile name.

    .DESCRIPTION
      Checks whether the provided name exists in the list of profiles found
      in the AWS CLI config file, as returned by Get-AWSConfigFile. If that
      file does not exist, a warning is displayed.

    .LINK
      https://www.github.com/jonscheiding/posh-awsprofile
  #>


  Param(
    [Parameter(Mandatory=$true, Position=1)]
    $ProfileName
  )

  $AvailableProfileNames = Get-AWSAvailableProfiles | ForEach-Object { $_.Name }

  if($AvailableProfileNames.Length -eq 0 -or !$AvailableProfileNames.Contains($ProfileName)) {
    Write-Warning "No configuration found for AWS profile '$($ProfileName)'."
    return $false
  }

  return $true
}

function Switch-AWSProfile {
  <#
    .SYNOPSIS
      Displays an interactive menu for choosing an AWS CLI profile.

    .DESCRIPTION
      Uses the following keys for navigation of the menu.
        [ Move up the list
        ] Move down the list
        \ Set your profile to the currently selected one
        - Clear your profile
        = Cancel with no changes

      Additionally, you can press any number key to select the profile
      indicated by that key.

    .PARAMETER ProfileName
      When provided, skips the menu and directly sets the profile name.

    .PARAMETER Persist
      Save the updated profile into the user's environment variables so that it persists
      across PowerShell restarts.

    .LINK
      https://www.github.com/jonscheiding/posh-awsprofile
  #>

  Param(
    [Parameter(Position=0)]
    [string] $ProfileName,
    [Parameter()]
    [switch] $Persist
  )

  $AvailableProfiles = Get-AWSAvailableProfiles
  if([string]::IsNullOrEmpty($ProfileName)) {
    $CurrentProfile = Get-AWSCurrentProfile

    if($AvailableProfiles.Length -eq 0) {
      Write-Error "There are no profiles configured."
      return 1
    }

    Write-Host "`nPress `e[31mDelete`e[0m to clear your profile setting."
    Write-Host "Press `e[33mEscape`e[0m to cancel."

    $SelectedProfile = Read-MenuSelection -Items $AvailableProfiles -CurrentItem $CurrentProfile
  } else {
    $SelectedProfile = $AvailableProfiles | Where-Object { $_.Name -eq $ProfileName } Select-Object -First 1
  }

  if("esc" -eq $SelectedProfile) {
    Write-Host "Leaving profile as '$CurrentProfile'."
    return
  }
  
  if($null -ne $SelectedProfile) {
    Set-AWSCurrentProfile -ProfileName $SelectedProfile.Name -Persist:$Persist
  } else {
    Set-AWSCurrentProfile -Clear -Persist:$Persist
  }

  Write-Host ""
  return
}

function Read-MenuSelection {
  <#
    .SYNOPSIS
      Utility function that implements the menu handling for
      Switch-AWSProfile.

    .LINK
      https://www.github.com/jonscheiding/posh-awsprofile
  #>


  Param(
    [Parameter(Mandatory = $true)] $Items,
    [Parameter(Mandatory = $true)] $CurrentItem
  )

  $SelectedItem = $null
  $CurrentIndex = $Items.IndexOf($CurrentItem)
  if($CurrentIndex -lt 0) { $CurrentIndex = 0 }

  function Get-ProfileName {
    Param(
      [Parameter(Mandatory = $true)] $Index
    )

    if ($null -eq $Items[$Index].Region) {
      return "$($Items[$Index].Name)"
    }
    return "$($Items[$Index].Name) ($($Items[$Index].Region))"
  }

  #
  # Initially write out the menu items, including a * indicator
  # to point out the currently set profile.
  #
  for($i = 0; $i -lt $Items.Length; $i++) {
    $Indicator = if ($CurrentIndex -eq $i) { "*" } else { " " }
    $Name = if ($CurrentIndex -eq $i) { "`e[36m$(Get-ProfileName $i)`e[0m" } else { "$(Get-ProfileName $i)" }
    $Index = if ($i -lt 10) { $i } else { " " }
    Write-Host "$Indicator $Index $Name"
  }

  #
  # Keep track of where the cursor ended up so we can update the
  # * indicator
  #
  $CursorTop = [Console]::CursorTop - $Items.Length

  while($null -eq $SelectedItem) {
    $MoveBy = 0
    $Key = [Console]::ReadKey($true)

    switch($Key.Key) {
      "UpArrow"   { if ($CurrentIndex -gt 0) { $MoveBy = -1 } }
      "DownArrow" { if ($CurrentIndex -lt $Items.Length - 1) { $MoveBy = 1 } }
      "Enter"     { $SelectedItem = $Items[$CurrentIndex] }
      "Escape"    { return "esc" }
      "Delete"    { return $null }
    }

    if([char]::IsNumber($Key.KeyChar)) {
      $Index = [int]::Parse($Key.KeyChar)
      if ($Index -lt $Items.Length) {
        $SelectedItem = $Items[$Index]
      }
    }

    if($MoveBy -ne 0) {
      #
      # If [ or ] was pressed, update where the * indicator is shown.
      #
      [Console]::SetCursorPosition(0, $CursorTop + $CurrentIndex)
      Write-Host -NoNewline " $CurrentIndex $(Get-ProfileName $CurrentIndex)"
      $CurrentIndex += $MoveBy
      [Console]::SetCursorPosition(0, $CursorTop + $CurrentIndex)
      Write-Host -NoNewline "* $CurrentIndex `e[36m$(Get-ProfileName $CurrentIndex)`e[0m"
      [Console]::SetCursorPosition(0, $CursorTop + $Items.Length)
    }
  }

  return $SelectedItem
}

function Test-IsWindows {
  <#
    .SYNOPSIS
      Utility function that checks if we are currently running on Windows.

    .LINK
      https://www.github.com/jonscheiding/posh-awsprofile
  #>


  if(!(Get-Variable -Name IsWindows -ErrorAction SilentlyContinue)) {
    #
    # No $IsWindows variable means we're on PowerShell Core 5.1 or
    # PowerShell Desktop, both of which are Windows-only.
    #
    return $true
  }

  return $IsWindows
}

New-Alias -Name awsp -Value Switch-AWSProfile -Force