In azure can we update the profile.ps1 file function app? - azure

We have a function in azure portal. When we create function app, we can see the profile.ps1 in App Files section of a function App. Can we edit this profile.ps1 file using PowerShell or CLI commands. If Yes, please help me out.
Any help can be appriciated...!

In this case, your option is to use Kudu API via powershell to update the profile.ps1, in my sample, I store the new profile.ps1 with the path C:\Users\Administrator\Desktop\profile.ps1 in local, it works fine on my side.
Sample:
$appsvWebAppName = "<functionapp-name>"
$resourceGroupName = "<group-name>"
$resource = Invoke-AzResourceAction -ResourceGroupName $resourceGroupName -ResourceType Microsoft.Web/sites/config -ResourceName "$appsvWebAppName/publishingcredentials" -Action list -ApiVersion 2018-02-01 -Force
$username = $resource.Properties.publishingUserName
$password = $resource.Properties.publishingPassword
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password)))
$userAgent = "powershell/1.0"
$apiUrl = "https://$appsvWebAppName.scm.azurewebsites.net/api/vfs/site/wwwroot/profile.ps1"
$filePath = "C:\Users\Administrator\Desktop\profile.ps1"
$headers = #{
'Authorization' = 'Basic ' + $base64AuthInfo
'If-Match' = '*'
}
Invoke-RestMethod -Uri $apiUrl -Headers $headers -UserAgent $userAgent -Method PUT -InFile $filePath -ContentType "multipart/form-data"
Check in the portal:

Related

No route registered for '/api/functions/admin/token'

I have 2 functions and have written a powershell script to get the JWT for the Azure Function app. In one of the functions, it's working and in the other, it's not. Below is a part of my script which I am using for generating the JWT:
$ResourceGroupName = <resource_group_name>
$functionAppName = <function_app_name>
$resourceType = "Microsoft.Web/sites/config"
$resourceName = "$functionAppName/publishingcredentials"
$publishingCredentials = Invoke-AzResourceAction -ResourceGroupName $resourceGroupName -ResourceType $resourceType -ResourceName $resourceName -Action list -ApiVersion 2015-08-01 -Force
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $publishingCredentials.Properties.PublishingUserName, $publishingCredentials.Properties.PublishingPassword)))
$jwt = Invoke-RestMethod -Uri "https://$functionAppName.scm.azurewebsites.net/api/functions/admin/token" -Headers #{Authorization = ("Basic {0}" -f $base64AuthInfo) } -Method GET
The only difference that I could see between the 2 function apps is: the script works for a Java function of Version 2 and the function where the script doesn't work is a Python function of Version 3.
I also tried to generate a token from Azure official documentation and it failed with the same error No route registered for '/api/functions/admin/token'. I then created a new function app in Python (Version 3) in a different subscription and tried the same and it worked for the new function app, but not for the previous one.
Here are a few lines before the error message:
Invoke-RestMethod: /home/vsts/work/1/s/setKeyFunctionCode.ps1:72
Line |
72 | $jwt = Invoke-RestMethod -Uri "https://$functionAppName.scm.azure …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| No route registered for '/api/functions/admin/token'
Is there some configuration that I'm missing out?
Please help me figure out the issue. Thanks in advance.

Azure Web Job Zip deployment Error due to Size

