azurerm icon indicating copy to clipboard operation
azurerm copied to clipboard

get_access_token_from_cli should be able to use cached service principal tokens

Open nickraptis opened this issue 6 years ago • 4 comments

I have a setup where azure-cli logs in as a service principal and would like to use the get_access_token_from_cli functionality. The cached tokens file looks like this:

~/.azure/accessToken.json
[{ "servicePrincipalId": "xxxxxxxxxxxxxxxxxxxxxxxx", "servicePrincipalTenant": "xxxxxxxxxxxxxxxxxxxxx", "accessToken": "xxxxxxxxxxxxxxxxxxxxx" }]

Resulting in this error:

  File "site-packages/azurerm/adalfns.py", line 64, in get_access_token_from_cli
   if key['userId'] == sub_username:
KeyError: 'userId'

I've also seen setups where the cached tokens are both user and service principal ones.

Should be easy to be able to retrieve both kinds of tokens from the cache file.

PS: This is something I'll probably work on anyway. Opening this issue mostly to judge interest for a PR.

nickraptis avatar May 16 '18 12:05 nickraptis

Thanks @nickraptis. When you have a service principal, why don't you call get_access_token()? Is it to make the Python code more portable? E.g. re-use the same code in any CLI environment without needing any additional config files? That makes sense. Please go ahead a submit a PR for this.

gbowerman avatar May 20 '18 17:05 gbowerman

@gbowerman Our use case is that we are using azurerm alongside azure-cli in a cicd pipeline. azure-cli is already logged in as a principal, so we didn't want to lug the principal credentials around if we didn't needed to.

I had overlooked the documentation's suggestion to use az account get-access-token. This did take some work to update to a version offering it, but ended up being the right choice, so I don't think an enhancement is needed after all. Other than considering catching the mentioned Exception, or more prominence in the documentation, I'm happy with closing the issue :)

nickraptis avatar May 22 '18 11:05 nickraptis

@nickraptis thanks the use case makes sense. I'll leave this open in case anyone wants to take on implementing it, or catching the exception and returning a meaningful message.

gbowerman avatar May 22 '18 16:05 gbowerman

BTW a recent change improved get_access_token_from_cli() so it works in Azure cloud shell (getting token from MSI endpoint). May not be useful in your case, but adding it to this issue as an FYI.

gbowerman avatar Dec 03 '18 19:12 gbowerman