It's possible to retrieve the access key to an Azure storage account using Get-AzureRmStorageAccountKey from Powershell. How would I get hold of the access key to a shared access policy of an Azure Service Bus?
More clarification
This is what I get when I use the Get-AzureRmServiceBusNamespaceKey cmdlet:
PS C:\Windows\system32> Login-AzureRmAccount -Credential $cred
Environment : AzureCloud
Account : ***redacted***
TenantId : ***redacted***
SubscriptionId : ***redacted***
CurrentStorageAccount :
PS C:\Windows\system32> Set-AzureRmContext -SubscriptionId ***redacted***
Environment : AzureCloud
Account : ***redacted***
TenantId : ***redacted***
SubscriptionId : ***redacted***
CurrentStorageAccount :
PS C:\Windows\system32> Get-AzureRmServiceBusNamespaceKey -ResourceGroup testresourcegroup -Name test-bus -AuthorizationRuleName SendPolicy
Get-AzureRmServiceBusNamespaceKey : Run Login-AzureRmAccount to login.
At line:1 char:1
+ Get-AzureRmServiceBusNamespaceKey -ResourceGroup testresourcegroup -Name test-bus ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-AzureRmServiceBusNamespaceKey], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.Azure.Commands.ServiceBus.Commands.Namespace.GetAzure RmServiceBusNamespaceKey
PS C:\Windows\system32> Get-AzureRmStorageAccountKey -ResourceGroupName testresourcegroup -Name teststoragexxx
Key1 Key2
---- ----
***redacted*** ***redacted***
Not with Get-AzureRmStorageAccountKey, but you can use Get-AzureRmServiceBusNamespaceKey
$resourceGroup = "myResourceGroup"
$serviceBusName ="myservicebusname"
$policyName = "policyname"
Get-AzureRmServiceBusNamespaceKey -ResourceGroup $resourceGroup -Name
$serviceBusName -AuthorizationRuleName $policyName
This will return the whole object, so you can pass it into a variable and get the keys or connection strings from that.
Please have a try to login with tenantId and ServicePrincipal. I do a demo test about that, it works correctly for me.
Login-AzureRmAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal -SubscriptionId $subscriptionId
The following is may detail steps.
1 . We need to install service Bus module if it is not install. More detail info about AzureRM.ServiceBus please refer to document.
Install-Module -Name AzureRM.ServiceBus
2.More detail info about Automatically login script please refer to another SO thread.
3.Run the test script and check the result.
$azureAplicationId ="Azure AD Application Id"
$azureTenantId= "Your Tenant Id"
$azurePassword = ConvertTo-SecureString "strong password" -AsPlainText -Force
$subscriptionId="Your subcription"
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Login-AzureRmAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal -SubscriptionId $subscriptionId
$resourceGroup = "Resource Group name"
$serviceBusName ="Service Bus Name"
$policyName = "Policy Name"
Get-AzureRmServiceBusNamespaceKey -ResourceGroup $resourceGroup -Name $serviceBusName -AuthorizationRuleName $policyName
Related
I'm trying to create an Azure Automation Runbook to write messages to an existing Azure Storage Queue using information from a SQL Query. The below works perfectly in Powershell ISE on my Windows 10 machine, but I'm getting an error when testing it in Azure the Automation.
The script is:
Connect-AzureRmAccount
Get-AzureRmSubscription
Set-AzureRmContext -SubscriptionId <our subscription id>
$resourceGroup = "our resource group"
$storageAccountName = "our storage account name"
$queueName = "our queue name"
$queue = Get-AzureRmStorageQueueQueue -resourceGroup $resourceGroup -storageAccountName $storageAccountName -queueName $queueName
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "our Azure SQL connection string"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $("SELECT SourceId FROM dbo.batches GROUP BY SourceId HAVING SourceId > 101")
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$Table = new-object system.data.datatable
$SqlAdapter.Fill($Table) | out-null
$SqlConnection.Close()
$compArray = #($Table | select -ExpandProperty SourceId)
foreach ($array in $compArray) {
Add-AzureRmStorageQueueMessage -queue $queue -message #{"SourceId"=$array;"RetryCount"=0;}
}
Again, this works perfectly in Powershell on my local machine, but in Azure Automation, I get this error:
Failed
Queue <our queue name> could not be retrieved/created from Storage Account <our storage account> on resource group (Queue <our queue name> could not be retrieved/created from Storage Account <our storage account> on resource group )
Set-AzureRmContext : Run Connect-AzureRmAccount to login.
At line:3 char:1
+ Set-AzureRmContext -SubscriptionId <our subscription id> ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Set-AzureRmContext], PSInvalidOperationException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.SetAzureRMContextCommand
Get-AzureRmStorageAccount : No subscription found in the context. Please ensure that the credentials you provided are
authorized to access an Azure subscription, then run Connect-AzureRmAccount to login.
At C:\Modules\User\AzureRmStorageQueue\AzureRmStorageQueueCoreHelper.psm1:86 char:19
+ ... aContext = (Get-AzureRmStorageAccount -ResourceGroupName $resourceGro ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzureRmStorageAccount], ApplicationException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Management.Storage.GetAzureStorageAccountCommand
Get-AzureStorageQueue : Could not get the storage context. Please pass in a storage context or set the current storage
context.
At C:\Modules\User\AzureRmStorageQueue\AzureRmStorageQueueCoreHelper.psm1:88 char:94
+ ... ue]$queue = Get-AzureStorageQueue -Name $queueName -Context $saContex ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzureStorageQueue], InvalidOperationException
+ FullyQualifiedErrorId :
InvalidOperationException,Microsoft.WindowsAzure.Commands.Storage.Queue.GetAzureStorageQueueCommand
New-AzureStorageQueue : Could not get the storage context. Please pass in a storage context or set the current storage
context.
At C:\Modules\User\AzureRmStorageQueue\AzureRmStorageQueueCoreHelper.psm1:92 char:95
+ ... ue]$queue = New-AzureStorageQueue -Name $queueName -Context $saContex ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureStorageQueue], InvalidOperationException
+ FullyQualifiedErrorId :
InvalidOperationException,Microsoft.WindowsAzure.Commands.Storage.Queue.NewAzureStorageQueueCommand
Could someone assist me in what I'm missing here? (I have confirmed that the AzureRmStorageQueue module is installed in Azure Automation.)
In the azure runbook, no need to use the interactive login, if you create an automation account, it will create a service principal and add it to your subscription as a contributor role automatically. So you just need to use the service principal to do what you need.
The command should be like as below, you could try it.
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
$resourceGroup = "our resource group"
$storageAccountName = "our storage account name"
$StorageAccountKey = (Get-AzureRmStorageAccountKey -ResourceGroupName $resourceGroup -AccountName $storageAccountName).Value[1]
$context=New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey
$queueName = "our queue name"
$queue = Get-AzureRmStorageQueueQueue -resourceGroup $resourceGroup -storageAccountName $storageAccountName -queueName $queueName -Context $context
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "our Azure SQL connection string"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $("SELECT SourceId FROM dbo.batches GROUP BY SourceId HAVING SourceId > 101")
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$Table = new-object system.data.datatable
$SqlAdapter.Fill($Table) | out-null
$SqlConnection.Close()
$compArray = #($Table | select -ExpandProperty SourceId)
foreach ($array in $compArray) {
Add-AzureRmStorageQueueMessage -queue $queue -message #{"SourceId"=$array;"RetryCount"=0;}
}
I'm trying to start an Azure VM using the following PowerShell script:
$subscriptionId = "00000000-0000-0000-0000-000000000000"
$azureVM = "VS2017"
$resourceGroup = "VS2017ResourceGroup"
Add-AzureRmAccount # here start interactive login
Select-AzureSubscription -SubscriptionId $subscriptionId
Start-AzureRmVM - -ResourceGroupName $resourceGroup -Name $azureVM
When executing the script, I receive the following response:
Start-AzureRmVM : A positional parameter cannot be found that accepts argument '-'.
At C:\Users\ralbano\Desktop\Senza nome7.ps1:11 char:1
+ Start-AzureRmVM - -ResourceGroupName "VS2017ResourceGroup" -Name $azu ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Start-AzureRmVM], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.Azure.Commands.Compute.StartAzureVMCommand
I am using Windows PowerShell ISE to run the script.
Am I doing something wrong?
I checked the subscription id and the resource group name and are correct (of course in the sample above the subscription id is a fake). The VM is in "Stopped (deallocated)" state on Azure.
Start-AzureRmVM - -ResourceGroupName $resourceGroup -Name $azureVM
According to your error message, we should use this command like this:
Start-AzureRmVM -ResourceGroupName $resourceGroup -Name $azureVM
I am trying to create an Azure SQL Database connection context e.g.
$cred = Get-Credential
$ctx = New-AzureSqlDatabaseServerContext -ServerName “mydatabasename” -credential $cred
or
$pwd = ConvertTo-SecureString "[password1234]" -AsPlainText -Force;
$cred1 = New-Object System.Management.Automation.PSCredential -ArgumentList "databaseadmin", $pwd
New-AzureSqlDatabaseServerContext -ServerName "myservername" -Credential $cred1
And the response is:
New-AzureSqlDatabaseServerContext : Object reference not set to an instance of an object.
At line:2 char:8
+ $ctx = New-AzureSqlDatabaseServerContext -ServerName “myservername” - ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureSqlDatabaseServerContext], NullReferenceException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.SqlDatabase.Database.Cmdlet.NewAzureSqlDatabaseServerContext
I've been through the docs and google searches but to no avail.
https://msdn.microsoft.com/en-us/library/dn546736.aspx
http://sqlmag.com/powershell/manage-azure-sql-databases-powershell
Thanks
Pavel
I recently ran into this issue in a PS runbook. After doing some searching, I found a solution that worked for me. Hopefully it will help you.
The error message isn't particularly helpful (big surprise), but the null object being referenced is the Azure subscription; I'm assuming the exception bubbles up from within the cmdlet rather than being thrown by your own code. By adding these three lines to my code:
$cert = Get-AutomationCertificate -Name $automationCertificateName;
Set-AzureSubscription -SubscriptionName $subName -Certificate $cert -SubscriptionId $subID;
Select-AzureSubscription -Current $subName;
I was able to get past the exception. Above, $automationCertificateName is a variable asset that I added to the automation account. See https://github.com/Microsoft/sql-server-samples/tree/master/samples/manage/azure-automation-automated-export for details about how to set that up.
Here is how I successfully created connection context:
$sqlServerUser = "test-user"
$sqlServerUserPassword = "P#$$w0rd"
$sqlServerName = "mysqlserver"
$sqlCred = New-Object System.Management.Automation.PSCredential($sqlServerUser, ($sqlServerUserPassword | ConvertTo-SecureString -asPlainText -Force))
$sqlContext = New-AzureSqlDatabaseServerContext -ServerName $sqlServerName -Credential $sqlCred
Please see this for more details.
I want to create an azure storage container in an existing storage account, through powershell.I have tried the following commands:
Set-AzureSubscription -CurrentStorageAccountName "storageaccountv1" -SubscriptionId $SubscriptionId
New-AzureStorageContainer -Name $ContainerName -Permission Off
For those who know, Azure has two types of storage accounts: v1, v2. v1 accounts are the ones that are available through the http://manage.windowsazure.com/ and v2 that can be created in http://portal.azure.com/. While the command New-AzureStorageContainer is working with a storage account in v1, the command is not working for a storage account in v2. It is giving the following error:
New-AzureStorageContainer : ResourceNotFound: The storage account 'storageaccountv2' was not found.
At CreateStorageContainer.ps1:31 char:1
+ New-AzureStorageContainer -Name $ContainerName -Permission Off
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureStorageContainer], CloudException
+ FullyQualifiedErrorId : CloudException,Microsoft.WindowsAzure.Commands.Storage.Blob.Cmdlet.NewAzureStorageContainerCommand
Can anyone tell how to create an azure storage container in v2 through powershell?
If using StorageAccountContext is an option, you can try the following:
$ctx = New-AzureStorageContext -StorageAccountName "account-name" -StorageAccountKey "account-key"
New-AzureStorageContainer -Name "container-name" -Context $ctx
Azure PowerShell 1.0 Preview (https://azure.microsoft.com/en-us/blog/azps-1-0-pre/) is release.
With Azure PowerShell 1.0 Preview, you can run following cmdlets:
Login-AzureRMAccount -SubscriptionId [SubscriptionID]
Set-AzureRmCurrentStorageAccount -StorageAccountName [accountName] -ResourceGroupName [ResourceGroupName]
Then you can run "New-AzureStorageContainer" with resource mode account (create in new portal) without context.
BTW, "Set-AzureSubscription" is only for Service mode account, not applicable to resource mode account.
Here is the idempotent code
[System.String]$script:ResourceGroupNameVariable = 'resourcegroupnameone'
[System.String]$script:StorageAccountNameVariable = 'storacctnameone'
[System.String]$script:ContainerNameVariable = 'containernameone'
Write-Host "Start Container Create"
#Get/Set the AzureRmStorageAccountKey
# the below -Name parameter may be -AccountName according to documentation
[System.Object[]]$currentAzureRmStorageAccountKeys = Get-AzureRmStorageAccountKey -ResourceGroupName $script:ResourceGroupNameVariable -Name $script:StorageAccountNameVariable;
#Write-Host "about to currentAzureRmStorageAccountKeys.GetType"
#Write-Output $currentAzureRmStorageAccountKeys.GetType().FullName
### Create the AzureStorageContext (you always do this, regardless if the container itself exists or not)
[Microsoft.WindowsAzure.Commands.Storage.AzureStorageContext]$currentAzureStorageContext = New-AzureStorageContext -StorageAccountName $script:StorageAccountNameVariable -StorageAccountKey $currentAzureRmStorageAccountKeys[0].Value;
#Write-Host "about to currentAzureStorageContext.GetType"
#Write-Output $currentAzureStorageContext.GetType().FullName
# Get/Set the AzureStorageContainer
[Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel.AzureStorageContainer]$currentAzureStorageContainerCheck=Get-AzureStorageContainer -Context $currentAzureStorageContext -Name $script:ContainerNameVariable;
if(!$currentAzureStorageContainerCheck)
{
### The container does not already exist. Create a Blob Container in the Storage Account
New-AzureStorageContainer -Context $currentAzureStorageContext -Name $script:ContainerNameVariable;
}
else{
#Write-Host "about to currentAzureStorageContainerCheck.GetType"
#Write-Output $currentAzureStorageContainerCheck.GetType().FullName
#Write-Host "about to currentAzureStorageContainerCheck"
#$currentAzureStorageContainerCheck
}
Write-Host "End Container Create"
This runs against : Version 4.3.1 (of AzureRM )
get-module –listavailable -Name "AzureRM"
this helped but I needed the ARM command and not the classic method.
Hope it helps
$NewRGName = 'Lab'
$NewRGLocation = "West US"
$NewStrAccName ="Labstorage2"
$SkuName = 'Standard_LRS'
# Create new storage account
New-AzureRmStorageAccount -Location $NewRGLocation -Name $NewStrAccName -ResourceGroupName $NewRGName -SkuName $SkuName
I am trying to create an azure website via a powershell script. The hosting plan has already been create, I simply wish to add a new website to it.
The script I'm using is this:
Switch-AzureMode AzureResourceManager
$targetServicePlan = Get-AzureResource -Name my-serviceplan -OutputObjectFormat New
New-AzureResource -Name MyTestSite -Location "West Europe" `
-ResourceGroupName Default-Web-WestEurope `
-ResourceType 'Microsoft.Web/sites' `
-PropertyObject #{"name" = "MyTestSite"; "ServerFarmId" = $targetServicePlan.ResourceId } `
-OutputObjectFormat New
The server farm ($targetServicePlan) has a resource id, so I'm assuming that it exists (there is also a hosting plan in the azure portal with this name). Yet when I try to create the website I get the error: "Server farm with name my-serviceplan not found."
The full error is:
New-AzureResource : {"Code":"NotFound","Message":"Server farm with name my-serviceplan not found.","Target":null,"Details":[{"Message":"Server farm with name
my-serviceplan not found."},{"Code":"NotFound"},{"ErrorEntity":{"Code":"NotFound","Message":"Server farm with name my-serviceplan not
found.","ExtendedCode":"11001","MessageTemplate":"Server farm with name {0} not found.","Parameters":["my-serviceplan"],"InnerErrors":null}}],"Innererror":null}
At line:1 char:1
+ New-AzureResource -Name MyTestSite -Location "West Europe" -ResourceGrou ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureResource], ErrorResponseMessageException
+ FullyQualifiedErrorId : NotFound,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.NewAzureResourceCmdlet
What am I missing?
Is your $targetServicePlan in 'West Europe'? If not that could be the reason for that not-so-helpful error.