async def test_example_certificate_list_operations(self, vault_client, **kwargs): certificate_client = vault_client.certificates # specify the certificate policy cert_policy = CertificatePolicy( issuer_name=WellKnownIssuerNames.self, subject="CN=*.microsoft.com", san_dns_names=["sdk.azure-int.net"], exportable=True, key_type="RSA", key_size=2048, reuse_key=False, content_type=CertificateContentType.pkcs12, validity_in_months=24, ) polling_interval = 0 if self.is_playback() else None create_certificate_pollers = [] for i in range(4): create_certificate_pollers.append( certificate_client.create_certificate( certificate_name="certificate{}".format(i), policy=cert_policy, _polling_interval=polling_interval)) for poller in create_certificate_pollers: await poller # [START list_properties_of_certificates] # list certificates certificates = certificate_client.list_properties_of_certificates() async for certificate in certificates: print(certificate.id) print(certificate.created_on) print(certificate.name) print(certificate.updated_on) print(certificate.enabled) # [END list_properties_of_certificates] # [START list_properties_of_certificate_versions] # get an iterator of all versions of a certificate certificate_versions = certificate_client.list_properties_of_certificate_versions( "cert-name") async for certificate in certificate_versions: print(certificate.id) print(certificate.properties.updated_on) print(certificate.properties.version) # [END list_properties_of_certificate_versions] # [START list_deleted_certificates] # get an iterator of deleted certificates (requires soft-delete enabled for the vault) deleted_certificates = certificate_client.list_deleted_certificates() async for certificate in deleted_certificates: print(certificate.id) print(certificate.name) print(certificate.scheduled_purge_date) print(certificate.recovery_id) print(certificate.deleted_on)
# Let's create a certificate for holding bank account credentials valid for 1 year. # if the certificate already exists in the Key Vault, then a new version of the certificate is created. print("\n.. Create certificate") # Before creating your certificate, let's create the management policy for your certificate. # Here you specify the properties of the key, secret, and issuer backing your certificate, # the X509 component of your certificate, and any lifetime actions you would like to be taken # on your certificate # Alternatively, if you would like to use our default policy, use CertificatePolicy.get_default() cert_policy = CertificatePolicy( issuer_name=WellKnownIssuerNames.self, subject="CN=*.microsoft.com", san_dns_names=["sdk.azure-int.net"], exportable=True, key_type="RSA", key_size=2048, reuse_key=False, content_type=CertificateContentType.pkcs12, validity_in_months=24, ) cert_name = "HelloWorldCertificate" # begin_create_certificate returns a poller. Calling result() on the poller will return the certificate # as a KeyVaultCertificate if creation is successful, and the CertificateOperation if not. The wait() # call on the poller will wait until the long running operation is complete. certificate = client.begin_create_certificate( certificate_name=cert_name, policy=cert_policy ).result() print("Certificate with name '{0}' created".format(certificate.name))
def test_example_certificate_crud_operations(self, vault_client, **kwargs): certificate_client = vault_client.certificates # [START create_certificate] from azure.keyvault.certificates import CertificatePolicy, SecretContentType # specify the certificate policy cert_policy = CertificatePolicy( exportable=True, key_type="RSA", key_size=2048, reuse_key=False, content_type=SecretContentType.PKCS12, issuer_name="Self", subject_name="CN=*.microsoft.com", validity_in_months=24, san_dns_names=["sdk.azure-int.net"], ) cert_name = "cert-name" # create a certificate with optional arguments, returns a long running operation poller certificate_operation_poller = certificate_client.begin_create_certificate( name=cert_name, policy=cert_policy) # Here we are waiting for the certificate creation operation to be completed certificate = certificate_operation_poller.result() # You can get the final status of the certificate operation poller using .result() print(certificate_operation_poller.result()) print(certificate.id) print(certificate.name) print(certificate.policy.issuer_name) # [END create_certificate] # [START get_certificate] # get the certificate certificate = certificate_client.get_certificate(name=cert_name) print(certificate.id) print(certificate.name) print(certificate.policy.issuer_name) # [END get_certificate] # [START update_certificate] # update attributes of an existing certificate tags = {"foo": "updated tag"} updated_certificate = certificate_client.update_certificate_properties( name=certificate.name, tags=tags) print(updated_certificate.properties.version) print(updated_certificate.properties.updated_on) print(updated_certificate.properties.tags) # [END update_certificate] # [START delete_certificate] # delete a certificate deleted_certificate = certificate_client.begin_delete_certificate( name=certificate.name).result() print(deleted_certificate.name) # if the vault has soft-delete enabled, the certificate's deleted date, # scheduled purge date, and recovery id are available print(deleted_certificate.deleted_date) print(deleted_certificate.scheduled_purge_date) print(deleted_certificate.recovery_id)
async def test_crud_operations(self, vault_client, **kwargs): self.assertIsNotNone(vault_client) client = vault_client.certificates cert_name = self.get_resource_name("cert") lifetime_actions = [ LifetimeAction(trigger=Trigger(lifetime_percentage=80), action=Action(action_type=ActionType.auto_renew)) ] cert_policy = CertificatePolicyGenerated( key_properties=KeyProperties(exportable=True, key_type="RSA", key_size=2048, reuse_key=False), secret_properties=SecretProperties( content_type="application/x-pkcs12"), issuer_parameters=IssuerParameters(name="Self"), lifetime_actions=lifetime_actions, x509_certificate_properties=X509CertificateProperties( subject="CN=DefaultPolicy", validity_in_months=12, key_usage=["digitalSignature", "keyEncipherment"]), ) polling_interval = 0 if self.is_playback() else None # create certificate cert = await client.create_certificate( certificate_name=cert_name, policy=CertificatePolicy.get_default(), _polling_interval=polling_interval) self._validate_certificate_bundle(cert=cert, vault=client.vault_url, cert_name=cert_name, cert_policy=cert_policy) self.assertEqual( (await client.get_certificate_operation(certificate_name=cert_name )).status.lower(), "completed") # get certificate cert = await client.get_certificate(certificate_name=cert_name) self._validate_certificate_bundle(cert=cert, vault=client.vault_url, cert_name=cert_name, cert_policy=cert_policy) # update certificate tags = {"tag1": "updated_value1"} cert_bundle = await client.update_certificate_properties(cert_name, tags=tags) self._validate_certificate_bundle(cert=cert_bundle, vault=client.vault_url, cert_name=cert_name, cert_policy=cert_policy) self.assertEqual(tags, cert_bundle.properties.tags) self.assertEqual(cert.id, cert_bundle.id) self.assertNotEqual(cert.properties.updated_on, cert_bundle.properties.updated_on) # delete certificate deleted_cert_bundle = await client.delete_certificate( certificate_name=cert_name, _polling_interval=polling_interval) self._validate_certificate_bundle(cert=deleted_cert_bundle, vault=client.vault_url, cert_name=cert_name, cert_policy=cert_policy) # get certificate returns not found try: await client.get_certificate_version( cert_name, deleted_cert_bundle.properties.version) self.fail("Get should fail") except Exception as ex: if not hasattr(ex, "message") or "not found" not in ex.message.lower(): raise ex
# Instantiate a certificate client that will be used to call the service. # Notice that the client is using default Azure credentials. # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID', # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials. VAULT_URL = os.environ["VAULT_URL"] credential = DefaultAzureCredential() client = CertificateClient(vault_url=VAULT_URL, credential=credential) print("\n.. Create Certificate") cert_name = "BackupRestoreCertificate" # Let's create a certificate for your key vault. # if the certificate already exists in the Key Vault, then a new version of the certificate is created. # A long running poller is returned for the create certificate operation. create_certificate_poller = client.begin_create_certificate( certificate_name=cert_name, policy=CertificatePolicy.get_default()) # The result call awaits the completion of the create certificate operation and returns the final result. # It will return a certificate if creation is successful, and will return the CertificateOperation if not. certificate = create_certificate_poller.result() print("Certificate with name '{0}' created.".format(cert_name)) # Backups are good to have, if in case certificates gets deleted accidentally. # For long term storage, it is ideal to write the backup to a file. print("\n.. Create a backup for an existing certificate") certificate_backup = client.backup_certificate(cert_name) print("Backup created for certificate with name '{0}'.".format(cert_name)) # The storage account certificate is no longer in use, so you can delete it. print("\n.. Delete the certificate") delete_operation = client.begin_delete_certificate(cert_name)
async def create_certificate(self): print("Creating a certificate...") await self.certificate_client.create_certificate( certificate_name=self.certificate_name, policy=CertificatePolicy.get_default()) print("\tdone")
VAULT_URL = os.environ["VAULT_URL"] credential = DefaultAzureCredential() certificate_client = CertificateClient(vault_url=VAULT_URL, credential=credential) # Instantiate a secret client that will be used to call the service. # Notice that this client can reuse the credential object created above. secret_client = SecretClient(vault_url=VAULT_URL, credential=credential) try: # Let's create a certificate in the vault. # If the certificate already exists in the Key Vault, then a new version of the certificate is created. print("\n.. Create certificate") # Before creating your certificate, let's create the management policy for your certificate. # Here we use the default policy. cert_name = "PrivateKeyCertificate" cert_policy = CertificatePolicy.get_default() # begin_create_certificate returns a poller. Calling result() on the poller will return the certificate # as a KeyVaultCertificate if creation is successful, and the CertificateOperation if not. The wait() # call on the poller will wait until the long running operation is complete. created_certificate = certificate_client.begin_create_certificate( certificate_name=cert_name, policy=cert_policy ).result() print("Certificate with name '{}' was created".format(created_certificate.name)) # Key Vault also creates a secret with the same name as the created certificate. # This secret contains the certificate's bytes, which include the private key if the certificate's # policy indicates that the key is exportable. print("\n.. Get a secret by name") certificate_secret = secret_client.get_secret(name=cert_name) print("Certificate secret with name '{}' was found.".format(certificate_secret.name))
secrets: [] certs: [] TEST_DATA = TestData(secrets=[{ 'name': f'test-secret-{str(uuid.uuid4())}', 'value': str(uuid.uuid4()) }, { 'name': f'test-secret-{str(uuid.uuid4())}', 'value': str(uuid.uuid4()) }], certs=[{ 'name': 'test-cert-' + str(uuid.uuid4()), 'policy': CertificatePolicy("Self", subject="CN=bedude.io") }, { 'name': 'test-cert-' + str(uuid.uuid4()), 'policy': CertificatePolicy("Self", subject="CN=bedude.io") }]) class AcsKeyVaultCase(unittest.TestCase): @classmethod def setUpClass(cls): cls._create_test_certs_and_secrets() @classmethod def tearDownClass(cls):
def test_async_request_cancellation_and_deletion(self, vault_client, **kwargs): self.assertIsNotNone(vault_client) client = vault_client.certificates cert_name = "asyncCanceledDeletedCert" cert_policy = CertificatePolicyGenerated( key_properties=KeyProperties(exportable=True, key_type="RSA", key_size=2048, reuse_key=False), secret_properties=SecretProperties( content_type="application/x-pkcs12"), issuer_parameters=IssuerParameters(name="Self"), x509_certificate_properties=X509CertificateProperties( subject="CN=*.microsoft.com", subject_alternative_names=SubjectAlternativeNames( dns_names=["sdk.azure-int.net"]), validity_in_months=24, ), ) # create certificate create_certificate_poller = client.begin_create_certificate( name=cert_name, policy=CertificatePolicy._from_certificate_policy_bundle( cert_policy)) # cancel certificate operation cancel_operation = client.cancel_certificate_operation(name=cert_name) self.assertTrue(hasattr(cancel_operation, "cancellation_requested")) self.assertTrue(cancel_operation.cancellation_requested) self._validate_certificate_operation( pending_cert_operation=cancel_operation, vault=client.vault_endpoint, cert_name=cert_name, cert_policy=cert_policy, ) self.assertEqual(create_certificate_poller.result().status.lower(), "cancelled") retrieved_operation = client.get_certificate_operation(name=cert_name) self.assertTrue(hasattr(retrieved_operation, "cancellation_requested")) self.assertTrue(retrieved_operation.cancellation_requested) self._validate_certificate_operation( pending_cert_operation=retrieved_operation, vault=client.vault_endpoint, cert_name=cert_name, cert_policy=cert_policy, ) # delete certificate operation deleted_operation = client.delete_certificate_operation(name=cert_name) self.assertIsNotNone(deleted_operation) self._validate_certificate_operation( pending_cert_operation=deleted_operation, vault=client.vault_endpoint, cert_name=cert_name, cert_policy=cert_policy, ) try: client.get_certificate_operation(name=cert_name) self.fail("Get should fail") except Exception as ex: if not hasattr(ex, "message") or "not found" not in ex.message.lower(): raise ex # delete cancelled certificate client.delete_certificate(cert_name)
async def run_sample(): # Instantiate a certificate client that will be used to call the service. # Notice that the client is using default Azure credentials. # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID', # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials. VAULT_URL = os.environ["VAULT_URL"] credential = DefaultAzureCredential() certificate_client = CertificateClient(vault_url=VAULT_URL, credential=credential) # Instantiate a secret client that will be used to call the service. # Notice that this client can reuse the credential object created above. secret_client = SecretClient(vault_url=VAULT_URL, credential=credential) try: # Let's create a certificate in the vault. # If the certificate already exists in the Key Vault, then a new version of the certificate is created. print("\n.. Create certificate") # Before creating your certificate, let's create the management policy for your certificate. # Here we use the default policy. cert_name = "PrivateKeyCertificate" cert_policy = CertificatePolicy.get_default() # Awaiting create_certificate will return the certificate as a KeyVaultCertificate # if creation is successful, and the CertificateOperation if not. created_certificate = await certificate_client.create_certificate( certificate_name=cert_name, policy=cert_policy) print("Certificate with name '{}' was created".format( created_certificate.name)) # Key Vault also creates a secret with the same name as the created certificate. # This secret contains protected information about the certificate, such as its private key. print("\n.. Get a secret by name") certificate_secret = await secret_client.get_secret(name=cert_name) print("Certificate secret with name '{}' was found.".format( certificate_secret.name)) # Now we can extract the private key and public certificate from the secret using the cryptography # package. `additional_certificates` will be empty since the secret only contains one certificate. # This example shows how to parse a certificate in PKCS12 format since it's the default in Key Vault, # but PEM certificates are supported as well. With a PEM certificate, you could use load_pem_private_key # in place of load_key_and_certificates. cert_bytes = base64.b64decode(certificate_secret.value) private_key, public_certificate, additional_certificates = pkcs12.load_key_and_certificates( data=cert_bytes, password=None) print("Certificate with name '{}' was parsed.".format( certificate_secret.name)) # Now we can clean up the vault by deleting, then purging, the certificate. print("\n.. Delete certificate") deleted_certificate = await certificate_client.delete_certificate( certificate_name=cert_name) print("Certificate with name '{}' was deleted.".format( deleted_certificate.name)) await certificate_client.purge_deleted_certificate( certificate_name=deleted_certificate.name) print("Certificate with name '{}' is being purged.".format( deleted_certificate.name)) except HttpResponseError as e: print("\nrun_sample has caught an error. {}".format(e.message)) finally: print("\nrun_sample done") await credential.close() await certificate_client.close() await secret_client.close()
def create_or_update_cert( kv_cert_name, *domains, use_prod=False, keyvault_url='https://ponti-certs-kvjwxwal2p6n.vault.azure.net/', dns_zone_resource_group='damienpontifex.com-rg', dns_zone_name='damienpontifex.com', registration_email='*****@*****.**', dns_subscription_id="fa2cbf67-1293-4f9c-8884-a0379a9e0c64"): # Get directory if use_prod: directory_url = 'https://acme-v02.api.letsencrypt.org/directory' user_key_name = 'acme' issuance_period_months = 3 else: directory_url = 'https://acme-staging-v02.api.letsencrypt.org/directory' user_key_name = 'acme-staging' issuance_period_months = 1 credential = DefaultAzureCredential() challenge_handler = functools.partial( dns_challenge_handler, credential=credential, subscription_id=dns_subscription_id, dns_zone_resource_group=dns_zone_resource_group, dns_zone_name=dns_zone_name) cert_client = CertificateClient(vault_url=keyvault_url, credential=credential) #%% key = KeyVaultRSAKey(credential, keyvault_url, user_key_name) account_key = josepy.JWKRSA(key=key) client_network = acme.client.ClientNetwork(account_key) directory = messages.Directory.from_json( client_network.get(directory_url).json()) client = acme.client.ClientV2(directory, client_network) new_regr = acme.messages.Registration.from_data( key=account_key, email=registration_email, terms_of_service_agreed=True) # Register or fetch account try: regr = client.new_account(new_regr) logger.info('Created new account') except acme.errors.ConflictError as e: regr = acme.messages.RegistrationResource(uri=e.location, body=new_regr) regr = client.query_registration(regr) logger.info('Got existing account') cert_policy = CertificatePolicy( issuer_name='Unknown', subject_name=f'CN={domains[0]}', exportable=True, key_type=KeyType.rsa, key_size=2048, content_type=CertificateContentType.pkcs12, san_dns_names=domains[1:] if len(domains) > 1 else [], validity_in_months=issuance_period_months) try: # Check an existing certificate operation isn't in progress cert_op = cert_client.get_certificate_operation( certificate_name=kv_cert_name) logger.info('Existing cert operation in progress') except ResourceNotFoundError: cert_op = cert_client.begin_create_certificate( certificate_name=kv_cert_name, policy=cert_policy) logger.info('New cert operation') # cert_op = kvclient.create_certificate(KEYVAULT_URL, certificate_name=kv_cert_name, certificate_policy=cert_policy) cert_op_res = cert_op.result() cert_op_r = cert_client.get_certificate_operation(kv_cert_name) logger.info('Created certificate request in key vault') # Wrap with header and footer for pem to show certificate request csr_pem = "-----BEGIN CERTIFICATE REQUEST-----\n" + base64.b64encode( cert_op_r.csr).decode() + "\n-----END CERTIFICATE REQUEST-----\n" # Submit order order_resource = client.new_order(csr_pem) logger.info('Submitted order') # Challenges from order # Respond to challenges challenges_to_respond_to = list( challenge_handler(authorizations=order_resource.authorizations, account_key=account_key)) for dns_challenge in challenges_to_respond_to: # Perform challenge auth_response = client.answer_challenge( dns_challenge, dns_challenge.chall.response(account_key)) logger.info('Answered challenges') # Poll for status # Finalize order # Download certificate final_order = client.poll_and_finalize(order_resource) logger.info('Finalised order') # Strip header and footer of BEGIN/END CERTIFICATE # with open('cert.pem', 'w') as f: # f.write(final_order.fullchain_pem) certificate_vals = [ val.replace('\n', '').encode() for val in final_order.fullchain_pem.split('-----') if 'CERTIFICATE' not in val and len(val.replace('\n', '')) != 0 ] cert_client.merge_certificate(name=kv_cert_name, x509_certificates=certificate_vals) logger.info('Merged certificate back to key vault')
# Instantiate a certificate client that will be used to call the service. Notice that the client is using default # Azure credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID', # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials. VAULT_URL = os.environ["VAULT_URL"] credential = DefaultAzureCredential() client = CertificateClient(vault_url=VAULT_URL, credential=credential) try: # Let's create a certificate for holding storage and bank accounts credentials. If the certificate # already exists in the Key Vault, then a new version of the certificate is created. print("\n.. Create Certificate") bank_cert_name = "BankListCertificate" storage_cert_name = "StorageListCertificate" bank_certificate_poller = client.begin_create_certificate( name=bank_cert_name, policy=CertificatePolicy.get_default()) storage_certificate_poller = client.begin_create_certificate( name=storage_cert_name, policy=CertificatePolicy.get_default()) # await the creation of the bank and storage certificate bank_certificate = bank_certificate_poller.result() storage_certificate = storage_certificate_poller.result() print("Certificate with name '{0}' was created.".format( bank_certificate.name)) print("Certificate with name '{0}' was created.".format( storage_certificate.name)) # Let's list the certificates. print("\n.. List certificates from the Key Vault") certificates = client.list_properties_of_certificates()
def deleted_certificate_recovery(self): """ a sample of enumerating, retrieving, recovering and purging deleted certificates from a key vault """ # create a vault enabling the soft delete feature vault = self.create_vault() # create a certificate client credential = DefaultAzureCredential() certificate_client = CertificateClient( vault_url=vault.properties.vault_uri, credential=credential) # create certificates in the vault cert_to_recover = get_name('cert') cert_to_purge = get_name('cert') create_certificate_poller = certificate_client.begin_create_certificate( cert_to_recover, policy=CertificatePolicy.get_default()) created_certificate = create_certificate_poller.result() print('created certificate {}'.format(created_certificate.name)) create_certificate_poller = certificate_client.begin_create_certificate( cert_to_purge, policy=CertificatePolicy.get_default()) created_certificate = create_certificate_poller.result() print('created certificate {}'.format(created_certificate.name)) # list the vault certificates certificates = certificate_client.list_properties_of_certificates() print('list the vault certificates') for certificate in certificates: print(certificate.name) # delete the certificates deleted_certificate_poller = certificate_client.begin_delete_certificate( cert_to_recover) deleted_certificate = deleted_certificate_poller.result() deleted_certificate_poller.wait() print('deleted certificate {}'.format(deleted_certificate.name)) deleted_certificate_poller = certificate_client.begin_delete_certificate( cert_to_purge) deleted_certificate = deleted_certificate_poller.result() deleted_certificate_poller.wait() print('deleted certificate {}'.format(deleted_certificate.name)) # list the deleted certificates deleted_certs = certificate_client.list_deleted_certificates() print('deleted certificates:') for deleted_cert in deleted_certs: print(deleted_cert.name) # recover a deleted certificate recovered_certificate_poller = certificate_client.begin_recover_deleted_certificate( cert_to_recover) recovered_certificate_certificate = recovered_certificate_poller.result( ) print('recovered certificate {}'.format( recovered_certificate_certificate.name)) # purge a deleted certificate certificate_client.purge_deleted_certificate(cert_to_purge) time.sleep(50) print('purged certificate {}'.format(cert_to_purge)) # list the vault certificates certificates = certificate_client.list_properties_of_certificates() print("all of the certificates in the client's vault:") for certificate in certificates: print(certificate.name)
async def run_sample(): # Instantiate a certificate client that will be used to call the service. Notice that the client is using default Azure credentials. # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID', # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials. VAULT_URL = os.environ["VAULT_URL"] credential = DefaultAzureCredential() client = CertificateClient(vault_url=VAULT_URL, credential=credential) try: # Let's create a certificate for holding storage and bank accounts credentials. If the certificate # already exists in the Key Vault, then a new version of the certificate is created. print("\n.. Create Certificate") bank_cert_name = "BankListCertificate" storage_cert_name = "StorageListCertificate" bank_certificate = await client.create_certificate( name=bank_cert_name, policy=CertificatePolicy.get_default()) storage_certificate = await client.create_certificate( name=storage_cert_name, policy=CertificatePolicy.get_default()) print("Certificate with name '{0}' was created.".format( bank_certificate.name)) print("Certificate with name '{0}' was created.".format( storage_certificate.name)) # Let's list the certificates. print("\n.. List certificates from the Key Vault") certificates = client.list_certificates() async for certificate in certificates: print("Certificate with name '{0}' was found.".format( certificate.name)) # You've decided to add tags to the certificate you created. Calling create_certificate on an existing # certificate creates a new version of the certificate in the Key Vault with the new value. tags = {"a": "b"} updated_bank_certificate_poller = await client.create_certificate( name=bank_cert_name, policy=CertificatePolicy.get_default(), tags=tags) bank_certificate = await updated_bank_certificate_poller print("Certificate with name '{0}' was created again with tags '{1}'". format(bank_certificate.name, bank_certificate.properties.tags)) # You need to check all the different tags your bank account certificate had previously. Lets print all the versions of this certificate. print("\n.. List versions of the certificate using its name") certificate_versions = client.list_certificate_versions(bank_cert_name) async for certificate_version in certificate_versions: print( "Bank Certificate with name '{0}' with version '{1}' has tags: '{2}'." .format(certificate_version.name, certificate_version.version, certificate_version.tags)) # The bank account and storage accounts got closed. Let's delete bank and storage accounts certificates. await client.delete_certificate(name=bank_cert_name) await client.delete_certificate(name=storage_cert_name) # You can list all the deleted and non-purged certificates, assuming Key Vault is soft-delete enabled. print("\n.. List deleted certificates from the Key Vault") deleted_certificates = client.list_deleted_certificates() async for deleted_certificate in deleted_certificates: print("Certificate with name '{0}' has recovery id '{1}'".format( deleted_certificate.name, deleted_certificate.recovery_id)) except HttpResponseError as e: if "(NotSupported)" in e.message: print( "\n{0} Please enable soft delete on Key Vault to perform this operation." .format(e.message)) else: print("\nrun_sample has caught an error. {0}".format(e.message)) finally: print("\nrun_sample done")
async def test_crud_operations(self, client, **kwargs): cert_name = self.get_resource_name("cert") lifetime_actions = [ LifetimeAction(lifetime_percentage=80, action=CertificatePolicyAction.auto_renew) ] cert_policy = CertificatePolicy( issuer_name="Self", subject="CN=DefaultPolicy", exportable=True, key_type=KeyType.rsa, key_size=2048, reuse_key=False, content_type=CertificateContentType.pkcs12, lifetime_actions=lifetime_actions, validity_in_months=12, key_usage=[ KeyUsageType.digital_signature, KeyUsageType.key_encipherment ], ) # create certificate cert = await client.create_certificate( certificate_name=cert_name, policy=CertificatePolicy.get_default()) self._validate_certificate_bundle(cert=cert, cert_name=cert_name, cert_policy=cert_policy) self.assertEqual( (await client.get_certificate_operation(certificate_name=cert_name )).status.lower(), "completed") # get certificate cert = await client.get_certificate(certificate_name=cert_name) self._validate_certificate_bundle(cert=cert, cert_name=cert_name, cert_policy=cert_policy) # update certificate, ensuring the new updated_on value is at least one second later than the original if self.is_live: await asyncio.sleep(1) tags = {"tag1": "updated_value1"} updated_cert = await client.update_certificate_properties(cert_name, tags=tags) self._validate_certificate_bundle(cert=updated_cert, cert_name=cert_name, cert_policy=cert_policy) self.assertEqual(tags, updated_cert.properties.tags) self.assertEqual(cert.id, updated_cert.id) self.assertNotEqual(cert.properties.updated_on, updated_cert.properties.updated_on) # delete certificate deleted_cert_bundle = await client.delete_certificate( certificate_name=cert_name) self._validate_certificate_bundle(cert=deleted_cert_bundle, cert_name=cert_name, cert_policy=cert_policy) # get certificate returns not found try: await client.get_certificate_version( cert_name, deleted_cert_bundle.properties.version) self.fail("Get should fail") except Exception as ex: if not hasattr(ex, "message") or "not found" not in ex.message.lower(): raise ex
async def test_example_certificate_list_operations(self, vault_client, **kwargs): from azure.keyvault.certificates import CertificatePolicy, SecretContentType certificate_client = vault_client.certificates # specify the certificate policy cert_policy = CertificatePolicy( exportable=True, key_type="RSA", key_size=2048, reuse_key=False, content_type=SecretContentType.PKCS12, issuer_name="Self", subject_name="CN=*.microsoft.com", validity_in_months=24, san_dns_names=["sdk.azure-int.net"], ) create_certificate_pollers = [] for i in range(4): create_certificate_pollers.append( certificate_client.create_certificate( name="certificate{}".format(i), policy=cert_policy)) for poller in create_certificate_pollers: await poller # [START list_certificates] # list certificates certificates = certificate_client.list_certificates() async for certificate in certificates: print(certificate.id) print(certificate.created_on) print(certificate.name) print(certificate.updated_on) print(certificate.enabled) # [END list_certificates] # [START list_certificate_versions] # get an iterator of all versions of a certificate certificate_versions = certificate_client.list_certificate_versions( name="cert-name") async for certificate in certificate_versions: print(certificate.id) print(certificate.properties.updated_on) print(certificate.properties.version) # [END list_certificate_versions] # [START list_deleted_certificates] # get an iterator of deleted certificates (requires soft-delete enabled for the vault) deleted_certificates = certificate_client.list_deleted_certificates() async for certificate in deleted_certificates: print(certificate.id) print(certificate.name) print(certificate.scheduled_purge_date) print(certificate.recovery_id) print(certificate.deleted_date)
async def test_async_request_cancellation_and_deletion( self, client, **kwargs): cert_name = "asyncCanceledDeletedCert" cert_policy = CertificatePolicy.get_default() # create certificate await client.create_certificate(certificate_name=cert_name, policy=cert_policy) # cancel certificate operation cancel_operation = await client.cancel_certificate_operation(cert_name) self.assertTrue(hasattr(cancel_operation, "cancellation_requested")) self.assertTrue(cancel_operation.cancellation_requested) self._validate_certificate_operation( pending_cert_operation=cancel_operation, vault=client.vault_url, cert_name=cert_name, original_cert_policy=cert_policy, ) cancelled = False for _ in range(10): if (await client.get_certificate_operation(cert_name) ).status.lower() == "cancelled": cancelled = True break await asyncio.sleep(10) self.assertTrue(cancelled) retrieved_operation = await client.get_certificate_operation( certificate_name=cert_name) self.assertTrue(hasattr(retrieved_operation, "cancellation_requested")) self.assertTrue(retrieved_operation.cancellation_requested) self._validate_certificate_operation( pending_cert_operation=retrieved_operation, vault=client.vault_url, cert_name=cert_name, original_cert_policy=cert_policy, ) # delete certificate operation deleted_operation = await client.delete_certificate_operation(cert_name ) self.assertIsNotNone(deleted_operation) self._validate_certificate_operation( pending_cert_operation=deleted_operation, vault=client.vault_url, cert_name=cert_name, original_cert_policy=cert_policy, ) try: await client.get_certificate_operation(certificate_name=cert_name) self.fail("Get should fail") except Exception as ex: if not hasattr(ex, "message") or "not found" not in ex.message.lower(): raise ex # delete cancelled certificate await client.delete_certificate(cert_name)
def create_certificate(self): self.certificate_client.begin_create_certificate( name=self.certificate_name, policy=CertificatePolicy.get_default()).wait() print("\tdone")
def test_crud_operations(self, vault_client, **kwargs): self.assertIsNotNone(vault_client) client = vault_client.certificates cert_name = self.get_resource_name("cert") lifetime_actions = [ LifetimeAction(lifetime_percentage=80, action=CertificatePolicyAction.auto_renew) ] cert_policy = CertificatePolicy( issuer_name="Self", subject="CN=DefaultPolicy", exportable=True, key_type=KeyType.rsa, key_size=2048, reuse_key=False, content_type=CertificateContentType.pkcs12, lifetime_actions=lifetime_actions, validity_in_months=12, key_usage=[ KeyUsageType.digital_signature, KeyUsageType.key_encipherment ]) polling_interval = 0 if self.is_playback() else None # create certificate certificate = client.begin_create_certificate( cert_name, CertificatePolicy.get_default(), _polling_interval=polling_interval).result() self._validate_certificate_bundle(cert=certificate, cert_name=cert_name, cert_policy=cert_policy) self.assertEqual( client.get_certificate_operation( certificate_name=cert_name).status.lower(), "completed") # get certificate cert = client.get_certificate(certificate_name=cert_name) self._validate_certificate_bundle(cert=cert, cert_name=cert_name, cert_policy=cert_policy) # update certificate tags = {"tag1": "updated_value1"} cert_bundle = client.update_certificate_properties(cert_name, tags=tags) self._validate_certificate_bundle(cert=cert_bundle, cert_name=cert_name, cert_policy=cert_policy) self.assertEqual(tags, cert_bundle.properties.tags) self.assertEqual(cert.id, cert_bundle.id) self.assertNotEqual(cert.properties.updated_on, cert_bundle.properties.updated_on) # delete certificate delete_cert_poller = client.begin_delete_certificate( cert_name, _polling_interval=polling_interval) deleted_cert_bundle = delete_cert_poller.result() self._validate_certificate_bundle(cert=deleted_cert_bundle, cert_name=cert_name, cert_policy=cert_policy) delete_cert_poller.wait() # get certificate returns not found try: client.get_certificate_version( cert_name, deleted_cert_bundle.properties.version) self.fail("Get should fail") except Exception as ex: if not hasattr(ex, "message") or "not found" not in ex.message.lower(): raise ex
# if the certificate already exists in the Key Vault, then a new version of the certificate is created. print("\n.. Create Certificate") # Before creating your certificate, let's create the management policy for your certificate. # Here you specify the properties of the key, secret, and issuer backing your certificate, # the X509 component of your certificate, and any lifetime actions you would like to be taken # on your certificate # Alternatively, if you would like to use our default policy, don't pass a policy parameter to # our certificate creation method cert_policy = CertificatePolicy( exportable=True, key_type="RSA", key_size=2048, reuse_key=False, content_type=SecretContentType.PKCS12, issuer_name="Self", subject_name="CN=*.microsoft.com", validity_in_months=24, san_dns_names=["sdk.azure-int.net"], ) cert_name = "HelloWorldCertificate" # begin_create_certificate returns a poller. Calling result() on the poller will return the certificate # as a KeyVaultCertificate if creation is successful, and the CertificateOperation if not. The wait() # call on the poller will wait until the long running operation is complete. certificate = client.begin_create_certificate(name=cert_name, policy=cert_policy).result() print("Certificate with name '{0}' created".format(certificate.name)) # Let's get the bank certificate using its name print("\n.. Get a Certificate by name")
# Notice that the client is using default Azure credentials. # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID', # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials. VAULT_URL = os.environ["VAULT_URL"] credential = DefaultAzureCredential() client = CertificateClient(vault_url=VAULT_URL, credential=credential) # Let's create certificates holding storage and bank accounts credentials. If the certificate # already exists in the Key Vault, then a new version of the certificate is created. print("\n.. Create Certificates") bank_cert_name = "BankRecoverCertificate" storage_cert_name = "ServerRecoverCertificate" bank_certificate_poller = client.begin_create_certificate( certificate_name=bank_cert_name, policy=CertificatePolicy.get_default() ) storage_certificate_poller = client.begin_create_certificate( certificate_name=storage_cert_name, policy=CertificatePolicy.get_default() ) bank_certificate = bank_certificate_poller.result() storage_certificate = storage_certificate_poller.result() print("Certificate with name '{0}' was created.".format(bank_certificate.name)) print("Certificate with name '{0}' was created.".format(storage_certificate.name)) # The storage account was closed, need to delete its credentials from the Key Vault. print("\n.. Delete a Certificate") deleted_bank_poller = client.begin_delete_certificate(bank_cert_name) deleted_bank_certificate = deleted_bank_poller.result() # To ensure certificate is deleted on the server side.
def test_example_certificate_list_operations(self, azure_keyvault_url, **kwargs): self._skip_if_not_configured(**kwargs) client = self.create_client(azure_keyvault_url, **kwargs) certificate_client = client # specify the certificate policy cert_policy = CertificatePolicy( issuer_name=WellKnownIssuerNames.self, subject="CN=*.microsoft.com", san_dns_names=["sdk.azure-int.net"], exportable=True, key_type="RSA", key_size=2048, reuse_key=False, content_type=CertificateContentType.pkcs12, validity_in_months=24, ) certificate_name = self.get_resource_name("cert") certificate_client.begin_create_certificate(certificate_name, cert_policy).wait() # [START list_properties_of_certificates] # get an iterator of certificates certificates = certificate_client.list_properties_of_certificates() for certificate in certificates: print(certificate.id) print(certificate.created_on) print(certificate.name) print(certificate.updated_on) print(certificate.enabled) # [END list_properties_of_certificates] # create a second version of the cert certificate_client.begin_create_certificate(certificate_name, cert_policy).wait() # [START list_properties_of_certificate_versions] # get an iterator of a certificate's versions certificate_versions = certificate_client.list_properties_of_certificate_versions( certificate_name) for certificate in certificate_versions: print(certificate.id) print(certificate.updated_on) print(certificate.version) # [END list_properties_of_certificate_versions] certificate_client.begin_delete_certificate(certificate_name).wait() # [START list_deleted_certificates] # get an iterator of deleted certificates (requires soft-delete enabled for the vault) deleted_certificates = certificate_client.list_deleted_certificates() for certificate in deleted_certificates: print(certificate.id) print(certificate.name) print(certificate.deleted_on) print(certificate.scheduled_purge_date) print(certificate.deleted_on)
async def test_async_request_cancellation_and_deletion( self, vault_client, **kwargs): self.assertIsNotNone(vault_client) client = vault_client.certificates cert_name = "asyncCanceledDeletedCert" cert_policy = CertificatePolicyGenerated( key_properties=KeyProperties(exportable=True, key_type="RSA", key_size=2048, reuse_key=False), secret_properties=SecretProperties( content_type="application/x-pkcs12"), issuer_parameters=IssuerParameters(name="Unknown"), x509_certificate_properties=X509CertificateProperties( subject="CN=*.microsoft.com", subject_alternative_names=SubjectAlternativeNames( dns_names=["sdk.azure-int.net"]), validity_in_months=24, ), ) polling_interval = 0 if self.is_playback() else None # create certificate await client.create_certificate( certificate_name=cert_name, policy=CertificatePolicy._from_certificate_policy_bundle( cert_policy), _polling_interval=polling_interval) # cancel certificate operation cancel_operation = await client.cancel_certificate_operation(cert_name) self.assertTrue(hasattr(cancel_operation, "cancellation_requested")) self.assertTrue(cancel_operation.cancellation_requested) self._validate_certificate_operation( pending_cert_operation=cancel_operation, vault=client.vault_url, cert_name=cert_name, cert_policy=cert_policy, ) cancelled = False for _ in range(10): if (await client.get_certificate_operation(cert_name) ).status.lower() == "cancelled": cancelled = True break await asyncio.sleep(10) self.assertTrue(cancelled) retrieved_operation = await client.get_certificate_operation( certificate_name=cert_name) self.assertTrue(hasattr(retrieved_operation, "cancellation_requested")) self.assertTrue(retrieved_operation.cancellation_requested) self._validate_certificate_operation( pending_cert_operation=retrieved_operation, vault=client.vault_url, cert_name=cert_name, cert_policy=cert_policy, ) # delete certificate operation deleted_operation = await client.delete_certificate_operation(cert_name ) self.assertIsNotNone(deleted_operation) self._validate_certificate_operation( pending_cert_operation=deleted_operation, vault=client.vault_url, cert_name=cert_name, cert_policy=cert_policy, ) try: await client.get_certificate_operation(certificate_name=cert_name) self.fail("Get should fail") except Exception as ex: if not hasattr(ex, "message") or "not found" not in ex.message.lower(): raise ex # delete cancelled certificate await client.delete_certificate(cert_name, _polling_interval=polling_interval)
def test_example_certificate_crud_operations(self, azure_keyvault_url, **kwargs): self._skip_if_not_configured(**kwargs) client = self.create_client(azure_keyvault_url, **kwargs) certificate_client = client cert_name = self.get_resource_name("cert-name") # [START create_certificate] from azure.keyvault.certificates import CertificatePolicy, CertificateContentType, WellKnownIssuerNames # specify the certificate policy cert_policy = CertificatePolicy( issuer_name=WellKnownIssuerNames.self, subject="CN=*.microsoft.com", san_dns_names=["sdk.azure-int.net"], exportable=True, key_type="RSA", key_size=2048, reuse_key=False, content_type=CertificateContentType.pkcs12, validity_in_months=24, ) # create a certificate with optional arguments, returns a long running operation poller certificate_operation_poller = certificate_client.begin_create_certificate( certificate_name=cert_name, policy=cert_policy) # Here we are waiting for the certificate creation operation to be completed certificate = certificate_operation_poller.result() # You can get the final status of the certificate operation poller using .result() print(certificate_operation_poller.result()) print(certificate.id) print(certificate.name) print(certificate.policy.issuer_name) # [END create_certificate] # [START get_certificate] # get the certificate certificate = certificate_client.get_certificate(cert_name) print(certificate.id) print(certificate.name) print(certificate.policy.issuer_name) # [END get_certificate] version = certificate.properties.version # [START get_certificate_version] certificate = certificate_client.get_certificate_version( cert_name, version) print(certificate.id) print(certificate.properties.version) # [END get_certificate_version] # [START update_certificate] # update attributes of an existing certificate tags = {"foo": "updated tag"} updated_certificate = certificate_client.update_certificate_properties( certificate_name=certificate.name, tags=tags) print(updated_certificate.properties.version) print(updated_certificate.properties.updated_on) print(updated_certificate.properties.tags) # [END update_certificate] # [START delete_certificate] # delete a certificate deleted_certificate = certificate_client.begin_delete_certificate( certificate.name).result() print(deleted_certificate.name) # if the vault has soft-delete enabled, the certificate's deleted date, # scheduled purge date, and recovery id are available print(deleted_certificate.deleted_on) print(deleted_certificate.scheduled_purge_date) print(deleted_certificate.recovery_id)
async def test_async_request_cancellation_and_deletion( self, vault_client, **kwargs): self.assertIsNotNone(vault_client) client = vault_client.certificates cert_name = 'asyncCanceledDeletedCert' cert_policy = CertificatePolicyGenerated( key_properties=KeyProperties(exportable=True, key_type='RSA', key_size=2048, reuse_key=False), secret_properties=SecretProperties( content_type='application/x-pkcs12'), issuer_parameters=IssuerParameters(name='Self'), x509_certificate_properties=X509CertificateProperties( subject='CN=*.microsoft.com', subject_alternative_names=SubjectAlternativeNames( dns_names=['sdk.azure-int.net']), validity_in_months=24)) # create certificate create_certificate_poller = await client.create_certificate( name=cert_name, policy=CertificatePolicy._from_certificate_policy_bundle( cert_policy)) # cancel certificate operation cancel_operation = await client.cancel_certificate_operation( name=cert_name) self.assertTrue(hasattr(cancel_operation, 'cancellation_requested')) self.assertTrue(cancel_operation.cancellation_requested) self._validate_certificate_operation( pending_cert_operation=cancel_operation, vault=client.vault_url, cert_name=cert_name, cert_policy=cert_policy) self.assertEqual(await create_certificate_poller, 'cancelled') retrieved_operation = await client.get_certificate_operation( name=cert_name) self.assertTrue(hasattr(retrieved_operation, 'cancellation_requested')) self.assertTrue(retrieved_operation.cancellation_requested) self._validate_certificate_operation( pending_cert_operation=retrieved_operation, vault=client.vault_url, cert_name=cert_name, cert_policy=cert_policy) # delete certificate operation deleted_operation = await client.delete_certificate_operation( name=cert_name) self.assertIsNotNone(deleted_operation) self._validate_certificate_operation( pending_cert_operation=deleted_operation, vault=client.vault_url, cert_name=cert_name, cert_policy=cert_policy) try: await client.get_certificate_operation(name=cert_name) self.fail('Get should fail') except Exception as ex: if not hasattr(ex, 'message') or 'not found' not in ex.message.lower(): raise ex # delete cancelled certificate await client.delete_certificate(cert_name)
async def run_sample(): # Instantiate a certificate client that will be used to call the service. # Notice that the client is using default Azure credentials. # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID', # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials. VAULT_URL = os.environ["VAULT_URL"] credential = DefaultAzureCredential() client = CertificateClient(vault_url=VAULT_URL, credential=credential) try: # Let's create certificates holding storage and bank accounts credentials. If the certificate # already exists in the Key Vault, then a new version of the certificate is created. print("\n.. Create Certificates") bank_cert_name = "BankRecoverCertificate" storage_cert_name = "ServerRecoverCertificate" bank_certificate = await client.create_certificate( name=bank_cert_name, policy=CertificatePolicy.get_default()) storage_certificate = await client.create_certificate( name=storage_cert_name, policy=CertificatePolicy.get_default()) print("Certificate with name '{0}' was created.".format( bank_certificate.name)) print("Certificate with name '{0}' was created.".format( storage_certificate.name)) # The storage account was closed, need to delete its credentials from the Key Vault. print("\n.. Delete a Certificate") deleted_bank_certificate = await client.delete_certificate( name=bank_cert_name) # To ensure certificate is deleted on the server side. await asyncio.sleep(30) print("Certificate with name '{0}' was deleted on date {1}.".format( deleted_bank_certificate.name, deleted_bank_certificate.deleted_date)) # We accidentally deleted the bank account certificate. Let's recover it. # A deleted certificate can only be recovered if the Key Vault is soft-delete enabled. print("\n.. Recover Deleted Certificate") recovered_bank_certificate = await client.recover_deleted_certificate( deleted_bank_certificate.name) print("Recovered Certificate with name '{0}'.".format( recovered_bank_certificate.name)) # Let's delete storage account now. # If the keyvault is soft-delete enabled, then for permanent deletion deleted certificate needs to be purged. await client.delete_certificate(name=storage_cert_name) # To ensure certificate is deleted on the server side. await asyncio.sleep(30) # To ensure permanent deletion, we might need to purge the secret. print("\n.. Purge Deleted Certificate") await client.purge_deleted_certificate(name=storage_cert_name) print("Certificate has been permanently deleted.") except HttpResponseError as e: if "(NotSupported)" in e.message: print( "\n{0} Please enable soft delete on Key Vault to perform this operation." .format(e.message)) else: print("\nrun_sample has caught an error. {0}".format(e.message)) finally: print("\nrun_sample done")
def test_example_certificate_list_operations(self, vault_client, **kwargs): from azure.keyvault.certificates import CertificatePolicy, SecretContentType certificate_client = vault_client.certificates # specify the certificate policy cert_policy = CertificatePolicy( exportable=True, key_type="RSA", key_size=2048, reuse_key=False, content_type=SecretContentType.PKCS12, issuer_name="Self", subject_name="CN=*.microsoft.com", validity_in_months=24, san_dns_names=["sdk.azure-int.net"], ) polling_interval = 0 if self.is_playback() else None for i in range(4): certificate_client.begin_create_certificate( name="certificate{}".format(i), policy=cert_policy, _polling_interval=polling_interval).wait() # [START list_properties_of_certificates] # get an iterator of certificates certificates = certificate_client.list_properties_of_certificates() for certificate in certificates: print(certificate.id) print(certificate.created_on) print(certificate.name) print(certificate.updated_on) print(certificate.enabled) # [END list_properties_of_certificates] # [START list_properties_of_certificate_versions] # get an iterator of a certificate's versions certificate_versions = certificate_client.list_properties_of_certificate_versions( name="certificate-name") for certificate in certificate_versions: print(certificate.id) print(certificate.updated_on) print(certificate.version) # [END list_properties_of_certificate_versions] # [START list_deleted_certificates] # get an iterator of deleted certificates (requires soft-delete enabled for the vault) deleted_certificates = certificate_client.list_deleted_certificates() for certificate in deleted_certificates: print(certificate.id) print(certificate.name) print(certificate.deleted_date) print(certificate.scheduled_purge_date) print(certificate.deleted_date)
async def run_sample(): # Instantiate a certificate client that will be used to call the service. # Notice that the client is using default Azure credentials. # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID', # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials. VAULT_URL = os.environ["VAULT_URL"] credential = DefaultAzureCredential() client = CertificateClient(vault_url=VAULT_URL, credential=credential) try: # Let's create a certificate for holding bank account credentials valid for 1 year. # if the certificate already exists in the Key Vault, then a new version of the certificate is created. print("\n.. Create Certificate") # Before creating your certificate, let's create the management policy for your certificate. # Here you specify the properties of the key, secret, and issuer backing your certificate, # the X509 component of your certificate, and any lifetime actions you would like to be taken # on your certificate # Alternatively, if you would like to use our default policy, don't pass a policy parameter to # our certificate creation method cert_policy = CertificatePolicy( exportable=True, key_type="RSA", key_size=2048, reuse_key=False, content_type=SecretContentType.PKCS12, issuer_name=WellKnownIssuerNames.Self, subject_name="CN=*.microsoft.com", validity_in_months=24, san_dns_names=["sdk.azure-int.net"], ) cert_name = "HelloWorldCertificate" # Awaiting create_certificate will return the certificate as a KeyVaultCertificate # if creation is successful, and the CertificateOperation if not. certificate = await client.create_certificate( certificate_name=cert_name, policy=cert_policy) print("Certificate with name '{0}' created".format(certificate.name)) # Let's get the bank certificate using its name print("\n.. Get a Certificate by name") bank_certificate = await client.get_certificate(cert_name) print("Certificate with name '{0}' was found.".format( bank_certificate.name)) # After one year, the bank account is still active, and we have decided to update the tags. print("\n.. Update a Certificate by name") tags = {"a": "b"} updated_certificate = await client.update_certificate_properties( certificate_name=bank_certificate.name, tags=tags) print("Certificate with name '{0}' was updated on date '{1}'".format( bank_certificate.name, updated_certificate.properties.updated_on)) print("Certificate with name '{0}' was updated with tags '{1}'".format( bank_certificate.name, updated_certificate.properties.tags)) # The bank account was closed, need to delete its credentials from the Key Vault. print("\n.. Delete Certificate") deleted_certificate = await client.delete_certificate( bank_certificate.name) print("Deleting Certificate..") print("Certificate with name '{0}' was deleted.".format( deleted_certificate.name)) except HttpResponseError as e: print("\nrun_sample has caught an error. {0}".format(e.message)) finally: print("\nrun_sample done")
async def test_example_certificate_crud_operations(self, client, **kwargs): certificate_client = client # [START create_certificate] from azure.keyvault.certificates import CertificatePolicy, CertificateContentType, WellKnownIssuerNames # specify the certificate policy cert_policy = CertificatePolicy( issuer_name=WellKnownIssuerNames.self, subject="CN=*.microsoft.com", san_dns_names=["sdk.azure-int.net"], exportable=True, key_type="RSA", key_size=2048, reuse_key=False, content_type=CertificateContentType.pkcs12, validity_in_months=24, ) cert_name = "cert-name" certificate = await certificate_client.create_certificate( certificate_name=cert_name, policy=cert_policy) print(certificate.id) print(certificate.name) print(certificate.policy.issuer_name) # [END create_certificate] # [START get_certificate] # get the latest version of a certificate certificate = await certificate_client.get_certificate(cert_name) print(certificate.id) print(certificate.name) print(certificate.policy.issuer_name) # [END get_certificate] version = certificate.properties.version # [START get_certificate_version] certificate = await certificate_client.get_certificate_version( cert_name, version) print(certificate.id) print(certificate.properties.version) # [END get_certificate_version] # [START update_certificate] # update attributes of an existing certificate tags = {"foo": "updated tag"} updated_certificate = await certificate_client.update_certificate_properties( certificate_name=certificate.name, tags=tags) print(updated_certificate.properties.version) print(updated_certificate.properties.updated_on) print(updated_certificate.properties.tags) # [END update_certificate] # [START delete_certificate] # delete a certificate deleted_certificate = await certificate_client.delete_certificate( cert_name) print(deleted_certificate.name) # if the vault has soft-delete enabled, the certificate's # scheduled purge date, deleted_on, and recovery id are available print(deleted_certificate.deleted_on) print(deleted_certificate.scheduled_purge_date) print(deleted_certificate.recovery_id)
async def test_example_certificate_list_operations(self, client, **kwargs): certificate_client = client # specify the certificate policy cert_policy = CertificatePolicy( issuer_name=WellKnownIssuerNames.self, subject="CN=*.microsoft.com", san_dns_names=["sdk.azure-int.net"], exportable=True, key_type="RSA", key_size=2048, reuse_key=False, content_type=CertificateContentType.pkcs12, validity_in_months=24, ) certificate_name = self.get_replayable_random_resource_name("cert") await certificate_client.create_certificate(certificate_name, cert_policy) # [START list_properties_of_certificates] # list certificates certificates = certificate_client.list_properties_of_certificates() async for certificate in certificates: print(certificate.id) print(certificate.created_on) print(certificate.name) print(certificate.updated_on) print(certificate.enabled) # [END list_properties_of_certificates] # create a second version of the cert await certificate_client.create_certificate(certificate_name, cert_policy) # [START list_properties_of_certificate_versions] # get an iterator of all versions of a certificate certificate_versions = certificate_client.list_properties_of_certificate_versions("cert-name") async for certificate in certificate_versions: print(certificate.id) print(certificate.properties.updated_on) print(certificate.properties.version) # [END list_properties_of_certificate_versions] await certificate_client.delete_certificate(certificate_name) # [START list_deleted_certificates] # get an iterator of deleted certificates (requires soft-delete enabled for the vault) deleted_certificates = certificate_client.list_deleted_certificates() async for certificate in deleted_certificates: print(certificate.id) print(certificate.name) print(certificate.scheduled_purge_date) print(certificate.recovery_id) print(certificate.deleted_on)