| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
from __future__ import absolute_import, division, print_function |
| 7 |
__metaclass__ = type |
| 8 |
|
| 9 |
|
| 10 |
DOCUMENTATION = ''' |
| 11 |
--- |
| 12 |
module: azure_rm_deployment |
| 13 |
|
| 14 |
version_added: "0.1.0" |
| 15 |
|
| 16 |
short_description: Create or destroy Azure Resource Manager template deployments |
| 17 |
|
| 18 |
description: |
| 19 |
- Create or destroy Azure Resource Manager template deployments via the Azure SDK for Python. |
| 20 |
- You can find some quick start templates in GitHub here U(https://github.com/azure/azure-quickstart-templates). |
| 21 |
- For more information on Azure Resource Manager templates see U(https://azure.microsoft.com/en-us/documentation/articles/resource-group-template-deploy/). |
| 22 |
|
| 23 |
options: |
| 24 |
resource_group: |
| 25 |
description: |
| 26 |
- The resource group name to use or create to host the deployed template. |
| 27 |
required: true |
| 28 |
type: str |
| 29 |
aliases: |
| 30 |
- resource_group_name |
| 31 |
name: |
| 32 |
description: |
| 33 |
- The name of the deployment to be tracked in the resource group deployment history. |
| 34 |
- Re-using a deployment name will overwrite the previous value in the resource group's deployment history. |
| 35 |
default: ansible-arm |
| 36 |
type: str |
| 37 |
aliases: |
| 38 |
- deployment_name |
| 39 |
location: |
| 40 |
description: |
| 41 |
- The geo-locations in which the resource group will be located. |
| 42 |
default: westus |
| 43 |
type: str |
| 44 |
deployment_mode: |
| 45 |
description: |
| 46 |
- In incremental mode, resources are deployed without deleting existing resources that are not included in the template. |
| 47 |
- In complete mode resources are deployed and existing resources in the resource group not included in the template are deleted. |
| 48 |
default: incremental |
| 49 |
type: str |
| 50 |
choices: |
| 51 |
- complete |
| 52 |
- incremental |
| 53 |
template: |
| 54 |
description: |
| 55 |
- A hash containing the templates inline. This parameter is mutually exclusive with I(template_link). |
| 56 |
- Either I(template) or I(template_link) is required if I(state=present). |
| 57 |
type: dict |
| 58 |
template_link: |
| 59 |
description: |
| 60 |
- Uri of file containing the template body. This parameter is mutually exclusive with I(template). |
| 61 |
- Either I(template) or I(template_link) is required if I(state=present). |
| 62 |
type: str |
| 63 |
parameters: |
| 64 |
description: |
| 65 |
- A hash of all the required template variables for the deployment template. This parameter is mutually exclusive with I(parameters_link). |
| 66 |
- Either I(parameters_link) or I(parameters) is required if I(state=present). |
| 67 |
type: dict |
| 68 |
parameters_link: |
| 69 |
description: |
| 70 |
- Uri of file containing the parameters body. This parameter is mutually exclusive with I(parameters). |
| 71 |
- Either I(parameters_link) or I(parameters) is required if I(state=present). |
| 72 |
type: str |
| 73 |
wait_for_deployment_completion: |
| 74 |
description: |
| 75 |
- Whether or not to block until the deployment has completed. |
| 76 |
type: bool |
| 77 |
default: true |
| 78 |
wait_for_deployment_polling_period: |
| 79 |
description: |
| 80 |
- Time (in seconds) to wait between polls when waiting for deployment completion. |
| 81 |
default: 10 |
| 82 |
type: int |
| 83 |
state: |
| 84 |
description: |
| 85 |
- If I(state=present), template will be created. |
| 86 |
- If I(state=present) and deployment exists, it will be updated. |
| 87 |
- If I(state=absent), the deployment resource will be deleted. |
| 88 |
default: present |
| 89 |
type: str |
| 90 |
choices: |
| 91 |
- present |
| 92 |
- absent |
| 93 |
|
| 94 |
extends_documentation_fragment: |
| 95 |
- azure.azcollection.azure |
| 96 |
- azure.azcollection.azure_tags |
| 97 |
|
| 98 |
author: |
| 99 |
- David Justice (@devigned) |
| 100 |
- Laurent Mazuel (@lmazuel) |
| 101 |
- Andre Price (@obsoleted) |
| 102 |
|
| 103 |
''' |
| 104 |
|
| 105 |
EXAMPLES = ''' |
| 106 |
# Destroy a template deployment |
| 107 |
- name: Destroy Azure Deploy |
| 108 |
azure_rm_deployment: |
| 109 |
resource_group: myResourceGroup |
| 110 |
name: myDeployment |
| 111 |
state: absent |
| 112 |
|
| 113 |
# Create or update a template deployment based on uris using parameter and template links |
| 114 |
- name: Create Azure Deploy |
| 115 |
azure_rm_deployment: |
| 116 |
resource_group: myResourceGroup |
| 117 |
name: myDeployment |
| 118 |
template_link: 'https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-vm-simple-linux/azuredeploy.json' |
| 119 |
parameters_link: 'https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-vm-simple-linux/azuredeploy.parameters.json' |
| 120 |
|
| 121 |
# Create or update a template deployment based on a uri to the template and parameters specified inline. |
| 122 |
# This deploys a VM with SSH support for a given public key, then stores the result in 'azure_vms'. The result is then |
| 123 |
# used to create a new host group. This host group is then used to wait for each instance to respond to the public IP SSH. |
| 124 |
|
| 125 |
- name: Create Azure Deploy |
| 126 |
azure_rm_deployment: |
| 127 |
resource_group: myResourceGroup |
| 128 |
name: myDeployment |
| 129 |
parameters: |
| 130 |
newStorageAccountName: |
| 131 |
value: devopsclestorage1 |
| 132 |
adminUsername: |
| 133 |
value: devopscle |
| 134 |
dnsNameForPublicIP: |
| 135 |
value: devopscleazure |
| 136 |
location: |
| 137 |
value: West US |
| 138 |
vmSize: |
| 139 |
value: Standard_A2 |
| 140 |
vmName: |
| 141 |
value: ansibleSshVm |
| 142 |
sshKeyData: |
| 143 |
value: YOUR_SSH_PUBLIC_KEY |
| 144 |
template_link: 'https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-vm-sshkey/azuredeploy.json' |
| 145 |
register: azure |
| 146 |
- name: Add new instance to host group |
| 147 |
add_host: |
| 148 |
hostname: "{{ item['ips'][0].public_ip }}" |
| 149 |
groupname: azure_vms |
| 150 |
loop: "{{ azure.deployment.instances }}" |
| 151 |
|
| 152 |
# Deploy an Azure WebApp running a hello world'ish node app |
| 153 |
- name: Create Azure WebApp Deployment at http://devopscleweb.azurewebsites.net/hello.js |
| 154 |
azure_rm_deployment: |
| 155 |
resource_group: myResourceGroup |
| 156 |
name: myDeployment |
| 157 |
parameters: |
| 158 |
repoURL: |
| 159 |
value: 'https://github.com/devigned/az-roadshow-oss.git' |
| 160 |
siteName: |
| 161 |
value: devopscleweb |
| 162 |
hostingPlanName: |
| 163 |
value: someplan |
| 164 |
siteLocation: |
| 165 |
value: westus |
| 166 |
sku: |
| 167 |
value: Standard |
| 168 |
template_link: 'https://raw.githubusercontent.com/azure/azure-quickstart-templates/master/201-web-app-github-deploy/azuredeploy.json' |
| 169 |
|
| 170 |
# Create or update a template deployment based on an inline template and parameters |
| 171 |
- name: Create Azure Deploy |
| 172 |
azure_rm_deployment: |
| 173 |
resource_group: myResourceGroup |
| 174 |
name: myDeployment |
| 175 |
template: |
| 176 |
$schema: "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#" |
| 177 |
contentVersion: "1.0.0.0" |
| 178 |
parameters: |
| 179 |
newStorageAccountName: |
| 180 |
type: "string" |
| 181 |
metadata: |
| 182 |
description: "Unique DNS Name for the Storage Account where the Virtual Machine's disks will be placed." |
| 183 |
adminUsername: |
| 184 |
type: "string" |
| 185 |
metadata: |
| 186 |
description: "User name for the Virtual Machine." |
| 187 |
adminPassword: |
| 188 |
type: "securestring" |
| 189 |
metadata: |
| 190 |
description: "Password for the Virtual Machine." |
| 191 |
dnsNameForPublicIP: |
| 192 |
type: "string" |
| 193 |
metadata: |
| 194 |
description: "Unique DNS Name for the Public IP used to access the Virtual Machine." |
| 195 |
ubuntuOSVersion: |
| 196 |
type: "string" |
| 197 |
defaultValue: "14.04.2-LTS" |
| 198 |
allowedValues: |
| 199 |
- "12.04.5-LTS" |
| 200 |
- "14.04.2-LTS" |
| 201 |
- "15.04" |
| 202 |
metadata: |
| 203 |
description: > |
| 204 |
The Ubuntu version for the VM. This will pick a fully patched image of this given Ubuntu version. |
| 205 |
Allowed values: 12.04.5-LTS, 14.04.2-LTS, 15.04." |
| 206 |
variables: |
| 207 |
location: "West US" |
| 208 |
imagePublisher: "Canonical" |
| 209 |
imageOffer: "UbuntuServer" |
| 210 |
OSDiskName: "osdiskforlinuxsimple" |
| 211 |
nicName: "myVMNic" |
| 212 |
addressPrefix: "192.0.2.0/24" |
| 213 |
subnetName: "Subnet" |
| 214 |
subnetPrefix: "10.0.0.0/24" |
| 215 |
storageAccountType: "Standard_LRS" |
| 216 |
publicIPAddressName: "myPublicIP" |
| 217 |
publicIPAddressType: "Dynamic" |
| 218 |
vmStorageAccountContainerName: "vhds" |
| 219 |
vmName: "MyUbuntuVM" |
| 220 |
vmSize: "Standard_D1" |
| 221 |
virtualNetworkName: "MyVNET" |
| 222 |
vnetID: "[resourceId('Microsoft.Network/virtualNetworks',variables('virtualNetworkName'))]" |
| 223 |
subnetRef: "[concat(variables('vnetID'),'/subnets/',variables('subnetName'))]" |
| 224 |
resources: |
| 225 |
- type: "Microsoft.Storage/storageAccounts" |
| 226 |
name: "[parameters('newStorageAccountName')]" |
| 227 |
apiVersion: "2015-05-01-preview" |
| 228 |
location: "[variables('location')]" |
| 229 |
properties: |
| 230 |
accountType: "[variables('storageAccountType')]" |
| 231 |
- apiVersion: "2015-05-01-preview" |
| 232 |
type: "Microsoft.Network/publicIPAddresses" |
| 233 |
name: "[variables('publicIPAddressName')]" |
| 234 |
location: "[variables('location')]" |
| 235 |
properties: |
| 236 |
publicIPAllocationMethod: "[variables('publicIPAddressType')]" |
| 237 |
dnsSettings: |
| 238 |
domainNameLabel: "[parameters('dnsNameForPublicIP')]" |
| 239 |
- type: "Microsoft.Network/virtualNetworks" |
| 240 |
apiVersion: "2015-05-01-preview" |
| 241 |
name: "[variables('virtualNetworkName')]" |
| 242 |
location: "[variables('location')]" |
| 243 |
properties: |
| 244 |
addressSpace: |
| 245 |
addressPrefixes: |
| 246 |
- "[variables('addressPrefix')]" |
| 247 |
subnets: |
| 248 |
- |
| 249 |
name: "[variables('subnetName')]" |
| 250 |
properties: |
| 251 |
addressPrefix: "[variables('subnetPrefix')]" |
| 252 |
- type: "Microsoft.Network/networkInterfaces" |
| 253 |
apiVersion: "2015-05-01-preview" |
| 254 |
name: "[variables('nicName')]" |
| 255 |
location: "[variables('location')]" |
| 256 |
dependsOn: |
| 257 |
- "[concat('Microsoft.Network/publicIPAddresses/', variables('publicIPAddressName'))]" |
| 258 |
- "[concat('Microsoft.Network/virtualNetworks/', variables('virtualNetworkName'))]" |
| 259 |
properties: |
| 260 |
ipConfigurations: |
| 261 |
- |
| 262 |
name: "ipconfig1" |
| 263 |
properties: |
| 264 |
privateIPAllocationMethod: "Dynamic" |
| 265 |
publicIPAddress: |
| 266 |
id: "[resourceId('Microsoft.Network/publicIPAddresses',variables('publicIPAddressName'))]" |
| 267 |
subnet: |
| 268 |
id: "[variables('subnetRef')]" |
| 269 |
- type: "Microsoft.Compute/virtualMachines" |
| 270 |
apiVersion: "2015-06-15" |
| 271 |
name: "[variables('vmName')]" |
| 272 |
location: "[variables('location')]" |
| 273 |
dependsOn: |
| 274 |
- "[concat('Microsoft.Storage/storageAccounts/', parameters('newStorageAccountName'))]" |
| 275 |
- "[concat('Microsoft.Network/networkInterfaces/', variables('nicName'))]" |
| 276 |
properties: |
| 277 |
hardwareProfile: |
| 278 |
vmSize: "[variables('vmSize')]" |
| 279 |
osProfile: |
| 280 |
computername: "[variables('vmName')]" |
| 281 |
adminUsername: "[parameters('adminUsername')]" |
| 282 |
adminPassword: "[parameters('adminPassword')]" |
| 283 |
storageProfile: |
| 284 |
imageReference: |
| 285 |
publisher: "[variables('imagePublisher')]" |
| 286 |
offer: "[variables('imageOffer')]" |
| 287 |
sku: "[parameters('ubuntuOSVersion')]" |
| 288 |
version: "latest" |
| 289 |
osDisk: |
| 290 |
name: "osdisk" |
| 291 |
vhd: |
| 292 |
uri: > |
| 293 |
[concat('http://',parameters('newStorageAccountName'),'.blob.core.windows.net/',variables('vmStorageAccountContainerName'),'/', |
| 294 |
variables('OSDiskName'),'.vhd')] |
| 295 |
caching: "ReadWrite" |
| 296 |
createOption: "FromImage" |
| 297 |
networkProfile: |
| 298 |
networkInterfaces: |
| 299 |
- |
| 300 |
id: "[resourceId('Microsoft.Network/networkInterfaces',variables('nicName'))]" |
| 301 |
diagnosticsProfile: |
| 302 |
bootDiagnostics: |
| 303 |
enabled: "true" |
| 304 |
storageUri: "[concat('http://',parameters('newStorageAccountName'),'.blob.core.windows.net')]" |
| 305 |
parameters: |
| 306 |
newStorageAccountName: |
| 307 |
value: devopsclestorage |
| 308 |
adminUsername: |
| 309 |
value: devopscle |
| 310 |
adminPassword: |
| 311 |
value: Password1! |
| 312 |
dnsNameForPublicIP: |
| 313 |
value: devopscleazure |
| 314 |
''' |
| 315 |
|
| 316 |
RETURN = ''' |
| 317 |
deployment: |
| 318 |
description: Deployment details. |
| 319 |
type: complex |
| 320 |
returned: always |
| 321 |
contains: |
| 322 |
group_name: |
| 323 |
description: |
| 324 |
- Name of the resource group. |
| 325 |
type: str |
| 326 |
returned: always |
| 327 |
sample: myResourceGroup |
| 328 |
id: |
| 329 |
description: |
| 330 |
- The Azure ID of the deployment. |
| 331 |
type: str |
| 332 |
returned: always |
| 333 |
sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Resources/deployments/myD |
| 334 |
eployment" |
| 335 |
instances: |
| 336 |
description: |
| 337 |
- Provides the public IP addresses for each VM instance. |
| 338 |
type: list |
| 339 |
returned: always |
| 340 |
contains: |
| 341 |
ips: |
| 342 |
description: |
| 343 |
- List of Public IP addresses. |
| 344 |
type: list |
| 345 |
returned: always |
| 346 |
contains: |
| 347 |
dns_settings: |
| 348 |
description: |
| 349 |
- DNS Settings. |
| 350 |
type: complex |
| 351 |
returned: always |
| 352 |
contains: |
| 353 |
domain_name_label: |
| 354 |
description: |
| 355 |
- Domain Name Label. |
| 356 |
type: str |
| 357 |
returned: always |
| 358 |
sample: myvirtualmachine |
| 359 |
fqdn: |
| 360 |
description: |
| 361 |
- Fully Qualified Domain Name. |
| 362 |
type: str |
| 363 |
returned: always |
| 364 |
sample: myvirtualmachine.eastus2.cloudapp.azure.com |
| 365 |
id: |
| 366 |
description: |
| 367 |
- Public IP resource id. |
| 368 |
returned: always |
| 369 |
type: str |
| 370 |
sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/p |
| 371 |
ublicIPAddresses/myPublicIP" |
| 372 |
name: |
| 373 |
description: |
| 374 |
- Public IP resource name. |
| 375 |
returned: always |
| 376 |
type: str |
| 377 |
sample: myPublicIP |
| 378 |
public_ip: |
| 379 |
description: |
| 380 |
- Public IP address value. |
| 381 |
returned: always |
| 382 |
type: str |
| 383 |
sample: 104.209.244.123 |
| 384 |
public_ip_allocation_method: |
| 385 |
description: |
| 386 |
- Public IP allocation method. |
| 387 |
returned: always |
| 388 |
type: str |
| 389 |
sample: Dynamic |
| 390 |
vm_name: |
| 391 |
description: |
| 392 |
- Virtual machine name. |
| 393 |
returned: always |
| 394 |
type: str |
| 395 |
sample: myvirtualmachine |
| 396 |
name: |
| 397 |
description: |
| 398 |
- Name of the deployment. |
| 399 |
type: str |
| 400 |
returned: always |
| 401 |
sample: myDeployment |
| 402 |
outputs: |
| 403 |
description: |
| 404 |
- Dictionary of outputs received from the deployment. |
| 405 |
type: dict |
| 406 |
returned: always |
| 407 |
sample: { "hostname": { "type": "String", "value": "myvirtualmachine.eastus2.cloudapp.azure.com" } } |
| 408 |
''' |
| 409 |
|
| 410 |
|
| 411 |
try: |
| 412 |
import time |
| 413 |
import json |
| 414 |
except ImportError as exc: |
| 415 |
IMPORT_ERROR = "Error importing module prerequisites: %s" % exc |
| 416 |
|
| 417 |
try: |
| 418 |
from azure.core.exceptions import ResourceNotFoundError |
| 419 |
|
| 420 |
except ImportError: |
| 421 |
|
| 422 |
pass |
| 423 |
|
| 424 |
from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase |
| 425 |
|
| 426 |
|
| 427 |
class AzureRMDeploymentManager(AzureRMModuleBase): |
| 428 |
|
| 429 |
def __init__(self): |
| 430 |
|
| 431 |
self.module_arg_spec = dict( |
| 432 |
resource_group=dict(type='str', required=True, aliases=['resource_group_name']), |
| 433 |
name=dict(type='str', default="ansible-arm", aliases=['deployment_name']), |
| 434 |
state=dict(type='str', default='present', choices=['present', 'absent']), |
| 435 |
template=dict(type='dict', default=None), |
| 436 |
parameters=dict(type='dict', default=None), |
| 437 |
template_link=dict(type='str', default=None), |
| 438 |
parameters_link=dict(type='str', default=None), |
| 439 |
location=dict(type='str', default="westus"), |
| 440 |
deployment_mode=dict(type='str', default='incremental', choices=['complete', 'incremental']), |
| 441 |
wait_for_deployment_completion=dict(type='bool', default=True), |
| 442 |
wait_for_deployment_polling_period=dict(type='int', default=10) |
| 443 |
) |
| 444 |
|
| 445 |
mutually_exclusive = [('template', 'template_link'), |
| 446 |
('parameters', 'parameters_link')] |
| 447 |
|
| 448 |
self.resource_group = None |
| 449 |
self.state = None |
| 450 |
self.template = None |
| 451 |
self.parameters = None |
| 452 |
self.template_link = None |
| 453 |
self.parameters_link = None |
| 454 |
self.location = None |
| 455 |
self.deployment_mode = None |
| 456 |
self.name = None |
| 457 |
self.wait_for_deployment_completion = None |
| 458 |
self.wait_for_deployment_polling_period = None |
| 459 |
self.tags = None |
| 460 |
self.append_tags = None |
| 461 |
|
| 462 |
self.results = dict( |
| 463 |
deployment=dict(), |
| 464 |
changed=False, |
| 465 |
msg="" |
| 466 |
) |
| 467 |
|
| 468 |
super(AzureRMDeploymentManager, self).__init__(derived_arg_spec=self.module_arg_spec, |
| 469 |
mutually_exclusive=mutually_exclusive, |
| 470 |
supports_check_mode=False) |
| 471 |
|
| 472 |
def exec_module(self, **kwargs): |
| 473 |
|
| 474 |
for key in list(self.module_arg_spec.keys()) + ['append_tags', 'tags']: |
| 475 |
setattr(self, key, kwargs[key]) |
| 476 |
|
| 477 |
if self.state == 'present': |
| 478 |
deployment = self.deploy_template() |
| 479 |
if deployment is None: |
| 480 |
self.results['deployment'] = dict( |
| 481 |
name=self.name, |
| 482 |
group_name=self.resource_group, |
| 483 |
id=None, |
| 484 |
outputs=None, |
| 485 |
instances=None |
| 486 |
) |
| 487 |
else: |
| 488 |
self.results['deployment'] = dict( |
| 489 |
name=deployment.name, |
| 490 |
group_name=self.resource_group, |
| 491 |
id=deployment.id, |
| 492 |
outputs=deployment.properties.outputs, |
| 493 |
instances=self._get_instances(deployment) |
| 494 |
) |
| 495 |
|
| 496 |
self.results['changed'] = True |
| 497 |
self.results['msg'] = 'deployment succeeded' |
| 498 |
else: |
| 499 |
try: |
| 500 |
if self.get_resource_group(self.resource_group): |
| 501 |
self.destroy_deployment_resource() |
| 502 |
self.results['changed'] = True |
| 503 |
self.results['msg'] = "deployment deleted" |
| 504 |
except Exception: |
| 505 |
|
| 506 |
pass |
| 507 |
|
| 508 |
return self.results |
| 509 |
|
| 510 |
def deploy_template(self): |
| 511 |
""" |
| 512 |
Deploy the targeted template and parameters |
| 513 |
:param module: Ansible module containing the validated configuration for the deployment template |
| 514 |
:param client: resource management client for azure |
| 515 |
:param conn_info: connection info needed |
| 516 |
:return: |
| 517 |
""" |
| 518 |
|
| 519 |
deploy_parameter = self.rm_models.DeploymentProperties(mode=self.deployment_mode) |
| 520 |
if not self.parameters_link: |
| 521 |
deploy_parameter.parameters = self.parameters |
| 522 |
else: |
| 523 |
deploy_parameter.parameters_link = self.rm_models.ParametersLink( |
| 524 |
uri=self.parameters_link |
| 525 |
) |
| 526 |
if not self.template_link: |
| 527 |
deploy_parameter.template = self.template |
| 528 |
else: |
| 529 |
deploy_parameter.template_link = self.rm_models.TemplateLink( |
| 530 |
uri=self.template_link |
| 531 |
) |
| 532 |
|
| 533 |
try: |
| 534 |
|
| 535 |
rg = self.rm_client.resource_groups.get(self.resource_group) |
| 536 |
if rg.tags: |
| 537 |
update_tags, self.tags = self.update_tags(rg.tags) |
| 538 |
except ResourceNotFoundError: |
| 539 |
|
| 540 |
pass |
| 541 |
|
| 542 |
params = self.rm_models.ResourceGroup(location=self.location, tags=self.tags) |
| 543 |
|
| 544 |
try: |
| 545 |
self.rm_client.resource_groups.create_or_update(self.resource_group, params) |
| 546 |
except Exception as exc: |
| 547 |
self.fail("Resource group create_or_update failed with status code: %s and message: %s" % |
| 548 |
(getattr(exc, 'status_code', 'N/A'), getattr(exc, 'message', str(exc)))) |
| 549 |
try: |
| 550 |
result = self.rm_client.deployments.begin_create_or_update(self.resource_group, |
| 551 |
self.name, |
| 552 |
{'properties': deploy_parameter}) |
| 553 |
|
| 554 |
deployment_result = None |
| 555 |
if self.wait_for_deployment_completion: |
| 556 |
deployment_result = self.get_poller_result(result) |
| 557 |
while deployment_result.properties is None or deployment_result.properties.provisioning_state not in ['Canceled', 'Failed', 'Deleted', |
| 558 |
'Succeeded']: |
| 559 |
time.sleep(self.wait_for_deployment_polling_period) |
| 560 |
deployment_result = self.rm_client.deployments.get(self.resource_group, self.name) |
| 561 |
except Exception as exc: |
| 562 |
failed_deployment_operations = self._get_failed_deployment_operations(self.name) |
| 563 |
self.log("Deployment failed %s: %s" % (getattr(exc, 'status_code', 'N/A'), getattr(exc, 'message', str(exc)))) |
| 564 |
error_msg = self._error_msg_from_cloud_error(exc) |
| 565 |
self.fail(error_msg, failed_deployment_operations=failed_deployment_operations) |
| 566 |
|
| 567 |
if self.wait_for_deployment_completion and deployment_result.properties.provisioning_state != 'Succeeded': |
| 568 |
self.log("provisioning state: %s" % deployment_result.properties.provisioning_state) |
| 569 |
failed_deployment_operations = self._get_failed_deployment_operations(self.name) |
| 570 |
self.fail('Deployment failed. Deployment id: %s' % deployment_result.id, |
| 571 |
failed_deployment_operations=failed_deployment_operations) |
| 572 |
|
| 573 |
return deployment_result |
| 574 |
|
| 575 |
def destroy_deployment_resource(self): |
| 576 |
""" |
| 577 |
Destroy the targeted resource group |
| 578 |
""" |
| 579 |
try: |
| 580 |
result = self.rm_client.deployments.begin_delete(self.resource_group, self.name) |
| 581 |
result.wait() |
| 582 |
except Exception as e: |
| 583 |
if getattr(e, 'status_code', None) in (404, 204): |
| 584 |
return |
| 585 |
else: |
| 586 |
self.fail("Delete resource group and deploy failed with status code: %s and message: %s" % |
| 587 |
(getattr(e, 'status_code', 'N/A'), getattr(e, 'message', str(e)))) |
| 588 |
|
| 589 |
def _get_failed_nested_operations(self, current_operations): |
| 590 |
new_operations = [] |
| 591 |
for operation in current_operations: |
| 592 |
if operation.properties.provisioning_state == 'Failed': |
| 593 |
new_operations.append(operation) |
| 594 |
if operation.properties.target_resource and \ |
| 595 |
'Microsoft.Resources/deployments' in operation.properties.target_resource.id: |
| 596 |
nested_deployment = operation.properties.target_resource.resource_name |
| 597 |
try: |
| 598 |
nested_operations = self.rm_client.deployment_operations.list(self.resource_group, |
| 599 |
nested_deployment) |
| 600 |
except Exception as exc: |
| 601 |
self.fail("List nested deployment operations failed with status code: %s and message: %s" % |
| 602 |
(getattr(exc, 'status_code', 'N/A'), getattr(exc, 'message', str(exc)))) |
| 603 |
new_nested_operations = self._get_failed_nested_operations(nested_operations) |
| 604 |
new_operations += new_nested_operations |
| 605 |
return new_operations |
| 606 |
|
| 607 |
def _get_failed_deployment_operations(self, name): |
| 608 |
results = [] |
| 609 |
|
| 610 |
|
| 611 |
|
| 612 |
try: |
| 613 |
operations = self.rm_client.deployment_operations.list(self.resource_group, name) |
| 614 |
except Exception as exc: |
| 615 |
self.fail("Get deployment failed with status code: %s and message: %s" % |
| 616 |
(getattr(exc, 'status_code', 'N/A'), getattr(exc, 'message', str(exc)))) |
| 617 |
try: |
| 618 |
results = [ |
| 619 |
dict( |
| 620 |
id=op.id, |
| 621 |
operation_id=op.operation_id, |
| 622 |
status_code=op.properties.status_code, |
| 623 |
status_message=self._serialize_status_message(op.properties.status_message), |
| 624 |
target_resource=dict( |
| 625 |
id=op.properties.target_resource.id, |
| 626 |
resource_name=op.properties.target_resource.resource_name, |
| 627 |
resource_type=op.properties.target_resource.resource_type |
| 628 |
) if op.properties.target_resource else None, |
| 629 |
provisioning_state=op.properties.provisioning_state, |
| 630 |
) |
| 631 |
for op in self._get_failed_nested_operations(operations) |
| 632 |
] |
| 633 |
except Exception: |
| 634 |
|
| 635 |
pass |
| 636 |
self.log(dict(failed_deployment_operations=results), pretty_print=True) |
| 637 |
return results |
| 638 |
|
| 639 |
def _get_instances(self, deployment): |
| 640 |
dep_tree = self._build_hierarchy(deployment.properties.dependencies) |
| 641 |
vms = self._get_dependencies(dep_tree, resource_type="Microsoft.Compute/virtualMachines") |
| 642 |
vms_and_nics = [(vm, self._get_dependencies(vm['children'], "Microsoft.Network/networkInterfaces")) |
| 643 |
for vm in vms] |
| 644 |
vms_and_ips = [(vm['dep'], self._nic_to_public_ips_instance(nics)) |
| 645 |
for vm, nics in vms_and_nics] |
| 646 |
return [dict(vm_name=vm.resource_name, ips=[self._get_ip_dict(ip) |
| 647 |
for ip in ips]) for vm, ips in vms_and_ips if len(ips) > 0] |
| 648 |
|
| 649 |
def _get_dependencies(self, dep_tree, resource_type): |
| 650 |
matches = [value for value in dep_tree.values() if value['dep'].resource_type == resource_type] |
| 651 |
for child_tree in [value['children'] for value in dep_tree.values()]: |
| 652 |
matches += self._get_dependencies(child_tree, resource_type) |
| 653 |
return matches |
| 654 |
|
| 655 |
def _build_hierarchy(self, dependencies, tree=None): |
| 656 |
tree = dict(top=True) if tree is None else tree |
| 657 |
for dep in dependencies: |
| 658 |
if dep.resource_name not in tree: |
| 659 |
tree[dep.resource_name] = dict(dep=dep, children=dict()) |
| 660 |
if isinstance(dep, self.rm_models.Dependency) and dep.depends_on is not None and len(dep.depends_on) > 0: |
| 661 |
self._build_hierarchy(dep.depends_on, tree[dep.resource_name]['children']) |
| 662 |
|
| 663 |
if 'top' in tree: |
| 664 |
tree.pop('top', None) |
| 665 |
keys = list(tree.keys()) |
| 666 |
for key1 in keys: |
| 667 |
for key2 in keys: |
| 668 |
if key2 in tree and key1 in tree[key2]['children'] and key1 in tree: |
| 669 |
tree[key2]['children'][key1] = tree[key1] |
| 670 |
tree.pop(key1) |
| 671 |
return tree |
| 672 |
|
| 673 |
def _get_ip_dict(self, ip): |
| 674 |
ip_dict = dict(name=ip.name, |
| 675 |
id=ip.id, |
| 676 |
public_ip=ip.ip_address, |
| 677 |
public_ip_allocation_method=str(ip.public_ip_allocation_method) |
| 678 |
) |
| 679 |
if ip.dns_settings: |
| 680 |
ip_dict['dns_settings'] = { |
| 681 |
'domain_name_label': ip.dns_settings.domain_name_label, |
| 682 |
'fqdn': ip.dns_settings.fqdn |
| 683 |
} |
| 684 |
return ip_dict |
| 685 |
|
| 686 |
def _nic_to_public_ips_instance(self, nics): |
| 687 |
nic_list = [] |
| 688 |
for nic in nics: |
| 689 |
resp = None |
| 690 |
try: |
| 691 |
resp = self.network_client.network_interfaces.get(self.resource_group, nic['dep'].resource_name) |
| 692 |
except ResourceNotFoundError: |
| 693 |
pass |
| 694 |
if resp is not None: |
| 695 |
nic_list.append(resp) |
| 696 |
|
| 697 |
return [self.network_client.public_ip_addresses.get(public_ip_id.split('/')[4], public_ip_id.split('/')[-1]) |
| 698 |
for nic_obj in nic_list |
| 699 |
for public_ip_id in [ip_conf_instance.public_ip_address.id |
| 700 |
for ip_conf_instance in nic_obj.ip_configurations |
| 701 |
if ip_conf_instance.public_ip_address]] |
| 702 |
|
| 703 |
@staticmethod |
| 704 |
def _serialize_status_message(status_message): |
| 705 |
"""Convert a StatusMessage SDK model to a JSON-serializable dict.""" |
| 706 |
if status_message is None: |
| 707 |
return None |
| 708 |
try: |
| 709 |
result = {'status': getattr(status_message, 'status', None)} |
| 710 |
error = getattr(status_message, 'error', None) |
| 711 |
if error is not None: |
| 712 |
error_dict = { |
| 713 |
'code': getattr(error, 'code', None), |
| 714 |
'message': getattr(error, 'message', None), |
| 715 |
'target': getattr(error, 'target', None), |
| 716 |
} |
| 717 |
if hasattr(error, 'details') and error.details: |
| 718 |
error_dict['details'] = [ |
| 719 |
{'code': getattr(d, 'code', None), 'message': getattr(d, 'message', None)} |
| 720 |
for d in error.details |
| 721 |
] |
| 722 |
result['error'] = error_dict |
| 723 |
return result |
| 724 |
except Exception: |
| 725 |
return str(status_message) |
| 726 |
|
| 727 |
def _error_msg_from_cloud_error(self, exc): |
| 728 |
""" |
| 729 |
Build a human-readable deployment error message from an Azure SDK exception. |
| 730 |
|
| 731 |
When the exception carries OData error details (exc.error.details), |
| 732 |
extract the per-resource messages. |
| 733 |
|
| 734 |
Some resource providers double-encode their error as JSON inside the message field, so we attempt to decode it. |
| 735 |
""" |
| 736 |
error = getattr(exc, 'error', None) |
| 737 |
if error is not None and getattr(error, 'details', None): |
| 738 |
detail_messages = [] |
| 739 |
for detail in error.details: |
| 740 |
raw_msg = getattr(detail, 'message', '') |
| 741 |
try: |
| 742 |
inner = json.loads(raw_msg) |
| 743 |
raw_msg = inner.get('message', raw_msg) |
| 744 |
except (json.JSONDecodeError, TypeError, AttributeError): |
| 745 |
pass |
| 746 |
code = getattr(detail, 'code', None) |
| 747 |
if code: |
| 748 |
raw_msg = '{0} (Code: {1})'.format(raw_msg, code) |
| 749 |
detail_messages.append(raw_msg) |
| 750 |
return 'Deployment failed: {0}'.format(' | '.join(detail_messages)) |
| 751 |
|
| 752 |
return 'Deployment failed: {0}'.format(getattr(exc, 'message', str(exc))) |
| 753 |
|
| 754 |
|
| 755 |
def main(): |
| 756 |
AzureRMDeploymentManager() |
| 757 |
|
| 758 |
|
| 759 |
if __name__ == '__main__': |
| 760 |
main() |