Skip to content
This repository was archived by the owner on Jun 17, 2024. It is now read-only.

Repository files navigation

page_typesample
languages
python
products
azure
descriptionThis sample explains how to use Azure Resource Manager templates to deploy your Resources to Azure.
urlFragmentresource-manager-python-template-deployment

Deploy an SSH Enabled VM with a Template in Python

This sample explains how to use Azure Resource Manager templates to deploy your Resources to Azure. It shows how to deploy your Resources by using the Azure SDK for Python.

When deploying an application definition with a template, you can provide parameter values to customize how the resources are created. You specify values for these parameters either inline or in a parameter file.

Incremental and complete deployments

By default, Resource Manager handles deployments as incremental updates to the resource group. With incremental deployment, Resource Manager:

  • leaves unchanged resources that exist in the resource group but are not specified in the template
  • adds resources that are specified in the template but do not exist in the resource group
  • does not re-provision resources that exist in the resource group in the same condition defined in the template

With complete deployment, Resource Manager:

  • deletes resources that exist in the resource group but are not specified in the template
  • adds resources that are specified in the template but do not exist in the resource group
  • does not re-provision resources that exist in the resource group in the same condition defined in the template

You specify the type of deployment through the Mode property, as shown in the examples below.

Deploy with Python

In this sample, we are going to deploy a resource template which contains an Ubuntu 16.04 LTS virtual machine using ssh public key authentication, storage account, and virtual network with public IP address. The virtual network contains a single subnet with a single network security group rule which allows traffic on port 22 for ssh with a single network interface belonging to the subnet. The virtual machine is a Standard_D1 size. You can find the template here.

To run this sample, do the following:

  1. If you don't already have it, install Python.

  2. We recommend using a virtual environment to run this example, but it's not mandatory. To initialize a virtual environment:

    pip install virtualenv
    virtualenv mytestenv
    cd mytestenv
    source bin/activate
    
  3. Create a Service Principal, either through Azure CLI, PowerShell or the portal.

  4. Clone this repository and navigate into it.

    git clone https://github.com/Azure-Samples/resource-manager-python-template-deployment.git
    cd resource-manager-python-template-deployment
    
  5. Install all required libraries within the virtual environment.

    pip install -r requirements.txt
    
  6. Create environment variables with the necessary IDs for Azure authentication. You can learn where to find the first three IDs in the Azure portal in this document. The subscription ID is in the subscription's overview in the "Subscriptions" blade of the portal.

    export AZURE_TENANT_ID={your tenant id}
    export AZURE_CLIENT_ID={your client id}
    export AZURE_CLIENT_SECRET={your client secret}
    export AZURE_SUBSCRIPTION_ID={your subscription id}
    
  7. Run the script.

    python azure_deployment.py
    

What is this azure_deployment.py Doing?

The entry point for this sample is azure_deployment.py. This script uses the Deployer class below to deploy the aforementioned template to the subscription and resource group specified in my_resource_group and my_subscription_id respectively. By default the script will use the ssh public key from your default ssh location.

Note: you must set each of the environment variables (AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET) prior to running the script, and either set AZURE_SUBSCRIPTION_ID or replace it in the script. See the numbered list above for instructions on how to do this.

importos.pathfromdeployerimportDeployer# This script expects that the following environment vars are set:## AZURE_TENANT_ID: with your Azure Active Directory tenant id or domain# AZURE_CLIENT_ID: with your Azure Active Directory Application Client ID# AZURE_CLIENT_SECRET: with your Azure Active Directory Application Secretmy_subscription_id=os.environ.get('AZURE_SUBSCRIPTION_ID', '11111111-1111-1111-1111-111111111111') # your Azure Subscription Idmy_resource_group='azure-python-deployment-sample'# the resource group for deploymentmy_pub_ssh_key_path=os.path.expanduser('~/.ssh/id_rsa.pub') # the path to your rsa public key filemsg="\nInitializing the Deployer class with subscription id: {}, resource group: {}" \
"\nand public key located at: {}...\n\n"msg=msg.format(my_subscription_id, my_resource_group, my_pub_ssh_key_path)
print(msg)
# Initialize the deployer classdeployer=Deployer(my_subscription_id, my_resource_group, my_pub_ssh_key_path)
print("Beginning the deployment... \n\n")
# Deploy the templatemy_deployment=deployer.deploy()
print("Done deploying!!\n\nYou can connect via: `ssh azureSample@{}.westus.cloudapp.azure.com`".format(deployer.dns_label_prefix))
# Destroy the resource group which contains the deployment# deployer.destroy()

What is this deployer.py Doing?

The Deployer class consists of the following:

"""A deployer class to deploy a template on Azure"""importos.pathimportjsonfromhaikunatorimportHaikunatorfromazure.common.credentialsimportServicePrincipalCredentialsfromazure.mgmt.resourceimportResourceManagementClientfromazure.mgmt.resource.resources.modelsimportDeploymentModeclassDeployer(object):
""" Initialize the deployer class with subscription, resource group and public key. :raises IOError: If the public key path cannot be read (access or not exists) :raises KeyError: If AZURE_CLIENT_ID, AZURE_CLIENT_SECRET or AZURE_TENANT_ID env variables or not defined """name_generator=Haikunator()
def__init__(self, subscription_id, resource_group, pub_ssh_key_path='~/.ssh/id_rsa.pub'):
self.subscription_id=subscription_idself.resource_group=resource_groupself.dns_label_prefix=self.name_generator.haikunate()
pub_ssh_key_path=os.path.expanduser(pub_ssh_key_path)
# Will raise if file not exists or not enough permissionwithopen(pub_ssh_key_path, 'r') aspub_ssh_file_fd:
self.pub_ssh_key=pub_ssh_file_fd.read()
self.credentials=ServicePrincipalCredentials(
client_id=os.environ['AZURE_CLIENT_ID'],
secret=os.environ['AZURE_CLIENT_SECRET'],
tenant=os.environ['AZURE_TENANT_ID']
)
self.client=ResourceManagementClient(self.credentials, self.subscription_id)
defdeploy(self):
"""Deploy the template to a resource group."""self.client.resource_groups.create_or_update(
self.resource_group,
{
'location':'westus'
}
)
template_path=os.path.join(os.path.dirname(__file__), 'templates', 'template.json')
withopen(template_path, 'r') astemplate_file_fd:
template=json.load(template_file_fd)
parameters= {
'sshKeyData': self.pub_ssh_key,
'vmName': 'azure-deployment-sample-vm',
'dnsLabelPrefix': self.dns_label_prefix
}
parameters= {k: {'value': v} fork, vinparameters.items()}
deployment_properties= {
'mode': DeploymentMode.incremental,
'template': template,
'parameters': parameters
}
deployment_async_operation=self.client.deployments.create_or_update(
self.resource_group,
'azure-sample',
deployment_properties
)
deployment_async_operation.wait()
defdestroy(self):
"""Destroy the given resource group"""self.client.resource_groups.delete(self.resource_group)

The __init__ method initializes the class with the subscription, resource group and public key. The method also fetches the Azure Active Directory bearer token, which will be used in each HTTP request to the Azure Management API. The class will raise exceptions under two conditions: if the public key path does not exist, or if there are empty values for AZURE_TENANT_ID, AZURE_CLIENT_ID or AZURE_CLIENT_SECRET environment variables.

The deploy method does the heavy lifting of creating or updating the resource group, preparing the template parameters and deploying the template.

The destroy method simply deletes the resource group thus deleting all of the resources within that group. Note that it is commented out in azure_deployment.py. But you can uncomment it to easily clean up the resources created by this sample if you no longer need them.

Each of the above methods use the azure.mgmt.resource.ResourceManagementClient class, which resides within the azure-mgmt-resource package (see the docs here).

After the script runs, you should see something like the following in your output:

$ python azure_deployment.py
Initializing the Deployer class with subscription id: 11111111-1111-1111-1111-111111111111, resource group: azure-python-deployment-sample
and public key located at: /Users/you/.ssh/id_rsa.pub...
Beginning the deployment...
Done deploying!!
You can connect via: `ssh azureSample@damp-dew-79.westus.cloudapp.azure.com`

You should be able to run ssh azureSample@{your dns value}.westus.cloudapp.azure.com to connect to your new VM.

About

An example illustrating how to use Python to deploy an Azure Resource Manager Template

Resources

Code of conduct

Contributing

Stars

31 stars

Watchers

386 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
GitHub - Azure-Samples/resource-manager-python-template-deployment: An example illustrating how to use Python to deploy an Azure Resource Manager Template · GitHub
Skip to content
This repository was archived by the owner on Jun 17, 2024. It is now read-only.

