Unable to create storage account thru azure automation runbook - azure

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

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

ARM Template deployment returing a value that I dont expect

I am working on writing some Powershell that I am going to use in Azure DevOPS pipelines. This is to create an AppServiceplan. I have included the code below. I have used this same basic template to deploy a few other things and I have not run into this problem before.
This piece of the code $appSP = Get-AzAppServicePlan -Name $appServicePlanName -ResourceGroupName $rgname does not return a value, which is expected because this is the first time running it, yet its triggering this piece of code Write-verbose "AppService Plan '$appServicePlanName' already exists."
So it seems that even though the Get-AzAppServicePlan appears to be blank, maybe its returning some sort of object that I cant see?
Any ideas?
function Assert-AppServicePlan {
<#
.SYNOPSIS
This function will ensure that specified AppServicePlan exists.
.DESCRIPTION
Function will check if specified Azure AppServicePlan exists, and if not - it will be created.
Will return AppServicePLan object or, in case of error, $null.
.PARAMETER appServicePlanName
App Service Plan to be checked or created.
.PARAMETER rgName
Resource Group.
.PARAMETER SKU
SKU for App Service Plan. Default is P2V2.
.EXAMPLE
Assert-AppServicePlan -appServicePlansName "BARF" -rgName "MyResourceGroup" -SKU "F1" -verbose
#>
param(
[Parameter(Mandatory = $true)][ValidateNotNullorEmpty()][string]$appServicePlanName,
[Parameter(Mandatory = $true)][ValidateNotNullorEmpty()][string]$rgName,
[Parameter(Mandatory = $true)][ValidateNotNullorEmpty()][string]$SKU
);
$appSP = Get-AzAppServicePlan -Name $appServicePlanName -ResourceGroupName $rgname
if ($notPresent)
{
Write-Verbose "App Service Plan '$appServicePlanName' doesn't exist. Creating it."
try
{
$appSP = New-AzResourceGroupDeployment -ResourceGroupName `
$rgname -TemplateFile .\templates\appserviceplan.json `
-TemplateParameterFile .\templates\appserviceplan.parameters.json `
-ErrorAction Stop
}
catch
{
Write-verbose "Error while creating App Service Plan."
Write-Error $_
}
}
else
{
Write-verbose "AppService Plan '$appServicePlanName' already exists."
}
return $appSP
}
The Get-AzAppServicePlan cmdlet returns the App Service Plan object if found in the specified resource group, else nothing. So, it would be sufficient to check on this result in your if condition.
Another case where the result might mislead returning null is when you query under an incorrect PS context or a different Subscription (locally). However, since you intend to run this as part of Azure DevOps pipelines, the Service connection used by the task would ensure it.
Just another suggestion, you can use ErrorVariable
Get-AzAppServicePlan -Name $appServicePlanName -ResourceGroupName $rgname -ErrorAction Silentlycontinue -ErrorVariable notPresent
if ($notPresent)
{
#create something
}
else {
#exits
}

Passing multiple Parameters in single Azure Storage Script for various environments

I have a powershell script that creates the storage and blob account for a given subscription that works fine . Subscription Name, resource group keeps changing for different environments like DEV,UAT,PROD
STRUCTURE OF MY TEMPLATE / CODE :
param(
[string] $subscriptionName ="ABC",
[string] $resourceGroupName = "XYZ",
[string] $resourceGroupLocation ="westus",
[string] $templateFilePath = "template.json",
[string] $parametersFilePath = "parameters.json"
)
Function RegisterRP {
Param(
[string]$ResourceProviderNamespace
)
Write-Host "Registering resource provider '$ResourceProviderNamespace'";
Register-AzureRmResourceProvider -ProviderNamespace $ResourceProviderNamespace;
}
$ErrorActionPreference = "Stop"
$confirmExecution = Read-Host -Prompt "Hit Enter to continue."
if($confirmExecution -ne '') {
Write-Host "Script was stopped by user." -ForegroundColor Yellow
exit
}
# sign in
Write-Host "Logging in...";
Login-AzureRmAccount;
# select subscription
Write-Host "Selecting subscription '$subscriptionName'";
Select-AzureRmSubscription -SubscriptionName $subscriptionName;
# Register RPs
$resourceProviders = #("microsoft.storage");
if($resourceProviders.length) {
Write-Host "Registering resource providers"
foreach($resourceProvider in $resourceProviders) {
RegisterRP($resourceProvider);
}
}
#Create or check for existing resource group
$resourceGroup = Get-AzureRmResourceGroup -Name $resourceGroupName -ErrorAction SilentlyContinue
if(!$resourceGroup)
{
Write-Host "Resource group '$resourceGroupName' does not exist. To create a new resource group, please enter a location.";
if(!$resourceGroupLocation) {
$resourceGroupLocation = Read-Host "resourceGroupLocation";
}
Write-Host "Creating resource group '$resourceGroupName' in location '$resourceGroupLocation'";
New-AzureRmResourceGroup -Name $resourceGroupName -Location $resourceGroupLocation
}
else{
Write-Host "Using existing resource group '$resourceGroupName'";
}
# Start the deployment
Write-Host "Starting deployment...";
if(Test-Path $parametersFilePath) {
New-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -Name $deploymentName -TemplateFile $templateFilePath -TemplateParameterFile $parametersFilePath -storageAccounts_name $storageAccountName
} else {
New-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -Name $deploymentName -TemplateFile $templateFilePath; -storageAccounts_name $storageAccountName
}
Approach 1 :
Created multiple powershell scripts for each denvironment
Created 1 Menu Based powershell script that calls the other script and executes like : Select 1 for Dev , 2 for UAt , 3 for PROD , this approach works but is not effective .
Approach 2 :
I would like to combine all scripts and just have one script for all environments and based on select should allow me to create the storage accounts. Only Subscription and resource group change rest all structure of the powershell remains same .
I tried using GET function commandlets and it selects but still throws the error
[string] $subscriptionName = Get-AzureSubscription,
[string] $resourceGroupName = Get-AzureRmLocation,
If i try to use it using an array based approach like passing the values as below im unable to understand how do i pass these array based values to the code and get it to work .
$environment=#('DEV','TEST','QA','PROD')
$resourcegroupname = #('test','test1','test2','test3')
$subscriptionName = #('devsub1','devsub2','test3','prod4')
I'm trying to call the functions using :
$environment[0]
$subscriptionName[0]
It returns the value as below if i execute it seperately but how do i pass these values to my script to create storage account ?
DEV
devsub1
Requesting expert help if anyone has come across such scenarios earlier and if you can help in changing the above code and provide a tested code that would be of great help.
APPROACH 3:
$subscription = #(Get-AzureRmSubscription)
$resourcegroup = #(Get-AzureRmResourceGroup)
$Environment = #('DEV','TEST','QA','PROD')
$resourceGroupName = $resourcegroup | Out-GridView -PassThru -Title 'Pick the environment'
$subscriptionName = $subscription | Out-GridView -PassThru -Title 'Pick the subscription'
Write-Host "Subscription:" $subscriptionName
Write-Host "ResourceGroup:" $resourcegroup
OUTPUT :
If you look at resource group it fails to give the selection option for resource group .
Subscription: < it returns the subscription name >
ResourceGroup: Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels.PSResourceGroup Microsoft.Azure.Commands.ResourceManager.Cmd
lets.SdkModels.PSResourceGroup Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels.PSResourceGroup Microsoft.Azure.Commands.Res
ourceManager.Cmdlets.SdkModels.PSResourceGroup
What you are proposing is an interesting approach. I would likely an input parameter that defines which environment the work will be done in, and then have a conditional block that sets the dynamic variables for that environment. There would be some duplication of initialization code for each environment, but the main code block would still be unified.

Azure webhook get VM status

I'm trying to do a runbook/webhook that return a status of machine. What I finally notices is that
Get-AzureRmVM
is only returning 2 resource groups. Where
Get-AzureRmResource
Does return many more but not all of them again!
I'm sure about my Resource Group Name but still it says resource group 'groupName' could not be found. when I try to run with specific name
Get-AzureRmVM -ResourceGroupName groupName
While my other start and stop runbook works just fine, so i'm confused I can't see the difference between the groups.
PS: I'm using Azure Run As Connection
param
(
[Parameter (Mandatory = $false)]
[object] $WebhookData
)
if ($WebhookData) {
$vms = (ConvertFrom-Json -InputObject $WebhookData.RequestBody)
Write-Output "Authenticating to Azure with service principal and certificate"
$ConnectionAssetName = "AzureRunAsConnection"
Write-Output "Get connection asset: $ConnectionAssetName"
$Conn = Get-AutomationConnection -Name $ConnectionAssetName
if ($Conn -eq $null)
{
throw "Could not retrieve connection asset: $ConnectionAssetName. Check that this asset exists in the Automation account."
}
Write-Output "Authenticating to Azure with service principal."
Add-AzureRmAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint | Write-Output
# Start each virtual machine
foreach ($vm in $vms)
{
$vmName = $vm.Name
Write-Output "Checking $vmName"
$vmstatus = Get-AzureRmVM -Name $vm.Name -ResourceGroupName $vm.ResourceGroup -Status# | Select-Object -ExpandProperty StatusesText | ConvertFrom-Json
#select code index and convert to $vmpowerstate
$vmPowerState = $vmstatus#[1].Code
#Write-Output "Resource Group: $vmResourceGroupName", ("VM Name: " + $VM.Name), "Status: $VMStatusDetail" `n
Write-Output ("VM Name: " + $vmName), "Status: $vmPowerState" `n
}
}
else {
write-Error "This is webhook only."
}
Because your resource groups are in the different subscriptions.
As #et3rnal mentioned,
I have 2 subscriptions and Get-AzureRmVM returning 2 vms only because the rest are classics. The automation account I created this runbook at is the other one and I can see that in the overview? its the same one I use to start/stop machines in the other subscription!
Update:
If you want to get the PowerState of the VM, you could try the command below, in your case, just put it in the loop, the $PowerState is the PowerState.
$status = Get-AzureRmVM -Name <VM Name> -ResourceGroupName <Resource Group Name> -Status
$PowerState = ($status.Statuses | Where-Object {$_.Code -like "PowerState/*"}).DisplayStatus
Update2:
1.For the classic VM, we need to use azure ASM powershell module command, you could try Get-AzureVM, may be the Example 3: Display a table of virtual machine statuses in that link will help.
2.Another option is to migrate the classic VM(ASM) to ARM, then use the ARM command Get-AzureRmVM.
References:
Platform-supported migration of IaaS resources from classic to Azure Resource Manager
Migrate IaaS resources from classic to Azure Resource Manager by using Azure PowerShell

Copy-BlobFromAzureStorage

I'm trying to copy-Blob from azure storage for that i have taken a runbook from the Azure runbook gallery named "Copy-BlobFromAzureStorage". When i try to test, it prompt me for "PATHTOPLACEBLOB" here i have given the default location "c:/" . and its running fine.But the thing is I don't understand where exactly i can find the stored blob, and it is given " PSComputerName" as "localhost". Can any one please suggest me regarding this.
Code:
workflow Copy-BlobFromAzureStorage{
param
(
[parameter(Mandatory=$True)]
[String]
$AzureSubscriptionName,
[parameter(Mandatory=$True)]
[PSCredential]
$AzureOrgIdCredential,
[parameter(Mandatory=$True)]
[String]
$StorageAccountName,
[parameter(Mandatory=$True)]
[String]
$ContainerName,
[parameter(Mandatory=$True)]
[String]
$BlobName,
[parameter(Mandatory=$False)]
[String]
$PathToPlaceBlob = "C:\"
)
$Null = Add-AzureAccount -Credential $AzureOrgIdCredential
$Null = Select-AzureSubscription -SubscriptionName $AzureSubscriptionName
Write-Verbose "Downloading $BlobName from Azure Blob Storage to $PathToPlaceBlob"
Set-AzureSubscription `
-SubscriptionName $AzureSubscriptionName `
-CurrentStorageAccount $StorageAccountName
$blob =
Get-AzureStorageBlobContent `
-Blob $BlobName `
-Container $ContainerName `
-Destination $PathToPlaceBlob `
-Force
try {
Get-Item -Path "$PathToPlaceBlob\$BlobName" -ErrorAction Stop
}
catch {
Get-Item -Path $PathToPlaceBlob
}}
The blob is placed on the sandbox where the Azure Automation runbook is running. There's not much point in putting it there, since this sandbox will be cleaned up after the runbook job finishes, but it can make sense, depending on your scenario, as an intermediary point to put the blob, such as to edit it or transfer it to somewhere else outside of the sandbox (ex another Azure Storage account or an FTP server).

Resources