Create Incremental Azure Storage Accounts on every run - azure-devops

Looking for a script to autogenerate a new storage account
with a prefix dev something like dev01.... and when i rerun the template should increment as dev02.. on second run and so on.
I tried giving the parameters / using default templates in github.
Issue is if i pass on a value under the value the system deploys it fine ,if i give the same name it would rerun and update the existing storage.
Instead i would like it to check if storage account exists and if not create a new account , please advise any pointers if any
Sample Parameters.Json file im using :
"parameters": {
"storageAccountName": {
"value": "dev01"
},

I recommand that you could use the Azure powershell script to customize your logic to do that.
The following is the demo code:
$resourceGroup = "rgName"
$storageAccount = "accountName"
$location = "Central US"
$SkuName = "Standard_LRS"
$kind = "StorageV2"
$i = 0;
while(1)
{
$storage = Get-AzureRmStorageAccount -ResourceGroupName $resourceGroup -Name $storageAccount
if($storage -ne $null)
{
$i++
$storageAccount = $storage.StorageAccountName + $i
$storage = New-AzureRmStorageAccount -ResourceGroupName $resourceGroup -Name $storageAccount -SkuName $SkuName -Location $location -Kind $kind
}
else
{
$storage = New-AzureRmStorageAccount -ResourceGroupName $resourceGroup -Name $storageAccount -SkuName $SkuName -Location $location -Kind $kind
$storageAccount = $storageAccount +$i;
}
if ($storage -ne $null)
{
break;
}
}
Task:

Related

Getting error when trying to set Azure Event Hub capture settings with PowerShell Set-AzEventHub cmdlet

I am trying to use PowerShell to set up an Event Hub with Capture set. However, I am experiencing problems when trying specify the capture settings with Set-AzEventHub. I have the following script commands:
$ehResourceGroup = 'kv-audit-resource'
$location = 'eastus'
$ehNameSpace = 'kv-audit-eh'
$ehName = 'security-logs'
$partitions = 1
$week = 7
# Creat resource group for hub
New-AzResourceGroup -Name $ehResourceGroup -Location $location
# Create namespace for hub
New-AzEventHubNamespace -ResourceGroupName $ehResourceGroup -NamespaceName $ehNameSpace -Location $location
# Make the hub
New-AzEventHub -ResourceGroupName $ehResourceGroup -NamespaceName $ehNameSpace -Name $ehName -PartitionCount $partitions -MessageRetentionInDays $week
# Get hub info
$loggingEventHub = Get-AzEventHub -ResourceGroupName $ehResourceGroup -NamespaceName $ehNameSpace -Name $ehName
# Add capture info
$loggingEventHub.CaptureDescription = New-Object -TypeName Microsoft.Azure.Commands.EventHub.Models.PSCaptureDescriptionAttributes
$loggingEventHub.CaptureDescription.Enabled = $true
$loggingEventHub.CaptureDescription.IntervalInSeconds = 60
$loggingEventHub.CaptureDescription.Encoding = "Avro"
$loggingEventHub.CaptureDescription.SizeLimitInBytes = 10485763
$loggingEventHub.CaptureDescription.Destination.Name = "EventHubArchive.AzureBlockBlob"
$loggingEventHub.CaptureDescription.Destination.BlobContainer = "cyberstorageaccount2"
$loggingEventHub.CaptureDescription.Destination.ArchiveNameFormat = "{Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}"
$loggingEventHub.CaptureDescription.Destination.StorageAccountResourceId = "/subscriptions/{SubscriptionId}/resourceGroups/$ehResourceGroup/providers/Microsoft.ClassicStorage/cyberstorageaccount2"
# Now update the hub with capture info
Set-AzEventHub -ResourceGroupName $ehResourceGroup -Namespace $ehNameSpace -Name $ehName -InputObject $loggingEventHub
I execute the first three commands to create the Event Hub without problems. The storage account, cyberstorageaccount2, already exists. I wait until the Azure dashboard shows that the Event Hub is successfully made and active, which takes several minutes. When I execute the last two commands to modify the capture settings, I get:
PS C:\> $loggingEventHub = Get-AzEventHub -ResourceGroupName $ehResourceGroup -NamespaceName $ehNameSpace -Name $ehName
>> $loggingEventHub.CaptureDescription = New-Object -TypeName Microsoft.Azure.Commands.EventHub.Models.PSCaptureDescriptionAttributes
>> $loggingEventHub.CaptureDescription.Enabled = $true
>> $loggingEventHub.CaptureDescription.IntervalInSeconds = 60
>> $loggingEventHub.CaptureDescription.Encoding = "Avro"
>> $loggingEventHub.CaptureDescription.SizeLimitInBytes = 10485763
>> $loggingEventHub.CaptureDescription.Destination.Name = "EventHubArchive.AzureBlockBlob"
>> $loggingEventHub.CaptureDescription.Destination.BlobContainer = "cyberstorageaccount2"
>> $loggingEventHub.CaptureDescription.Destination.ArchiveNameFormat = "{Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}"
>> $loggingEventHub.CaptureDescription.Destination.StorageAccountResourceId = "/subscriptions/{SubscriptionId}/resourceGroups/$ehResourceGroup/providers/Microsoft.ClassicStorage/cyberstorageaccount2"
>> Set-AzEventHub -ResourceGroupName $ehResourceGroup -Namespace $ehNameSpace -Name $ehName -InputObject $loggingEventHub
Set-AzEventHub : Operation returned an invalid status code 'BadRequest'
At line:11 char:1
+ Set-AzEventHub -ResourceGroupName $ehResourceGroup -Namespace $ehName ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (Microsoft.Azure...ExecuteCmdlet():ErrorResponseException) [Set-AzEventHub],
ErrorResponseException
+ FullyQualifiedErrorId : SubCode=40000. StorageAccountResourceId. TrackingId:ea7e4590-486a-4597-9351-b5e8508857b8
_M6CH3_M6CH3_G28, SystemTracker:kv-audit-eh.servicebus.windows.net:security-logs, Timestamp:2020-12-08T12:37:56 Co
rrelationId: 4b1edeed-6585-47f0-b14e-476614404a23,Microsoft.Azure.Commands.EventHub.Commands.EventHub.SetAzureEven
tHub
What am I doing wrong? It looks like it's griping about the storage account, but when I display the contents of $loggingEventHub.CaptureDescription.Destination.StorageAccountResourceId, the path appears correct.
Thanks in advance for any info.
Storage resource-id seems malformed. It is missing 'storageaccounts' segment.
"/subscriptions/{SubscriptionId}/resourceGroups/$ehResourceGroup/providers/Microsoft.ClassicStorage/storageAccounts/cyberstorageaccount2"
I got this to work. My code was based on an example provided by Microsoft, but their example assumed you had set up a lot of things previously. What follows is my PowerShell code that fills in some of the gaps in their example. The code is commented (slightly) and has debug output that you can delete. It assumes that you have already made an Event Hub with the prerequisite resource group and namespace.
$ehResourceGroup = 'kv-audit-resource'
$location = 'eastus'
$ehNameSpace = 'kv-audit-eh'
$ehName = 'security-logs'
$partitions = 1
$week = 7
$kvStorageAccount = 'cybersecurityaccount2'
$kvContainer = 'security-container'
# Create the storage account for the Event Hub
Write-Output("Create storage account $kvStorageAccount")
$storageAcct = New-AzStorageAccount -ResourceGroupName $ehResourceGroup -AccountName $kvStorageAccount -Location $location -SkuName Standard_GRS -Kind BlobStorage -AccessTier Cool
# Get the "context" required for the container
$accountContext = $storageAcct.Context
# Create a container for the storage account
Write-Output("Create storage account container $kvContainer")
New-AzStorageContainer -Name $kvContainer -Context $accountContext -Permission 'Container'
# Get the storage account ID for the Event Hub
Write-Output("Get ID of storage account $kvStorageAccount")
$kvStorageAccountId = (Get-AzStorageAccount -ResourceGroupName $ehResourceGroup -Name $kvStorageAccount).Id
# Get Event Hub object
Write-Output("Get Event Hub object")
$loggingEventHub = Get-AzEventHub -ResourceGroupName $ehResourceGroup -Namespace $ehNameSpace -Name $ehName
# Update Event Hub capture description
Write-Output("Update Event Hub object")
$loggingEventHub.CaptureDescription = New-Object -TypeName Microsoft.Azure.Commands.EventHub.Models.PSCaptureDescriptionAttributes
$loggingEventHub.CaptureDescription.Enabled = $true
$loggingEventHub.CaptureDescription.IntervalInSeconds = 60
$loggingEventHub.CaptureDescription.Encoding = "Avro"
$loggingEventHub.CaptureDescription.SizeLimitInBytes = 10485763
$loggingEventHub.CaptureDescription.Destination.Name = "EventHubArchive.AzureBlockBlob"
$loggingEventHub.CaptureDescription.Destination.BlobContainer = $kvContainer
$loggingEventHub.CaptureDescription.Destination.ArchiveNameFormat = "{Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}"
$loggingEventHub.CaptureDescription.Destination.StorageAccountResourceId = $kvStorageAccountId
Set-AzEventHub -ResourceGroupName $ehResourceGroup -Namespace $ehNameSpace -Name $ehName -InputObject $loggingEventHub
Write-Output($loggingEventHub)

Why would Test-AzureName always return false?

Running this script in Azure:
Write-Host "Running ps_example.ps1"
$resourceGroupName = 'myGroupName'
$storageName = "psexample"
$storageType = "Standard_LRS"
$location = "centralus"
if (Test-AzureName -Storage $storageName) {
Write-Host "Use existing storage account - $storageName"
} Else {
Write-Host "Make new storage account - $storageName"
New-AzureRmStorageAccount -ResourceGroupName $resourceGroupName -Name $storageName -Type $storageType -Location $location
}
The first run shows:
Running ps_example.ps1
Make new storage account - psexample
The second run shows:
Running ps_example.ps1
Make new storage account - psexample
The storage account named psexample is already taken.
Why? That would seem to indicate that if (Test-AzureName -Storage $storageName) always returns false.
If I tell Azure to use powershell 1, the version is 1.113.5. Requesting version 2.0 results in 2.0.11. The behavior is the same for both.
EDIT:
Running this:
$result = Test-AzureName -Storage $storageName
Write-Host $result
always prints False, whether psexample exists or not.
You are combining RM and SM cmdlets in Azure. Test-AzureName is a Service Management cmdlet, while New-AzureRmStorageAccount is a Resource Manager cmdlet.
You may want to try to use
if ((Get-AzureRmStorageAccountNameAvailability -Name $storageName).NameAvailable) {
Write-Host "Make new storage account - $storageName"
New-AzureRmStorageAccount -ResourceGroupName $resourceGroupName -Name $storageName -Type $storageType -Location $location
} Else {
Write-Host "Use existing storage account - $storageName"
}
to check for the name or you can create your storage account with:
New-AzureStorageAccount
Depending on what you want to use, SM or RM.

Add a Azure WebApp to an Existing VPN using a Point-to-Site connection (RM Powershell)

I have hunted around for an answer to this, but I am not having much luck. All the articles I can find are either setting up a Point-to-Site or are instructions for classic Azure, not Azure 2.0 (Resource Group)
Currently, we are dialing up a whole new resource group everytime we do a new built. This consists of Web apps and SQL DBs. When we have a new build we start up the new and del the old resource group. Simple. To minimize the start-up time we have a static resource group that isn't deleted that houses the VPN connection to our on Prem resources.
The problem I'm having is when I add the new websites using AzureRM Powershell cmd's to the Point-to-site it says it's successful. The Azure Portal says its good but it does let me communicate. If I remove and add it from one of the 8 WebApps they all start working.
I am out of ideas. Any help would be greatly appreciated.
Azure VPN
Below is the function I have put togeather from what I can find out there.
function AddExistingVnet{
param(
[string] $subscriptionId,
[string] $resourceGroupName,
[string] $webAppName
)
$Vnet = Get-AzureRmVirtualNetwork | Where-Object {$_.ResourceGroupName -like "*Static*"}
IF($Vnet.Name.count -gt 1) {write-host 'Two or networks have been returned. Unable to continue ' return}
$gatewaySubnet = $vnet.Subnets | Where-Object { $_.Name -eq "GatewaySubnet" }
$vnetName = $vnet.Name
$uriParts = $gatewaySubnet.IpConfigurations[0].Id.Split('/')
$gatewayResourceGroup = $uriParts[4]
$gatewayName = $uriParts[8]
$gateway = Get-AzureRmVirtualNetworkGateway -ResourceGroupName $vnet.ResourceGroupName -Name $gatewayName
Write-Host "Creating App association to VNET"
$propertiesObject = #{
"vnetResourceId" = "/subscriptions/$($subscriptionId)/resourceGroups/$($vnet.ResourceGroupName)/providers/Microsoft.Network/virtualNetworks/$($vnetName)"
}
$virtualNetwork = New-AzureRmResource -Location $location -Properties $PropertiesObject -ResourceName "$($webAppName)/$($vnet.Name)" -ResourceType "Microsoft.Web/sites/virtualNetworkConnections" -ApiVersion 2015-08-01 -ResourceGroupName $resourceGroupName -Force
# Now finish joining by getting the VPN package and giving it to the App
Write-Host "Retrieving VPN Package and supplying to App"
$packageUri = Get-AzureRmVpnClientPackage -ResourceGroupName $vnet.ResourceGroupName -VirtualNetworkGatewayName $gateway.Name -ProcessorArchitecture Amd64
# Put the VPN client configuration package onto the App
$PropertiesObject = #{
"vnetName" = $vnet.Name; "vpnPackageUri" = $packageUri
}
New-AzureRmResource -Location $location -Properties $PropertiesObject -ResourceName "$($webAppName)/$($vnet.Name)/primary" -ResourceType "Microsoft.Web/sites/virtualNetworkConnections/gateways" -ApiVersion 2015-08-01 -ResourceGroupName $resourceGroupName -WarningAction silentlyContinue -Force
}
So after 2 weeks of going back and forth with Microsoft (had a really good guy Charles) we managed to find the problem.
When requesting
$packageUri = Get-AzureRmVpnClientPackage -ResourceGroupName $vnet.ResourceGroupName -VirtualNetworkGatewayName $gateway.Name -ProcessorArchitecture Amd64
It was giving me an output of:
"https://mdsbrketwprodsn1prod.blob.core.windows.net/cmakexe/xxx~xxx/amd64/xxxx~xxxx&sp=r&fileExtension=.exe"
For some reason (that Microsoft could explain) why it kept adding in " to the beginning and end of the variable.
I find it odd that it lets the script work with " and allows the WebApps to join to the VPN.
Any why here is the fix which basicly removes the " from the begining and end of $packageUri :
$packageUri = $packageUri.ToString();
$packageUri = $packageUri.Substring(1, $packageUri.Length-2);
So hope that helps someone else out there who is banging there head agaist the same problem.
Here is the complete function if any one is intrested:
function AddExistingVnet{
param(
[string] $subscriptionId,
[string] $resourceGroupName,
[string] $webAppName
)
$Vnet = Get-AzureRmVirtualNetwork | Where-Object {$_.ResourceGroupName -like "*Static*"}
IF($Vnet.Name.count -gt 1) {write-host 'Two or networks have been returned. Unable to continue ' return}
$gatewaySubnet = $vnet.Subnets | Where-Object { $_.Name -eq "GatewaySubnet" }
$vnetName = $vnet.Name
$uriParts = $gatewaySubnet.IpConfigurations[0].Id.Split('/')
$gatewayResourceGroup = $uriParts[4]
$gatewayName = $uriParts[8]
$gateway = Get-AzureRmVirtualNetworkGateway -ResourceGroupName $vnet.ResourceGroupName -Name $gatewayName
$webApp = Get-AzureRmResource -ResourceName $webAppName -ResourceType "Microsoft.Web/sites" -ApiVersion 2015-08-01 -ResourceGroupName $resourceGroupName
$location = $webApp.Location
Write-Host "Creating App association to VNET"
$propertiesObject = #{
"vnetResourceId" = "/subscriptions/$($subscriptionId)/resourceGroups/$($vnet.ResourceGroupName)/providers/Microsoft.Network/virtualNetworks/$($vnetName)"
}
$virtualNetwork = New-AzureRmResource -Location $location -Properties $PropertiesObject -ResourceName "$($webAppName)/$($vnet.Name)" -ResourceType "Microsoft.Web/sites/virtualNetworkConnections" -ApiVersion 2015-08-01 -ResourceGroupName $resourceGroupName -Force
# Now finish joining by getting the VPN package and giving it to the App
Write-Host "Retrieving VPN Package and supplying to App"
$packageUri = Get-AzureRmVpnClientPackage -ResourceGroupName $vnet.ResourceGroupName -VirtualNetworkGatewayName $gateway.Name -ProcessorArchitecture Amd64
$packageUri = $packageUri.ToString();
$packageUri = $packageUri.Substring(1, $packageUri.Length-2);
# Put the VPN client configuration package onto the App
$PropertiesObject = #{
"vnetName" = $vnet.Name; "vpnPackageUri" = $packageUri.ToString()
}
$date = Get-Date -format "HH:mm tt"
New-AzureRmResource -Location $location -Properties $PropertiesObject -ResourceName "$($webAppName)/$($vnet.Name)/primary" -ResourceType "Microsoft.Web/sites/virtualNetworkConnections/gateways" -ApiVersion 2015-08-01 -ResourceGroupName $resourceGroupName -WarningAction silentlyContinue -Force
}
Enjoy

