Reputation: 21619
I have automated an Azure deployment using AzureRM
commandlets. Those commandlets need a login, so I tried to provide a saved profile using Save-AzureRMProfile
/Select-AzureRMProfile
.
However after some time profile seems to expire and I need to login again. I want to run my script automatically on a schedule, so manual re-login is not a solution.
How can I avoid the profile expiry?
Upvotes: 2
Views: 2015
Reputation: 12228
The simple answer is that you can't avoid the expiry, your token expires and needs to be reauthenticated. (it would be worrying if those credentials could be persisted) - However
Add-AzureRmAccount
does take a pscredential parameter. So you can save your credentials to a file and instead automatically log in with live credentials every time.
You can just use the standard pscredential save mechanisms, the problem in this for you is that a pscredential isn't transportable, to get around this you can create your own key to pass to pscredential.
$key = New-Object byte[](32)
$rng = [System.Security.Cryptography.RNGCryptoServiceProvider]::Create()
$rng.GetBytes($key)
You can then use this key to create a transportable secure string. Obviously this key is your authentication at this point, so it needs to be stored securely.
$cred = Get-Credential
$SecureStringWithKey = $cred.Password | ConvertFrom-SecureString -Key $key
You can encode the key with base64 and add it as an environment variable etc
$base64key = [Convert]::ToBase64String($key)
At the other end, decode the string
$key = [System.Convert]::FromBase64String($base64key)
and push it back through SecureString, and rebuild a credential object.
$secureStringPassword = $AuthObject.SecureStringWithKey | ConvertTo-SecureString -Key $key
$cred = new-object -typename System.Management.Automation.PSCredential `
-argumentlist $Username, $secureStringPassword
You can then log in with
Add-AzureRmAccount -Credential $cred
My personal approach to all of this was to create a psobject with all of those details saved, (they key, the tenantid, and the pscredential) to create a json string, and then encrypt that with a certificate. That way I can store the encrypted json file on a blob, and download, decrypt and sign in on any system I'm sat at.
Upvotes: 4