Deploy Certificates to VMs from customer-managed Key Vault in Python

Автор: Laurent Mazuel
Последнее обновление: 18.12.2017
Редактирование в GitHub

This sample explains how you can create a VM in Python, with certificates installed automatically from a Key Vault account.

Getting Started



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

    This sample (and the SDK) is compatible with Python 2.7, 3.4, 3.5 and 3.6.

  2. We recommend that you use a virtual environment to run this example, but it's not required. Install and initialize the virtual environment with the "venv" module on Python 3 (you must install virtualenv for Python 2.7):

    python -m venv mytestenv # Might be "python3" or "py -3.6" depending on your Python installation
    cd mytestenv
    source bin/activate      # Linux shell (Bash, ZSH, etc.) only
    ./scripts/activate       # PowerShell only
    ./scripts/activate.bat   # Windows CMD only
  3. Clone the repository.

    git clone
  4. Install the dependencies using pip.

    cd key-vault-python-deploy-certificates-to-vm
    pip install -r requirements.txt
  5. Export these environment variables into your current shell or update the credentials in the example file.

    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}
  6. Run the sample.



Preliminary operations

This example setup some preliminary components that are no the topic of this sample and do not differ from regular scenarios:

  • A Resource Group
  • A Virtual Network
  • A Subnet
  • A Public IP
  • A Network Interface

For details about creation of these components, you can refer to the generic samples:

Creating a KeyVault account enabled for deployment

    vault = kv_mgmt_client.vaults.create_or_update(
            'location': LOCATION,
            'properties': {
                'sku': {
                    'name': 'standard'
                'tenant_id': os.environ['AZURE_TENANT_ID'],
                'access_policies': [{
                    'tenant_id': os.environ['AZURE_TENANT_ID'],
                    'object_id': sp_object_id,
                    'permissions': {
                        # Only "certificates" and "secrets" are needed for this sample
                        'certificates': ['all'],
                        'secrets': ['all']
                # Critical to allow the VM to download certificates later
                'enabled_for_deployment': True

You can also found different example on how to create a Key Vault account:

  • From CLI 2.0:
  • From Python SDK:

In order to execute this sample, your Key Vault account MUST have the "enabled-for-deployment" special permission. The EnabledForDeployment flag explicitly gives Azure (Microsoft.Compute resource provider) permission to use the certificates stored as secrets for this deployment.

Note that access policy takes an object_id, not a client_id as parameter. This samples also provide a quick way to convert a Service Principal client_id to an object_id using the azure-graphrbac client.

Ask Key Vault to create a certificate for you


An example of DEFAULT_POLICY is described in the sample file: python DEFAULT_POLICY = CertificatePolicy( KeyProperties(True, 'RSA', 2048, True), SecretProperties('application/x-pkcs12'), issuer_parameters=IssuerParameters('Self'), x509_certificate_properties=X509CertificateProperties( subject='CN=CLIGetDefaultPolicy', validity_in_months=12, key_usage=[ "cRLSign", "dataEncipherment", "digitalSignature", "keyEncipherment", "keyAgreement", "keyCertSign" ] ), lifetime_actions=[{ "action": Action( action_type="AutoRenew" ), "trigger": Trigger( days_before_expiry=90 ) }] )

This is the same policy that:

  • Is pre-configured in the Portal when you choose "Generate" in the Certificates tab
  • You get when you use the CLI 2.0: az keyvault certificate get-default-policy

Create certificate is an async operation. This sample provides a simple polling mechanism example.

Create a VM with Certificates from Key Vault

First, get your certificate as a Secret object:

    certificate_as_secret = kv_client.get_secret(,
        "" # Latest version

During the creation of the VM, use the secrets atribute to assign your certificate:.

params_create = {
    'location': LOCATION,
    'hardware_profile': get_hardware_profile(),
    'network_profile': get_network_profile(,
    'storage_profile': get_storage_profile(),
    'os_profile': {
        'admin_username': ADMIN_LOGIN,
        'admin_password': ADMIN_PASSWORD,
        'computer_name': 'testkvcertificates',
        # This is the Key Vault critical part
        'secrets': [{
            'source_vault': {
            'vault_certificates': [{

vm_poller = compute_client.virtual_machines.create_or_update(
vm_result = vm_poller.result()