How to get cognitive services account key using powershell function app? - azure

I have created cognitive services account . I want to get cognitive services account key and store it in a variable using powershell script.
I have used below script :
$resourceGroup = "Demo"
$AccountName = "DemoCs"
$Key = Get-AzCognitiveServicesAccountKey -ResourceGroupName $resourceGroup -Name $AccountName
Write-Host "account key 1 = " $Key
after executing the script result is :
2020-05-20T08:30:31Z [Information] INFORMATION: account key 1 = Microsoft.Azure.Commands.Management.CognitiveServices.Models.PSCognitiveServicesAccountKeys
Above script is able to list keys in the cloud shell but not in powershell function app .

You cannot simply call Import-Module Az.CognitiveServices like on your local machine where you have previously installed Az.CognitiveServices from that site. But you have to copy all files from that locally installed package into specific folder inside of your Function App in Azure.
1.Install Az.CognitiveServices in local and go to its folder to get all the content in it.
2.Go to your function KUDU. Click CMD>site>wwwroot>yourFunctionName then create a directory called modules.
3.Simply drag-and-drop all files from your local powershell module location to your Azure Function App folder create above(modules).
4.Include Az.CognitiveServices PowerShell module in run.ps1 file like that example below:
Import-Module "D:\home\site\wwwroot\HttpTrigger1\modules\Az.CognitiveServices.psd1"
5.Then run the script as below with $Key.Key1 to specify the Key1.
$Key = Get-AzCognitiveServicesAccountKey -ResourceGroupName $resourceGroup -Name $AccountName
Write-Host "account key 1 = " $Key.Key1
For more details, you could refer to this tutorial and this one.

Related

PS Azure automation runbook ; How to Mount Azure File Share?