I am deploying a web job through powershell script and can manage to get the publishing credentials and then add the access token in the authorization header. All is fine until it uploads the zip file when I receive file size error: The remote server returned an error: (413) Request Entity Too Large.
#Function to get Publishing credentials for the WebApp :
function Get-PublishingProfileCredentials($resourceGroupName, $AppServiceNameToDeployWebJobs) {
$resourceType = "Microsoft.Web/sites/config"
$resourceName = "$AppServiceNameToDeployWebJobs/publishingcredentials"
$publishingCredentials = Invoke-AzResourceAction -ResourceGroupName $resourceGroupName -ResourceType `
$resourceType -ResourceName $resourceName -Action list -ApiVersion $Apiversion -Force
return $publishingCredentials
}
#Pulling authorization access token :
function Get-KuduApiAuthorisationHeaderValue($resourceGroupName, $AppServiceNameToDeployWebJobs) {
$publishingCredentials = Get-PublishingProfileCredentials $resourceGroupName $AppServiceNameToDeployWebJobs
return ("Basic {0}" -f [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f `
$publishingCredentials.Properties.PublishingUserName, $publishingCredentials.Properties.PublishingPassword))))
}
$accessToken = Get-KuduApiAuthorisationHeaderValue $resourceGroupName $AppServiceNameToDeployWebJobs
#Generating header to create and publish the Webjob :
$Header = #{
'Content-Disposition' = 'attachment; attachment; filename=Copy.zip'
'Authorization' = $accessToken
}
$apiUrl = "http://xxxx.scm.azurewebsites.net/app_data/jobs/triggered/Test/"
$result = Invoke-RestMethod -Uri $apiUrl -Headers $Header -Method put `
-InFile "D:\Work\WebJobs\WebJobsBuild\Test.zip" -ContentType 'application/zip' `
-TimeoutSec 600
The zip file size is only 43MB. How can I check the upper limit of file size allowed and how can I increase it? I've tried both Invoke-WebRequest and Invoke-RestMethod but the result is the same
I modify $apiUrl and it works for me.
It should be like
$apiUrl = "https://$AppServiceNameToDeployWebJobs.scm.azurewebsites.net/api/triggeredwebjobs/MyWebJob1"
Step 1. My test webjob in portal, and I will create MyWebJob1 later.
Step 2. Before running cmd.
Step 3. Modify the web job name as MyWebJob1.
Step 4. Check the webjob in portal.
Sample Code
$resourceGroupName='***';
$AppServiceNameToDeployWebJobs='jas***pp';
$Apiversion='2019-08-01';
#Function to get Publishing credentials for the WebApp :
function Get-PublishingProfileCredentials($resourceGroupName, $AppServiceNameToDeployWebJobs) {
$resourceType = "Microsoft.Web/sites/config"
$resourceName = "$AppServiceNameToDeployWebJobs/publishingcredentials"
$publishingCredentials = Invoke-AzResourceAction -ResourceGroupName $resourceGroupName -ResourceType `
$resourceType -ResourceName $resourceName -Action list -ApiVersion $Apiversion -Force
return $publishingCredentials
}
#Pulling authorization access token :
function Get-KuduApiAuthorisationHeaderValue($resourceGroupName, $AppServiceNameToDeployWebJobs) {
$publishingCredentials = Get-PublishingProfileCredentials $resourceGroupName $AppServiceNameToDeployWebJobs
return ("Basic {0}" -f [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f `
$publishingCredentials.Properties.PublishingUserName, $publishingCredentials.Properties.PublishingPassword))))
}
$accessToken = Get-KuduApiAuthorisationHeaderValue $resourceGroupName $AppServiceNameToDeployWebJobs
#Generating header to create and publish the Webjob :
$Header = #{
'Content-Disposition' = 'attachment; attachment; filename=test.zip'
'Authorization' = $accessToken
}
$apiUrl = "https://$AppServiceNameToDeployWebJobs.scm.azurewebsites.net/api/triggeredwebjobs/MyWebJob1"
$result = Invoke-RestMethod -Uri $apiUrl -Headers $Header -Method put `
-InFile "E:\test.zip" -ContentType 'application/zip' `
-TimeoutSec 600

Use Powershell to Publish to a WebApp Virtual Directory