Repository files navigation

page_typesample
languages
python
products
azure
descriptionThis sample explains how to use Azure Resource Manager templates to deploy your Resources to Azure.
urlFragmentresource-manager-python-template-deployment

Deploy an SSH Enabled VM with a Template in Python

This sample explains how to use Azure Resource Manager templates to deploy your Resources to Azure. It shows how to deploy your Resources by using the Azure SDK for Python.

When deploying an application definition with a template, you can provide parameter values to customize how the resources are created. You specify values for these parameters either inline or in a parameter file.

Incremental and complete deployments

By default, Resource Manager handles deployments as incremental updates to the resource group. With incremental deployment, Resource Manager:

  • leaves unchanged resources that exist in the resource group but are not specified in the template
  • adds resources that are specified in the template but do not exist in the resource group
  • does not re-provision resources that exist in the resource group in the same condition defined in the template

With complete deployment, Resource Manager:

  • deletes resources that exist in the resource group but are not specified in the template
  • adds resources that are specified in the template but do not exist in the resource group
  • does not re-provision resources that exist in the resource group in the same condition defined in the template

You specify the type of deployment through the Mode property, as shown in the examples below.

Deploy with Python

In this sample, we are going to deploy a resource template which contains an Ubuntu 16.04 LTS virtual machine using ssh public key authentication, storage account, and virtual network with public IP address. The virtual network contains a single subnet with a single network security group rule which allows traffic on port 22 for ssh with a single network interface belonging to the subnet. The virtual machine is a Standard_D1 size. You can find the template here.

To run this sample, do the following:

  1. If you don't already have it, install Python.

  2. We recommend using a virtual environment to run this example, but it's not mandatory. To initialize a virtual environment:

    pip install virtualenv
    virtualenv mytestenv
    cd mytestenv
    source bin/activate
    
  3. Create a Service Principal, either through Azure CLI, PowerShell or the portal.

  4. Clone this repository and navigate into it.

    git clone https://github.com/Azure-Samples/resource-manager-python-template-deployment.git
    cd resource-manager-python-template-deployment
    
  5. Install all required libraries within the virtual environment.

    pip install -r requirements.txt
    
  6. Create environment variables with the necessary IDs for Azure authentication. You can learn where to find the first three IDs in the Azure portal in this document. The subscription ID is in the subscription's overview in the "Subscriptions" blade of the portal.

    export AZURE_TENANT_ID={your tenant id}
    export AZURE_CLIENT_ID={your client id}
    export AZURE_CLIENT_SECRET={your client secret}
    export AZURE_SUBSCRIPTION_ID={your subscription id}
    
  7. Run the script.

    python azure_deployment.py
    

What is this azure_deployment.py Doing?

The entry point for this sample is azure_deployment.py. This script uses the Deployer class below to deploy the aforementioned template to the subscription and resource group specified in my_resource_group and my_subscription_id respectively. By default the script will use the ssh public key from your default ssh location.

Note: you must set each of the environment variables (AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET) prior to running the script, and either set AZURE_SUBSCRIPTION_ID or replace it in the script. See the numbered list above for instructions on how to do this.

importos.pathfromdeployerimportDeployer# This script expects that the following environment vars are set:## AZURE_TENANT_ID: with your Azure Active Directory tenant id or domain# AZURE_CLIENT_ID: with your Azure Active Directory Application Client ID# AZURE_CLIENT_SECRET: with your Azure Active Directory Application Secretmy_subscription_id=os.environ.get('AZURE_SUBSCRIPTION_ID', '11111111-1111-1111-1111-111111111111') # your Azure Subscription Idmy_resource_group='azure-python-deployment-sample'# the resource group for deploymentmy_pub_ssh_key_path=os.path.expanduser('~/.ssh/id_rsa.pub') # the path to your rsa public key filemsg="\nInitializing the Deployer class with subscription id: {}, resource group: {}" \
"\nand public key located at: {}...\n\n"msg=msg.format(my_subscription_id, my_resource_group, my_pub_ssh_key_path)
print(msg)
# Initialize the deployer classdeployer=Deployer(my_subscription_id, my_resource_group, my_pub_ssh_key_path)
print("Beginning the deployment... \n\n")
# Deploy the templatemy_deployment=deployer.deploy()
print("Done deploying!!\n\nYou can connect via: `ssh azureSample@{}.westus.cloudapp.azure.com`".format(deployer.dns_label_prefix))
# Destroy the resource group which contains the deployment# deployer.destroy()

What is this deployer.py Doing?

The Deployer class consists of the following:

"""A deployer class to deploy a template on Azure"""importos.pathimportjsonfromhaikunatorimportHaikunatorfromazure.common.credentialsimportServicePrincipalCredentialsfromazure.mgmt.resourceimportResourceManagementClientfromazure.mgmt.resource.resources.modelsimportDeploymentModeclassDeployer(object):
""" Initialize the deployer class with subscription, resource group and public key. :raises IOError: If the public key path cannot be read (access or not exists) :raises KeyError: If AZURE_CLIENT_ID, AZURE_CLIENT_SECRET or AZURE_TENANT_ID env variables or not defined """name_generator=Haikunator()
def__init__(self, subscription_id, resource_group, pub_ssh_key_path='~/.ssh/id_rsa.pub'):
self.subscription_id=subscription_idself.resource_group=resource_groupself.dns_label_prefix=self.name_generator.haikunate()
pub_ssh_key_path=os.path.expanduser(pub_ssh_key_path)
# Will raise if file not exists or not enough permissionwithopen(pub_ssh_key_path, 'r') aspub_ssh_file_fd:
self.pub_ssh_key=pub_ssh_file_fd.read()
self.credentials=ServicePrincipalCredentials(
client_id=os.environ['AZURE_CLIENT_ID'],
secret=os.environ['AZURE_CLIENT_SECRET'],
tenant=os.environ['AZURE_TENANT_ID']
)
self.client=ResourceManagementClient(self.credentials, self.subscription_id)
defdeploy(self):
"""Deploy the template to a resource group."""self.client.resource_groups.create_or_update(
self.resource_group,
{
'location':'westus'
}
)
template_path=os.path.join(os.path.dirname(__file__), 'templates', 'template.json')
withopen(template_path, 'r') astemplate_file_fd:
template=json.load(template_file_fd)
parameters= {
'sshKeyData': self.pub_ssh_key,
'vmName': 'azure-deployment-sample-vm',
'dnsLabelPrefix': self.dns_label_prefix
}
parameters= {k: {'value': v} fork, vinparameters.items()}
deployment_properties= {
'mode': DeploymentMode.incremental,
'template': template,
'parameters': parameters
}
deployment_async_operation=self.client.deployments.create_or_update(
self.resource_group,
'azure-sample',
deployment_properties
)
deployment_async_operation.wait()
defdestroy(self):
"""Destroy the given resource group"""self.client.resource_groups.delete(self.resource_group)

The __init__ method initializes the class with the subscription, resource group and public key. The method also fetches the Azure Active Directory bearer token, which will be used in each HTTP request to the Azure Management API. The class will raise exceptions under two conditions: if the public key path does not exist, or if there are empty values for AZURE_TENANT_ID, AZURE_CLIENT_ID or AZURE_CLIENT_SECRET environment variables.

The deploy method does the heavy lifting of creating or updating the resource group, preparing the template parameters and deploying the template.

The destroy method simply deletes the resource group thus deleting all of the resources within that group. Note that it is commented out in azure_deployment.py. But you can uncomment it to easily clean up the resources created by this sample if you no longer need them.

Each of the above methods use the azure.mgmt.resource.ResourceManagementClient class, which resides within the azure-mgmt-resource package (see the docs here).

After the script runs, you should see something like the following in your output:

$ python azure_deployment.py
Initializing the Deployer class with subscription id: 11111111-1111-1111-1111-111111111111, resource group: azure-python-deployment-sample
and public key located at: /Users/you/.ssh/id_rsa.pub...
Beginning the deployment...
Done deploying!!
You can connect via: `ssh azureSample@damp-dew-79.westus.cloudapp.azure.com`

You should be able to run ssh azureSample@{your dns value}.westus.cloudapp.azure.com to connect to your new VM.

About

An example illustrating how to use Python to deploy an Azure Resource Manager Template

Resources

Code of conduct

Contributing

Stars

31 stars

Watchers

386 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - Azure-Samples/resource-manager-python-template-deployment: An example illustrating how to use Python to deploy an Azure Resource Manager Template · GitHub
Skip to content
This repository was archived by the owner on Jun 17, 2024. It is now read-only.

