Using Pulumi with multiple accounts

When logging into Pulumi, using pulumi login the effect is machine wide. If, like me, you have multiple accounts i.e. personal and work, switching accounts by logging out and logging back in again becomes tedious fast. It's also risky when you find yourself logged into the wrong account and you do a pulumi up...

AWS CLI has a concept of named profiles that allows you select the profile an AWS CLI command applies to. Unfortunately Pulumi does not support such a concept. It does however support an environment variable PULUMI_ACCESS_TOKEN that takes precedence over the machine level access token. Using this with a function in your PowerShell $profile / Bash .bashrc, we can switch profiles on-the-fly for the current terminal session and any processes spawned from there. This neatly also allows you to use different accounts in separate terminal sessions at the same time.

To set this up, first go to your each of your Pulumi accounts' settings and generate an Access Token for each profile.

Then, if you are a PowerShell user, add this function to your PowerShell's $profile (obviously replace the tokens with your real tokens) :

  1. function pulumi-profile([string]$profile){
  2. if($profile -eq ""){
  3. Write-Host "Profile name argument missing."
  4. return
  5. }
  6. pulumi logout
  7. $env:PULUMI_ACCESS_TOKEN = ""
  8. if($profile -eq "local"){
  9. pulumi login --local --non-interactive
  10. return
  11. }
  12. elseif($profile -eq "work"){
  13. $env:PULUMI_ACCESS_TOKEN = "pul-work-token"
  14. }
  15. elseif($profile -eq "personal"){
  16. $env:PULUMI_ACCESS_TOKEN = "pul-personal-token"
  17. }
  18. else{
  19. Write-Host "Unknown profile"
  20. return
  21. }
  22. pulumi login --non-interactive
  23. }

Or, if you are a Bash user, add this function to your ~/.bashrc :

  1. pulumi-profile() {
  2. if [ $# -eq 0 ]; then
  3. echo "Profile name argument missing."
  4. return
  5. fi
  6. pulumi logout
  7. export PULUMI_ACCESS_TOKEN=""
  8. if [ $1 == "local" ]; then
  9. pulumi login --local --non-interactive
  10. elif [ $1 == "work" ]; then
  11. export PULUMI_ACCESS_TOKEN="pul-work-token"
  12. elif [ $1 == "personal" ]; then
  13. export PULUMI_ACCESS_TOKEN="pul-personal-token"
  14. else
  15. echo "Unknown profile"
  16. return
  17. fi
  18. pulumi login --non-interactive
  19. }

You can then switch Pulumi profile using by calling pulumi-profile <profile-name> in your terminal.

Example in PowerShell:

Powershell terminal

Example in Bash:

Bash terminal

Hope that helps!

Comments or feedback? Respond to this tweet.