Is there any problem with my query to get my token? - azure

I'm trying to get an oauth token from my Azure AD using Powershell.
I try to generate my token into a text file to see the result for the 1rst step of my request.
I'm trying to get an Azure Digital Twins token. The constant you see in $resourceId is given by Microsoft to request AzureDigitalTwins.
And here is my script :
# Load ADAL methods
Add-Type -Path ".\MyPath\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
$resultToken = ".\TokenTest.txt"
# Conf here
$aadInstance = "https://login.microsoftonline.com/"
$tenantId = "myTenantID"
$applicationId = "myAppID"
$applicationSecretKey = "myAppSecret"
$resourceId = "0b07f429-9f4b-4714-9392-cc5e8e80c8b0"
# Get an Access Token with ADAL
$authContext = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext($aadInstance + $tenantId)
$clientCredential = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential($applicationId, $applicationSecretKey)
$authenticationResult = $authContext.AcquireTokenAsync($resourceId, $clientCredential)
($token = $authenticationResult.AccessToken) | Out-File $resultToken
After i run the script my Text file is empty but i get no error.
I use the exact same code in C# to get a token and it's working perfectly but not in Powershell apparently.
Is there a problem with this ?
Thanks for your answers.

Found the answer !
Just needed to add .GetAwaiter().GetResult() to the AcquireTokenAsync method !
$authenticationResult = $authContext.AcquireTokenAsync($resourceId, $clientCredential).GetAwaiter().GetResult()

Related

How do I normalize this URL in powershell?

I have the following code for Azure key vault resources:
$tempkeyid = (Get-AzKeyVaultKey -VaultName $vaultname -Name $tempkeyname).Id
$tempkeyid = $tempkeyid.Substring(0, $tempkeyid.LastIndexOf('/'))
$tempkeyid
New-AzSynapseWorkspaceKey -ResourceGroupName $resourcegroup -WorkspaceName $workspacename -Name $tempkeyname -EncryptionKeyIdentifier $tempkeyid
Line 2 is there because the key vault returns the versioned identifier but line 4 needs the versionless identifier
The value for $tempkeyid in line 3 is:
https://keyvaultname.vault.azure.net:443/keys/keyname
I get the error:
New-AzSynapseWorkspaceKey: Key Vault URL should be a normalized URL
I've tried to encode and decode the URL with the code below but the encode attempt gets the same error and the decode attempt gets an error that says "Invalid URI: The format of the URI could not be determined". I'm not sure how to normalize it otherwise, or what specifically isn't normalized. The value of $tempkeyid looks correct to me.
$tempkeyid = [System.Web.HttpUtility]::UrlEncode($tempkeyid)
$tempkeyid = [System.Web.HttpUtility]::UrlDecode($tempkeyid)
Encoding is not the same as URI normalisation which refers to expressing the uri in a standard format. (See wikipedia entry). In your case, I would guess it doesn't like the use of the default port (:443). To systematically get a normalised uri, try something like this:
$tempkeyiduri = [System.Uri]($tempkeyid)
$tempkeyid = $tempkeyiduri.AbsoluteUri

Create Automation Action Group in Azure using powershell

