Skip to content

Commit 08c3ad4

Browse files
authored
Merge pull request #226485 from SnehaSudhirG/07Feb-Pythontutorial-docupdate
Feedback incorporated
2 parents 22e0804 + fdbc481 commit 08c3ad4

File tree

1 file changed

+90
-85
lines changed

1 file changed

+90
-85
lines changed

articles/automation/learn/automation-tutorial-runbook-textual-python-3.md

Lines changed: 90 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
---
2-
title: Create a Python 3 runbook (preview) in Azure Automation
3-
description: This article teaches you to create, test, and publish a simple Python 3 runbook (preview) in your Azure Automation account.
2+
title: Create a Python 3.8 runbook (preview) in Azure Automation
3+
description: This article teaches you to create, test, and publish a simple Python 3.8 runbook (preview) in your Azure Automation account.
44
services: automation
55
ms.subservice: process-automation
6-
ms.date: 04/28/2021
6+
ms.date: 02/07/2023
77
ms.topic: tutorial
88
ms.custom: has-adal-ref, devx-track-python, py-fresh-zinc
99
---
1010

11-
# Tutorial: Create a Python 3 runbook (preview)
11+
# Tutorial: Create a Python 3.8 runbook (preview)
1212

13-
This tutorial walks you through the creation of a [Python 3 runbook](../automation-runbook-types.md#python-runbooks) (preview) in Azure Automation. Python runbooks compile under Python 2 and 3. You can directly edit the code of the runbook using the text editor in the Azure portal.
13+
This tutorial walks you through the creation of a [Python 3.8 runbook](../automation-runbook-types.md#python-runbooks) (preview) in Azure Automation. Python runbooks compile under Python 2.7 and 3.8 You can directly edit the code of the runbook using the text editor in the Azure portal.
1414

1515
> [!div class="checklist"]
1616
> * Create a simple Python runbook
@@ -20,31 +20,35 @@ This tutorial walks you through the creation of a [Python 3 runbook](../automati
2020
2121
## Prerequisites
2222

23-
To complete this tutorial, you need the following:
23+
To complete this tutorial, you need:
2424

25-
- Azure subscription. If you don't have one yet, you can [activate your MSDN subscriber benefits](https://azure.microsoft.com/pricing/member-offers/msdn-benefits-details/) or sign up for a [free account](https://azure.microsoft.com/free/?WT.mc_id=A261C142F).
25+
- An Azure subscription. If you don't have one yet, you can [activate your MSDN subscriber benefits](https://azure.microsoft.com/pricing/member-offers/msdn-benefits-details/) or sign up for a [free account](https://azure.microsoft.com/free/?WT.mc_id=A261C142F).
2626

27-
- [Automation account](../automation-security-overview.md) to hold the runbook and authenticate to Azure resources. This account must have permission to start and stop the virtual machine. The [Run As account](../automation-security-overview.md#run-as-accounts) is required for this tutorial.
28-
29-
- An Azure virtual machine. During this tutorial, you will start and stop this machine, so it should not be a production VM.
27+
- An [Automation account](../automation-security-overview.md) to hold the runbook and authenticate to Azure resources using Managed Identities. A managed identity is automatically created for you when you create the Automation account.
28+
29+
- An Azure virtual machine. During this tutorial, you'll start and stop this machine, so it shouldn't be a production VM.
3030

3131
## Create a new runbook
3232

3333
You start by creating a simple runbook that outputs the text *Hello World*.
3434

3535
1. In the Azure portal, open your Automation account.
3636

37-
The Automation account page gives you a quick view of the resources in this account. You should already have some assets. Most of those assets are the modules that are automatically included in a new Automation account. You should also have the Run As account credential asset that's mentioned in the [prerequisites](#prerequisites).
37+
The Automation account page gives you a quick view of the resources in this account. You should already have some assets. Most of those assets are the modules that are automatically included in a new Automation account.
38+
39+
You should also have a managed identity enabled that's mentioned in the [prerequisites](#prerequisites). You can verify that by viewing the **Identity** resource under **Account Settings**.
3840

39-
2. Select **Runbooks** under **Process Automation** to open the list of runbooks.
41+
1. Select **Runbooks** under **Process Automation** to open the list of runbooks.
4042

41-
3. Select **Add a runbook** to create a new runbook.
43+
1. Select **Create a runbook** to create a new runbook.
4244

43-
4. Give the runbook the name **MyFirstRunbook-Python**.
45+
1. Give the runbook the name **MyFirstRunbook-Python**.
4446

45-
5. Select **Python 3** for **Runbook type**.
47+
1. Select **Python** for the **Runbook type**.
4648

47-
6. Select **Create** to create the runbook and open the textual editor.
49+
1. Select **Python 3.8** for the **Runtime version**.
50+
51+
1. Select **Create** to create the runbook and open the textual editor.
4852

4953
## Add code to the runbook
5054

@@ -62,116 +66,117 @@ Before you publish the runbook to make it available in production, you want to t
6266

6367
1. Select **Test pane** to open the **Test** pane.
6468

65-
2. Select **Start** to start the test. This should be the only enabled option.
69+
1. Select **Start** to start the test. This option should be the only enabled option.
6670

67-
3. A [runbook job](../automation-runbook-execution.md) is created and its status displayed.
68-
The job status starts as **Queued**, indicating that it is waiting for a runbook worker in the cloud to become available. It changes to **Starting** when a worker claims the job, and then **Running** when the runbook actually starts running.
71+
1. A [runbook job](../automation-runbook-execution.md) is created and its status displayed.
72+
The job status starts as **Queued**, indicating that it's waiting for a runbook worker in the cloud to become available. It changes to **Starting** when a worker claims the job, and then **Running** when the runbook actually starts running.
6973

70-
4. When the runbook job completes, its output is displayed. In this case, you should see `Hello World`.
74+
1. When the runbook job completes, its output is displayed. In this case, you should see `Hello World`.
7175

72-
5. Close the **Test** pane to return to the canvas.
76+
1. Close the **Test** pane to return to the canvas.
7377

7478
## Publish and start the runbook
7579

7680
The runbook that you created is still in draft mode. You need to publish it before you can run it in production. When you publish a runbook, you overwrite the existing published version with the draft version. In this case, you don't have a published version yet because you just created the runbook.
7781

7882
1. Select **Publish** to publish the runbook and then **Yes** when prompted.
7983

80-
2. If you scroll left to view the runbook on the **Runbooks** page, you should see an **Authoring Status** of **Published**.
84+
1. If you close the **MyFirstRunbook_python** pane, you are back on the **Runbooks** page where you should see an **Authoring Status** of **Published**.
8185

82-
3. Scroll back to the right to view the pane for **MyFirstRunbook-Python3**.
86+
1. Select the **MyFirstRunbook-Python** name in the list, you'll go back into the **MyFirstRunbook-Python** pane.
8387

84-
The options across the top allow you to start the runbook, view the runbook, or schedule it to start at some time in the future.
88+
The options across the top allow you to start the runbook, view the runbook, edit the runbook, schedule it to start at some time in the future, and other actions.
8589

86-
4. Select **Start** and then select **OK** when the **Start Runbook** pane opens.
90+
1. Select **Start** and then select **OK** when the **Start Runbook** pane opens.
8791

88-
5. A **Job** pane is opened for the runbook job that you created. You can close this pane, but let's leave it open so that you can watch the job's progress.
92+
1. A **Job** pane is opened for the runbook job that you created. You can close this pane, but let's keep it open, so that you can watch the job's progress.
8993

90-
6. The job status is shown in **Job Summary** and matches the statuses that you saw when you tested the runbook.
94+
1. The job status is shown in **Status** field under **Essentials**. The values here match the status values when you tested the runbook.
9195

92-
7. Once the runbook status shows **Completed**, select **Output**. The **Output** pane is opened, where you can see `Hello World`.
96+
1. Once the runbook status shows **Completed**, select the **Output** tab. In the **Output** tab, you can see `Hello World`.
9397

94-
8. Close the **Output** pane.
98+
1. Close the **Output** tab.
9599

96-
9. Select **All Logs** to open the **Streams** pane for the runbook job. You should only see `Hello World` in the Output stream. However, this pane can show other streams for a runbook job, such as **Verbose** and **Error**, if the runbook writes to them.
100+
1. Select **All Logs** tab to view streams for the runbook job. You should only see `Hello World` in the output stream. However, this tab can show other streams for a runbook job, such as **Verbose** and **Error**, if the runbook writes to them.
97101

98-
10. Close the **Streams** pane and the **Job** pane to return to the **MyFirstRunbook-Python3** pane.
102+
1. Close the **Jobs** pane to return to the **MyFirstRunbook-Python** pane.
99103

100-
11. Select **Jobs** to open the **Jobs** page for this runbook. This page lists all jobs created by this runbook. You should only see one job listed since you only ran the job once.
104+
1. Select **Jobs** resource to open the **Jobs** resource page for this runbook. This page lists all jobs created by this runbook. You should only see one job listed since you only ran the job once.
101105

102-
12. You can select this job to open the same **Job** pane that you viewed when you started the runbook. This pane allows you to go back in time and view the details of any job that was created for a particular runbook.
106+
1. You can select this job to open the same **Job** pane that you viewed when you started the runbook. This pane allows you to go back in time and view the details of any job that was created for a particular runbook.
103107

104108
## Add authentication to manage Azure resources
105109

106-
You've tested and published your runbook, but so far it doesn't do anything useful. You want to have it manage Azure resources.
107-
To do this, the script has to authenticate using the Run As account credential from your Automation account.
110+
You've tested and published your runbook, but so far it doesn't do anything useful. You want to have it manage Azure resources. To manage resources, the script has to authenticate.
111+
112+
The recommended way to authenticate is with **managed identity**. When you create an Azure Automation Account, a managed identity is automatically created for you.
113+
114+
To use these samples, [add the following packages](../python-3-packages.md) in the **Python Packages** resource of the Automation Account. You can add the WHL files for these packages with these links.
115+
116+
* [azure-core](https://pypi.org/project/azure-core/#files)
117+
* [azure-identity](https://pypi.org/project/azure-identity/#files)
118+
* [azure-mgmt-compute](https://pypi.org/project/azure-mgmt-compute/#files)
119+
* [azure-mgmt-core](https://pypi.org/project/azure-mgmt-core/#files)
120+
* [msal](https://pypi.org/project/msal/#files)
121+
* [typing-extensions](https://pypi.org/project/typing-extensions/#files)
122+
123+
When you add these packages, select a runtime version that matches your runbook.
108124

109125
> [!NOTE]
110-
> The Automation account must have been created with the Run As account for there to be a Run As certificate.
111-
> If your Automation account was not created with the Run As account, you can authenticate as described in
112-
> [Authenticate with the Azure Management Libraries for Python](/azure/developer/python/sdk/authentication-overview) or [create a Run As account](../create-run-as-account.md).
126+
> The following code was tested with runtime version 3.8.
127+
128+
### Managed identity
113129

114-
1. Open the textual editor by selecting **Edit** on the **MyFirstRunbook-Python3** pane.
130+
To use managed identity, ensure that it is enabled:
131+
132+
* To verify if the Managed identity is enabled for the Automation account go to your **Automation account** > **Account Settings** > **Identity** and set the **Status** to **On**.
133+
* The managed identity has a role assigned to manage the resource. In this example of managing a virtual machine resource, add the "Virtual Machine Contributor" role on the resource group of that contains the Virtual Machine. For more information, see [Assign Azure roles using the Azure portal](../../role-based-access-control/role-assignments-portal.md)
134+
135+
With the manage identity role configured, you can start adding code.
136+
137+
1. Open the textual editor by selecting **Edit** on the **MyFirstRunbook-Python** pane.
115138

116139
2. Add the following code to authenticate to Azure:
117140

118-
```python
119-
import os
120-
from azure.mgmt.compute import ComputeManagementClient
121-
import azure.mgmt.resource
122-
import automationassets
123-
124-
def get_automation_runas_credential(runas_connection):
125-
from OpenSSL import crypto
126-
import binascii
127-
from msrestazure import azure_active_directory
128-
import adal
129-
130-
# Get the Azure Automation RunAs service principal certificate
131-
cert = automationassets.get_automation_certificate("AzureRunAsCertificate")
132-
pks12_cert = crypto.load_pkcs12(cert)
133-
pem_pkey = crypto.dump_privatekey(crypto.FILETYPE_PEM,pks12_cert.get_privatekey())
134-
135-
# Get run as connection information for the Azure Automation service principal
136-
application_id = runas_connection["ApplicationId"]
137-
thumbprint = runas_connection["CertificateThumbprint"]
138-
tenant_id = runas_connection["TenantId"]
139-
140-
# Authenticate with service principal certificate
141-
resource ="https://management.core.windows.net/"
142-
authority_url = ("https://login.microsoftonline.com/"+tenant_id)
143-
context = adal.AuthenticationContext(authority_url)
144-
return azure_active_directory.AdalAuthentication(
145-
lambda: context.acquire_token_with_client_certificate(
146-
resource,
147-
application_id,
148-
pem_pkey,
149-
thumbprint)
150-
)
151-
152-
# Authenticate to Azure using the Azure Automation RunAs service principal
153-
runas_connection = automationassets.get_automation_connection("AzureRunAsConnection")
154-
azure_credential = get_automation_runas_credential(runas_connection)
155-
```
141+
```python
142+
#!/usr/bin/env python3
143+
from azure.identity import DefaultAzureCredential
144+
from azure.mgmt.compute import ComputeManagementClient
145+
146+
SUBSCRIPTION_ID="YOUR_SUBSCRIPTION_ID"
147+
148+
azure_credential = DefaultAzureCredential()
149+
150+
import os
151+
import requests
152+
# printing environment variables
153+
endpoint = os.getenv('IDENTITY_ENDPOINT')+"?resource=https://management.azure.com/"
154+
identityHeader = os.getenv('IDENTITY_HEADER')
155+
payload={}
156+
headers = {
157+
'X-IDENTITY-HEADER' : identityHeader,
158+
'Metadata' : True
159+
}
160+
response = requests.get(endpoint, headers)
161+
print(response.text)
162+
```
156163

157164
## Add code to create Python Compute client and start the VM
158165

159166
To work with Azure VMs, create an instance of the [Azure Compute client for Python](/python/api/azure-mgmt-compute/azure.mgmt.compute.computemanagementclient).
160167

161-
Use the compute client to start the VM. Add the following code to the runbook:
162-
163168
```python
164-
# Initialize the compute management client with the Run As credential and specify the subscription to work against.
169+
# Initialize client with the credential and subscription.
165170
compute_client = ComputeManagementClient(
166171
azure_credential,
167-
str(runas_connection["SubscriptionId"])
172+
SUBSCRIPTION_ID
168173
)
169174

170-
171175
print('\nStart VM')
172-
async_vm_start = compute_client.virtual_machines.start(
176+
async_vm_start = compute_client.virtual_machines.begin_start(
173177
"MyResourceGroup", "TestVM")
174178
async_vm_start.wait()
179+
print('\nFinished start.')
175180
```
176181

177182
Where `MyResourceGroup` is the name of the resource group that contains the VM, and `TestVM` is the name of the VM that you want to start.
@@ -191,12 +196,12 @@ resource_group_name = str(sys.argv[1])
191196
vm_name = str(sys.argv[2])
192197
```
193198

194-
This imports the `sys` module, and creates two variables to hold the resource group and VM names. Notice that the element of the argument list, `sys.argv[0]`, is the name of the script, and is not input by the user.
199+
This code imports the `sys` module, and creates two variables to hold the resource group and VM names. Notice that the element of the argument list, `sys.argv[0]`, is the name of the script, and isn't input by the user.
195200

196201
Now you can modify the last two lines of the runbook to use the input parameter values instead of using hard-coded values:
197202

198203
```python
199-
async_vm_start = compute_client.virtual_machines.start(
204+
async_vm_start = compute_client.virtual_machines.begin_start(
200205
resource_group_name, vm_name)
201206
async_vm_start.wait()
202207
```

0 commit comments

Comments
 (0)