Repository files navigation

page_typesample
languages
python
products
azure
descriptionThis sample explains how to use Azure Resource Manager templates to deploy your Resources to Azure.
urlFragmentresource-manager-python-template-deployment

Deploy an SSH Enabled VM with a Template in Python

This sample explains how to use Azure Resource Manager templates to deploy your Resources to Azure. It shows how to deploy your Resources by using the Azure SDK for Python.

When deploying an application definition with a template, you can provide parameter values to customize how the resources are created. You specify values for these parameters either inline or in a parameter file.

Incremental and complete deployments

By default, Resource Manager handles deployments as incremental updates to the resource group. With incremental deployment, Resource Manager:

  • leaves unchanged resources that exist in the resource group but are not specified in the template
  • adds resources that are specified in the template but do not exist in the resource group
  • does not re-provision resources that exist in the resource group in the same condition defined in the template

With complete deployment, Resource Manager:

  • deletes resources that exist in the resource group but are not specified in the template
  • adds resources that are specified in the template but do not exist in the resource group
  • does not re-provision resources that exist in the resource group in the same condition defined in the template

You specify the type of deployment through the Mode property, as shown in the examples below.

Deploy with Python

In this sample, we are going to deploy a resource template which contains an Ubuntu 16.04 LTS virtual machine using ssh public key authentication, storage account, and virtual network with public IP address. The virtual network contains a single subnet with a single network security group rule which allows traffic on port 22 for ssh with a single network interface belonging to the subnet. The virtual machine is a Standard_D1 size. You can find the template here.

To run this sample, do the following:

  1. If you don't already have it, install Python.

  2. We recommend using a virtual environment to run this example, but it's not mandatory. To initialize a virtual environment:

    pip install virtualenv
    virtualenv mytestenv
    cd mytestenv
    source bin/activate
    
  3. Create a Service Principal, either through Azure CLI, PowerShell or the portal.

  4. Clone this repository and navigate into it.

    git clone https://github.com/Azure-Samples/resource-manager-python-template-deployment.git
    cd resource-manager-python-template-deployment
    
  5. Install all required libraries within the virtual environment.

    pip install -r requirements.txt
    
  6. Create environment variables with the necessary IDs for Azure authentication. You can learn where to find the first three IDs in the Azure portal in this document. The subscription ID is in the subscription's overview in the "Subscriptions" blade of the portal.

    export AZURE_TENANT_ID={your tenant id}
    export AZURE_CLIENT_ID={your client id}
    export AZURE_CLIENT_SECRET={your client secret}
    export AZURE_SUBSCRIPTION_ID={your subscription id}
    
  7. Run the script.

    python azure_deployment.py
    

What is this azure_deployment.py Doing?

The entry point for this sample is azure_deployment.py. This script uses the Deployer class below to deploy the aforementioned template to the subscription and resource group specified in my_resource_group and my_subscription_id respectively. By default the script will use the ssh public key from your default ssh location.

Note: you must set each of the environment variables (AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET) prior to running the script, and either set AZURE_SUBSCRIPTION_ID or replace it in the script. See the numbered list above for instructions on how to do this.

importos.pathfromdeployerimportDeployer# This script expects that the following environment vars are set:## AZURE_TENANT_ID: with your Azure Active Directory tenant id or domain# AZURE_CLIENT_ID: with your Azure Active Directory Application Client ID# AZURE_CLIENT_SECRET: with your Azure Active Directory Application Secretmy_subscription_id=os.environ.get('AZURE_SUBSCRIPTION_ID', '11111111-1111-1111-1111-111111111111') # your Azure Subscription Idmy_resource_group='azure-python-deployment-sample'# the resource group for deploymentmy_pub_ssh_key_path=os.path.expanduser('~/.ssh/id_rsa.pub') # the path to your rsa public key filemsg="\nInitializing the Deployer class with subscription id: {}, resource group: {}" \
"\nand public key located at: {}...\n\n"msg=msg.format(my_subscription_id, my_resource_group, my_pub_ssh_key_path)
print(msg)
# Initialize the deployer classdeployer=Deployer(my_subscription_id, my_resource_group, my_pub_ssh_key_path)
print("Beginning the deployment... \n\n")
# Deploy the templatemy_deployment=deployer.deploy()
print("Done deploying!!\n\nYou can connect via: `ssh azureSample@{}.westus.cloudapp.azure.com`".format(deployer.dns_label_prefix))
# Destroy the resource group which contains the deployment# deployer.destroy()

What is this deployer.py Doing?

The Deployer class consists of the following:

"""A deployer class to deploy a template on Azure"""importos.pathimportjsonfromhaikunatorimportHaikunatorfromazure.common.credentialsimportServicePrincipalCredentialsfromazure.mgmt.resourceimportResourceManagementClientfromazure.mgmt.resource.resources.modelsimportDeploymentModeclassDeployer(object):
""" Initialize the deployer class with subscription, resource group and public key. :raises IOError: If the public key path cannot be read (access or not exists) :raises KeyError: If AZURE_CLIENT_ID, AZURE_CLIENT_SECRET or AZURE_TENANT_ID env variables or not defined """name_generator=Haikunator()
def__init__(self, subscription_id, resource_group, pub_ssh_key_path='~/.ssh/id_rsa.pub'):
self.subscription_id=subscription_idself.resource_group=resource_groupself.dns_label_prefix=self.name_generator.haikunate()
pub_ssh_key_path=os.path.expanduser(pub_ssh_key_path)
# Will raise if file not exists or not enough permissionwithopen(pub_ssh_key_path, 'r') aspub_ssh_file_fd:
self.pub_ssh_key=pub_ssh_file_fd.read()
self.credentials=ServicePrincipalCredentials(
client_id=os.environ['AZURE_CLIENT_ID'],
secret=os.environ['AZURE_CLIENT_SECRET'],
tenant=os.environ['AZURE_TENANT_ID']
)
self.client=ResourceManagementClient(self.credentials, self.subscription_id)
defdeploy(self):
"""Deploy the template to a resource group."""self.client.resource_groups.create_or_update(
self.resource_group,
{
'location':'westus'
}
)
template_path=os.path.join(os.path.dirname(__file__), 'templates', 'template.json')
withopen(template_path, 'r') astemplate_file_fd:
template=json.load(template_file_fd)
parameters= {
'sshKeyData': self.pub_ssh_key,
'vmName': 'azure-deployment-sample-vm',
'dnsLabelPrefix': self.dns_label_prefix
}
parameters= {k: {'value': v} fork, vinparameters.items()}
deployment_properties= {
'mode': DeploymentMode.incremental,
'template': template,
'parameters': parameters
}
deployment_async_operation=self.client.deployments.create_or_update(
self.resource_group,
'azure-sample',
deployment_properties
)
deployment_async_operation.wait()
defdestroy(self):
"""Destroy the given resource group"""self.client.resource_groups.delete(self.resource_group)

The __init__ method initializes the class with the subscription, resource group and public key. The method also fetches the Azure Active Directory bearer token, which will be used in each HTTP request to the Azure Management API. The class will raise exceptions under two conditions: if the public key path does not exist, or if there are empty values for AZURE_TENANT_ID, AZURE_CLIENT_ID or AZURE_CLIENT_SECRET environment variables.

The deploy method does the heavy lifting of creating or updating the resource group, preparing the template parameters and deploying the template.

The destroy method simply deletes the resource group thus deleting all of the resources within that group. Note that it is commented out in azure_deployment.py. But you can uncomment it to easily clean up the resources created by this sample if you no longer need them.

Each of the above methods use the azure.mgmt.resource.ResourceManagementClient class, which resides within the azure-mgmt-resource package (see the docs here).

After the script runs, you should see something like the following in your output:

$ python azure_deployment.py
Initializing the Deployer class with subscription id: 11111111-1111-1111-1111-111111111111, resource group: azure-python-deployment-sample
and public key located at: /Users/you/.ssh/id_rsa.pub...
Beginning the deployment...
Done deploying!!
You can connect via: `ssh azureSample@damp-dew-79.westus.cloudapp.azure.com`

You should be able to run ssh azureSample@{your dns value}.westus.cloudapp.azure.com to connect to your new VM.

About

An example illustrating how to use Python to deploy an Azure Resource Manager Template

Resources

Code of conduct

Contributing

Stars

31 stars

Watchers

386 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - Azure-Samples/resource-manager-python-template-deployment: An example illustrating how to use Python to deploy an Azure Resource Manager Template · GitHub
Skip to content
This repository was archived by the owner on Jun 17, 2024. It is now read-only.

