Skip to content

Commit a6fb93a

Browse files
author
Jill Grant
authored
Merge pull request #235803 from tfitzmac/0424deploy
Add python deploy template
2 parents 1bd28bc + 514e890 commit a6fb93a

File tree

2 files changed

+345
-0
lines changed

2 files changed

+345
-0
lines changed
Lines changed: 342 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,342 @@
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+
25+
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}`
26+
27+
* The examples in this article use CLI-based authentication (`AzureCliCredential`). Depending on your environment, you may need to run `az login` first to authenticate.
28+
29+
[!INCLUDE [permissions](../../../includes/template-deploy-permissions.md)]
30+
31+
## Deployment scope
32+
33+
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.
34+
35+
* 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):
36+
37+
* 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):
38+
39+
For more information about subscription level deployments, see [Create resource groups and resources at the subscription level](deploy-to-subscription.md).
40+
41+
* 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).
42+
43+
For more information about management group level deployments, see [Create resources at the management group level](deploy-to-management-group.md).
44+
45+
* 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).
46+
47+
For more information about tenant level deployments, see [Create resources at the tenant level](deploy-to-tenant.md).
48+
49+
For every scope, the user deploying the template must have the required permissions to create resources.
50+
51+
## Deployment name
52+
53+
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`.
54+
55+
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.
56+
57+
To create a unique name, you can assign a random number.
58+
59+
```python
60+
import random
61+
62+
suffix = random.randint(1, 1000)
63+
deployment_name = f"ExampleDeployment{suffix}"
64+
```
65+
66+
Or, add a date value.
67+
68+
```python
69+
from datetime import datetime
70+
71+
today = datetime.now().strftime("%m-%d-%Y")
72+
deployment_name = f"ExampleDeployment{today}"
73+
```
74+
75+
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`.
76+
77+
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.
78+
79+
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.
80+
81+
To avoid conflicts with concurrent deployments and to ensure unique entries in the deployment history, give each deployment a unique name.
82+
83+
## Deploy local template
84+
85+
You can deploy a template from your local machine or one that is stored externally. This section describes deploying a local template.
86+
87+
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.
88+
89+
```python
90+
import os
91+
from azure.identity import AzureCliCredential
92+
from azure.mgmt.resource import ResourceManagementClient
93+
94+
credential = AzureCliCredential()
95+
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
96+
97+
resource_client = ResourceManagementClient(credential, subscription_id)
98+
99+
rg_result = resource_client.resource_groups.create_or_update(
100+
"exampleGroup",
101+
{
102+
"location": "Central US"
103+
}
104+
)
105+
106+
print(f"Provisioned resource group with ID: {rg_result.id}")
107+
```
108+
109+
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`.
110+
111+
```python
112+
import os
113+
import json
114+
from azure.identity import AzureCliCredential
115+
from azure.mgmt.resource import ResourceManagementClient
116+
from azure.mgmt.resource.resources.models import DeploymentMode
117+
118+
credential = AzureCliCredential()
119+
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
120+
121+
resource_client = ResourceManagementClient(credential, subscription_id)
122+
123+
with open("storage.json", "r") as template_file:
124+
template_body = json.load(template_file)
125+
126+
rg_deployment_result = resource_client.deployments.begin_create_or_update(
127+
"exampleGroup",
128+
"exampleDeployment",
129+
{
130+
"properties": {
131+
"template": template_body,
132+
"parameters": {
133+
"storagePrefix": {
134+
"value": "demostore"
135+
},
136+
},
137+
"mode": DeploymentMode.incremental
138+
}
139+
}
140+
)
141+
```
142+
143+
The deployment can take several minutes to complete.
144+
145+
## Deploy remote template
146+
147+
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.
148+
149+
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.
150+
151+
```python
152+
import os
153+
from azure.identity import AzureCliCredential
154+
from azure.mgmt.resource import ResourceManagementClient
155+
156+
credential = AzureCliCredential()
157+
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
158+
159+
resource_client = ResourceManagementClient(credential, subscription_id)
160+
161+
rg_result = resource_client.resource_groups.create_or_update(
162+
"exampleGroup",
163+
{
164+
"location": "Central US"
165+
}
166+
)
167+
168+
print(f"Provisioned resource group with ID: {rg_result.id}")
169+
```
170+
171+
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.
172+
173+
```python
174+
import os
175+
from azure.identity import AzureCliCredential
176+
from azure.mgmt.resource import ResourceManagementClient
177+
from azure.mgmt.resource.resources.models import DeploymentMode
178+
179+
credential = AzureCliCredential()
180+
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
181+
182+
resource_client = ResourceManagementClient(credential, subscription_id)
183+
184+
resource_group_name = "exampleGroup"
185+
location = "westus"
186+
template_uri = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/quickstarts/microsoft.storage/storage-account-create/azuredeploy.json"
187+
188+
rg_deployment_result = resource_client.deployments.begin_create_or_update(
189+
resource_group_name,
190+
"exampleDeployment",
191+
{
192+
"properties": {
193+
"templateLink": {
194+
"uri": template_uri
195+
},
196+
"parameters": {
197+
"location": {
198+
"value": location
199+
}
200+
},
201+
"mode": DeploymentMode.incremental
202+
}
203+
}
204+
)
205+
```
206+
207+
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. If you keep your templates in a storage account that doesn't allow anonymous access, you need to provide a SAS token.
208+
209+
```python
210+
import os
211+
from azure.identity import AzureCliCredential
212+
from azure.mgmt.resource import ResourceManagementClient
213+
from azure.mgmt.resource.resources.models import DeploymentMode
214+
215+
credential = AzureCliCredential()
216+
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
217+
sas_token = os.environ["SAS_TOKEN"]
218+
219+
resource_client = ResourceManagementClient(credential, subscription_id)
220+
221+
resource_group_name = "exampleGroup"
222+
location = "westus"
223+
template_uri = f"https://stage20230425.blob.core.windows.net/templates/storage.json?{sas_token}"
224+
225+
rg_deployment_result = resource_client.deployments.begin_create_or_update(
226+
resource_group_name,
227+
"exampleDeployment",
228+
{
229+
"properties": {
230+
"templateLink": {
231+
"uri": template_uri
232+
},
233+
"parameters": {
234+
"location": {
235+
"value": location
236+
}
237+
},
238+
"mode": DeploymentMode.incremental
239+
}
240+
}
241+
)
242+
```
243+
244+
For more information, see [Use relative path for linked templates](./linked-templates.md#linked-template).
245+
246+
## Deploy template spec
247+
248+
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.
249+
250+
The following examples show how to create and deploy a template spec.
251+
252+
First, create the template spec by providing the ARM template.
253+
254+
```python
255+
import os
256+
import json
257+
from azure.identity import AzureCliCredential
258+
from azure.mgmt.resource.templatespecs import TemplateSpecsClient
259+
from azure.mgmt.resource.templatespecs.models import TemplateSpecVersion, TemplateSpec
260+
261+
credential = AzureCliCredential()
262+
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
263+
264+
template_specs_client = TemplateSpecsClient(credential, subscription_id)
265+
266+
template_spec = TemplateSpec(
267+
location="westus2",
268+
description="Storage Spec"
269+
)
270+
271+
template_specs_client.template_specs.create_or_update(
272+
"templateSpecsRG",
273+
"storageSpec",
274+
template_spec
275+
)
276+
277+
with open("storage.json", "r") as template_file:
278+
template_body = json.load(template_file)
279+
280+
version = TemplateSpecVersion(
281+
location="westus2",
282+
description="Storage Spec",
283+
main_template=template_body
284+
)
285+
286+
template_spec_result = template_specs_client.template_spec_versions.create_or_update(
287+
"templateSpecsRG",
288+
"storageSpec",
289+
"1.0.0",
290+
version
291+
)
292+
293+
print(f"Provisioned template spec with ID: {template_spec_result.id}")
294+
```
295+
296+
Then, get the ID for template spec and deploy it.
297+
298+
```python
299+
import os
300+
from azure.identity import AzureCliCredential
301+
from azure.mgmt.resource import ResourceManagementClient
302+
from azure.mgmt.resource.resources.models import DeploymentMode
303+
from azure.mgmt.resource.templatespecs import TemplateSpecsClient
304+
305+
credential = AzureCliCredential()
306+
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
307+
308+
resource_client = ResourceManagementClient(credential, subscription_id)
309+
template_specs_client = TemplateSpecsClient(credential, subscription_id)
310+
311+
template_spec = template_specs_client.template_spec_versions.get(
312+
"templateSpecsRg",
313+
"storageSpec",
314+
"1.0.0"
315+
)
316+
317+
rg_deployment_result = resource_client.deployments.begin_create_or_update(
318+
"exampleGroup",
319+
"exampleDeployment",
320+
{
321+
"properties": {
322+
"template_link": {
323+
"id": template_spec.id
324+
},
325+
"mode": DeploymentMode.incremental
326+
}
327+
}
328+
)
329+
```
330+
331+
For more information, see [Azure Resource Manager template specs](template-specs.md).
332+
333+
## Preview changes
334+
335+
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.
336+
337+
## Next steps
338+
339+
- To roll back to a successful deployment when you get an error, see [Rollback on error to successful deployment](rollback-on-error.md).
340+
- 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).
341+
- To understand how to define parameters in your template, see [Understand the structure and syntax of ARM templates](./syntax.md).
342+
- 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)