I want to use this command Set-AzActionGroup to action the standard automation runbook restart VM but there don't seem to be any examples of this around. To do this in Set-AzActionGroup I need to reference the VM, an automation account and some things called service uri and webhook resource id (which I think refers to the runbook). Has anyone got a fully specified example? I have a azure automation account but would need a webhook.
Just try the PowerShell below to create an Action group with restart VM AutomationRunbookReceiver:
$automationAccountResourceGroup = ""
$automationAccountName = ""
$webhookName = "Webhook20210316"
$receiverEmail = ""
$actionGroupName = ""
#create automationRunbookReceivers
$webhook = New-AzAutomationWebhook -Name $webhookName -IsEnabled $true -ExpiryTime "10/2/2030" -RunbookName "RestartAzureVmInResponseToVmAlertGlobalRunbook" -ResourceGroup $automationAccountResourceGroup -AutomationAccountName $automationAccountName -Force
$serviceURI = $webhook.WebhookURI
$automationAccountID = (Get-AzResource -ResourceGroup $automationAccountResourceGroup -name $automationAccountName).ResourceId
$WebhookResourceID = $automationAccountID + "/webhooks/" + $webhook.name
$AutomationRunbookReceiver = New-AzActionGroupReceiver -Name 'restartVM' -RunbookName 'Restart VM' -AutomationAccountId $automationAccountID.ToLower() -IsGlobalRunbook -AutomationRunbookServiceUri $serviceURI -WebhookResourceId $WebhookResourceID
#create email receivers
$EmailReceiver = New-AzActionGroupReceiver -Name $receiverEmail -EmailReceiver -EmailAddress $receiverEmail
Set-AzActionGroup -ResourceGroupName $automationAccountResourceGroup -Name $actionGroupName -ShortName $actionGroupName -Receiver $EmailReceiver,$AutomationRunbookReceiver
Result:
I also tested it on my side under some rules and it works as excepted:

Why do I get error "Name or Service not known" when encrypting Azure VM?

I am trying to encrypt a VM in Azure using the following code
$keyVault = Get-AzureRmKeyVault –VaultName “azkeyvaultWestUS” -ResourceGroupName “azkeyvault”;
$diskEncryptionKeyVaultUrl = $keyVault.VaultUri;
$keyVaultResourceId = $keyVault.ResourceId;
$keyEncryptionKeyUrl = (Get-AzureKeyVaultKey –VaultName “azkeyvaultWestUS” –Name “azpavdiskencryption”).Key.kid;
But when I tried to run it, I got the message
Get-AzKeyVaultKey: Name or Service not known
After the instruction ending in .Key.kid
Does anyone know how to fix this?
Thanks in advance.
Try accessing it separately and it should bye key.id
$Key = Add-AzureKeyVaultKey -VaultName "azkeyvaultWestUS" -Name 'azpavdiskencryption'
#get uri
$keyEncryptionKeyUrl = $Key.key.kid

Invoke-AzureRmVMRunCommand parameter passing suddenly fails

