Menu

Virtual Geek

Tales from real IT system administrators world and non-production environment

Create an Azure Automation account on using Portal PowerShell and AzureCLI

Azure Automation Account is Azure resource allows you to automate tasks against services and resources in Azure, on-premises and with other cloud providers such as Amazon Web Services (AWS). You can write and use runbooks to automate your tasks, or a Hybrid Runbook Worker if you have business or operational processes to manage outside of Azure. Working in any one of these environments require permissions to securely access the resources with the minimal rights required.

This is step by step guide to create new Automation Accounts on Microsoft Azure. Start search on portal for Automation Accounts and click on it.

Microsoft Azure quickstart create an Azure automation accounts powershell powercli storage accounts sendgrid azure maps free azure account access control (IAM) deployment.png

Next provide a Name for automation account, The account name must be a unique value. The name can contain only letters, numbers, and hyphens. The name must start with a letter, and it must end with a letter or a number. The account name length must be from 6 to 50 characters. Select Subscription, Resource group and Location.  

If you have chosen not to create a Run As Account. Doing so might block the execution of some runbooks due to lack of access to required resources. Azure Run As Accounts provide a means for authentication in Azure, so that your Azure Runbooks can manage Azure resources. Otherwise, you would need to authenticate to Azure in your Runbook scripts as you would from your own computer remotely. 

Click Create button.

Microsoft Azure Add automation account create an automation accounts subscription resource group location azure run as account sponsership get azure free account contact dsc.png

Creating new Automation Account goes into Microsoft.AutomationAccount Deployment task, it takes few minutes to create it. If you are creating this Resource for first few additional examples runbooks are created for tutorial purpose with name starting AzureAutomationTutorial. You can go directly to resource or check under Resource Group.

Microsoft azure resource group deployments microsoft.AutomationAccount Overview template security center go to resource create an azure account automation deployment.png

Inside the Resource Group where this resource is created, you will see 3 tutorial runbooks created for Powershell and Python version for test.

Azure Automation accounts resource group python playbooks tutorials key vault runbook powershell dsc desired state configuration devops.png

My Azure Automation Account is created sucessfully and there are no activities in it.

Microsoft Azure Automation Account Resource Groups overview script center runbooks desired state configuration dsc update management jobs schedules inventory change tracking.png

Powershell

Here is the process to create an Automation Account with Run As Account using PowerShell. As I am creating it with RunAsAccount, it involves multiple steps. Run As accounts in Azure Automation provide authentication for managing resources on the Azure Resource Manager or Azure Classic deployment model using Automation runbooks and other Automation features. 

Powershell step include

Microsoft azure Portal Automation Account SSL self singned certificate Auatomation account connection azure ad appliction app registrations service principal azure ad acitve directory run as.png

After Automation Account is created you can check Azure Run As Account properties, it is successfully created.

Microsoft Azure portal powershell automation account run as account thumbprint connection application ID subscription Tenant Id service Principal role contributer tutorial runbook.png

While using this script change first few line input from 4 to 9 as per your requirement. Download this script here or it is also available on github.com.

  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
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#Written By - vcloud-lab.com #vJanvi
#Create new Azure Automation Account Run As

$automationAccount = 'AutomationAC01' 
$certExpiryMonths = 24
$certPfxPassword = '123456'
$certExportPath = 'C:\Temp\Certs'
$resourceGroup = 'vCloud-lab.com'
$location = "East Us"

$certPassword = ConvertTo-SecureString $certPfxPassword -AsPlainText -Force

#Region
#Generate SSL certificate
Write-Host "Generate self signed certificate for - $automationAccount"
$selfSignedCertSplat = @{
    DnsName = $automationAccount
    Subject = $automationAccount
    CertStoreLocation = 'cert:\CurrentUser\My' 
    KeyExportPolicy = 'Exportable'
    Provider = 'Microsoft Enhanced RSA and AES Cryptographic Provider'
    NotAfter = (Get-Date).AddMonths($certExpiryMonths) 
    HashAlgorithm = 'SHA256'
}
$selfSignedCert = New-SelfSignedCertificate @selfSignedCertSplat

#Export SSL certificate to files
Write-Host "Export self signed certificate to folder - $certExportPath"
$certThumbPrint = 'cert:\CurrentUser\My\' + $selfSignedCert.Thumbprint
Export-PfxCertificate -Cert $certThumbPrint -FilePath "$certExportPath\$automationAccount.pfx" -Password $certPassword -Force | Write-Verbose
Export-Certificate -Cert $certThumbPrint -FilePath "$certExportPath\$automationAccount.cer" -Type CERT | Write-Verbose
#EndRegion - Generate self signed certificate

#Region
#Read PFX Certificate
Write-Host "Read PFX file"
$pfxCertSplat = @{
    TypeName = 'System.Security.Cryptography.X509Certificates.X509Certificate2'
    ArgumentList = @("$certExportPath\$automationAccount.pfx",  $certPfxPassword)
}
$pfxCert = New-Object @pfxCertSplat

#Create an Azure AD application (App Registrations)
Write-Host "Create Azure AD application - $automationAccount"
$azADAppRegistrationsSplat = @{
    DisplayName = $automationAccount
    HomePage = "http://$automationAccount"
    IdentifierUris = "http://$automationAccount"
}
$azADAppRegistrations = New-AzADApplication @azADAppRegistrationsSplat

