How to connect to Az.module without run as account in Azure Automation. I am trying to do with system assigned identity - azure

Below is the code :
$sub = Get-AzSubscription -ErrorAction SilentlyContinue
if(-not($sub))
{
Connect-AzAccount -Identity
}
$storageaccountname="stgacct"
$resourcegroupname="RSG1"
$acctKey= (Get-AzStorageAccountKey -ResourceGroupName $resourcegroupname -AccountName
$storageaccountname).Value[0]
it throws an error :
Run Connect-AzAccount to login.
Environments
{[AzureChinaCloud, AzureChinaCloud], [AzureCloud, AzureCloud], [AzureGermanCloud,
AzureGermanCloud], [AzureUSGovernme...
'this.Client.SubscriptionId' cannot be null.
System.Management.Automation.RuntimeException: Cannot index into a null array.
at CallSite.Target(Closure , CallSite , Object , Int32 )
at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1
arg1)
at System.Management.Automation.Interpreter.DynamicInstruction`3.Run(InterpretedFrame frame)
at
System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame
frame)

Get-AzSubscription also requires you to be logged in. This is why you are getting the error, but your code is still running through successfully to retrieve the key. See my output below and I wrote a line to print out the storage key(which it did).
What you can try is complete omit the getting of subscription like below.
Connect-AzAccount -Identity
$storageaccountname="anustorage1980"
$resourcegroupname="testRG"
$acctKey= (Get-AzStorageAccountKey -ResourceGroupName $resourcegroupname -AccountName $storageaccountname).Value[0]
Or put the Get-AzSubscription after the Connect-AzAccount -Identity

Related

Why are write-host statements are not appearing when calling a script with an azure commandlet in it?

I have a very simplistic 2 scripts and I'm trying to call the powershell script from another powershell run script
run script (run.ps1)
.\NewRG.ps1 -rgName "singleVM12" -location "Canada Central" -tags #{dept="Marketing"}
called script (newRG.ps1)
[CmdletBinding()]
param (
[string]$rgName = "Test1-rg",
[string]$location = "Canada Central",
[Parameter(Mandatory)]
[hashtable]$tags)
$newRG = New-AzResourceGroup -name $rgName -location $location -tags #{dept="marketing"}
write-output "test"
I would expect that I should get test in the console but I get the properties of the Resource group
ResourceGroupName : singleVM12
Location : canadacentral
ProvisioningState : Succeeded
The issue is I have more complex scripts with multiple write-host entries that I want shown but none of it appears when I run the "run.ps1" file, it works fine if I just call the called script by itself. I tried using write-output and same thing happens. I noticed that hello world works, so I'm guessing something about the Azure commandlets are maybe causing this. Any way around this?
I am using Write-Output to print the values in prompt. I have followed the same way you did.
Follow the workaround:
testout.ps1
# I am getting resource information
[CmdletBinding()]
param (
[string]$rgName = "test")
#$newRG = New-AzResourceGroup -name $rgName -location $location -tags #{dept="marketing"}
$getResource = Get-AzResource -ResourceGroupName $rgName
write-output "azure resoure get successfully- " $rgName
$getResource = Get-AzResource -ResourceGroupName $rgName
write-output "test2- " $rgName
$getResource = Get-AzResource -ResourceGroupName $rgName
write-output "test3 - " $rgName
$getResource = Get-AzResource
write-output "test4- " $rgName
# you can use return to send the the required data to promt as well. But you can use end of your script otherwise it will skip after the return statement.
return $getResource.ResourceGroupName
test2.ps1
Calling testout.ps1 in test2.ps1 script.
# Connect Azure Account using specific Subscription Id if you are using more subscription in single account
Connect-AzAccount -SubscriptionId '<Your subscription Id>'
# calling test.ps1 script
.\testout.ps1 -rgName "<Your Resourcegroup Name>"
Result

Creating Azure AD user from Azure Runbook

I'm trying to use an Azure Automation account + accompanying powershell runbook to automate the process of creating an Azure Active Directory user.
When I run the following command, I'm presented with the error, am I trying to achieve the impossible here or is there an easy fix to this problem:
System.Management.Automation.ParameterBindingException: A parameter cannot be found that matches parameter name 'Surname'.
at System.Management.Automation.CmdletParameterBinderController.VerifyArgumentsProcessed(ParameterBindingException originalBindingException)
at System.Management.Automation.CmdletParameterBinderController.BindCommandLineParametersNoValidation(Collection`1 arguments)
at System.Management.Automation.CmdletParameterBinderController.BindCommandLineParameters(Collection`1 arguments)
at System.Management.Automation.CommandProcessor.BindCommandLineParameters()
at System.Management.Automation.CommandProcessorBase.DoPrepare(IDictionary psDefaultParameterValues)
at System.Management.Automation.Internal.PipelineProcessor.Start(Boolean incomingStream)
at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input)
at System.Management.Automation.PipelineOps.InvokePipeline(Object input, Boolean ignoreInput, CommandParameterInternal[][] pipeElements, CommandBaseAst[] pipeElementAsts, CommandRedirection[][] commandRedirections, FunctionContext funcContext)
at System.Management.Automation.Interpreter.ActionCallInstruction`6.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
My runbook has the following script:
Param
(
[parameter(Mandatory=$true)]
[string] $firstname,
[parameter(Mandatory=$true)]
[string] $lastname,
[parameter(Mandatory=$true)]
[string] $city,
[parameter(Mandatory=$true)]
[string] $phone,
[parameter(Mandatory=$true)]
[string] $pw,
[string]$method,
[string]$UAMI
)
$displayname = $firstname + " " + $lastname
$upn = "$firstname.$lastname" + "#aguafriawindowslive.onmicrosoft.com"
#Secret Password
$secureStrPassword = ConvertTo-SecureString -String $pw -AsPlainText -Force
$automationAccount = "automationaccount01"
# Ensures you do not inherit an AzContext in your runbook
Disable-AzContextAutosave -Scope Process | Out-Null
# Connect using a Managed Service Identity
try {
$AzureContext = (Connect-AzAccount -Identity).context
}
catch{
Write-Output "There is no system-assigned user identity. Aborting.";
exit
}
# set and store context
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription `
-DefaultProfile $AzureContext
if ($method -eq "SA")
{
Write-Output "Using system-assigned managed identity"
}
elseif ($method -eq "UA")
{
Write-Output "Using user-assigned managed identity"
# Connects using the Managed Service Identity of the named user-assigned managed identity
$identity = Get-AzUserAssignedIdentity -ResourceGroupName $resourceGroup `
-Name $UAMI -DefaultProfile $AzureContext
# validates assignment only, not perms
if ((Get-AzAutomationAccount -ResourceGroupName $resourceGroup `
-Name $automationAccount `
-DefaultProfile $AzureContext).Identity.UserAssignedIdentities.Values.PrincipalId.Contains($identity.PrincipalId))
{
$AzureContext = (Connect-AzAccount -Identity -AccountId $identity.ClientId).context
# set and store context
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext
}
else {
Write-Output "Invalid or unassigned user-assigned managed identity"
exit
}
}
else {
Write-Output "Invalid method. Choose UA or SA."
exit
}
#Create User
New-AzADUser -DisplayName $displayname -UserPrincipalName $upn -Surname $lastname -City $city -Password $secureStrPassword -MailNickname $firstname -ForceChangePasswordNextLogin
Insufficient privileges error occurs when you have missed giving role required to do operation on the resources.Ensure that your runbook account has permissions to access any resources used in your script.
Try this:
Go to Azure portal --> Azure AD --> roles and Administrator-->Directory Readers role --> assign this role to the your runbook account name.
or
Try to add the application permissions > Directory.Read.All in for the azure ad App of your automation run as account and also Directory.ReadWrite.All if required and grant admin consent to it.