Create Azure website with Standard pricing tier via Powershell

I'm trying to fix my continious deployment scenario and for this to work an Azure website has to exist and be able to swap between the Staging and Production. We want this website to work in the Standard pricing tier.
The script I have at the moment creates a new ResourceGroup, Hosting Plan and after these are created, the website itself. The problem I'm facing is the website is always in Free mode. I should be able to fix this by using the Set-AzureResource cmdlet, but this one is throwing an message telling me I should specify the Location. Problem with this is this specific cmdlet doesn't has a Location parameter.
Set-AzureResource : {
"Error": {
"Code": "LocationRequired",
"Message": "The location property is required for this definition.",
"Target": null,
"Details": null
}
}
This is the (simplified) script I'm using to create all of the resources:
#Create the resource group
New-AzureResourceGroup -Location $location -Name $resourceGroupName -Force
#Create the hosting plan
$hostingPlanParameters = #{"name" = $hostingPlanName; "sku" = "Standard"; "computeMode" = "Standard"; "workerSize" = "0"; "numberOfWorkers" = "1"}
New-AzureResource -ApiVersion 2014-04-01 -Name $hostingPlanName -ResourceGroupName $resourceGroupName `
-ResourceType Microsoft.Web/serverFarms -Location $location `
-PropertyObject $hostingPlanParameters -Verbose -Force
#Create the website
$analyticsSite = #{"sku" = "Standard"; "webHostingPlan" = $hostingplan; "computeMode" = "Standard"; }
New-AzureResource -Name $label -ResourceType Microsoft.Web/sites `
-ResourceGroupName $resourceGroupName -Location $location `
-ApiVersion $apiVersion -PropertyObject $analyticsSite -Force
Set-AzureResource -Name $label -ResourceType Microsoft.Web/sites `
-ResourceGroupName $resourceGroupName -ApiVersion $apiVersion `
-PropertyObject $analyticsSite -Force
I've read the website should inherit the sku of the specified hosting plan, so I should not need to update it. This does not appear to work for my above script. The hosting plan is specified, but the settings aren't inheritted.
The created hosting plan properties look like this:
PropertiesText : {
"name": "devHostingPlanWestEU10",
"sku": "Standard",
"workerSize": 0,
"workerSizeId": 0,
"numberOfWorkers": 1,
"currentWorkerSize": 0,
"currentWorkerSizeId": 0,
"currentNumberOfWorkers": 1,
"status": 0,
"webSpace": "ResourceGroupWestEU10-WestEuropewebspace",
"subscription": "ad7add9b-8b7a-45df-8e95-0e7fccbr78a5",
"adminSiteName": null,
"hostingEnvironment": null,
"maximumNumberOfWorkers": 0,
"planName": null,
"perSiteScaling": null,
"hostingEnvironmentId": null
}
This looks kind of ok to me.
Once the website is created, these properties are printed:
PropertiesText : {
"name": "Testert10",
"state": "Running",
"hostNames": [
"testert10.azurewebsites.net"
],
"webSpace": "ResourceGroupWestEU10-WestEuropewebspace",
...
"repositorySiteName": "Testert10",
"owner": null,
"usageState": 0,
"enabled": true,
...
"computeMode": null,
"serverFarm": "Default1",
"serverFarmId": null,
"lastModifiedTimeUtc": "2015-05-21T11:52:30.773",
"storageRecoveryDefaultState": "Running",
"contentAvailabilityState": 0,
"runtimeAvailabilityState": 0,
"siteConfig": null,
"deploymentId": "Testert10",
"trafficManagerHostNames": null,
"sku": "Free",
"premiumAppDeployed": null,
"scmSiteAlsoStopped": false,
"targetSwapSlot": null,
"hostingEnvironment": null,
"microService": "WebSites",
"gatewaySiteName": null,
"kind": null,
"cloningInfo": null,
"hostingEnvironmentId": null
}
As you can see, the computeMode, serverFarm, hostingEnvironment and sku aren't set with the properties I set in the $analyticsSite object.
Therefore I probably need to update the resource, but this throws the error mentioned above.
I've also tried using the New-AzureWebsite, using Troy Hunt's blogpost as an example. However, this post also relies on using the Set-AzureResource, so I'll fall into the same problem. A different problem with this example is you can't control on which resource group and hosting plan the site is created which will cause a bit of trouble when searching for the site.
This is possible so easily in the new RM cmdlets. Make sure that you have the latest version of Azure PowerShell first.
First create an App service plan that defines the Standard Price tier, then create a web app with the app service plan.
function Create-AppServicePlan()
{
#https://msdn.microsoft.com/en-us/library/mt619306.aspx
$resource = Find-AzureRmResource -ResourceNameContains $ServicePlanName -ResourceGroupNameContains $ResourceGroupName -ResourceType "Microsoft.Web/ServerFarms"
if(!$resource)
{
# Specify the Tier type that you would like
$servicePlan = New-AzureRmAppServicePlan -ResourceGroupName $ResourceGroupName -Name $ServicePlanName -Location $WebAppLocation -Tier Standard -NumberofWorkers 1 -WorkerSize "Small"
}
}
Next create the web app with the app service plan as a parameter.
function Create-AzureRmWebApp()
{
#https://msdn.microsoft.com/en-us/library/mt619250.aspx
$resource = Find-AzureRmResource -ResourceNameContains $WebAppName -ResourceGroupNameContains $ResourceGroupName -ResourceType "Microsoft.Web/sites"
if(!$resource)
{
$webApp = New-AzureRmWebApp -ResourceGroupName $ResourceGroupName -Name $WebAppName -Location $WebAppLocation -AppServicePlan $ServicePlanName
}
}
This is the full working script that is verified working.
$ServicePlanName = "PSScriptAppServicePlann"
$WebAppName = "WebAppByPSlooksCool"
$ResourceGroupName = "MyResourceGroup"
$WebAppLocation = "australiaeast"
$ErrorActionPreference = "Stop"
# Step 1: Create the application service plan
Create-AppServicePlan
# Step 2: Create the web app using the service plan name.
Create-AzureRmWebApp
function Create-AzureRmWebApp()
{
#https://msdn.microsoft.com/en-us/library/mt619250.aspx
$resource = Find-AzureRmResource -ResourceNameContains $WebAppName -ResourceGroupNameContains $ResourceGroupName -ResourceType "Microsoft.Web/sites"
if(!$resource)
{
$webApp = New-AzureRmWebApp -ResourceGroupName $ResourceGroupName -Name $WebAppName -Location $WebAppLocation -AppServicePlan $ServicePlanName
}
}
function Create-AppServicePlan()
{
#https://msdn.microsoft.com/en-us/library/mt619306.aspx
$resource = Find-AzureRmResource -ResourceNameContains $ServicePlanName -ResourceGroupNameContains $ResourceGroupName -ResourceType "Microsoft.Web/ServerFarms"
if(!$resource)
{
# Specify the Tier type that you would like
$servicePlan = New-AzureRmAppServicePlan -ResourceGroupName $ResourceGroupName -Name $ServicePlanName -Location $WebAppLocation -Tier Standard -NumberofWorkers 1 -WorkerSize "Small"
}
}
The problem is that you created your site in a default free App Service Plan (aka Server Farm or Web Hosting Plan - they're all the same thing), called "Default1". Yet the App Service Plan you scaled to the Standard size was a different one called "devHostingPlanWestEU10".
To create a site in a pre-existing App Service Plan use the following command:
(split into multiple lines for readability)
New-AzureResource
-Name <YourSiteName>
-Location "West US"
-ResourceGroupName <YourResourceGroupName>
-ApiVersion 2014-11-01
-ResourceType "Microsoft.Web/sites"
-PropertyObject #{ "serverFarm" = "<Your service plan name>" }
With the New Azure Resource Manager Cmdlet. You can create a new App Service Plan and Pass it to the New-AzureRmWebApp Cmdlet.
New-AzureRmAppServicePlan -Name StdPlan -Location <"Location"> -ResourceGroupName <"ResourceGroupName"> -Tier Standard
New-AzureRmWebApp -ResourceGroupName <"ResourceGroupName"> -Name <"WebAppname"> -Location <"Location"> -AppServicePlan StdPlan
Reference Article: https://learn.microsoft.com/en-us/azure/app-service-web/app-service-web-app-azure-resource-manager-powershell

Azure: How to check storage account exists in Azure with Get-AzureStorageAccount

I am building a power shell script to automate the setup of a website environment in Azure. This web uses an account storage. I want to the script not to create the account storage if exists.
I thought that using Get-AzureStorageAccount this way may work but it does not:
Write-Verbose "[Start] creating $Name storage account $Location location"
$storageAcct = Get-AzureStorageAccount –StorageAccountName $Name
if (!$storageAcct)
{
$storageAcct = New-AzureStorageAccount -StorageAccountName $Name -Location $Location -Verbose
if ($storageAcct)
{
Write-Verbose "[Finish] creating $Name storage account in $Location location"
}
else
{
throw "Failed to create a Windows Azure storage account. Failure in New-AzureStorage.ps1"
}
}
else
{
Write-Verbose "$Name storage account in $Location location already exists, skipping creation"
}
The issue is I don't know how to handle the return of Get-AzureStorageAccount.
Thank you very much in advance!
I would suggest using the Test-AzureName cmdlet to determine if it exists. So, something like this.
if (!(Test-AzureName -Storage $Name))
{
Write-Host "Creating Storage Account $Name"
New-AzureStorageAccount -StorageAccountName $Name -Location $Location
}
You can use Test-AzureName for other services too, such as Cloud Services, WebSites, and ServiceBus. It returns True if it exists, False otherwise.
Get-AzureRmStorageAccountNameAvailability -Name "accountname"
Try this:
$Name = "myStorageAccount"
$Location = "myLocation"
Write-Host "[Start] creating $Name storage account $Location location"
try{
Get-AzureStorageAccount –StorageAccountName $Name -ErrorAction Stop | Out-Null
Write-Host "$Name storage account in $Location location already exists, skipping creation"
}
catch{
Write-Host "[Finish] creating $Name storage account in $Location location"
New-AzureStorageAccount -StorageAccountName $Name -Location $Location -Verbose
}
Test-AzureName didn't work with our build agents and we already had a try/catch in code so a second one would require building it out as a function. I opted for that standard get and check if null, use -ErrorAction Ignore to stop it throwing an exception
# Check for storage account and create if not found
$StorageAccount = Get-AzureRmStorageAccount -Name $StorageAccountName -ResourceGroupName $StorageAccountRG -ErrorAction Ignore
if ($StorageAccount -eq $null)
{
New-AzureRmStorageAccount -Location "West Europe" -Name $StorageAccountName -ResourceGroupName $StorageAccountRG -SkuName Standard_LRS -Kind Storage
$StorageAccount = Get-AzureRmStorageAccount -Name $StorageAccountName -ResourceGroupName $StorageAccountRG
}
#Rick Rainey's solution works if you're logged in using Add-AzureAccount. However, Azure and powershell have a conflicting and confusing suite of login accounts (Windows Live versus AD) and login mechanisms (Classic: Add-AzureAccount; Resource manager: Login-AzureRmAccount). Some Azure powershell cmdlets require a specific login; further, some require a specific account type!
To clear through this thicket of complicated, undocumented, and confusing permission issues, we always use an AD account, logging in via Login-AzureRmAccount. We also use Azure resource manager (ARM) resources and cmdlets, following Microsoft's movement to ARM as its recommended and strategic approach. However, #RIck's solution is one which the ARM login doesn't work with. :-( So you need another approach, which is #Darren's (for storage). However, for a generic replacement for Test-AzureName I'd suggest Find-AzureRmResource. In the case of storage
$StorageObject = Find-AzureRmResource -ResourceType "Microsoft.Storage/storageAccounts" | Where-Object {$_.Name -eq $storageName}
if ( !$StorageObject ) {
$storageLocation = (Get-AzureRmResourceGroup -ResourceGroupName $resourceGroup).Location
$storageType = "Standard_LRS"
New-AzureRmStorageAccount -ResourceGroupName $resourceGroup -Name $storageName -Location $storageLocation -Type $storageType
}
You should use the latest Powershell module Az.
if ($(Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccountName) -eq $null)
{
# does not exist
}
With the current Az module for PowerShell Version 7, the Get-AzStorageAccountNameAvailability cmdlet might offer a more efficient solution as it was designed specifically for this task. Here is an example:
# ... declare variables and specify values ...
$checkNameAvail = (Get-AzStorageAccountNameAvailability -Name $storageAccountName) | `
Select-Object NameAvailable
if ($checkNameAvail.NameAvailable)
{
Write-Host 'Account name available! Please wait while your resource is being created'
# Create account. Variables used in this example would have been declared earlier in the script.
$storageAccount = (New-AzStorageAccount -ResourceGroupName $resourceGroupName `
-AccountName $storageAccountName `
-Location $location `
-SkuName $skuType `
-AllowBlobPublicAccess $false -EnableHttpsTrafficOnly $true)
# ...
}
else
{
# This section of the script executes if the name is not available
Write-Host "The name <$storageAccountName> is not available. Suggest a new globally unique name!"
}
The condition above will return False, and execute the else statement because the boolean value returned by the cmdlet is in [0] as shown in the PowerShell command-line test below. The availability information (boolean) can thus be stripped from the object returned by the cmdlet and (as in this example) used as a condition in the rest of the script.
PS C:\> Get-AzStorageAccountNameAvailability -Name testaccount1
NameAvailable Reason Message
------------- ------ -------
False AlreadyExists The storage account named testaccount1 is already taken.
Use the error variable
Get-AzStorageAccount -ResourceGroupName 'RG-QA-TEST' -Name 'staccountfor12334ff' -ErrorVariable ev1 -ErrorAction SilentlyContinue
if ($ev1) {
Write-Host "-------------------------- Creating OEM Storage"
//create storage account
}
I had this challenge when setting up Azure storage accounts for Static website hosting using Powershell in Octopus Deploy.
Here's how I fixed it:
Using the Az module for Azure Powershell I did the following:
# Define Variables
$RESOURCE_GROUP_NAME = my-resource-group
$LOCATION = northeurope
$STORAGE_ACCOUNT_NAME = myapplication
$SKU_NAME = Standard_GRS
$STORAGE_KIND = StorageV2
# Check Storage Account and Create if not Found
$STORAGE_ACCOUNT = Get-AzStorageAccount -ResourceGroupName $RESOURCE_GROUP_NAME -Name $STORAGE_ACCOUNT_NAME -ErrorAction Ignore
if ($STORAGE_ACCOUNT -eq $null) {
Write-Host 'Creating storage account'
New-AzStorageAccount -ResourceGroupName $RESOURCE_GROUP_NAME -AccountName $STORAGE_ACCOUNT_NAME -Location $LOCATION -SkuName $SKU_NAME -Kind $STORAGE_KIND
Write-Host "$STORAGE_ACCOUNT_NAME storage account successfully created"
}
else {
Write-Host "$STORAGE_ACCOUNT_NAME storage account already exists"
}
Note:
-ErrorAction Ignore - This ignores the exception that would arise if the storage account does not exist
Write-Host " " - Double quotes were used to allow for string interpolation since we are connecting strings and variables.
That's all.
I hope this helps