Context: Running an Azure Automation Account solution where a caller PS script executes another PS script (executed on a VM) with parameter passing via 'Invoke-AzureRmVMRunCommand'.
Story: I had running a PowerShell (caller) script that executed another (called) PowerShell script on a remote Azure Win VM. That flow ran via an Automation Account schedule every day but suddenly stopped working two days ago because the parameter passing from the caller to the called script is not working anymore. I currently blame the MSFT Azure people for breaking my PRD solution.
Here the caller PS script code for the arguments to pass on:
$hshParams = #{
strSAName = $hshParameters.strStagingSA
strSAAccessKey = $strSAAccessKey
strFileShare = '"' + $strFileShare + '"'
strCopyObjects = $hshParameters.strCopyObjects
strSrcDriveLetter = $strSrcDriveLetter
strDstDriveLetter = $strDstDriveLetter
}
Here the invocaton of the VM-run PS script:
Invoke-AzureRmVMRunCommand -ResourceGroupName $objVM.ResourceGroupName -Name $objVM.Name `
-CommandId 'RunPowerShellScript' -ScriptPath $strRemoteScriptFileNameTmp -Parameter $hshParams
Here the parameter reception code on the VM-run PS script side:
# Parameters
Param (
[string] $strCopyObjects = $null,
[string] $strSAAccessKey = $null,
[string] $strFileShare = $null,
[string] $strSAName = $null,
[string] $strDstDriveLetter = $null,
[string] $strSrcDriveLetter = $null
)
Until two days ago all those six string values were populated properly and according to the argument setup in the hash table '$hshParams':
$strSAAccessKey = 92LO1Q4tuyeiqxxx
$strFileShare = 129xxxa1.file.core.windows.net\solutionfiles
$strSAName = 12xsa1
$strDstDriveLetter = D
$strSrcDriveLetter = Z
$strCopyObjects = AutoTopUp\Application\Live
Problem: Now I see five string values suddenly not being populated anymore with one being garbage, here is what they look like today:
$strSAAccessKey = []
$strFileShare = []
$strSAName = []
$strDstDriveLetter = []
$strSrcDriveLetter = []
$strCopyObjects = AutoTopUp\Application\Live" -strSAAccessKey 92LO1Q4tuyeiqxxx -strFileShare 129xxxa1.file.core.windows.net\solutionfiles -strSAName 12xsa1 -strDstDriveLetter D -strSrcDriveLetter Z
The solution was not touched, it just had been running as per schedule. $Args.Count on the VM-run script returns '2'.
My Question: Anyone with an explanation on this new behaviour? Frustratingly, I did not manage to arrange the parameter passing in a different way as it is all a bit unclear what the proper way of receiving the hash table values would be. The MSFT help page for 'Invoke-AzureRmVMRunCommand' is (of course) not helping here, also did I not find any other clear ways on the parameter passing on SO or Google...
Related question is raised in this MSDN thread; Just sharing this for the benefit of broader audience who might face similar issue.

Unable to authenticate Looker API in Databricks using Python

I want to access some charts -which I have saved in Looker- within Databricks. Part of this process is the authentication. I have one Looker auth-script which works but only pulls the tabular results into Databricks which corresponds to a Looker-View. Instead, I want ONLY the charts to be accessed in Databricks which will correspond to a Looker-look or Looker-space. However, when I follow the tutorial on https://discourse.looker.com/t/generating-a-powerpoint-presentation-from-all-looks-in-a-space/8191, I am not able to authenticate with their script. Hopefully, someone can help.
**Working auth-script for Looker-Views**
import looker_tools as tools
api=tools.LookerApi(
api_endpoint="abcd",
client_id=dbutils.secrets.get(scope="looker-api", key="looker_client_id"),
client_secret=dbutils.secrets.get(scope="looker-api",key="looker_client_secret")
)
token = api.login()
**Desired auth-script for Looker-Space/Looks as per tutorial link**
looker_instance = 'your-company.looker.com'
target_space = # 'Period over Period' Space on the Looker instance
client_id = 'xxxxxxxx'
client_secret = 'xxxxxxxx'
# instantiate Auth API
unauthenticated_client = looker_client.ApiClient(configuration=None)
unauthenticated_client.configuration.host = f'https://{looker_instance}:19999/api/3.0/'
unauthenticated_authApi = looker_client.ApiAuthApi(unauthenticated_client)
# authenticate client
token = unauthenticated_authApi.login(client_id=client_id, client_secret=client_secret)
client = looker_client.ApiClient(header_name='Authorization', header_value='token ' + token.access_token)
client.configuration.host = f'https://{looker_instance}:19999/api/3.0/'
I tried translating the code from Current to DESIRED auth-script but the error states the looker_client is not defined!
looker_instance = 'abcd'
target_space = 123
client_id = dbutils.secrets.get(scope="looker-api", key="looker_client_id")
client_secret = dbutils.secrets.get(scope="looker-api",key="looker_client_secret")
# instantiate Auth API
unauthenticated_client = looker_client.ApiClient(configuration=None) --> This line fails!!
unauthenticated_client.configuration.host = f'https://{looker_instance}:19999/api/3.0/'
unauthenticated_authApi = looker_client.ApiAuthApi(unauthenticated_client)
# authenticate client
token = unauthenticated_authApi.login(client_id=client_id, client_secret=client_secret)
client = looker_client.ApiClient(header_name='Authorization', header_value='token ' + token.access_token)
client.configuration.host = f'https://{looker_instance}:19999/api/3.0/'
I hope someone can help on how to define looker_client properly. Thanks.
It looks like this one was resolved here: https://discourse.looker.com/t/generating-a-powerpoint-presentation-from-all-looks-in-a-space/8191/15?u=izzy for those following along at home. There's another issue, but the NameError: name ‘looker_client’ is not defined error was resolved by adding a necessary import:
import looker_client_30 as looker_client

Resources