Repository files navigation

page_typesample
languages
python
products
azure
descriptionThis sample explains how to use Azure Resource Manager templates to deploy your Resources to Azure.
urlFragmentresource-manager-python-template-deployment

Deploy an SSH Enabled VM with a Template in Python

This sample explains how to use Azure Resource Manager templates to deploy your Resources to Azure. It shows how to deploy your Resources by using the Azure SDK for Python.

When deploying an application definition with a template, you can provide parameter values to customize how the resources are created. You specify values for these parameters either inline or in a parameter file.

Incremental and complete deployments

By default, Resource Manager handles deployments as incremental updates to the resource group. With incremental deployment, Resource Manager:

  • leaves unchanged resources that exist in the resource group but are not specified in the template
  • adds resources that are specified in the template but do not exist in the resource group
  • does not re-provision resources that exist in the resource group in the same condition defined in the template

With complete deployment, Resource Manager:

  • deletes resources that exist in the resource group but are not specified in the template
  • adds resources that are specified in the template but do not exist in the resource group
  • does not re-provision resources that exist in the resource group in the same condition defined in the template

You specify the type of deployment through the Mode property, as shown in the examples below.

Deploy with Python

In this sample, we are going to deploy a resource template which contains an Ubuntu 16.04 LTS virtual machine using ssh public key authentication, storage account, and virtual network with public IP address. The virtual network contains a single subnet with a single network security group rule which allows traffic on port 22 for ssh with a single network interface belonging to the subnet. The virtual machine is a Standard_D1 size. You can find the template here.

To run this sample, do the following:

  1. If you don't already have it, install Python.

  2. We recommend using a virtual environment to run this example, but it's not mandatory. To initialize a virtual environment:

    pip install virtualenv
    virtualenv mytestenv
    cd mytestenv
    source bin/activate
    
  3. Create a Service Principal, either through Azure CLI, PowerShell or the portal.

  4. Clone this repository and navigate into it.

    git clone https://github.com/Azure-Samples/resource-manager-python-template-deployment.git
    cd resource-manager-python-template-deployment
    
  5. Install all required libraries within the virtual environment.

    pip install -r requirements.txt
    
  6. Create environment variables with the necessary IDs for Azure authentication. You can learn where to find the first three IDs in the Azure portal in this document. The subscription ID is in the subscription's overview in the "Subscriptions" blade of the portal.

    export AZURE_TENANT_ID={your tenant id}
    export AZURE_CLIENT_ID={your client id}
    export AZURE_CLIENT_SECRET={your client secret}
    export AZURE_SUBSCRIPTION_ID={your subscription id}
    
  7. Run the script.

    python azure_deployment.py
    

What is this azure_deployment.py Doing?

The entry point for this sample is azure_deployment.py. This script uses the Deployer class below to deploy the aforementioned template to the subscription and resource group specified in my_resource_group and my_subscription_id respectively. By default the script will use the ssh public key from your default ssh location.

Note: you must set each of the environment variables (AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET) prior to running the script, and either set AZURE_SUBSCRIPTION_ID or replace it in the script. See the numbered list above for instructions on how to do this.

importos.pathfromdeployerimportDeployer# This script expects that the following environment vars are set:## AZURE_TENANT_ID: with your Azure Active Directory tenant id or domain# AZURE_CLIENT_ID: with your Azure Active Directory Application Client ID# AZURE_CLIENT_SECRET: with your Azure Active Directory Application Secretmy_subscription_id=os.environ.get('AZURE_SUBSCRIPTION_ID', '11111111-1111-1111-1111-111111111111') # your Azure Subscription Idmy_resource_group='azure-python-deployment-sample'# the resource group for deploymentmy_pub_ssh_key_path=os.path.expanduser('~/.ssh/id_rsa.pub') # the path to your rsa public key filemsg="\nInitializing the Deployer class with subscription id: {}, resource group: {}" \
"\nand public key located at: {}...\n\n"msg=msg.format(my_subscription_id, my_resource_group, my_pub_ssh_key_path)
print(msg)
# Initialize the deployer classdeployer=Deployer(my_subscription_id, my_resource_group, my_pub_ssh_key_path)
print("Beginning the deployment... \n\n")
# Deploy the templatemy_deployment=deployer.deploy()
print("Done deploying!!\n\nYou can connect via: `ssh azureSample@{}.westus.cloudapp.azure.com`".format(deployer.dns_label_prefix))
# Destroy the resource group which contains the deployment# deployer.destroy()

What is this deployer.py Doing?

The Deployer class consists of the following:

"""A deployer class to deploy a template on Azure"""importos.pathimportjsonfromhaikunatorimportHaikunatorfromazure.common.credentialsimportServicePrincipalCredentialsfromazure.mgmt.resourceimportResourceManagementClientfromazure.mgmt.resource.resources.modelsimportDeploymentModeclassDeployer(object):
""" Initialize the deployer class with subscription, resource group and public key. :raises IOError: If the public key path cannot be read (access or not exists) :raises KeyError: If AZURE_CLIENT_ID, AZURE_CLIENT_SECRET or AZURE_TENANT_ID env variables or not defined """name_generator=Haikunator()
def__init__(self, subscription_id, resource_group, pub_ssh_key_path='~/.ssh/id_rsa.pub'):
self.subscription_id=subscription_idself.resource_group=resource_groupself.dns_label_prefix=self.name_generator.haikunate()
pub_ssh_key_path=os.path.expanduser(pub_ssh_key_path)
# Will raise if file not exists or not enough permissionwithopen(pub_ssh_key_path, 'r') aspub_ssh_file_fd:
self.pub_ssh_key=pub_ssh_file_fd.read()
self.credentials=ServicePrincipalCredentials(
client_id=os.environ['AZURE_CLIENT_ID'],
secret=os.environ['AZURE_CLIENT_SECRET'],
tenant=os.environ['AZURE_TENANT_ID']
)
self.client=ResourceManagementClient(self.credentials, self.subscription_id)
defdeploy(self):
"""Deploy the template to a resource group."""self.client.resource_groups.create_or_update(
self.resource_group,
{
'location':'westus'
}
)
template_path=os.path.join(os.path.dirname(__file__), 'templates', 'template.json')
withopen(template_path, 'r') astemplate_file_fd:
template=json.load(template_file_fd)
parameters= {
'sshKeyData': self.pub_ssh_key,
'vmName': 'azure-deployment-sample-vm',
'dnsLabelPrefix': self.dns_label_prefix
}
parameters= {k: {'value': v} fork, vinparameters.items()}
deployment_properties= {
'mode': DeploymentMode.incremental,
'template': template,
'parameters': parameters
}
deployment_async_operation=self.client.deployments.create_or_update(
self.resource_group,
'azure-sample',
deployment_properties
)
deployment_async_operation.wait()
defdestroy(self):
"""Destroy the given resource group"""self.client.resource_groups.delete(self.resource_group)

The __init__ method initializes the class with the subscription, resource group and public key. The method also fetches the Azure Active Directory bearer token, which will be used in each HTTP request to the Azure Management API. The class will raise exceptions under two conditions: if the public key path does not exist, or if there are empty values for AZURE_TENANT_ID, AZURE_CLIENT_ID or AZURE_CLIENT_SECRET environment variables.

The deploy method does the heavy lifting of creating or updating the resource group, preparing the template parameters and deploying the template.

The destroy method simply deletes the resource group thus deleting all of the resources within that group. Note that it is commented out in azure_deployment.py. But you can uncomment it to easily clean up the resources created by this sample if you no longer need them.

Each of the above methods use the azure.mgmt.resource.ResourceManagementClient class, which resides within the azure-mgmt-resource package (see the docs here).

After the script runs, you should see something like the following in your output:

$ python azure_deployment.py
Initializing the Deployer class with subscription id: 11111111-1111-1111-1111-111111111111, resource group: azure-python-deployment-sample
and public key located at: /Users/you/.ssh/id_rsa.pub...
Beginning the deployment...
Done deploying!!
You can connect via: `ssh azureSample@damp-dew-79.westus.cloudapp.azure.com`

You should be able to run ssh azureSample@{your dns value}.westus.cloudapp.azure.com to connect to your new VM.

About

An example illustrating how to use Python to deploy an Azure Resource Manager Template

Resources

Code of conduct

Contributing

Stars

31 stars

Watchers

