This repository has been archived by the owner on Jun 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
/
deployer.py
73 lines (61 loc) · 2.65 KB
/
deployer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""A deployer class to deploy a template on Azure"""
import os.path
import json
from haikunator import Haikunator
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.resource.resources.models import DeploymentMode
class Deployer(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_id
self.resource_group = resource_group
self.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 permission
with open(pub_ssh_key_path, 'r') as pub_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)
def deploy(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')
with open(template_path, 'r') as template_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} for k, v in parameters.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()
def destroy(self):
"""Destroy the given resource group"""
self.client.resource_groups.delete(self.resource_group)