Skip to content

Commit 80927ab

Browse files
committed
Add python deploy template
1 parent 907ffe3 commit 80927ab

File tree

2 files changed

+348
-0
lines changed

2 files changed

+348
-0
lines changed
Lines changed: 345 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,345 @@
1+
---
2+
title: Deploy resources with Python and template
3+
description: Use Azure Resource Manager and Python to deploy resources to Azure. The resources are defined in an Azure Resource Manager template.
4+
ms.topic: conceptual
5+
ms.date: 04/24/2023
6+
ms.custom: devx-track-azurepowershell, devx-track-arm-template, ai-gen-docs
7+
---
8+
9+
# Deploy resources with ARM templates and Python
10+
11+
This article explains how to use Python with Azure Resource Manager templates (ARM templates) to deploy your resources to Azure. If you aren't familiar with the concepts of deploying and managing your Azure solutions, see [template deployment overview](overview.md).
12+
13+
[!INCLUDE [AI attribution](../../../includes/ai-generated-attribution.md)]
14+
15+
## Prerequisites
16+
17+
* A template to deploy. If you don't already have one, download and save an [example template](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/quickstarts/microsoft.storage/storage-account-create/azuredeploy.json) from the Azure Quickstart templates repo.
18+
19+
* Python 3.7 or later installed. To install the latest, see [Python.org](https://www.python.org/downloads/)
20+
21+
* The following Azure library packages for Python installed in your virtual environment. To install any of the packages, use `pip install {package-name}`
22+
* azure-identity
23+
* azure-mgmt-resource
24+
* azure-mgmt-storage
25+
26+
If you have older versions of these packages already installed in your virtual environment, you may need to update them with `pip install --upgrade {package-name}`
27+
28+
* The examples in this article use CLI-based authentication (`AzureCliCredential`). Depending on your environment, you may need to run `az login` first to authenticate.
29+
30+
[!INCLUDE [permissions](../../../includes/template-deploy-permissions.md)]
31+
32+
## Deployment scope
33+
34+
You can target your deployment to a resource group, subscription, management group, or tenant. Depending on the scope of the deployment, you use different methods.
35+
36+
* To deploy to a **resource group**, use [ResourceManagementClient.deployments.begin_create_or_update](/python/api/azure-mgmt-resource/azure.mgmt.resource.resources.v2022_09_01.operations.deploymentsoperations#azure-mgmt-resource-resources-v2022-09-01-operations-deploymentsoperations-begin-create-or-update):
37+
38+
* To deploy to a **subscription**, use [ResourceManagementClient.deployments.begin_create_or_update_at_subscription_scope](/python/api/azure-mgmt-resource/azure.mgmt.resource.resources.v2022_09_01.operations.deploymentsoperations#azure-mgmt-resource-resources-v2022-09-01-operations-deploymentsoperations-begin-create-or-update-at-subscription-scope):
39+
40+
For more information about subscription level deployments, see [Create resource groups and resources at the subscription level](deploy-to-subscription.md).
41+
42+
* To deploy to a **management group**, use [ResourceManagementClient.deployments.begin_create_or_update_at_management_group_scope](/python/api/azure-mgmt-resource/azure.mgmt.resource.resources.v2022_09_01.operations.deploymentsoperations#azure-mgmt-resource-resources-v2022-09-01-operations-deploymentsoperations-begin-create-or-update-at-management-group-scope).
43+
44+
For more information about management group level deployments, see [Create resources at the management group level](deploy-to-management-group.md).
45+
46+
* To deploy to a **tenant**, use [ResourceManagementClient.deployments.begin_create_or_update_at_tenant_scope](/python/api/azure-mgmt-resource/azure.mgmt.resource.resources.v2022_09_01.operations.deploymentsoperations#azure-mgmt-resource-resources-v2022-09-01-operations-deploymentsoperations-begin-create-or-update-at-tenant-scope).
47+
48+
For more information about tenant level deployments, see [Create resources at the tenant level](deploy-to-tenant.md).
49+
50+
For every scope, the user deploying the template must have the required permissions to create resources.
51+
52+
## Deployment name
53+
54+
When deploying an ARM template, you can give the deployment a name. This name can help you retrieve the deployment from the deployment history. If you don't provide a name for the deployment, the name of the template file is used. For example, if you deploy a template named `azuredeploy.json` and don't specify a deployment name, the deployment is named `azuredeploy`.
55+
56+
Every time you run a deployment, an entry is added to the resource group's deployment history with the deployment name. If you run another deployment and give it the same name, the earlier entry is replaced with the current deployment. If you want to maintain unique entries in the deployment history, give each deployment a unique name.
57+
58+
To create a unique name, you can assign a random number.
59+
60+
```python
61+
import random
62+
63+
suffix = random.randint(1, 1000)
64+
deployment_name = f"ExampleDeployment{suffix}"
65+
```
66+
67+
Or, add a date value.
68+
69+
```python
70+
from datetime import datetime
71+
72+
today = datetime.now().strftime("%m-%d-%Y")
73+
deployment_name = f"ExampleDeployment{today}"
74+
```
75+
76+
If you run concurrent deployments to the same resource group with the same deployment name, only the last deployment is completed. Any deployments with the same name that haven't finished are replaced by the last deployment. For example, if you run a deployment named `newStorage` that deploys a storage account named `storage1`, and at the same time run another deployment named `newStorage` that deploys a storage account named `storage2`, you deploy only one storage account. The resulting storage account is named `storage2`.
77+
78+
However, if you run a deployment named `newStorage` that deploys a storage account named `storage1`, and immediately after it completes you run another deployment named `newStorage` that deploys a storage account named `storage2`, then you have two storage accounts. One is named `storage1`, and the other is named `storage2`. But, you only have one entry in the deployment history.
79+
80+
When you specify a unique name for each deployment, you can run them concurrently without conflict. If you run a deployment named `newStorage1` that deploys a storage account named `storage1`, and at the same time run another deployment named `newStorage2` that deploys a storage account named `storage2`, then you have two storage accounts and two entries in the deployment history.
81+
82+
To avoid conflicts with concurrent deployments and to ensure unique entries in the deployment history, give each deployment a unique name.
83+
84+
## Deploy local template
85+
86+
You can deploy a template from your local machine or one that is stored externally. This section describes deploying a local template.
87+
88+
If you're deploying to a resource group that doesn't exist, create the resource group. The name of the resource group can only include alphanumeric characters, periods, underscores, hyphens, and parenthesis. It can be up to 90 characters. The name can't end in a period.
89+
90+
```python
91+
import os
92+
from azure.identity import AzureCliCredential
93+
from azure.mgmt.resource import ResourceManagementClient
94+
95+
credential = AzureCliCredential()
96+
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
97+
98+
resource_client = ResourceManagementClient(credential, subscription_id)
99+
100+
rg_result = resource_client.resource_groups.create_or_update(
101+
"ExampleGroup",
102+
{
103+
"location": "Central US"
104+
}
105+
)
106+
107+
print(f"Provisioned resource group with ID: {rg_result.id}")
108+
```
109+
110+
To deploy an ARM template, use [ResourceManagementClient.deployments.begin_create_or_update](/python/api/azure-mgmt-resource/azure.mgmt.resource.resources.v2022_09_01.operations.deploymentsoperations#azure-mgmt-resource-resources-v2022-09-01-operations-deploymentsoperations-begin-create-or-update). The following example requires a local template named `storage.json`.
111+
112+
```python
113+
import os
114+
import json
115+
from azure.identity import AzureCliCredential
116+
from azure.mgmt.resource import ResourceManagementClient
117+
from azure.mgmt.resource.resources.models import DeploymentMode
118+
119+
credential = AzureCliCredential()
120+
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
121+
122+
resource_client = ResourceManagementClient(credential, subscription_id)
123+
124+
with open("storage.json", "r") as template_file:
125+
template_body = json.load(template_file)
126+
127+
rg_deployment_result = resource_client.deployments.begin_create_or_update(
128+
"exampleGroup",
129+
"exampleDeployment",
130+
{
131+
"properties": {
132+
"template": template_body,
133+
"parameters": {
134+
"storagePrefix": {
135+
"value": "demostore"
136+
},
137+
},
138+
"mode": DeploymentMode.incremental
139+
}
140+
}
141+
)
142+
```
143+
144+
The deployment can take several minutes to complete.
145+
146+
## Deploy remote template
147+
148+
Instead of storing ARM templates on your local machine, you may prefer to store them in an external location. You can store templates in a source control repository (such as GitHub). Or, you can store them in an Azure storage account for shared access in your organization.
149+
150+
If you're deploying to a resource group that doesn't exist, create the resource group. The name of the resource group can only include alphanumeric characters, periods, underscores, hyphens, and parenthesis. It can be up to 90 characters. The name can't end in a period.
151+
152+
```python
153+
import os
154+
from azure.identity import AzureCliCredential
155+
from azure.mgmt.resource import ResourceManagementClient
156+
157+
credential = AzureCliCredential()
158+
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
159+
160+
resource_client = ResourceManagementClient(credential, subscription_id)
161+
162+
rg_result = resource_client.resource_groups.create_or_update(
163+
"ExampleGroup",
164+
{
165+
"location": "Central US"
166+
}
167+
)
168+
169+
print(f"Provisioned resource group with ID: {rg_result.id}")
170+
```
171+
172+
To deploy an ARM template, use [ResourceManagementClient.deployments.begin_create_or_update](/python/api/azure-mgmt-resource/azure.mgmt.resource.resources.v2022_09_01.operations.deploymentsoperations#azure-mgmt-resource-resources-v2022-09-01-operations-deploymentsoperations-begin-create-or-update). The following example deploys a [remote template](https://github.com/Azure/azure-quickstart-templates/tree/master/quickstarts/microsoft.storage/storage-account-create). That template creates a storage account.
173+
174+
```python
175+
import os
176+
from azure.identity import AzureCliCredential
177+
from azure.mgmt.resource import ResourceManagementClient
178+
from azure.mgmt.resource.resources.models import DeploymentMode
179+
180+
credential = AzureCliCredential()
181+
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
182+
183+
resource_client = ResourceManagementClient(credential, subscription_id)
184+
185+
resource_group_name = "exampleGroup"
186+
location = "westus"
187+
template_uri = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/quickstarts/microsoft.storage/storage-account-create/azuredeploy.json"
188+
189+
rg_deployment_result = resource_client.deployments.begin_create_or_update(
190+
resource_group_name,
191+
"exampleDeployment",
192+
{
193+
"properties": {
194+
"templateLink": {
195+
"uri": template_uri
196+
},
197+
"parameters": {
198+
"location": {
199+
"value": location
200+
}
201+
},
202+
"mode": DeploymentMode.incremental
203+
}
204+
}
205+
)
206+
```
207+
208+
The preceding example requires a publicly accessible URI for the template, which works for most scenarios because your template shouldn't include sensitive data. If you need to specify sensitive data (like an admin password), pass that value as a secure parameter. However, if you want to manage access to the template, consider using [template specs](#deploy-template-spec).
209+
210+
To deploy a protected, remote template, add a SAS token.
211+
212+
```python
213+
import os
214+
from azure.identity import AzureCliCredential
215+
from azure.mgmt.resource import ResourceManagementClient
216+
from azure.mgmt.resource.resources.models import DeploymentMode
217+
218+
credential = AzureCliCredential()
219+
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
220+
sas_token = os.environ["SAS_TOKEN"]
221+
222+
resource_client = ResourceManagementClient(credential, subscription_id)
223+
224+
resource_group_name = "exampleGroup"
225+
location = "westus"
226+
template_uri = f"https://stage20230425.blob.core.windows.net/templates/storage.json?{sas_token}"
227+
228+
rg_deployment_result = resource_client.deployments.begin_create_or_update(
229+
resource_group_name,
230+
"exampleDeployment",
231+
{
232+
"properties": {
233+
"templateLink": {
234+
"uri": template_uri
235+
},
236+
"parameters": {
237+
"location": {
238+
"value": location
239+
}
240+
},
241+
"mode": DeploymentMode.incremental
242+
}
243+
}
244+
)
245+
```
246+
247+
For more information, see [Use relative path for linked templates](./linked-templates.md#linked-template).
248+
249+
## Deploy template spec
250+
251+
Instead of deploying a local or remote template, you can create a [template spec](template-specs.md). The template spec is a resource in your Azure subscription that contains an ARM template. It makes it easy to securely share the template with users in your organization. You use Azure role-based access control (Azure RBAC) to grant access to the template spec. This feature is currently in preview.
252+
253+
The following examples show how to create and deploy a template spec.
254+
255+
First, create the template spec by providing the ARM template.
256+
257+
```python
258+
import os
259+
import json
260+
from azure.identity import AzureCliCredential
261+
from azure.mgmt.resource.templatespecs import TemplateSpecsClient
262+
from azure.mgmt.resource.templatespecs.models import TemplateSpecVersion, TemplateSpec
263+
264+
credential = AzureCliCredential()
265+
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
266+
267+
template_specs_client = TemplateSpecsClient(credential, subscription_id)
268+
269+
template_spec = TemplateSpec(
270+
location="westus2",
271+
description="Storage Spec"
272+
)
273+
274+
template_specs_client.template_specs.create_or_update(
275+
"templateSpecsRG",
276+
"storageSpec",
277+
template_spec
278+
)
279+
280+
with open("c:/bicep/storage.json", "r") as template_file:
281+
template_body = json.load(template_file)
282+
283+
version = TemplateSpecVersion(
284+
location="westus2",
285+
description="Storage Spec",
286+
main_template=template_body
287+
)
288+
289+
template_spec_result = template_specs_client.template_spec_versions.create_or_update(
290+
"templateSpecsRG",
291+
"storageSpec",
292+
"1.0.0",
293+
version
294+
)
295+
296+
print(f"Provisioned template spec with ID: {template_spec_result.id}")
297+
```
298+
299+
Then, get the ID for template spec and deploy it.
300+
301+
```python
302+
import os
303+
from azure.identity import AzureCliCredential
304+
from azure.mgmt.resource import ResourceManagementClient
305+
from azure.mgmt.resource.resources.models import DeploymentMode
306+
from azure.mgmt.resource.templatespecs import TemplateSpecsClient
307+
308+
credential = AzureCliCredential()
309+
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
310+
311+
resource_client = ResourceManagementClient(credential, subscription_id)
312+
template_specs_client = TemplateSpecsClient(credential, subscription_id)
313+
314+
template_spec = template_specs_client.template_spec_versions.get(
315+
"templateSpecsRg",
316+
"storageSpec",
317+
"1.0.0"
318+
)
319+
320+
rg_deployment_result = resource_client.deployments.begin_create_or_update(
321+
"exampleGroup",
322+
"exampleDeployment",
323+
{
324+
"properties": {
325+
"template_link": {
326+
"id": template_spec.id
327+
},
328+
"mode": DeploymentMode.incremental
329+
}
330+
}
331+
)
332+
```
333+
334+
For more information, see [Azure Resource Manager template specs](template-specs.md).
335+
336+
## Preview changes
337+
338+
Before deploying your template, you can preview the changes the template will make to your environment. Use the [what-if operation](./deploy-what-if.md) to verify that the template makes the changes that you expect. What-if also validates the template for errors.
339+
340+
## Next steps
341+
342+
- To roll back to a successful deployment when you get an error, see [Rollback on error to successful deployment](rollback-on-error.md).
343+
- To specify how to handle resources that exist in the resource group but aren't defined in the template, see [Azure Resource Manager deployment modes](deployment-modes.md).
344+
- To understand how to define parameters in your template, see [Understand the structure and syntax of ARM templates](./syntax.md).
345+
- For information about deploying a template that requires a SAS token, see [Deploy private ARM template with SAS token](secure-template-with-sas-token.md).

articles/azure-resource-manager/templates/toc.yml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,9 @@
375375
- name: Deploy - PowerShell
376376
displayName: deployment
377377
href: deploy-powershell.md
378+
- name: Python
379+
displayName: deployment
380+
href: deploy-python.md
378381
- name: Deploy - REST API
379382
displayName: deployment
380383
href: deploy-rest.md

0 commit comments

Comments
 (0)