386 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' GitHub - Azure-Samples/resource-manager-python-template-deployment: An example illustrating how to use Python to deploy an Azure Resource Manager Template · GitHub
Skip to content
This repository was archived by the owner on Jun 17, 2024. It is now read-only.

Repository files navigation

page_typesample
languages
python
products
azure
descriptionThis sample explains how to use Azure Resource Manager templates to deploy your Resources to Azure.
urlFragmentresource-manager-python-template-deployment

Deploy an SSH Enabled VM with a Template in Python

This sample explains how to use Azure Resource Manager templates to deploy your Resources to Azure. It shows how to deploy your Resources by using the Azure SDK for Python.

When deploying an application definition with a template, you can provide parameter values to customize how the resources are created. You specify values for these parameters either inline or in a parameter file.

Incremental and complete deployments

By default, Resource Manager handles deployments as incremental updates to the resource group. With incremental deployment, Resource Manager:

  • leaves unchanged resources that exist in the resource group but are not specified in the template
  • adds resources that are specified in the template but do not exist in the resource group
  • does not re-provision resources that exist in the resource group in the same condition defined in the template

With complete deployment, Resource Manager:

  • deletes resources that exist in the resource group but are not specified in the template
  • adds resources that are specified in the template but do not exist in the resource group
  • does not re-provision resources that exist in the resource group in the same condition defined in the template

You specify the type of deployment through the Mode property, as shown in the examples below.

Deploy with Python

In this sample, we are going to deploy a resource template which contains an Ubuntu 16.04 LTS virtual machine using ssh public key authentication, storage account, and virtual network with public IP address. The virtual network contains a single subnet with a single network security group rule which allows traffic on port 22 for ssh with a single network interface belonging to the subnet. The virtual machine is a Standard_D1 size. You can find the template here.

To run this sample, do the following:

  1. If you don't already have it, install Python.

  2. We recommend using a virtual environment to run this example, but it's not mandatory. To initialize a virtual environment:

    pip install virtualenv
    virtualenv mytestenv
    cd mytestenv
    source bin/activate
    
  3. Create a Service Principal, either through Azure CLI, PowerShell or the portal.

  4. Clone this repository and navigate into it.

    git clone https://github.com/Azure-Samples/resource-manager-python-template-deployment.git
    cd resource-manager-python-template-deployment
    
  5. Install all required libraries within the virtual environment.

    pip install -r requirements.txt
    
  6. Create environment variables with the necessary IDs for Azure authentication. You can learn where to find the first three IDs in the Azure portal in this document. The subscription ID is in the subscription's overview in the "Subscriptions" blade of the portal.

    export AZURE_TENANT_ID={your tenant id}
    export AZURE_CLIENT_ID={your client id}
    export AZURE_CLIENT_SECRET={your client secret}
    export AZURE_SUBSCRIPTION_ID={your subscription id}
    
  7. Run the script.

    python azure_deployment.py
    

What is this azure_deployment.py Doing?

The entry point for this sample is azure_deployment.py. This script uses the Deployer class below to deploy the aforementioned template to the subscription and resource group specified in my_resource_group and my_subscription_id respectively. By default the script will use the ssh public key from your default ssh location.

Note: you must set each of the environment variables (AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET) prior to running the script, and either set AZURE_SUBSCRIPTION_ID or replace it in the script. See the numbered list above for instructions on how to do this.

importos.pathfromdeployerimportDeployer# This script expects that the following environment vars are set:## AZURE_TENANT_ID: with your Azure Active Directory tenant id or domain# AZURE_CLIENT_ID: with your Azure Active Directory Application Client ID# AZURE_CLIENT_SECRET: with your Azure Active Directory Application Secretmy_subscription_id=os.environ.get('AZURE_SUBSCRIPTION_ID', '11111111-1111-1111-1111-111111111111') # your Azure Subscription Idmy_resource_group='azure-python-deployment-sample'# the resource group for deploymentmy_pub_ssh_key_path=os.path.expanduser('~/.ssh/id_rsa.pub') # the path to your rsa public key filemsg="\nInitializing the Deployer class with subscription id: {}, resource group: {}" \
"\nand public key located at: {}...\n\n"msg=msg.format(my_subscription_id, my_resource_group, my_pub_ssh_key_path)
print(msg)
# Initialize the deployer classdeployer=Deployer(my_subscription_id, my_resource_group, my_pub_ssh_key_path)
print("Beginning the deployment... \n\n")
# Deploy the templatemy_deployment=deployer.deploy()
print("Done deploying!!\n\nYou can connect via: `ssh azureSample@{}.westus.cloudapp.azure.com`".format(deployer.dns_label_prefix))
# Destroy the resource group which contains the deployment# deployer.destroy()

What is this deployer.py Doing?

The Deployer class consists of the following:

"""A deployer class to deploy a template on Azure"""importos.pathimportjsonfromhaikunatorimportHaikunatorfromazure.common.credentialsimportServicePrincipalCredentialsfromazure.mgmt.resourceimportResourceManagementClientfromazure.mgmt.resource.resources.modelsimportDeploymentModeclassDeployer(object):
""" Initialize the deployer class with subscription, resource group and public key. :raises IOError: If the public key path cannot be read (access or not exists) :raises KeyError: If AZURE_CLIENT_ID, AZURE_CLIENT_SECRET or AZURE_TENANT_ID env variables or not defined """name_generator=Haikunator()
def__init__(self, subscription_id, resource_group, pub_ssh_key_path='~/.ssh/id_rsa.pub'):
self.subscription_id=subscription_idself.resource_group=resource_groupself.dns_label_prefix=self.name_generator.haikunate()
pub_ssh_key_path=os.path.expanduser(pub_ssh_key_path)
# Will raise if file not exists or not enough permissionwithopen(pub_ssh_key_path, 'r') aspub_ssh_file_fd:
self.pub_ssh_key=pub_ssh_file_fd.read()
self.credentials=ServicePrincipalCredentials(
client_id=os.environ['AZURE_CLIENT_ID'],
secret=os.environ['AZURE_CLIENT_SECRET'],
tenant=os.environ['AZURE_TENANT_ID']
)
self.client=ResourceManagementClient(self.credentials, self.subscription_id)
defdeploy(self):
"""Deploy the template to a resource group."""self.client.resource_groups.create_or_update(
self.resource_group,
{
'location':'westus'
}
)
template_path=os.path.join(os.path.dirname(__file__), 'templates', 'template.json')
withopen(template_path, 'r') astemplate_file_fd:
template=json.load(template_file_fd)
parameters= {
'sshKeyData': self.pub_ssh_key,
'vmName': 'azure-deployment-sample-vm',
'dnsLabelPrefix': self.dns_label_prefix
}
parameters= {k: {'value': v} fork, vinparameters.items()}
deployment_properties= {
'mode': DeploymentMode.incremental,
'template': template,
'parameters': parameters
}
deployment_async_operation=self.client.deployments.create_or_update(
self.resource_group,
'azure-sample',
deployment_properties
)
deployment_async_operation.wait()
defdestroy(self):
"""Destroy the given resource group"""self.client.resource_groups.delete(self.resource_group)

The __init__ method initializes the class with the subscription, resource group and public key. The method also fetches the Azure Active Directory bearer token, which will be used in each HTTP request to the Azure Management API. The class will raise exceptions under two conditions: if the public key path does not exist, or if there are empty values for AZURE_TENANT_ID, AZURE_CLIENT_ID or AZURE_CLIENT_SECRET environment variables.

The deploy method does the heavy lifting of creating or updating the resource group, preparing the template parameters and deploying the template.

The destroy method simply deletes the resource group thus deleting all of the resources within that group. Note that it is commented out in azure_deployment.py. But you can uncomment it to easily clean up the resources created by this sample if you no longer need them.

Each of the above methods use the azure.mgmt.resource.ResourceManagementClient class, which resides within the azure-mgmt-resource package (see the docs here).

After the script runs, you should see something like the following in your output:

$ python azure_deployment.py
Initializing the Deployer class with subscription id: 11111111-1111-1111-1111-111111111111, resource group: azure-python-deployment-sample
and public key located at: /Users/you/.ssh/id_rsa.pub...
Beginning the deployment...
Done deploying!!
You can connect via: `ssh azureSample@damp-dew-79.westus.cloudapp.azure.com`

You should be able to run ssh azureSample@{your dns value}.westus.cloudapp.azure.com to connect to your new VM.

About

An example illustrating how to use Python to deploy an Azure Resource Manager Template

Resources

Code of conduct

Contributing

Stars

31 stars

Watchers

