Skip to content

Instantly share code, notes, and snippets.

@tyconsulting
Created June 14, 2017 01:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tyconsulting/99ac239c4b7522917c89cc80be097f23 to your computer and use it in GitHub Desktop.
Save tyconsulting/99ac239c4b7522917c89cc80be097f23 to your computer and use it in GitHub Desktop.
Sample PowerShell script to create Azure Automation runbook webhook that is targeting a Hybrid Worker group
#Function to generate Azure AD authorization token for the ARM rest API
Function Get-AADToken {
[CmdletBinding()]
[OutputType([string])]
PARAM (
[Parameter(Position=0,Mandatory=$true)]
[ValidateScript({
try
{
[System.Guid]::Parse($_) | Out-Null
$true
}
catch
{
$false
}
})]
[Alias('tID')]
[String]$TenantID,
[Parameter(Position=1,Mandatory=$true)][Alias('cred')]
[pscredential]
[System.Management.Automation.CredentialAttribute()]
$Credential,
[Parameter(Position=0,Mandatory=$false)][Alias('type')]
[ValidateSet('UserPrincipal', 'ServicePrincipal')]
[String]$AuthenticationType = 'UserPrincipal'
)
Try
{
$Username = $Credential.Username
$Password = $Credential.Password
If ($AuthenticationType -ieq 'UserPrincipal')
{
# Set well-known client ID for Azure PowerShell
$clientId = '1950a258-227b-4e31-a9cf-717495945fc2'
# Set Resource URI to Azure Service Management API
$resourceAppIdURI = 'https://management.azure.com/'
# Set Authority to Azure AD Tenant
$authority = 'https://login.microsoftonline.com/common/' + $TenantID
Write-Verbose "Authority: $authority"
$AADcredential = [Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential]::new($UserName, $Password)
$authContext = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext]::new($authority)
$authResult = $authContext.AcquireTokenAsync($resourceAppIdURI,$clientId,$AADcredential)
$Token = $authResult.Result.CreateAuthorizationHeader()
} else {
# Set Resource URI to Azure Service Management API
$resourceAppIdURI = 'https://management.core.windows.net/'
# Set Authority to Azure AD Tenant
$authority = 'https://login.windows.net/' + $TenantId
$ClientCred = [Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential]::new($UserName, $Password)
$authContext = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext]::new($authority)
$authResult = $authContext.AcquireTokenAsync($resourceAppIdURI,$ClientCred)
$Token = $authResult.Result.CreateAuthorizationHeader()
}
}
Catch
{
Throw $_
$ErrorMessage = 'Failed to aquire Azure AD token.'
Write-Error -Message 'Failed to aquire Azure AD token'
}
$Token
}
#Variables for your Azure subscription and Automation Account
$subscriptionId = 'specify-your-subscription-id'
$AADTenantId = 'specify-your-AAD-tenant-id'
$resourceGroup = 'specify-resource-group-name-for-azure-automation-account'
$automationAccount = 'specify-azure-automation-account-name'
$HybridWorkerGroup = 'specify-hybrid-worker-group-name'
#Specify an organization account to sign in to Azure (using AAD token)
$AzureAdminUserName = 'admin@yourcompany.onmicrosoft.com'
$AzureAdminPassword = Read-Host "Enter password for $AzureAdminUserName" -AsSecureString
$AzureAdminCred = New-object System.Management.Automation.PSCredential($AzureAdminUserName, $AzureAdminPassword)
#Generate AAD token and construct HTTP request header
$AADToken = Get-AADToken -TenantID $AADTenantId -Credential $AzureAdminCred
$RESTAPIHeaders = $RESTAPIHeaders = @{'Authorization'=$AADToken;'Accept'='application/json'; 'Content-Type'='application/json'}
#Specify Runbook information
$runbookName = 'HelloWorld'
$runbookParameters = @{
Name = 'Tao'
}
$webhookName = "$runbookName_$HybridWorkerGroup"
#Generate webhook URI
$GenerateWebhookURIRequestURI = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.Automation/automationAccounts/$automationAccount/webhooks/generateUri?api-version=2015-10-31"
$WebhookUriRequest = Invoke-WebRequest -UseBasicParsing -Uri $GenerateWebhookURIRequestURI -Method Post -Headers $RESTAPIHeaders
If ($WebhookUriRequest.StatusCode -ge 200 -and $WebhookUriRequest.StatusCode -le 299)
{
#request successful
$WebhookUri = ($WebhookUriRequest.Content.TrimStart('"')).trimEnd('"')
} else {
Throw "Failed to generate the webhook URI."
}
#Create webhook that expires in 10 years
$UTCNow = [Datetime]::UtcNow
$webhookExpiryDate = $UTCNow.AddYears(10)
$NewWebHookRequestURI = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.Automation/automationAccounts/$automationAccount/webhooks/$webhookName`?api-version=2015-10-31"
$webhookrequestbody = @{
name = $webhookName
properties = @{
isEnabled = $true
Uri = $webhookuri
expiryTime = $webhookExpiryDate
runbook = @{
name = $runbookName
}
runOn = $HybridWorkerGroup
parameters = $runbookParameters
}
}
$webhookrequestbodyjson = $webhookrequestbody | ConvertTo-Json
$NewWebhookRequest = Invoke-WebRequest -UseBasicParsing -Uri $NewWebHookRequestURI -Headers $RESTAPIHeaders -Method Put -Body $webhookrequestbodyjson
If ($NewWebhookRequest.StatusCode -ge 200 -and $NewWebhookRequest.StatusCode -le 299)
{
Write-Output "Webhook created. URL: '$webookuri'"
} else {
Throw "Failed to create the webhook."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment