How to deploy to Azure with powershell? - powershell

I want to deploy my application to azure with powershell. So far I have created a certificate in the localmachine store, I'm not going to run the deploy script as me, uploaded the script to azure. The next step is to get access to the service on azure in powershell but there it fails. The script I have so far is:
$cert = Get-Item Cert:\LocalMachine\deploy\xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Set-AzureSubscription -SubscriptionName $subscriptionName -SubscriptionId $subscriptionId -Certificate $cert
Select-AzureSubscription $subscriptionName
$service = Get-AzureService $azureId
It fails on the last row with the following message:
Get-AzureService : Communication could not be established. This could be due to an invalid subscription ID. Note that subscription IDs are case sensitive.
At F:\DeployTest\deploy.ps1:9 char:12
+ $service = Get-AzureService $azureId
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-AzureService], Exception
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Management.ServiceManagement.HostedServices.GetAzureServiceCommand
Get-AzureService : HTTP Status Code: AuthenticationFailed - HTTP Error Message: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.
Operation ID:
At F:\DeployTest\deploy.ps1:9 char:12
+ $service = Get-AzureService $azureId
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzureService], CommunicationException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Management.ServiceManagement.HostedServices.GetAzureServiceCommand
I really don't know what the problem is, the certificate I'm trying to use is uploaded so it feels like there is something fundamental I've missed.
Update: I did get it to work after downloading the .publishsettings-file and importing that instead of trying to use Set-AzureSubscription. I'm still a little bit confused though, shouldn't it be possible to use the method I tried above?

I finally found the problem, and of course it was a user problem. First when I was in the azure portal I didn't find where to upload the certificate, so I uploaded it to first place I found mentioning certificates. What I did found out was that this area was the wrong one, I uploaded the certificate to the certificate area under the cloud service I wanted to administrate, which is the wrong place.
The correct place to upload the certificate to is under settings in the admin portal of azure. So the code above works if the certificate is uploaded to the correct location.

Related

PowerShell Script with Clixml and Taskscheduler

Here's the problem:
When I run my PowerShell script manually, everything works fine. But it doesn't work via task scheduling.
The reason is probably my stored credentials for Active Directory and Mobile Device Management.I stored them with "Export-Clixml" but the xml files cant be read when i open the script with task scheduler. Without it works perfect.
The task scheduler is executed with the same user who saved the credentials in the XML before.
I hope you understand what I mean.
Edit 1:
I've tried the Solution from "Bender the Greatest".
Unfortunately it still doesn't work. I exported my credentials with "Export-Clixml" and import them with "Import-Clixml".
It doesn't matter if I generate them manually via my admin account or via the system account (with psexec). If I then execute it via the corresponding account with which the credentials were generated, it still doesn't work.
But it seems to find the credentials (I saw that in the log). But The import doesn't seem to work.
If I manually include the credentials in the script it works fine, but I would have liked to store them encrypted.
[Lizenzauswertung] Überprüfe Zugangsdaten
[Lizenzauswertung] MDM Zugangsdaten gefunden - Credentials found
[Lizenzauswertung] MDM AccessToken gefunden - Credentials found
[Lizenzauswertung] AD Zugangsdaten gefunden - Credentials found
Here im trying to decrypt the Password from the XML File:
It is not possible to call a method for an expression that has NULL.(Translated)
In C:\Scripts\ADAuswertung\AD_Auswertung_GKZ.ps1:171 Zeichen:1
+ $PSCPW = $CredsMDM.GetNetworkCredential().Password
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
It is not possible to call a method for an expression that has NULL.(Translated)
In C:\Scripts\ADAuswertung\AD_Auswertung_GKZ.ps1:171 Zeichen:1
+ $PSCPW = $CredsMDM.GetNetworkCredential().Password
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
This is a replacement for the username to have the right spelling for a webrequest:
It is not possible to call a method for an expression that has NULL.(Translated)
In C:\Scripts\ADAuswertung\AD_Auswertung_GKZ.ps1:172 Zeichen:1
+ $RPSCUser = $PSCUser.Replace("INTRA","intra.lan")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
It is not possible to call a method for an expression that has NULL.(Translated)
In C:\Scripts\ADAuswertung\AD_Auswertung_GKZ.ps1:172 Zeichen:1
+ $RPSCUser = $PSCUser.Replace("INTRA","intra.lan")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Here you can see the errors that occur when importing the MDM credentials. The reason for the errors is described above. I edit the credentials after importing them before they are passed to the script.
The MDM Access Token is not encrypted and can be read.
The AD credentials are not processed beforehand, but passed directly to the AD commands. Therefore, no error is displayed here. Since it does not finish the AD report, which I saw in the log, these are not imported either.
Here is a little Codesnippet of the Import/Export. Just got the code here for the MDM credentials. The other queries are the same.
If (Test-Path $CredentialsMDM){
$CredsMDM = Import-Clixml -Path $CredentialsMDM
Write-Host "[Lizenzauswertung] MDM Zugangsdaten gefunden" -ForegroundColor Green
} else {
Write-Host "[Lizenzauswertung] MDM Zugangsdaten nicht gefunden" -ForegroundColor Yellow
Get-Credential -Message "Zugangsdaten für MDM / Airwatch" | export-clixml -path $CredentialsMDM
$CredsMDM = Import-Clixml -Path $CredentialsMDM
}
Write-Host "[Lizenzauswertung] Zugangsdaten überprüft" -ForegroundColor Green
$PSCUser = $CredsMDM.UserName
$PSCPW = $CredsMDM.GetNetworkCredential().Password
$RPSCUser = $PSCUser.Replace("INTRA","intra.lan")
$AccessToken = $CredsMDMAT.accesstoken
$Auth = $CredsAD
(I am sorry for the spaghetti code.)
You need to provide the error you're getting but I'm going to take a shot in the dark here. I'm guessing you're either exporting secretAD.xml as one user and running your script as another user from Task Scheduler, or exporting secretAD.xml on another computer/server. By default, credentials are able to be decrypted only by the user that built it on that specific server. This is how Windows' Data Protection API (DPAPI) works.
The easy way to fix this is to generate secretAD.xml as the user you intend to run the script as. You can specify your own key for decryption, which can be used by any user on any box, but you will need to figure out a method of secure delivery of the decryption key to the runtime. If you want/need to run the script as NT Authority\SYSTEM, I recommend using psexec to open an interactive SYSTEM Powershell session, generate the credential, and then use Export-CliXml to serialize the credential to secretAD.xml.
Note that the default DPAPI key gets changed when an account password is rotated, so you'll need to remember to rebuild the credential when that happens.
I've found the solution to my problem.
The reason was that the path to the credentials was ".\secretMDM.xml".
The task scheduler executes the script at a different location.
Therefore I had to specify the whole path of the file.
Thanks for the help anyway.
Edit:
Out of interest I created the "Credential" - XML files with the Task Scheduler. Have a look where it stores the files ;)