386 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - Azure-Samples/resource-manager-python-template-deployment: An example illustrating how to use Python to deploy an Azure Resource Manager Template · GitHub
Skip to content
This repository was archived by the owner on Jun 17, 2024. It is now read-only.

Repository files navigation

page_typesample
languages
python
products
azure
descriptionThis sample explains how to use Azure Resource Manager templates to deploy your Resources to Azure.
urlFragmentresource-manager-python-template-deployment

Deploy an SSH Enabled VM with a Template in Python

This sample explains how to use Azure Resource Manager templates to deploy your Resources to Azure. It shows how to deploy your Resources by using the Azure SDK for Python.

When deploying an application definition with a template, you can provide parameter values to customize how the resources are created. You specify values for these parameters either inline or in a parameter file.

Incremental and complete deployments

By default, Resource Manager handles deployments as incremental updates to the resource group. With incremental deployment, Resource Manager:

  • leaves unchanged resources that exist in the resource group but are not specified in the template
  • adds resources that are specified in the template but do not exist in the resource group
  • does not re-provision resources that exist in the resource group in the same condition defined in the template

With complete deployment, Resource Manager:

  • deletes resources that exist in the resource group but are not specified in the template
  • adds resources that are specified in the template but do not exist in the resource group
  • does not re-provision resources that exist in the resource group in the same condition defined in the template

You specify the type of deployment through the Mode property, as shown in the examples below.

Deploy with Python

In this sample, we are going to deploy a resource template which contains an Ubuntu 16.04 LTS virtual machine using ssh public key authentication, storage account, and virtual network with public IP address. The virtual network contains a single subnet with a single network security group rule which allows traffic on port 22 for ssh with a single network interface belonging to the subnet. The virtual machine is a Standard_D1 size. You can find the template here.

To run this sample, do the following:

  1. If you don't already have it, install Python.

  2. We recommend using a virtual environment to run this example, but it's not mandatory. To initialize a virtual environment:

    pip install virtualenv
    virtualenv mytestenv
    cd mytestenv
    source bin/activate
    
  3. Create a Service Principal, either through Azure CLI, PowerShell or the portal.

  4. Clone this repository and navigate into it.

    git clone https://github.com/Azure-Samples/resource-manager-python-template-deployment.git
    cd resource-manager-python-template-deployment
    
  5. Install all required libraries within the virtual environment.

    pip install -r requirements.txt
    
  6. Create environment variables with the necessary IDs for Azure authentication. You can learn where to find the first three IDs in the Azure portal in this document. The subscription ID is in the subscription's overview in the "Subscriptions" blade of the portal.

    export AZURE_TENANT_ID={your tenant id}
    export AZURE_CLIENT_ID={your client id}
    export AZURE_CLIENT_SECRET={your client secret}
    export AZURE_SUBSCRIPTION_ID={your subscription id}
    
  7. Run the script.

    python azure_deployment.py
    

What is this azure_deployment.py Doing?

The entry point for this sample is azure_deployment.py. This script uses the Deployer class below to deploy the aforementioned template to the subscription and resource group specified in my_resource_group and my_subscription_id respectively. By default the script will use the ssh public key from your default ssh location.

Note: you must set each of the environment variables (AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET) prior to running the script, and either set AZURE_SUBSCRIPTION_ID or replace it in the script. See the numbered list above for instructions on how to do this.

importos.pathfromdeployerimportDeployer# This script expects that the following environment vars are set:## AZURE_TENANT_ID: with your Azure Active Directory tenant id or domain# AZURE_CLIENT_ID: with your Azure Active Directory Application Client ID# AZURE_CLIENT_SECRET: with your Azure Active Directory Application Secretmy_subscription_id=os.environ.get('AZURE_SUBSCRIPTION_ID', '11111111-1111-1111-1111-111111111111') # your Azure Subscription Idmy_resource_group='azure-python-deployment-sample'# the resource group for deploymentmy_pub_ssh_key_path=os.path.expanduser('~/.ssh/id_rsa.pub') # the path to your rsa public key filemsg="\nInitializing the Deployer class with subscription id: {}, resource group: {}" \
"\nand public key located at: {}...\n\n"msg=msg.format(my_subscription_id, my_resource_group, my_pub_ssh_key_path)
print(msg)
# Initialize the deployer classdeployer=Deployer(my_subscription_id, my_resource_group, my_pub_ssh_key_path)
print("Beginning the deployment... \n\n")
# Deploy the templatemy_deployment=deployer.deploy()
print("Done deploying!!\n\nYou can connect via: `ssh azureSample@{}.westus.cloudapp.azure.com`".format(deployer.dns_label_prefix))
# Destroy the resource group which contains the deployment# deployer.destroy()

What is this deployer.py Doing?

The Deployer class consists of the following:

"""A deployer class to deploy a template on Azure"""importos.pathimportjsonfromhaikunatorimportHaikunatorfromazure.common.credentialsimportServicePrincipalCredentialsfromazure.mgmt.resourceimportResourceManagementClientfromazure.mgmt.resource.resources.modelsimportDeploymentModeclassDeployer(object):
""" Initialize the deployer class with subscription, resource group and public key. :raises IOError: If the public key path cannot be read (access or not exists) :raises KeyError: If AZURE_CLIENT_ID, AZURE_CLIENT_SECRET or AZURE_TENANT_ID env variables or not defined """name_generator=Haikunator()
def__init__(self, subscription_id, resource_group, pub_ssh_key_path='~/.ssh/id_rsa.pub'):
self.subscription_id=subscription_idself.resource_group=resource_groupself.dns_label_prefix=self.name_generator.haikunate()
pub_ssh_key_path=os.path.expanduser(pub_ssh_key_path)
# Will raise if file not exists or not enough permissionwithopen(pub_ssh_key_path, 'r') aspub_ssh_file_fd:
self.pub_ssh_key=pub_ssh_file_fd.read()
self.credentials=ServicePrincipalCredentials(
client_id=os.environ['AZURE_CLIENT_ID'],
secret=os.environ['AZURE_CLIENT_SECRET'],
tenant=os.environ['AZURE_TENANT_ID']
)
self.client=ResourceManagementClient(self.credentials, self.subscription_id)
defdeploy(self):
"""Deploy the template to a resource group."""self.client.resource_groups.create_or_update(
self.resource_group,
{
'location':'westus'
}
)
template_path=os.path.join(os.path.dirname(__file__), 'templates', 'template.json')
withopen(template_path, 'r') astemplate_file_fd:
template=json.load(template_file_fd)
parameters= {
'sshKeyData': self.pub_ssh_key,
'vmName': 'azure-deployment-sample-vm',
'dnsLabelPrefix': self.dns_label_prefix
}
parameters= {k: {'value': v} fork, vinparameters.items()}
deployment_properties= {
'mode': DeploymentMode.incremental,
'template': template,
'parameters': parameters
}
deployment_async_operation=self.client.deployments.create_or_update(
self.resource_group,
'azure-sample',
deployment_properties
)
deployment_async_operation.wait()
defdestroy(self):
"""Destroy the given resource group"""self.client.resource_groups.delete(self.resource_group)

The __init__ method initializes the class with the subscription, resource group and public key. The method also fetches the Azure Active Directory bearer token, which will be used in each HTTP request to the Azure Management API. The class will raise exceptions under two conditions: if the public key path does not exist, or if there are empty values for AZURE_TENANT_ID, AZURE_CLIENT_ID or AZURE_CLIENT_SECRET environment variables.

The deploy method does the heavy lifting of creating or updating the resource group, preparing the template parameters and deploying the template.

The destroy method simply deletes the resource group thus deleting all of the resources within that group. Note that it is commented out in azure_deployment.py. But you can uncomment it to easily clean up the resources created by this sample if you no longer need them.

Each of the above methods use the azure.mgmt.resource.ResourceManagementClient class, which resides within the azure-mgmt-resource package (see the docs here).

After the script runs, you should see something like the following in your output:

$ python azure_deployment.py
Initializing the Deployer class with subscription id: 11111111-1111-1111-1111-111111111111, resource group: azure-python-deployment-sample
and public key located at: /Users/you/.ssh/id_rsa.pub...
Beginning the deployment...
Done deploying!!
You can connect via: `ssh azureSample@damp-dew-79.westus.cloudapp.azure.com`

You should be able to run ssh azureSample@{your dns value}.westus.cloudapp.azure.com to connect to your new VM.

About

An example illustrating how to use Python to deploy an Azure Resource Manager Template

Resources

Code of conduct

Contributing

Stars

31 stars

Watchers