is there a way of automating $credential = Get-Credential when running Set-AzVMADDomainExtension

I need to automate domain join in a pipleine for Azure vm , Im using this code, however I dont want the user to enter the credential during runtime, how can i use a saved credential?
$DomainName = "abc.com"
$VMName = "VMNAME01"
$credential = Get-Credential
$ResourceGroupName = "RG01"
Set-AzVMADDomainExtension -DomainName $DomainName -VMName $VMName -Credential $credential -ResourceGroupName $ResourceGroupName -JoinOption 0x00000001 -Restart -Verbose

VM has reported a failure when processing extension AzureDiskEncryption

I am running the following script:
$keyVault = Get-AzKeyVault -VaultName $keyVaultName -ResourceGroupName $rgName;
$diskEncryptionKeyVaultUrl = $keyVault.VaultUri;
$keyVaultResourceId = $keyVault.ResourceId;
$keyEncryptionKeyUrl = (Get-AzureKeyVaultKey -VaultName $keyVaultName -Name myKey).Key.kid;
Set-AzVMDiskEncryptionExtension -ResourceGroupName $rgName `
-VMName "myVM" `
-DiskEncryptionKeyVaultUrl $diskEncryptionKeyVaultUrl `
-DiskEncryptionKeyVaultId $keyVaultResourceId `
-KeyEncryptionKeyUrl $keyEncryptionKeyUrl `
-KeyEncryptionKeyVaultId $keyVaultResourceId
which is returning the following around 1 minutes of processing:
Set-AzureRmVmDiskEncryptionExtension : Long running operation failed
with status 'Failed'. Additional Info:'VM has reported a failure when
processing extension 'AzureDiskEncryption'. Error message: "Failed to
send DiskEncryptionData, Check KeyVault inputs, ResourceIds and retry
encryption operation".' ErrorCode: VMExtensionProvisioningError
ErrorMessage: VM has reported a failure when processing extension
'AzureDiskEncryption'. Error message: "Failed to send
DiskEncryptionData, Check KeyVault inputs, ResourceIds and retry
encryption operation". ErrorTarget: StartTime: 3/2/19 2:10:59 PM
EndTime: 3/2/19 2:10:59 PM
i have verified the values are all correctly passed to the set command and no nulls are being passed.
in this case OP needed to enable Key Vault for disk encryption, under advanced access policies.
I had this issue but banging my head for days the below steps fixed my issue.
Check the values of the $KeyVault, $DiskEncryptionKeyVaultUrl, and $KeyVaultResourceId
variables and make sure they are not null or empty.
If step 1 is completed, check the Key Vault creation process thoroughly, and
check if it is in the same region as the VM and that it has been enabled
for disk encryption:Set-AzureRmKeyVaultAccessPolicy -VaultName $keyVaultName -
EnabledForDiskEncryption
If you are still facing the issue, you can try this:
Go to the disk of a VM that needs to be encrypted.
Click Identity
Turn Status to "ON" for a system or user assigned.
Then execute below commands.
It is available with explanation on https://learn.microsoft.com/en-us/azure/virtual-machines/windows/encrypt-disks
$keyVault = Get-AzKeyVault -VaultName $keyVaultName -ResourceGroupName $rgName;
$diskEncryptionKeyVaultUrl = $keyVault.VaultUri;
$keyVaultResourceId = $keyVault.ResourceId;
$keyEncryptionKeyUrl = (Get-AzKeyVaultKey -VaultName $keyVaultName -Name myKey).Key.kid;
Set-AzVMDiskEncryptionExtension -ResourceGroupName $rgName `
-VMName "myVM"
-DiskEncryptionKeyVaultUrl $diskEncryptionKeyVaultUrl `
-DiskEncryptionKeyVaultId $keyVaultResourceId `
-KeyEncryptionKeyUrl $keyEncryptionKeyUrl `
-KeyEncryptionKeyVaultId $keyVaultResourceId$

Unable to create storage account thru azure automation runbook

I am trying hands on on azure automation runbook, below is the small script i am using to create a storage account.
Param
(
[Parameter(Mandatory=$true)]
[String]
$AzureResourceGroup,
[Parameter(Mandatory=$true)]
[String]
$StorageAC,
[Parameter(Mandatory=$true)]
[String]
$Loc,
[Parameter(Mandatory=$true)]
[String]
$sku
)
$CredentialAssetName = "AutomationAccount";
$Cred = Get-AutomationPSCredential -Name $CredentialAssetName
if(!$Cred) {
Throw "Could not find an Automation Credential Asset named
'${CredentialAssetName}'. Make sure you have created one in this Automation
Account."
}
Add-AzureRmAccount -Credential $Cred
Add-AzureAccount -Credential $Cred
$storeac = Get-AzureRmStorageAccount -ResourceGroupName $AzureResourceGroup
if ($storeac.StorageAccountName -eq "testdd" ){
write-output " AC found !";
} else {
New-AzureRmStorageAccount -ResourceGroupName $AzureResourceGroup -Name
$StorageAC -Location $Loc -SkuName $sku
}
However, when ever i run it after publishing, the job is completed with an error
(New-AzureRmStorageAccount : A parameter cannot be found that matches parameter name 'SkuName')
Can someone tell me what am i doing wrong ??
To resolve the error :
New-AzureRmStorageAccount : A parameter cannot be found that matches parameter name 'SkuName'
Please update the Azure modules in you automation account and by clicking : "Update Azure Modules" under Automation Accounts => Modules and retry the runbook
Update Azure Modules

Resources