How to connect to PnPConnect then Get-PnPProvisioningTemplate in Azure Automations Runbook using MFA?

Rob at Notebook Publishing 1 Reputation point
2021-02-22T22:25:33.787+00:00

Hi All

I have been trying for over a week now to run the below command in a Automations Runbook. But I have hit brick walls with every attempt at authentications. Has anyone successfully managed to automate PnPProvisioningTemplate?

# Dynamic Parameters, will be passed from Flow
param(
  [parameter(Mandatory=$true)]
  [string]$SiteTemplateURL = "https://domain.sharepoint.com/sites/contosoportal",
  [parameter(Mandatory=$true)]
  [string]$ApplyTemplatetoURL = "https://domain.sharepoint.com/sites/contosositeportal"
)
# Credentials
$myCred = Get-AutomationPSCredential -Name "SPOAdminCred" 
# Connect to source site for creating the package or site template
Connect-PnPOnline -url $SiteTemplateURL -Credentials  $myCred
Get-PnPProvisioningTemplate -out template.pnp -Handlers PageContents -IncludeAllClientSidePages -PersistBrandingFiles
# Connect to destination site for applying the package or site template
Connect-PnPOnline -url $ApplyTemplatetoURL -Credentials  $myCred 
Apply-PnPProvisioningTemplate .\template.pnp

Attempts made so far

  1. https://pnp.github.io/powershell/articles/authentication.html?fbclid=IwAR2VEitB10520iTgy9kzQE3fs0AtduNvmVMm8AIoOFEx_stvCytRI1_tAjU#setting-up-access-to-your-own-azure-ad-app

Using code

Register-PnPAzureADApp -ApplicationName PnPRocks -Tenant mytenant.onmicrosoft.com -OutPath c:\mycertificates -DeviceLogin

Error
Can't up load the .pfx cert to Azure Automation Account. I get the Error "Specified network password not recognised" (copy and pasting password from txt file) then every attempt to upload after that "There was a error processing your request, please try again in a few moments"

  1. Using a RunAsAccount & Cert

Using code

Connect-PnPOnline -Url "https://contoso.sharepoint.com" -ClientId 6c5c98c7-e05a-4a0f-bcfa-0cfc65aa1f28 -Tenant 'contoso.onmicrosoft.com' -Thumbprint 34CFAA860E5FB8C44335A38A097C1E41EEA206AA

Error

Account has insufficient privileges to access the sites to Get and Apply provisioning template (401 error)

  1. Adding credentials using a service account (None MFA enabled).

using code

$myCred = Get-AutomationPSCredential -Name "SPOAdminCred" 

Error
Account has insufficient privileges to access the sites to Get and Apply provisioning template (401 error) But does work if I add the service account manually as the owner of both sites. (Defeating the automation, and means having a non MFA account in our tenant)

Any solutions welcome :)

Azure Automation
Azure Automation
An Azure service that is used to automate, configure, and install updates across hybrid environments.
1,172 questions
{count} votes