386 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - Azure-Samples/resource-manager-python-template-deployment: An example illustrating how to use Python to deploy an Azure Resource Manager Template · GitHub
Skip to content
This repository was archived by the owner on Jun 17, 2024. It is now read-only.

Repository files navigation

page_typesample
languages
python
products
azure
descriptionThis sample explains how to use Azure Resource Manager templates to deploy your Resources to Azure.
urlFragmentresource-manager-python-template-deployment

Deploy an SSH Enabled VM with a Template in Python

This sample explains how to use Azure Resource Manager templates to deploy your Resources to Azure. It shows how to deploy your Resources by using the Azure SDK for Python.

When deploying an application definition with a template, you can provide parameter values to customize how the resources are created. You specify values for these parameters either inline or in a parameter file.

Incremental and complete deployments

By default, Resource Manager handles deployments as incremental updates to the resource group. With incremental deployment, Resource Manager:

  • leaves unchanged resources that exist in the resource group but are not specified in the template
  • adds resources that are specified in the template but do not exist in the resource group
  • does not re-provision resources that exist in the resource group in the same condition defined in the template

With complete deployment, Resource Manager:

  • deletes resources that exist in the resource group but are not specified in the template
  • adds resources that are specified in the template but do not exist in the resource group
  • does not re-provision resources that exist in the resource group in the same condition defined in the template

You specify the type of deployment through the Mode property, as shown in the examples below.

Deploy with Python

In this sample, we are going to deploy a resource template which contains an Ubuntu 16.04 LTS virtual machine using ssh public key authentication, storage account, and virtual network with public IP address. The virtual network contains a single subnet with a single network security group rule which allows traffic on port 22 for ssh with a single network interface belonging to the subnet. The virtual machine is a Standard_D1 size. You can find the template here.

To run this sample, do the following:

  1. If you don't already have it, install Python.

  2. We recommend using a virtual environment to run this example, but it's not mandatory. To initialize a virtual environment:

    pip install virtualenv
    virtualenv mytestenv
    cd mytestenv
    source bin/activate
    
  3. Create a Service Principal, either through Azure CLI, PowerShell or the portal.

  4. Clone this repository and navigate into it.

    git clone https://github.com/Azure-Samples/resource-manager-python-template-deployment.git
    cd resource-manager-python-template-deployment
    
  5. Install all required libraries within the virtual environment.

    pip install -r requirements.txt
    
  6. Create environment variables with the necessary IDs for Azure authentication. You can learn where to find the first three IDs in the Azure portal in this document. The subscription ID is in the subscription's overview in the "Subscriptions" blade of the portal.

    export AZURE_TENANT_ID={your tenant id}
    export AZURE_CLIENT_ID={your client id}
    export AZURE_CLIENT_SECRET={your client secret}
    export AZURE_SUBSCRIPTION_ID={your subscription id}
    
  7. Run the script.

    python azure_deployment.py
    

What is this azure_deployment.py Doing?

The entry point for this sample is azure_deployment.py. This script uses the Deployer class below to deploy the aforementioned template to the subscription and resource group specified in my_resource_group and my_subscription_id respectively. By default the script will use the ssh public key from your default ssh location.

Note: you must set each of the environment variables (AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET) prior to running the script, and either set AZURE_SUBSCRIPTION_ID or replace it in the script. See the numbered list above for instructions on how to do this.

importos.pathfromdeployerimportDeployer# This script expects that the following environment vars are set:## AZURE_TENANT_ID: with your Azure Active Directory tenant id or domain# AZURE_CLIENT_ID: with your Azure Active Directory Application Client ID# AZURE_CLIENT_SECRET: with your Azure Active Directory Application Secretmy_subscription_id=os.environ.get('AZURE_SUBSCRIPTION_ID', '11111111-1111-1111-1111-111111111111') # your Azure Subscription Idmy_resource_group='azure-python-deployment-sample'# the resource group for deploymentmy_pub_ssh_key_path=os.path.expanduser('~/.ssh/id_rsa.pub') # the path to your rsa public key filemsg="\nInitializing the Deployer class with subscription id: {}, resource group: {}" \
"\nand public key located at: {}...\n\n"msg=msg.format(my_subscription_id, my_resource_group, my_pub_ssh_key_path)
print(msg)
# Initialize the deployer classdeployer=Deployer(my_subscription_id, my_resource_group, my_pub_ssh_key_path)
print("Beginning the deployment... \n\n")
# Deploy the templatemy_deployment=deployer.deploy()
print("Done deploying!!\n\nYou can connect via: `ssh azureSample@{}.westus.cloudapp.azure.com`".format(deployer.dns_label_prefix))
# Destroy the resource group which contains the deployment# deployer.destroy()

What is this deployer.py Doing?

The Deployer class consists of the following:

"""A deployer class to deploy a template on Azure"""importos.pathimportjsonfromhaikunatorimportHaikunatorfromazure.common.credentialsimportServicePrincipalCredentialsfromazure.mgmt.resourceimportResourceManagementClientfromazure.mgmt.resource.resources.modelsimportDeploymentModeclassDeployer(object):
""" Initialize the deployer class with subscription, resource group and public key. :raises IOError: If the public key path cannot be read (access or not exists) :raises KeyError: If AZURE_CLIENT_ID, AZURE_CLIENT_SECRET or AZURE_TENANT_ID env variables or not defined """name_generator=Haikunator()
def__init__(self, subscription_id, resource_group, pub_ssh_key_path='~/.ssh/id_rsa.pub'):
self.subscription_id=subscription_idself.resource_group=resource_groupself.dns_label_prefix=self.name_generator.haikunate()
pub_ssh_key_path=os.path.expanduser(pub_ssh_key_path)
# Will raise if file not exists or not enough permissionwithopen(pub_ssh_key_path, 'r') aspub_ssh_file_fd:
self.pub_ssh_key=pub_ssh_file_fd.read()
self.credentials=ServicePrincipalCredentials(
client_id=os.environ['AZURE_CLIENT_ID'],
secret=os.environ['AZURE_CLIENT_SECRET'],
tenant=os.environ['AZURE_TENANT_ID']
)
self.client=ResourceManagementClient(self.credentials, self.subscription_id)
defdeploy(self):
"""Deploy the template to a resource group."""self.client.resource_groups.create_or_update(
self.resource_group,
{
'location':'westus'
}
)
template_path=os.path.join(os.path.dirname(__file__), 'templates', 'template.json')
withopen(template_path, 'r') astemplate_file_fd:
template=json.load(template_file_fd)
parameters= {
'sshKeyData': self.pub_ssh_key,
'vmName': 'azure-deployment-sample-vm',
'dnsLabelPrefix': self.dns_label_prefix
}
parameters= {k: {'value': v} fork, vinparameters.items()}
deployment_properties= {
'mode': DeploymentMode.incremental,
'template': template,
'parameters': parameters
}
deployment_async_operation=self.client.deployments.create_or_update(
self.resource_group,
'azure-sample',
deployment_properties
)
deployment_async_operation.wait()
defdestroy(self):
"""Destroy the given resource group"""self.client.resource_groups.delete(self.resource_group)

The __init__ method initializes the class with the subscription, resource group and public key. The method also fetches the Azure Active Directory bearer token, which will be used in each HTTP request to the Azure Management API. The class will raise exceptions under two conditions: if the public key path does not exist, or if there are empty values for AZURE_TENANT_ID, AZURE_CLIENT_ID or AZURE_CLIENT_SECRET environment variables.

The deploy method does the heavy lifting of creating or updating the resource group, preparing the template parameters and deploying the template.

The destroy method simply deletes the resource group thus deleting all of the resources within that group. Note that it is commented out in azure_deployment.py. But you can uncomment it to easily clean up the resources created by this sample if you no longer need them.

Each of the above methods use the azure.mgmt.resource.ResourceManagementClient class, which resides within the azure-mgmt-resource package (see the docs here).

After the script runs, you should see something like the following in your output:

$ python azure_deployment.py
Initializing the Deployer class with subscription id: 11111111-1111-1111-1111-111111111111, resource group: azure-python-deployment-sample
and public key located at: /Users/you/.ssh/id_rsa.pub...
Beginning the deployment...
Done deploying!!
You can connect via: `ssh azureSample@damp-dew-79.westus.cloudapp.azure.com`

You should be able to run ssh azureSample@{your dns value}.westus.cloudapp.azure.com to connect to your new VM.

About

An example illustrating how to use Python to deploy an Azure Resource Manager Template

Resources

Code of conduct

Contributing

Stars

31 stars

Watchers

