#Import-AzureRmContext
Explore tagged Tumblr posts
Text
Select-AzureRmProfile : The term 'Select-AzureRmProfile' is not recognized as the name of a cmdlet, function, script file, or operable program
Select-AzureRmProfile : The term ‘Select-AzureRmProfile’ is not recognized as the name of a cmdlet, function, script file, or operable program
I got a chance to work with PowerShell automation script to automate the login process. In the script, the profile is loaded using the Select-AzureRmProfile. If you try to log in using Select-AzureRmProfile you most likely encounter the following error message.
Error Message:
Select-AzureRmProfile : The term ‘Select-AzureRmProfile’ is not recognized as the name of a cmdlet, function, script file,…
View On WordPress
0 notes
Text
[AzureScript][T1:E3] Login Automático
¡Hola de nuevo! si te perdiste la primera parte, te dejo un link donde vemos el porque usar Azure desde linea de comando, y la forma de instalarlo.
T1:E1 - Introducción
T1:E2 - Usos Básicos
En esta ocasión les voy a comentar algo que deje pendiente al final del post anterior, y es como loguear a Azure sin la interacción del usuario. Esto es importante porque si tenemos procesos automatizados, dado que nuestros scripts deberían poder autenticarse en Azure sin la necesidad de que haya alguien ingresando manualmente las contraseñas. Hay varias formas de hacer esto, les voy a comentar 2 que son las que considero más prácticas:
Logueo mediante contexto de Azure
Logueo mediante Service Principal
Logueo mediante contexto de Azure.
En este caso, lo que se hace es almacenar un token de autenticacion de Azure en un archivo json. Luego al comienzo de cada script podemos cargar ese archivo json y eso automáticamente nos autenticará contra Azure. Es muy práctico de implementar, pero tiene una desventaja importante: el token vence luego de 30 días. Aun así, nos puede salvar de apuros hasta que tengamos una solución mas robusta.
Lo primero que debemos hacer para almacenar este token, es abrir Powershell y loguear de modo manual como ya hemos visto en episodios anteriores:
Login-AzureRmAccount
Luego, debemos elegir donde se almacenará y como se llamará este archivo json que contendrá el token, puede ser cualquier carpeta y cualquier nombre. Como ya hemos hecho antes, almacenamos la ruta en una variable y luego llamamos al cmdlet correspondiente:
$ruta = "C:/Ruta/Al/Archivo/AzureAuth.json" Save-AzureRmContext -Path $ruta
De este modo, habremos generado un archivo json que contiene un token para autenticarnos sin interacción del usuario en Azure. Ahora para que nuestros scripts sean 100% autónomos, podemos reemplazar la parte de Login-AzureRmAccount por esto:
$ruta = "C:/Ruta/Al/Archivo/AzureAuth.json" Import-AzureRmContext -Path $ruta
¡Así de sencillo! Al ejecutar esto ya estaremos autenticados. La gran contra que tiene este método, como ya comente, es que el token expira luego de un mes y hay que regenerarlo. Esto implica que alguien debe loguear manualmente y guardar el contexto nuevamente para que sea válido el token.
Logueo mediante Service Principal
Para evitar tener problemas con el contexto y su token, lo recomendable es usar este método. Un service principal es un usuario de servicio, que nos permitirá administrar recursos de Azure para los cuales tenga permisos asignados. Este método lleva unos pasos extra, pero nos da la opción de programar scripts que no tienen fecha de caducidad, y ademas es más seguro porque al loguear solo tendremos permisos para administrar algunos recursos sobre los que tenga permiso el service principal, y no sobre todos los que disponga un usuario en particular como en el caso del contexto. Para loguear con un service principal, el primer paso es tener uno. Para crear uno, tenemos la opción de hacerlo mediante el portal o mediante Powershell con el cmdlet New-AzureRmADServicePrincipal. Como es algo que haremos solo una vez, explicaré como hacerlo en el portal de modo gráfico. Para esto, dentro del portal vamos a la opción Azure Active Directory en la parte izquierda de la pantalla. Una vez ahí, elegimos App Registrations, y luego en el símbolo +, que dice New Registration.
Al momento de crear un service principal solo debemos asignarle un nombre, procura que sea un nombre que describa su función, o a que recursos tendrá acceso. Luego de ponerle un nombre damos click en Register. Luego de crearlo, ya podremos asignarle permisos a nuestro service principal a los recursos que queremos que pueda administrar desde Access Control (IAM) en el correspondiente recurso, como si se tratara de un usuario más. Después de darle los permisos correspondientes, tomaremos nota de algunos valores que necesitaremos al momento de autenticarnos en nuestro script, estos valores son: TenantId, ApplicationId, y SecretId.
A continuación, te explico como obtener cada uno:
ApplicationId: lo podemos obtener dentro de Azure Active Directory -> App Registration -> Selecciona el service principal creado. Nos mostrará algunos códigos, pero el que nos interesa en este caso es este "Application (client) ID".
SecretId: en la misma ventana de donde sacamos el ApplicationId, podemos ver a la izquierda "Certificates & secrets", clickeamos ahí. Después vamos a "New Client Secret", asignamos un nombre a nuestro secret, y damos click en "Add". Esto generará un nuevo secreto, ¡asegúrate de guardarlo bien! Una vez que cierres esta ventana no podrás volver a obtenerlo!!
TenantId: este es más sencillo, lo obtenemos de Azure Active Directory -> Properties -> Directory Id.
Entonces, ahora ya tenemos nuestro service principal creado, con sus permisos y tenemos los datos que necesitamos para autenticarnos en nuestro script. ¡Manos a la obra! Como hemos hecho con anterioridad, almacenaremos en variables y luego las llamaremos. El código es un poco más largo esta vez, pero no mucho:
$ServPpalSecret = "ServicePrincipalSecret" $ServPpalAppId = "ServicePrincipalAppId" $TenantId = "DirectoryId"$secpasswd = ConvertTo-SecureString $ServPpalSecret -AsPlainText -Force $creds = New-Object System.Management.Automation.PSCredential ($ServPpalAppId, $secpasswd)Login-AzureRmAccount -Credential $creds -ServicePrincipal -TenantId $TenantId
¡Listo! Al ejecutar éstas lineas nuestro script estará logueado con este service principal de forma 100% autónoma! Ahora si podremos usar nuestros scripts como runbooks en Azure Automation, o almacenarlos como .ps1 y llamarlos desde el programador de tareas de Windows (o cron desde Linux, si usamos Powershell Core), sin preocuparnos por fechas de caducidad de tokens, con la tranquilidad de que no requerirán ninguna interacción por parte del usuario.
Espero que les haya gustado, ¡¡no se pierdan el próximo episodio!! :)
Escrito por Martín Zurita.
0 notes
Text
Exporting Certificates and Certificate Private Keys Created in Azure Using PowerShell
利用PowerShell导出Azure中创建的证书和证书私钥 利用AZURE的额度,可以购买域名证书和通配符证书. 但是通常不能够从网页中导出来,但是可以利用PowerShell导出证书和私钥. 这样就可以拿着证书和私钥为所欲为了~ 需要在本机的PowerShell中安装AzureRM模块,还有OpenSSL支持. 请在更高级的WINDOWS上尝试,版本过低可能不支持. 安装OpenSSL: 下载openssl-1.1.0g-win64.zip 备份下载 将压缩包内的以下三个文件解压至%WINDIR%\System32文件夹中. openssl.exe libcrypto-1_1-x64.dll libssl-1_1-x64.dll 获取PowerShell脚本: 点击下载 get_cert.ps1 https://github.com/koryelu/files/blob/master/get_cert.ps1 将以下行修改为自己的订阅资源的详情: 1 2 3 4 $appServiceCertificateName = "" #资源名称 $resourceGroupName = "" #资源组名称 $azureLoginEmailId = "" #登陆邮箱 $subscriptionId = "" #订阅ID 以管理员权限执行get_cert.ps1脚本 以管理员身份打开PowerShell 切换到get_cert.ps1所在路径 1 2 #示例(切换到D盘根目录): cd d:\ 执行get_cert.ps1 1 .\get_cert.ps1 如遇”因为在此系统上禁止运行脚本“相关报错,执行以下命令即可. 1 Set-ExecutionPolicy RemoteSigned 如遇提问全部回答: Y. 补全证书链:从微软Azure里购买的通配符证书的二级证书 将下列内容粘贴至证书文件末尾. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 -----BEGIN CERTIFICATE----- MIIE0DCCA7igAwIBAgIBBzANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT EUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp ZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTExMDUwMzA3MDAwMFoXDTMxMDUwMzA3 MDAwMFowgbQxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH EwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjEtMCsGA1UE CxMkaHR0cDovL2NlcnRzLmdvZGFkZHkuY29tL3JlcG9zaXRvcnkvMTMwMQYDVQQD EypHbyBEYWRkeSBTZWN1cmUgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IC0gRzIwggEi MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC54MsQ1K92vdSTYuswZLiBCGzD BNliF44v/z5lz4/OYuY8UhzaFkVLVat4a2ODYpDOD2lsmcgaFItMzEUz6ojcnqOv K/6AYZ15V8TPLvQ/MDxdR/yaFrzDN5ZBUY4RS1T4KL7QjL7wMDge87Am+GZHY23e cSZHjzhHU9FGHbTj3ADqRay9vHHZqm8A29vNMDp5T19MR/gd71vCxJ1gO7GyQ5HY pDNO6rPWJ0+tJYqlxvTV0KaudAVkV4i1RFXULSo6Pvi4vekyCgKUZMQWOlDxSq7n eTOvDCAHf+jfBDnCaQJsY1L6d8EbyHSHyLmTGFBUNUtpTrw700kuH9zB0lL7AgMB AAGjggEaMIIBFjAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNV HQ4EFgQUQMK9J47MNIMwojPX+2yz8LQsgM4wHwYDVR0jBBgwFoAUOpqFBxBnKLbv 9r0FQW4gwZTaD94wNAYIKwYBBQUHAQEEKDAmMCQGCCsGAQUFBzABhhhodHRwOi8v b2NzcC5nb2RhZGR5LmNvbS8wNQYDVR0fBC4wLDAqoCigJoYkaHR0cDovL2NybC5n b2RhZGR5LmNvbS9nZHJvb3QtZzIuY3JsMEYGA1UdIAQ/MD0wOwYEVR0gADAzMDEG CCsGAQUFBwIBFiVodHRwczovL2NlcnRzLmdvZGFkZHkuY29tL3JlcG9zaXRvcnkv MA0GCSqGSIb3DQEBCwUAA4IBAQAIfmyTEMg4uJapkEv/oV9PBO9sPpyIBslQj6Zz 91cxG7685C/b+LrTW+C05+Z5Yg4MotdqY3MxtfWoSKQ7CC2iXZDXtHwlTxFWMMS2 RJ17LJ3lXubvDGGqv+QqG+6EnriDfcFDzkSnE3ANkR/0yBOtg2DZ2HKocyQetawi DsoXiWJYRBuriSUBAA/NxBti21G00w9RKpv0vHP8ds42pM3Z2Czqrpv1KrKQ0U11 GIo/ikGQI31bS/6kA1ibRrLDYGCD+H1QQc7CoZDDu+8CL9IVVO5EFdkKrqeKM+2x LXY2JtwE65/3YR8V3Idv7kaWKK2hJn0KCacuBKONvPi8BDAB -----END CERTIFICATE----- 利用PowerShell导出证书脚本预览: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 Install-Module PowerShellGet -Force Install-Module -Name AzureRM -AllowClobber Set-ExecutionPolicy RemoteSigned Import-Module -Name AzureRM Login-AzureRmAccount $appServiceCertificateName = "" $resourceGroupName = "" $azureLoginEmailId = "" $subscriptionId = "" Set-AzureRmContext -SubscriptionId $subscriptionId $ascResource = Get-AzureRmResource -ResourceName $appServiceCertificateName -ResourceGroupName $resourceGroupName -ResourceType "Microsoft.CertificateRegistration/certificateOrders" -ApiVersion "2015-08-01" $keyVaultId = "" $keyVaultSecretName = "" $certificateProperties=Get-Member -InputObject $ascResource.Properties.certificates[0] -MemberType NoteProperty $certificateName = $certificateProperties[0].Name $keyVaultId = $ascResource.Properties.certificates[0].$certificateName.KeyVaultId $keyVaultSecretName = $ascResource.Properties.certificates[0].$certificateName.KeyVaultSecretName $keyVaultIdParts = $keyVaultId.Split("/") $keyVaultName = $keyVaultIdParts[$keyVaultIdParts.Length - 1] $keyVaultResourceGroupName = $keyVaultIdParts[$keyVaultIdParts.Length - 5] $secret = Get-AzureKeyVaultSecret -VaultName $keyVaultName -Name $keyVaultSecretName $pfxCertObject=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList @([Convert]::FromBase64String($secret.SecretValueText),"", [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable) $pfxPassword = "MoeClub" $currentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath cd $currentDirectory [Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath [io.file]::WriteAllBytes(".\certificate.pfx", $pfxCertObject.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $pfxPassword)) Write-Host "Created an App Service Certificate copy at: $currentDirectory\certificate.pfx" openssl pkcs12 -in certificate.pfx -nokeys -out cert.pem -password pass:$pfxPassword Write-Host "Exported a certificate at: $currentDirectory\cert.pem" openssl pkcs12 -in certificate.pfx -nocerts -nodes -out key.pem -password pass:$pfxPassword Write-Host "Exported a private key at: $currentDirectory\key.pem"
0 notes
Text
Triggering Azure Automation Runbooks using the Azure ARM REST API
There are many ways to start an Azure Automation Runbook. You can start the Runbook from the Azure Portal, using PowerShell cmdlets or a Webhook. And maybe even more.
If you want to call a Runbook from another tool, like OMS or any other tooling supporting web requests you can create a Webhook for the Runbook which to be called from the external tool.
A Webhook allows you to start a particular runbook in Azure Automation through a single HTTP request. This allows external services such as Visual Studio Team Services, GitHub, Microsoft Operations Management Suite Log Analytics, or custom applications to start runbooks without implementing a full solution using the Azure Automation API.
A disadvantage of using a Webhook for an Azure Automation Runbook is the lack of authentication for calling the Webhook. The only security available for calling the Azure Automation Runbook Webhook is the secret token that is generated during the creation of the Webhook.
After creation the URL can't be viewed anymore but anyone knowing the Webhook URL is able to call the Runbook via the Webhook. Provided they also know the needed parameter inputs.
So how could you call an Azure Automation Runbook via a web request using a username and password?
Azure REST API
Azure Resource Manager provides a way for you to deploy and manage the services that make up your applications. For an introduction to deploying and managing resources with Resource Manager, see Azure Resource Manager Overview. Most, but not all, services support Resource Manager, and some services support Resource Manager only partially. Microsoft will enable Resource Manager for every service that is important for future solutions, but until the support is consistent, you need to know the current status for each service. For information about the available services and how to work with them, see Resource Manager providers, regions, API versions and schemas. [*from Azure Resource Manager REST API Reference]
How to call an Azure Automation Runbook with Azure ARM REST API?
So how does the authentication work when you want to to do a web request call against the Azure ARM REST API? You need to supply a bearer Access Token in the request Header of the web request. But how do you get that AccessToken? You can retrieve the AccessToken by creating an Active Directory application and service principal and use a ClientID and ClientSecret to retrieve the AccessToken. We will use PowerShell to create the Service Principal to access resources in Azure.
Create a service principal to access resources
Create the AD application with a password
Create the service principal
Assign the Contributor role to the service principal
#region variables $ADApplicationName = 'demowebrequest' $HomePage = 'http://ift.tt/2etcKN4' $ADApplicationPassword = 'P@ssw0rd!' #endregion #region Login to Azure Add-AzureRmAccount #Select Azure Subscription $subscription = (Get-AzureRmSubscription | Out-GridView ` -Title 'Select an Azure Subscription ...' ` -PassThru) Set-AzureRmContext -SubscriptionId $subscription.Id -TenantId $subscription.TenantID Select-AzureRmSubscription -SubscriptionName $subscription.Name #endregion #region create SPN with Password New-AzureRmADApplication -DisplayName "demowebrequest" -HomePage $ADApplicationName -IdentifierUris $HomePage -Password $ADApplicationPassword -OutVariable app New-AzureRmADServicePrincipal -ApplicationId $app.ApplicationId New-AzureRmRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $app.ApplicationId.Guid Get-AzureRmADApplication -DisplayNameStartWith 'demowebrequest' -OutVariable app Get-AzureRmADServicePrincipal -ServicePrincipalName $app.ApplicationId.Guid -OutVariable SPN #endregion
Remark:
If you want the Service Principal only to manage Automation Runbooks you should give this service account the "Automation Operator" Role and limit access to the Scope where the Automation Account is created.
You now need to follow the steps described in the blog post Using the Azure ARM REST API – Get Access Token.
If you followed the steps described there you should have a ClientId and ClientSecret which are going to be used to Authenticate against the Azure ARM REST API.
You can verify correct authentication using the following commands from bash. An access token is returned.
curl --request POST "http://ift.tt/2vO0z7L" --data-urlencode "resource=http://ift.tt/ORHUID" --data-urlencode "client_id=[clientid]" --data-urlencode "grant_type=client_credentials" --data-urlencode "client_secret=[clientsecret]"
Or if you prefer PowerShell you can use the following commands:
#Azure Authtentication Token #requires -Version 3 #SPN ClientId and Secret $ClientID = "clientid" #ApplicationID $ClientSecret = "ClientSecret" #key from Application $tennantid = "TenantID" $TokenEndpoint = {http://ift.tt/1fZDn6l} -f $tenantid $ARMResource = "http://ift.tt/ORHUID"; $Body = @{ 'resource'= $ARMResource 'client_id' = $ClientID 'grant_type' = 'client_credentials' 'client_secret' = $ClientSecret } $params = @{ ContentType = 'application/x-www-form-urlencoded' Headers = @{'accept'='application/json'} Body = $Body Method = 'Post' URI = $TokenEndpoint } $token = Invoke-RestMethod @params $token | select access_token, @{L='Expires';E={[timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($_.expires_on))}} | fl *
The next step is to call an Azure Automation Runbook using a web request against the Azure REST API with the earlier retrieved access token.
Azure Automation Runbook Web Request
Let's first start with retrieving Azure Automation Runbook information.
Method Request URI GET 'http://ift.tt/2uoY0FF}'
Example web request call using curl from bash:
#!/bin/bash # bash script to retrieve Azure Runbook information using plain Azure ARM REST API web requests #Azure Subscription variables ClientID="[applicatie clientid" #ApplicationID ClientSecret="application client secret" #key from Application TenantID="[azure tenantid]" SubscriptionID="[azure subscriptionid]" ResourceGroupName="[resourcegroup name for azure automation account]" AutomationAccountName="[azure automation account name]" APIVersion="2015-10-31" accesstoken=$(curl -s --header "accept: application/json" --request POST "http://ift.tt/2vNREmB" --data-urlencode "resource=http://ift.tt/ORHUID" --data-urlencode "client_id=$ClientID" --data-urlencode "grant_type=client_credentials" --data-urlencode "client_secret=$ClientSecret" | jq -r '.access_token') #Use AccessToken in Azure ARM REST API call for Runbook Info runbookURI="http://ift.tt/2uoWhjE" curl -s --header "authorization: Bearer $accesstoken" --request GET $runbookURI | jq .
Result running script in WSL (Bash for Windows)
Trigger Azure Automation Runbook with web request:
Simple Hello World Runbook PowerShell Script (HelloWorld.ps1):
[CmdletBinding()] param( $firstname, $lastname ) Write-Output "Hello $firstname $lastname"
This Runbook has two parameters, FirstName and LastName.
If we now want to trigger this Runbook using a web request we need the following information.
Method Request URI POST 'http://ift.tt/2vNIXsn}' BODY
Example web request using curl:
#!/bin/bash # bash script to retrieve Azure Runbook information using plain Azure ARM REST API web requests #Azure Subscription variables ClientID="[applicatie clientid" #ApplicationID ClientSecret="application client secret" #key from Application TenantID="[azure tenantid]" SubscriptionID="[azure subscriptionid]" ResourceGroupName="[resourcegroup name for azure automation account]" AutomationAccountName="[azure automation account name]" APIVersion="2015-10-31" GUID=$(uuidgen) accesstoken=$(curl -s --header "accept: application/json" --request POST "http://ift.tt/2vNREmB" --data-urlencode "resource=http://ift.tt/ORHUID" --data-urlencode "client_id=$ClientID" --data-urlencode "grant_type=client_credentials" --data-urlencode "client_secret=$ClientSecret" | jq -r '.access_token') #Use AccessToken in Azure ARM REST API call for Runbook Info runbookURI="http://ift.tt/2vNJ9rV" curl -s --header "authorization: Bearer $accesstoken" --header "Content-Type: application/json" -d '{"tags":{},"properties":{"runbook":{"name":'"'$RunbookName'"'},"parameters":{"LastName":"Stranger","FirstName":"Stefan"}}}' --request PUT $runbookURI | jq .
Result output:
You can also check the Runbook output in the Azure Portal.
If you prefer to use PowerShell to call the Azure Automation Runbook via the Azure REST API you can use the following code:
#requires -Version 3 # --------------------------------------------------- # Script: CallRunbookFromRESTAPI.ps1 # Version: # Author: Stefan Stranger # Date: 09/08/2017 15:16:25 # Description: Call Azure Automation Runbook using Azure ARM REST API calls. # Comments: http://ift.tt/2uoXZS7 # Changes: # Disclaimer: # This example is provided "AS IS" with no warranty expressed or implied. Run at your own risk. # **Always test in your lab first** Do this at your own risk!! # The author will not be held responsible for any damage you incur when making these changes! # --------------------------------------------------- #region variables $ClientID = '[ClientID]' #ApplicationID $ClientSecret = '[ClientSecret]' #key from Application $tenantid = '[Azure Tenant Id]' $SubscriptionId = '[Azure Subscription Id]' $resourcegroupname = '[Resource Group Automation Account]' $AutomationAccountName = '[Automation Account Name]' $RunbookName = '[Runbook Name]' $APIVersion = '2015-10-31' #endregion #region Get Access Token $TokenEndpoint = {http://ift.tt/1fZDn6l} -f $tenantid $ARMResource = "http://ift.tt/ORHUID"; $Body = @{ 'resource'= $ARMResource 'client_id' = $ClientID 'grant_type' = 'client_credentials' 'client_secret' = $ClientSecret } $params = @{ ContentType = 'application/x-www-form-urlencoded' Headers = @{'accept'='application/json'} Body = $Body Method = 'Post' URI = $TokenEndpoint } $token = Invoke-RestMethod @params #endregion #region get Runbooks $Uri = 'http://ift.tt/2vNSMGU}' -f $SubscriptionId, $resourcegroupname, $AutomationAccountName, $APIVersion $params = @{ ContentType = 'application/x-www-form-urlencoded' Headers = @{ 'authorization' = "Bearer $($token.Access_Token)" } Method = 'Get' URI = $Uri } Invoke-RestMethod @params -OutVariable Runbooks #endregion #region Start Runbook $Uri = 'http://ift.tt/2upnanF}' -f $SubscriptionId, $resourcegroupname, $AutomationAccountName, $((New-Guid).guid), $APIVersion $body = @{ 'properties' = @{ 'runbook' = @{ 'name' = $RunbookName } 'parameters' = @{ 'FirstName' = 'Stefan' 'LastName' = 'Stranger' } } 'tags' = @{} } | ConvertTo-Json $body $params = @{ ContentType = 'application/json' Headers = @{ 'authorization' = "Bearer $($token.Access_Token)" } Method = 'Put' URI = $Uri Body = $body } Invoke-RestMethod @params -OutVariable Runbook $Runbook.properties #endregion #region get Runbook Status $Uri ='http://ift.tt/2vO5sNW' -f $SubscriptionId, $resourcegroupname, $AutomationAccountName, $($Runbook.properties.jobId) $params = @{ ContentType = 'application/application-json' Headers = @{ 'authorization' = "Bearer $($token.Access_Token)" } Method = 'Get' URI = $Uri } Invoke-RestMethod @params -OutVariable Status $Status.properties #endregion
Have fun with calling your Runbooks using web requests against the Azure ARM REST API!
References:
Azure Automation Runbook Webhook lesson learned
What is a Webhooks Push-Styled API and How Does It Work?
Using the Azure ARM REST API – Get Access Token
Using the Azure ARM REST API – Get Subscription Information
Using the Azure ARM REST API – End to end Example Part 1
Using the Azure ARM REST API – End to end Example Part 2
Use Role-Based Access Control to manage access to your Azure subscription resources
from Stefan Stranger's Weblog – Manage your IT Infrastructure http://ift.tt/2updWaF via IFTTT
0 notes