I have an Azure WebApp, that is split into two virtual directories - UI and API.
I've managed to create the virtual directories in code, but cannot find a means of publishing to them.
Here's my code so far:
# Set UI Virtaul Directory (call /ui )
$website = Get-AzWebApp -Name $appsvWebAppName -ResourceGroupName $resourceGroupName
$VDApp = New-Object Microsoft.Azure.Management.WebSites.Models.VirtualApplication
$VDApp.VirtualPath = "/ui"
$VDApp.PhysicalPath = "site\wwwroot\ui"
$VDApp.PreloadEnabled ="YES"
$website.siteconfig.VirtualApplications.Add($VDApp)
$website | Set-AzWebApp -Verbose
# Set API Virtual Directory (call /api )
$website = Get-AzWebApp -Name $appsvWebAppName -ResourceGroupName $resourceGroupName
$VDApp = New-Object Microsoft.Azure.Management.WebSites.Models.VirtualApplication
$VDApp.VirtualPath = "/api"
$VDApp.PhysicalPath = "site\wwwroot\api"
$VDApp.PreloadEnabled ="YES"
$website.siteconfig.VirtualApplications.Add($VDApp)
$website | Set-AzWebApp -Verbose
$website.SiteConfig.VirtualApplications
# Dotnet publish & convert to zip here, removed for brevity ...
$uiZipPath = $zipFilesFolder + "\ui.zip"
$publishprofile = Get-AzWebAppPublishingProfile -ResourceGroupName $resourceGroupName `
-Name $appsvWebAppName `
-OutputFile $publishProfileFileName
Publish-AzWebApp -ArchivePath $uiZipPath `
-ResourceGroupName $resourceGroupName `
-Name $appsvWebAppName
I can't see how to point Publish-AzWebApp at a virtual directory.
The publish can be done manually, but I really want to automate it (using Publish-AzWebApp or another means).
How can I do this please?
The Publish-AzWebApp does not support that, you could use Kudu API in powershell to automate it.
In my sample, it uses VFS to create the directory first, then upload the zip file via Zip.
$appsvWebAppName = "xxxxxxx"
$resourceGroupName = "xxxxxxx"
$resource = Invoke-AzResourceAction -ResourceGroupName $resourceGroupName -ResourceType Microsoft.Web/sites/config -ResourceName "$appsvWebAppName/publishingcredentials" -Action list -ApiVersion 2018-02-01 -Force
$username = $resource.Properties.publishingUserName
$password = $resource.Properties.publishingPassword
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password)))
$userAgent = "powershell/1.0"
# Create the folder, not lose `/` after `ui`
$apiUrl = "https://$appsvWebAppName.scm.azurewebsites.net/api/vfs/site/wwwroot/ui/"
Invoke-RestMethod -Uri $apiUrl -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -UserAgent $userAgent -Method PUT
#Upload the zip file
$apiUrl = "https://$appsvWebAppName.scm.azurewebsites.net/api/zip/site/wwwroot/ui"
$filePath = "C:\Users\joyw\Desktop\testdep.zip"
Invoke-RestMethod -Uri $apiUrl -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -UserAgent $userAgent -Method PUT -InFile $filePath -ContentType "multipart/form-data"
For the site\wwwroot\api, it is the same logic, just change ui to api in the script.

How to script External collaboration settings in Azure

Would like to be able to control two settings in Azure Active Directory user settings:
External collaboration settings > “Members can invite”
External collaboration settings > “Guests can invite”
As we already know, you can control just about everything in Azure with powershell, except these two things.
The internet, azure docs, and other resources, known to me, have been utilized to no real results.
Code: this is what we are looking to start.
Would like to say "Get-AzAADExternalCollaborationsSettings" then use the results to say "Set-AzAADExternalCollaborationsSettings".
AzAADUserSettings Picture
AFAIK, there is no built-in powershell command for the external collaboration settings, the two settings call the azure undisclosed api https://main.iam.ad.ext.azure.com/api/xxxx, the workaround I can just find is to invoke the api with powershell, here is a sample for you to refer, it calls a different api, but the logic should be similar. You can catch the requests of the two settings via fiddler and follow the sample to have a try.
Sample:http://www.lieben.nu/liebensraum/2018/04/how-to-grant-oauth2-permissions-to-an-azure-ad-application-using-powershell-unattended-silently/
Function Grant-OAuth2PermissionsToApp{
Param(
[Parameter(Mandatory=$true)]$Username, #global administrator username
[Parameter(Mandatory=$true)]$Password, #global administrator password
[Parameter(Mandatory=$true)]$azureAppId #application ID of the azure application you wish to admin-consent to
)
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($Username, $secpasswd)
$res = login-azurermaccount -Credential $mycreds
$context = Get-AzureRmContext
$tenantId = $context.Tenant.Id
$refreshToken = #($context.TokenCache.ReadItems() | Where-Object {$_.tenantId -eq $tenantId -and $_.ExpiresOn -gt (Get-Date)})[0].RefreshToken
$body = "grant_type=refresh_token&refresh_token=$($refreshToken)&resource=74658136-14ec-4630-ad9b-26e160ff0fc6"
$apiToken = Invoke-RestMethod "https://login.windows.net/$tenantId/oauth2/token" -Method POST -Body $body -ContentType 'application/x-www-form-urlencoded'
$header = #{
'Authorization' = 'Bearer ' + $apiToken.access_token
'X-Requested-With'= 'XMLHttpRequest'
'x-ms-client-request-id'= [guid]::NewGuid()
'x-ms-correlation-id' = [guid]::NewGuid()}
$url = "https://main.iam.ad.ext.azure.com/api/RegisteredApplications/$azureAppId/Consent?onBehalfOfAll=true"
Invoke-RestMethod –Uri $url –Headers $header –Method POST -ErrorAction Stop
}
Through monitoring the webbrowser network reuest i was able to get the correct API URL https://main.iam.ad.ext.azure.com/api/Directories/B2BDirectoryProperties
This should be a Powershell command. Hopfully Microsoft does't break this API.
Here are some snippets of what i am using:
# Get API Token
$mycreds = Get-Credential
if($tenantId){
$res = login-azurermaccount -Credential $mycreds -TenantId $tenantId.ToLower()
}else{
$res = login-azurermaccount -Credential $mycreds
}
$context = Get-AzureRmContext
$tenantId = $context.Tenant.Id
$refreshToken = $context.TokenCache.ReadItems().RefreshToken
$body = "grant_type=refresh_token&refresh_token=$($refreshToken)&resource=74658136-14ec-4630-ad9b-26e160ff0fc6"
$apiToken = Invoke-RestMethod "https://login.windows.net/$tenantId/oauth2/token" -Method POST -Body $body -ContentType 'application/x-www-form-urlencoded'
# Get current settings
$header = #{
'X-Requested-With'= 'XMLHttpRequest'
"Origin"="https://portal.azure.com"
'Authorization' = 'Bearer ' + $apiToken.access_token
'x-ms-client-request-id'= [guid]::NewGuid()
}
$url = "https://main.iam.ad.ext.azure.com/api/Directories/B2BDirectoryProperties"
Invoke-WebRequest -Uri $url -Headers $header -ContentType "application/json" -ErrorAction Stop
# Change settings
$settings = #{
allowInvitations = $true
limitedAccessCanAddExternalUsers = $false
restrictDirectoryAccess = $true
usersCanAddExternalUsers = $false
}
$body = $settings | ConvertTo-Json
$header = #{
'X-Requested-With'= 'XMLHttpRequest'
"Origin"="https://portal.azure.com"
'Authorization' = 'Bearer ' + $apiToken.access_token
'x-ms-client-request-id'= [guid]::NewGuid()
}
$url = "https://main.iam.ad.ext.azure.com/api/Directories/B2BDirectoryProperties"
Invoke-WebRequest -Uri $url -Method "PUT" -Headers $header -ContentType "application/json" -Body $body
Thnx for pointing me in the right direction Joy.