386 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); GitHub - Azure-Samples/resource-manager-python-template-deployment: An example illustrating how to use Python to deploy an Azure Resource Manager Template · GitHub
Skip to content
This repository was archived by the owner on Jun 17, 2024. It is now read-only.

Repository files navigation

page_typesample
languages
python
products
azure
descriptionThis sample explains how to use Azure Resource Manager templates to deploy your Resources to Azure.
urlFragmentresource-manager-python-template-deployment

Deploy an SSH Enabled VM with a Template in Python

This sample explains how to use Azure Resource Manager templates to deploy your Resources to Azure. It shows how to deploy your Resources by using the Azure SDK for Python.

When deploying an application definition with a template, you can provide parameter values to customize how the resources are created. You specify values for these parameters either inline or in a parameter file.

Incremental and complete deployments

By default, Resource Manager handles deployments as incremental updates to the resource group. With incremental deployment, Resource Manager:

  • leaves unchanged resources that exist in the resource group but are not specified in the template
  • adds resources that are specified in the template but do not exist in the resource group
  • does not re-provision resources that exist in the resource group in the same condition defined in the template

With complete deployment, Resource Manager:

  • deletes resources that exist in the resource group but are not specified in the template
  • adds resources that are specified in the template but do not exist in the resource group
  • does not re-provision resources that exist in the resource group in the same condition defined in the template

You specify the type of deployment through the Mode property, as shown in the examples below.

Deploy with Python

In this sample, we are going to deploy a resource template which contains an Ubuntu 16.04 LTS virtual machine using ssh public key authentication, storage account, and virtual network with public IP address. The virtual network contains a single subnet with a single network security group rule which allows traffic on port 22 for ssh with a single network interface belonging to the subnet. The virtual machine is a Standard_D1 size. You can find the template here.

To run this sample, do the following:

  1. If you don't already have it, install Python.

  2. We recommend using a virtual environment to run this example, but it's not mandatory. To initialize a virtual environment:

    pip install virtualenv
    virtualenv mytestenv
    cd mytestenv
    source bin/activate
    
  3. Create a Service Principal, either through Azure CLI, PowerShell or the portal.

  4. Clone this repository and navigate into it.

    git clone https://github.com/Azure-Samples/resource-manager-python-template-deployment.git
    cd resource-manager-python-template-deployment
    
  5. Install all required libraries within the virtual environment.

    pip install -r requirements.txt
    
  6. Create environment variables with the necessary IDs for Azure authentication. You can learn where to find the first three IDs in the Azure portal in this document. The subscription ID is in the subscription's overview in the "Subscriptions" blade of the portal.

    export AZURE_TENANT_ID={your tenant id}
    export AZURE_CLIENT_ID={your client id}
    export AZURE_CLIENT_SECRET={your client secret}
    export AZURE_SUBSCRIPTION_ID={your subscription id}
    
  7. Run the script.

    python azure_deployment.py
    

What is this azure_deployment.py Doing?

The entry point for this sample is azure_deployment.py. This script uses the Deployer class below to deploy the aforementioned template to the subscription and resource group specified in my_resource_group and my_subscription_id respectively. By default the script will use the ssh public key from your default ssh location.

Note: you must set each of the environment variables (AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET) prior to running the script, and either set AZURE_SUBSCRIPTION_ID or replace it in the script. See the numbered list above for instructions on how to do this.

importos.pathfromdeployerimportDeployer# This script expects that the following environment vars are set:## AZURE_TENANT_ID: with your Azure Active Directory tenant id or domain# AZURE_CLIENT_ID: with your Azure Active Directory Application Client ID# AZURE_CLIENT_SECRET: with your Azure Active Directory Application Secretmy_subscription_id=os.environ.get('AZURE_SUBSCRIPTION_ID', '11111111-1111-1111-1111-111111111111') # your Azure Subscription Idmy_resource_group='azure-python-deployment-sample'# the resource group for deploymentmy_pub_ssh_key_path=os.path.expanduser('~/.ssh/id_rsa.pub') # the path to your rsa public key filemsg="\nInitializing the Deployer class with subscription id: {}, resource group: {}" \
"\nand public key located at: {}...\n\n"msg=msg.format(my_subscription_id, my_resource_group, my_pub_ssh_key_path)
print(msg)
# Initialize the deployer classdeployer=Deployer(my_subscription_id, my_resource_group, my_pub_ssh_key_path)
print("Beginning the deployment... \n\n")
# Deploy the templatemy_deployment=deployer.deploy()
print("Done deploying!!\n\nYou can connect via: `ssh azureSample@{}.westus.cloudapp.azure.com`".format(deployer.dns_label_prefix))
# Destroy the resource group which contains the deployment# deployer.destroy()

What is this deployer.py Doing?

The Deployer class consists of the following:

"""A deployer class to deploy a template on Azure"""importos.pathimportjsonfromhaikunatorimportHaikunatorfromazure.common.credentialsimportServicePrincipalCredentialsfromazure.mgmt.resourceimportResourceManagementClientfromazure.mgmt.resource.resources.modelsimportDeploymentModeclassDeployer(object):
""" Initialize the deployer class with subscription, resource group and public key. :raises IOError: If the public key path cannot be read (access or not exists) :raises KeyError: If AZURE_CLIENT_ID, AZURE_CLIENT_SECRET or AZURE_TENANT_ID env variables or not defined """name_generator=Haikunator()
def__init__(self, subscription_id, resource_group, pub_ssh_key_path='~/.ssh/id_rsa.pub'):
self.subscription_id=subscription_idself.resource_group=resource_groupself.dns_label_prefix=self.name_generator.haikunate()
pub_ssh_key_path=os.path.expanduser(pub_ssh_key_path)
# Will raise if file not exists or not enough permissionwithopen(pub_ssh_key_path, 'r') aspub_ssh_file_fd:
self.pub_ssh_key=pub_ssh_file_fd.read()
self.credentials=ServicePrincipalCredentials(
client_id=os.environ['AZURE_CLIENT_ID'],
secret=os.environ['AZURE_CLIENT_SECRET'],
tenant=os.environ['AZURE_TENANT_ID']
)
self.client=ResourceManagementClient(self.credentials, self.subscription_id)
defdeploy(self):
"""Deploy the template to a resource group."""self.client.resource_groups.create_or_update(
self.resource_group,
{
'location':'westus'
}
)
template_path=os.path.join(os.path.dirname(__file__), 'templates', 'template.json')
withopen(template_path, 'r') astemplate_file_fd:
template=json.load(template_file_fd)
parameters= {
'sshKeyData': self.pub_ssh_key,
'vmName': 'azure-deployment-sample-vm',
'dnsLabelPrefix': self.dns_label_prefix
}
parameters= {k: {'value': v} fork, vinparameters.items()}
deployment_properties= {
'mode': DeploymentMode.incremental,
'template': template,
'parameters': parameters
}
deployment_async_operation=self.client.deployments.create_or_update(
self.resource_group,
'azure-sample',
deployment_properties
)
deployment_async_operation.wait()
defdestroy(self):
"""Destroy the given resource group"""self.client.resource_groups.delete(self.resource_group)

The __init__ method initializes the class with the subscription, resource group and public key. The method also fetches the Azure Active Directory bearer token, which will be used in each HTTP request to the Azure Management API. The class will raise exceptions under two conditions: if the public key path does not exist, or if there are empty values for AZURE_TENANT_ID, AZURE_CLIENT_ID or AZURE_CLIENT_SECRET environment variables.

The deploy method does the heavy lifting of creating or updating the resource group, preparing the template parameters and deploying the template.

The destroy method simply deletes the resource group thus deleting all of the resources within that group. Note that it is commented out in azure_deployment.py. But you can uncomment it to easily clean up the resources created by this sample if you no longer need them.

Each of the above methods use the azure.mgmt.resource.ResourceManagementClient class, which resides within the azure-mgmt-resource package (see the docs here).

After the script runs, you should see something like the following in your output:

$ python azure_deployment.py
Initializing the Deployer class with subscription id: 11111111-1111-1111-1111-111111111111, resource group: azure-python-deployment-sample
and public key located at: /Users/you/.ssh/id_rsa.pub...
Beginning the deployment...
Done deploying!!
You can connect via: `ssh azureSample@damp-dew-79.westus.cloudapp.azure.com`

You should be able to run ssh azureSample@{your dns value}.westus.cloudapp.azure.com to connect to your new VM.

About

An example illustrating how to use Python to deploy an Azure Resource Manager Template

Resources

Code of conduct

Contributing

Stars

31 stars

Watchers

386 watching

Forks

Releases

Packages

Used by

Contributors

Languages