Trying to mount Azure FS from Powershell runbook in Azure Automation.
Via username and key
$UserName = "localhost\trex4xfs"
$Key = "Zav---mykey-----1Tdw=="
$RemotePath = "\\myshare.file.core.windows.net\mainfs"
$MapDrive = "z:"
Get-Command -Name *SmbMapping* | ft
[securestring]$pass = ConvertTo-SecureString $key -AsPlainText -Force
$credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $UserName, $pass
new-psdrive -name T -PsProvider FileSystem -root $RemotePath -credential $credential
Get-PSDrive | ft
echo "--------now import smb"
Import-Module smbshare
echo "--------now smb"
New-SmbMapping -LocalPath $MapDrive -RemotePath $RemotePath -UserName $UserName -Password $Key
Above works great on "plain Powershell on Windows"
Tried
Runbook with 5.1 and 7.1 PS version
new-psdrive (error: This function is not supported on this system )
New-SmbMapping (error 7.1: The 'New-SmbMapping' command was found in the module 'SmbShare', but the module could not be loaded. For more information, run 'Import-Module SmbShare'
New-SmbMapping (error 5.1: Cannot connect to CIM server. The specified service does not exist as an installed service. )
Import-Module smbshare (error Failed to generate proxies for remote module 'smbshare'. Cannot overwrite the item C:\Users\Client\Temp\tmp_5t22mi1k.oh0\remoteIpMoProxy_smbshare_2.0.0.0_localhost_f29e4e95-e8cf-4256-a4db-fc9381c6563c.format.ps1xml with itself.)
New-CimSession (error: The specified service does not exist as an installed service.)
Seem to be related to New-CimSession not available on Azure Automation runbook
other questions related to this:
Azure Runbook - Get a file from Azure File System Storage
Not able to access Azure FileShare Storage container from Azure Automation Runbook
Map a Azure Fileshare to Azure Runbook local drive to use as temporary storage
One of the related question which you have shared already provides the answer (i.e., this one) which basically says to use hybrid runbook worker in your use case scenario.

Azure DevOps - Set-Azcontext - The term 'Set-Azcontext' is not recognized

I have created one Azure DevOps pipeline.
99% of this pipeline calls PowerShell scripts (PowerShell Core script type).
Within the Power Shell scripts are calls to the AZ module - this all works fine.
I now have to add a new step within the DevOps pipeline to set the 'VulnerabilityAssessment' on an SQL server - however this time I need to call module 'Set-Azcontext' as part of the PowerShell script which is shown below...
[CmdletBinding()]
param(
$prgname,
$psqlservername,
$psaname,
$pnotificationmmail = 'john.doe#hotmail.com',
$psubscriptionname = 'ABC'
)
#debug
#Get-Module -Name AZ -ListAvailable
# working in powershell and need to set the correct subscription in powershell (ABC)
Set-Azcontext -Subscription "ABC"
#Enable-AzSqlServerAdvancedDataSecurity -ResourceGroupName $prgname -ServerName $pservername -DoNotConfigureVulnerabilityAssessment
# https://learn.microsoft.com/en-us/powershell/module/az.sql/update-
azsqlservervulnerabilityassessmentsetting?view=azps-7.5.0
#Update-AzSqlServerVulnerabilityAssessmentSetting -ResourceGroupName $prgname -ServerName $pservername -StorageAccountName $psaname -ScanResultsContainerName "vulnerability-assessment" -RecurringScansInterval Weekly -EmailAdmins $true -NotificationEmail #pnotificationmmail
When the Azure devOps pipeline runs it fails on step...Set-Azcontext -Subscription "ABC"
update-vulnerability-assessment.ps1 : The term 'Set-Azcontext' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
The devOps process is running on a Azure agent. It looks like a module is not available or loaded.
Maybe I need to install/load the module containing 'Set-Azcontext' as part of the powershell script ? (if so how do I do this)
OR
Install a new capibility of the agent to have the module containing 'Set-Azcontext' installed?(if so how do I do this)
Going to instead via an ARM template in the Azure pipeline for setting the vulneratibilty of Azure SQL server

Taking configuration backups from Azure webapp wwwroot folder

I'm trying to take specific configuration backup in Azure webapp wwwroot folder with below powershell script which was working fine in public App service plan(Standard and Premium) but the same powershell script is not working fine in Private App service plan(Isolated(App service Environment) - I1,I2,I3). Please find the code below.
Code:
Import-Module Kudu-api
$userNm="`$Testapp"
$password="*******"
$token = New-KuduAuthorizationToken $userNm $password
$sitename="Testapp"
Set-Location "C:\Users\admin\Desktop\Backups"
sleep -Seconds 2
Receive-KuduFile $sitename $token '/site/wwwroot/appsettings.json' ./appsettings.json`
Getting the below error when trying the above script in Isolated(I1) appservice plan:
Error : Invoke-RestMethod : The remote name could not be resolved: 'Testapp.scm.azurewebsites.net'
Please suggest how we can resolve this.

Azure CLI script variables giving errors

I'm trying to run the sample script found here: https://learn.microsoft.com/en-au/azure/service-fabric/service-fabric-quickstart-containers-linux#create-a-service-fabric-cluster
#!/bin/bash
# Variables
ResourceGroupName='containertestcluster'
ClusterName='containertestcluster'
Location='eastus'
Password='q6D7nN%6ck#6'
Subject='containertestcluster.eastus.cloudapp.azure.com'
VaultName='containertestvault'
VmPassword='Mypa$$word!321'
VmUserName='sfadminuser'
# Login to Azure and set the subscription
az login
az account set --subscription <mySubscriptionID>
# Create resource group
az group create --name $ResourceGroupName --location $Location
# Create secure five node Linux cluster. Creates a key vault in a resource group
# and creates a certficate in the key vault. The certificate's subject name must match
# the domain that you use to access the Service Fabric cluster. The certificate is downloaded locally.
az sf cluster create --resource-group $ResourceGroupName --location $Location --certificate-output-folder . --certificate-password $Password --certificate-subject-name $Subject --cluster-name $ClusterName --cluster-size 5 --os UbuntuServer1604 --vault-name $VaultName --vault-resource-group $ResourceGroupName --vm-password $VmPassword --vm-user-name $VmUserName
From the command prompt or PowerShell, I run "az login" and login, then I copy & paste this script into the console but get errors when it comes to the variables.
I see you use the Shell script, it's more appropriate to run in Linux. For Windows, the PowerShell script is more suitable. And in Windows, the variables need to be set like this:
$varName = 'xxxx'
So you need to change all the variables like above. And I suggest you change the script into a PowerShell script.

How to create a Microsoft Team using a Queue Triggered Azure Function writed in PowerShell?

I want to create a Team by using an azure function triggered by an Azure Queue.
Unfortunetly when I run the code it is not working inside the Azure Function.
I'm wondering. Is there a way to create a Microsoft Team using PowerShell inside an Azure Function ?
Import-module MicrosoftTeams
$group = New-Team -MailNickname "teamTitle" -displayname "teamTitle" -Visibility "private"
Add-TeamUser -GroupId $group.GroupId -User "user#etc.com"
New-TeamChannel -GroupId $group.GroupId -DisplayName "General"
Working locally. Not working within the Azure Function.
Bellow the error i'm getting :
ERROR: Import-Module : The specified module 'MicrosoftTeams' was not loaded because no valid
module file was found in any module directory. At D:\home\site\wwwroot\CreateTeam\run.ps1:3
char:1 + Import-Module MicrosoftTeams + [...]
Thank you
Based on the error message, your Function app does not have the MicrosoftTeams module installed. You need to include a reference to this module to the requirements.psd1 file (see https://learn.microsoft.com/azure/azure-functions/functions-reference-powershell#dependency-management for more details).
Currently this module is not yet natively integrated into the azure functions under powershell
To see all the available packages go in App Service -> Advanced Tools -> DebugConsole -> Powershell and run :
Write-Output ‘Getting PowerShell Module’
$result = Get-Module -ListAvailable |
Select-Object Name, Version, ModuleBase |
Sort-Object -Property Name |
Format-Table -wrap |
Out-String
Write-output `n$result
To manually add a package, It is necessary to create a directory "Module" At the same level as the directory of the function, They will be automatically preloaded.
(https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-powershell step "Function app-level Modules folder")
After installation of the module. use below code in your script to automate the process.
$securedpassword = ConvertTo-SecureString $Password -AsPlainText -Force
$mycredentials = New-Object System.Management.Automation.PSCredential ($Username, $securedpassword )
$res = Connect-MicrosoftTeams -Credential $mycredentials

Resources