#Create Azure active directory Application Credential (App Registrations)
Write-Host "Create credential for Azure AD application - $automationAccount"
$azADAppRegistrationsCredSplat = @{
    ApplicationId = $azADAppRegistrations.ApplicationId
    CertValue = [System.Convert]::ToBase64String($pfxCert.GetRawCertData())
    StartDate = $pfxCert.NotBefore 
    EndDate = $pfxCert.NotAfter
}
[void](New-AzADAppCredential @azADAppRegistrationsCredSplat)

#Azure AD Service Principal
Write-Host "Create Azure AD Service Principal - $automationAccount"
[void](New-AzADServicePrincipal -ApplicationId $azADAppRegistrations.ApplicationId)
Start-Sleep -Seconds 15

#Provide contributer access on Serivce Principal
Write-Host "Assign contributer azure role on Azure AD application / SP - $automationAccount"
$AzRoleAssignment = New-AzRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $azADAppRegistrations.ApplicationId -ErrorAction SilentlyContinue
$i = 0;
While (($null -eq $AzRoleAssignment) -and ($i -le 6)) 
{
    Start-Sleep -Seconds 10
    New-AzRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $azADAppRegistrations.ApplicationId -ErrorAction SilentlyContinue
    $AzRoleAssignment = Get-AzRoleAssignment -ServicePrincipalName $azADAppRegistrations.ApplicationId -ErrorAction SilentlyContinue
    $i++
}
#EndRegion - Azure AD application 

#Region
Write-Host "Create Azure Automation Account - $automationAccount"
[void](New-AzAutomationAccount -Name $automationAccount -Location $location -ResourceGroupName $resourceGroup)

Write-Host "Create Azure Automation Account Run as certificate - $automationAccount"
Start-Sleep -Seconds 15
$azAutomationCertSplat = @{
    ResourceGroupName =  $resourceGroup 
    AutomationAccountName = $automationAccount
    Path = "$certExportPath\$automationAccount.pfx"
    Name = 'AzureRunAsCertificate' #$automationAccount
    Password = $certPassword
    Description = "This certificate is used to authenticate with the service principal that was automatically created for this account. For details on this service principal and certificate, or to recreate them, go to this account’s Settings. For example usage, see the tutorial runbook in this account."
}
[void](New-AzAutomationCertificate @azAutomationCertSplat -Exportable:$true) 

Write-Host "Create Azure Automation Account connection - $automationAccount"
Start-Sleep -Seconds 15
$azSubscriptionContext = Get-AzContext
$azAutomationConnectionSplat = @{
    ResourceGroupName = $resourceGroup
    AutomationAccountName = $automationAccount
    Name = 'AzureRunAsConnection' #$automationAccount
    ConnectionTypeName = 'AzureServicePrincipal'
    Description = "This connection contains information about the service principal that was automatically created for this automation account. For details on this service principal and its certificate, or to recreate them, go to this account’s Settings. For example usage, see the tutorial runbook in this account."
    ConnectionFieldValues = @{
        ApplicationId = $azADAppRegistrations.ApplicationId.Guid
        TenantId = $azSubscriptionContext.Tenant.Id
        CertificateThumbprint = $pfxCert.Thumbprint
        SubscriptionId = $azSubscriptionContext.Subscription
    }
}
[void](New-AzAutomationConnection @azAutomationConnectionSplat)
#EndRegion

AzureCLI

Here is AzureCLI automation account creation one-liner example without Run As Account, If you don't have automation extension installed it will prompt for to download and install it, Also automation account when creating with AzureCLI is experimental and under development.

Microsoft Azure Automation Account Portal az automation account create --automation-account-name --location -sku --resource-group extension azurecli az config dynamic install.png

az automation account create --automation-account-name "AutomationAc02" --location "East US" --sku "Free" --resource-group "vCloud-lab.com"

The command requires the extension automation. Do you want to install it now? The command will continue to run after the extension 
is installed. (Y/n): Y
Run 'az config set extension.use_dynamic_install=yes_without_prompt' to allow installing extensions without prompt.
The installed extension 'automation' is experimental and not covered by customer support. Please use with discretion.
Command group 'automation account' is experimental and under development. Reference and support levels: https://aka.ms/CLI_refstatus
{
  "creationTime": "2021-06-12T05:46:44.293333+00:00",
  "description": null,
  "etag": null,
  "id": "/subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/vCloud-lab.com/providers/Microsoft.Automation/automationAccounts/AutomationAc02",
  "lastModifiedBy": null,
  "lastModifiedTime": "2021-06-12T05:46:44.293333+00:00",
  "location": "eastus",
  "name": "AutomationAc02",
  "resourceGroup": "vCloud-lab.com",
  "sku": {
    "capacity": null,
    "family": null,
    "name": "Basic"
  },
  "state": "Ok",
  "tags": {},
  "type": "Microsoft.Automation/AutomationAccounts"
}

Useful Information
Create an Azure App registrations in Azure Active Directory using PowerShell & AzureCLI
Get started and configure with certificate-based authentication in Azure
Create a Virtual machine on Microsoft Azure
PowerShell List All Azure Resverations
Powershell get the list of Azure Reservations Virtual Machines instances
Get the list Azure Reservation Catalog with PowerShell and AzureCLI
Azure automation account DSC for On-Premise Virtual Machine on boarding
Azure Powershell : Operation returned an invalid status code 'BadRequest'
Get Azure virtual machine backup reports using Powershell

Go Back

Comment

Blog Search

Page Views

5937386

Follow me on Blogarama