Forced Conversion from AzureRM to AZ powershell

We have found that our AzureRM scripts have started to fail with Request to a Error downlevel service failed. This has forced us to change our scripts to start using the AZ powershell module, https://learn.microsoft.com/en-us/powershell/azure/new-azureps-module-az?view=azps-1.6.0. The conversion has worked really well except I haven't found the replacement for New-AzureWebsiteJob. Has anyone else run into this?
For New-AzureWebsiteJob cmdlet, there is no direct equivalent in the Az or ARM PowerShell Cmdlets.
You can follow this blog to achieve your purpose, and note that if you are using Az powershell module, please modify ARM Powershell to Az powershell respectively.
Sample code for Az powershell like below:
#Resource details :
$resourceGroupName = "<Resourcegroup name>";
$webAppName = "<WebApp name>";
$Apiversion = 2015-08-01
#Function to get Publishing credentials for the WebApp :
function Get-PublishingProfileCredentials($resourceGroupName, $webAppName){
$resourceType = "Microsoft.Web/sites/config"
$resourceName = "$webAppName/publishingcredentials"
$publishingCredentials = Invoke-AzResourceAction -ResourceGroupName $resourceGroupName -ResourceType
$resourceType -ResourceName $resourceName -Action list -ApiVersion $Apiversion -Force
return $publishingCredentials
}
#Pulling authorization access token :
function Get-KuduApiAuthorisationHeaderValue($resourceGroupName, $webAppName){
$publishingCredentials = Get-PublishingProfileCredentials $resourceGroupName $webAppName
return ("Basic {0}" -f [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f
$publishingCredentials.Properties.PublishingUserName, $publishingCredentials.Properties.PublishingPassword))))
}
$accessToken = Get-KuduApiAuthorisationHeaderValue $resourceGroupName $webAppname
#Generating header to create and publish the Webjob :
$Header = #{
'Content-Disposition'='attachment; attachment; filename=Copy.zip'
'Authorization'=$accessToken
}
$apiUrl = "https://$webAppName.scm.azurewebsites.net/api/<Webjob-type>/<Webjob-name>"
$result = Invoke-RestMethod -Uri $apiUrl -Headers $Header -Method put -InFile "<Complete path of the file>\
<filename>.zip" -ContentType 'application/zip'

Resources