# Buggy code
def create_default_storage_account(self):
    """
    Create a default storage account <vm name>XXXX, where XXXX is a random number. If <vm name>XXXX exists, use it.
    Otherwise, create one.

    :return: storage account object
    """
    account = None
    valid_name = False

    # Attempt to find a valid storage account name
    storage_account_name_base = self.name[:20].lower()
    for i in range(0, 5):
        rand = random.randrange(1000, 9999)
        storage_account_name = storage_account_name_base + str(rand)
        if self.check_storage_account_name(storage_account_name):
            valid_name = True
            break

    if not valid_name:
        self.fail(
            "Failed to create a unique storage account name for {0}. Try using a different VM name.".format(
                self.name
            )
        )

    try:
        account = self.storage_client.storage_accounts.get_properties(
            self.resource_group, storage_account_name
        )
    except CloudError:
        pass

    if account:
        self.log("Storage account {0} found.".format(storage_account_name))
        self.check_provisioning_state(account)
        return account
    sku = Sku(SkuName.standard_lrs)
    Sku.tier = SkuTier.standard
    kind = Kind.storage
    parameters = StorageAccountCreateParameters(sku, kind, self.location)
    self.log(
        "Creating storage account {0} in location {1}".format(
            storage_account_name, self.location
        )
    )
    self.results["actions"].append(
        "Created storage account {0}".format(storage_account_name)
    )
    try:
        poller = self.storage_client.storage_accounts.create(
            self.resource_group, storage_account_name, parameters
        )
        self.get_poller_result(poller)
    except Exception as exc:
        self.fail(
            "Failed to create storage account: {0} - {1}".format(
                storage_account_name, str(exc)
            )
        )
    return self.get_storage_account(storage_account_name)


# Traceback (AttributeError)
TASK [Clean up VM] **************************************************************************************************************************
task path: /home/elaurijssens/voyager-image-factory/playbooks/azure/vm_delete.yml:19
Using module file /usr/lib/python2.7/site-packages/ansible-2.4.0-py2.7.egg/ansible/modules/cloud/azure/azure_rm_virtualmachine.py
<localhost> ESTABLISH LOCAL CONNECTION FOR USER: root
<localhost> EXEC /bin/sh -c 'echo ~ &amp;&amp; sleep 0'
<localhost> EXEC /bin/sh -c '( umask 77 &amp;&amp; mkdir -p "` echo /root/.ansible/tmp/ansible-tmp-1505157460.96-218311556974775 `" &amp;&amp; echo ansible-tmp-1505157460.96-218311556974775="` echo /root/.ansible/tmp/ansible-tmp-1505157460.96-218311556974775 `" ) &amp;&amp; sleep 0'
<localhost> PUT /tmp/tmpb9uhEf TO /root/.ansible/tmp/ansible-tmp-1505157460.96-218311556974775/azure_rm_virtualmachine.py
<localhost> EXEC /bin/sh -c 'chmod u+x /root/.ansible/tmp/ansible-tmp-1505157460.96-218311556974775/ /root/.ansible/tmp/ansible-tmp-1505157460.96-218311556974775/azure_rm_virtualmachine.py &amp;&amp; sleep 0'
<localhost> EXEC /bin/sh -c '/usr/bin/python /root/.ansible/tmp/ansible-tmp-1505157460.96-218311556974775/azure_rm_virtualmachine.py; rm -rf "/root/.ansible/tmp/ansible-tmp-1505157460.96-218311556974775/" > /dev/null 2>&amp;1 &amp;&amp; sleep 0'
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_QSCsG6/ansible_module_azure_rm_virtualmachine.py", line 1524, in <module>
main()
File "/tmp/ansible_QSCsG6/ansible_module_azure_rm_virtualmachine.py", line 1521, in main
AzureRMVirtualMachine()
File "/tmp/ansible_QSCsG6/ansible_module_azure_rm_virtualmachine.py", line 652, in __init__
supports_check_mode=True)
File "/tmp/ansible_QSCsG6/ansible_modlib.zip/ansible/module_utils/azure_rm_common.py", line 255, in __init__
File "/tmp/ansible_QSCsG6/ansible_module_azure_rm_virtualmachine.py", line 1074, in exec_module
self.delete_vm(vm)
File "/tmp/ansible_QSCsG6/ansible_module_azure_rm_virtualmachine.py", line 1191, in delete_vm
vhd_uris.append(vm.storage_profile.os_disk.vhd.uri)
AttributeError: 'NoneType' object has no attribute 'uri'

fatal: [localhost]: FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_QSCsG6/ansible_module_azure_rm_virtualmachine.py\", line 1524, in <module>\n    main()\n  File \"/tmp/ansible_QSCsG6/ansible_module_azure_rm_virtualmachine.py\", line 1521, in main\n    AzureRMVirtualMachine()\n  File \"/tmp/ansible_QSCsG6/ansible_module_azure_rm_virtualmachine.py\", line 652, in __init__\n    supports_check_mode=True)\n  File \"/tmp/ansible_QSCsG6/ansible_modlib.zip/ansible/module_utils/azure_rm_common.py\", line 255, in __init__\n  File \"/tmp/ansible_QSCsG6/ansible_module_azure_rm_virtualmachine.py\", line 1074, in exec_module\n    self.delete_vm(vm)\n  File \"/tmp/ansible_QSCsG6/ansible_module_azure_rm_virtualmachine.py\", line 1191, in delete_vm\n    vhd_uris.append(vm.storage_profile.os_disk.vhd.uri)\nAttributeError: 'NoneType' object has no attribute 'uri'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def create_default_storage_account(self):
    """
    Create a default storage account <vm name>XXXX, where XXXX is a random number. If <vm name>XXXX exists, use it.
    Otherwise, create one.

    :return: storage account object
    """
    account = None
    valid_name = False

    # Attempt to find a valid storage account name
    storage_account_name_base = re.sub("[^a-zA-Z0-9]", "", self.name[:20].lower())
    for i in range(0, 5):
        rand = random.randrange(1000, 9999)
        storage_account_name = storage_account_name_base + str(rand)
        if self.check_storage_account_name(storage_account_name):
            valid_name = True
            break

    if not valid_name:
        self.fail(
            "Failed to create a unique storage account name for {0}. Try using a different VM name.".format(
                self.name
            )
        )

    try:
        account = self.storage_client.storage_accounts.get_properties(
            self.resource_group, storage_account_name
        )
    except CloudError:
        pass

    if account:
        self.log("Storage account {0} found.".format(storage_account_name))
        self.check_provisioning_state(account)
        return account
    sku = Sku(SkuName.standard_lrs)
    Sku.tier = SkuTier.standard
    kind = Kind.storage
    parameters = StorageAccountCreateParameters(sku, kind, self.location)
    self.log(
        "Creating storage account {0} in location {1}".format(
            storage_account_name, self.location
        )
    )
    self.results["actions"].append(
        "Created storage account {0}".format(storage_account_name)
    )
    try:
        poller = self.storage_client.storage_accounts.create(
            self.resource_group, storage_account_name, parameters
        )
        self.get_poller_result(poller)
    except Exception as exc:
        self.fail(
            "Failed to create storage account: {0} - {1}".format(
                storage_account_name, str(exc)
            )
        )
    return self.get_storage_account(storage_account_name)