ADAL in Azure Automation: Type not loading intermittantly

I'm working on an Azure Automation script where I need to retrieve an access token to call the AAD Graph API. I wanted to use ADAL to do this so I zipped up Microsoft.IdentityModel.Clients.ActiveDirectory.dll and uploaded it as a module. When I run from the test blade, it sometimes works, and sometimes fails with this error:
New-Object : Cannot find type [Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential]: verify that the
assembly containing this type is loaded.
At line:22 char:9
+ $cred = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredent ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
When it fails I just run it again and it works. Now I've published and scheduled this runbook as a daily job 3 days ago. So far it has failed every day with this same error.
Has any one else seen this? Any suggestions on next steps?
I fixed this by adding the following line to my script:
Add-Type -Path "C:\Modules\User\Microsoft.IdentityModel.Clients.ActiveDirectory\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
Still not sure why it was working intermittently before. I guess depending on what else was going on ADAL may or may not have been loaded?

Powershell to Federate Office 365 domain

I am attempting to Federate office 365 and use it as a Service Provider, but I can't seem to change the SigningCertificate information in the FederationSettings. I am trying to use this powershell command:
Set-MsolDomainAuthentication -IssuerUri $entity -LogOffUri $logout -PassiveLogOnUri $url -PreferredAuthenticationProtocol SAMLP -SigningCertificate $cert
This command only works if I remove -SigningCertificate $cert. And I can't change the SigningCertificate once I've set up federation either. Also I am not using ADFS. I really appreciate any help anyone can provide for why this won't work.
Error Message:
Set-MsolDomainAuthentication : Invalid value for parameter. Parameter Name:
.
At line:1 char:1
+ Set-MsolDomainAuthentication -IssuerUri $entity -LogOffUri $logout
-PassiveLogOn ...
CategoryInfo:OperationStopped: (:) [Set-MsolDomainAuthenticaion], MicrosoftOnlineException + FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.ProprtyValidationException,Microsoft.Online.Administration.Automation.SetDomainAuthentication
In case anyone else finds themselves in this situation the answer is to make sure all the spaces are removed from the certificate string.

Security Token Validation Error with JWT token -- HDInsight

I created a new storage account and provisioned an HDInsight cluster on Windows Azure. However, when I try to run any command on Windows Azure Powershell related to the cluster, I get the following error:
PS C:\> Get-AzureHDInsightCluster -Name $clusterName
Get-AzureHDInsightCluster : Request failed with code:Unauthorized
Content:<Error xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Code>AuthenticationFailed</Code><Message>A security token
validation error occured for the received JWT token.</Message></Error>
At line:1 char:1
+ Get-AzureHDInsightCluster -Name $clusterName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-AzureHDInsightCluster], HttpLayerException
+ FullyQualifiedErrorId : Microsoft.Hadoop.Client.HttpLayerException,Microsoft.WindowsAzure.Management.HDInsight.C
mdlet.PSCmdlets.GetAzureHDInsightClusterCmdlet
I'm completely new to HDInsight, but I ran a script before this command to add the Azure account, create variables for the subscription name, storage account name, and container name from this page.
Do you know what this error means? And how to fix it? I'm trying to run a script with Pig commands after following this website.
It looks like the PowerShell environment is not properly setup. You should add your Azure subscription first with GetAzureSubscription. See: http://www.windowsazure.com/en-us/documentation/articles/install-configure-powershell/#Connect

Windows Azure Powershell command Get-AzureWebsite results in error String was not recognized as a valid Boolean

I'm trying to manage some of my Azure Services via Powershell, using http://windowsazurewebsitescheatsheet.info/#powershell as a starting point. I was able to download and import my subscription settings just fine (Import-AzurePublishSettingsFile and Select-AzureSubscription)
After choosing my subscription, I'm attempting to run the Get-AzureWebsite command to view all of my websites, and continue onward from there. When I run that command, however, I get the following:
Import-AzurePublishSettingsFile "C:\AzureCredentials.publishsettings"
Select-AzureSubscription "My Azure Subscription"
Get-AzureWebsite
Get-AzureWebsite : String was not recognized as a valid Boolean.
At line:1 char:1
+ Get-AzureWebsite
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzureWebsite], FormatException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.Websites.GetAzureWebsiteCommand
Anyone have similar issues? I get this error if I run the command as stated above, or if I specify the name of my website. TIA for any help!
This might be related to a known issue enumerating a sites with SSL bindings
There was new release of Windows Azure Powershell released on 02/12. Please try with the new version.
Please run the command again with -Debug turned on, this will display request and response messages and make it easier to pinpoint the issue.