How to delete content in ADO wiki page

30 Views Asked by At

We have a python script that listing existing azure virtual machines and their corresponding information and pushes this information onto the ADO wiki page.

The wiki page has markdown format, so part of my script takes that into consideration.

In the script, there is a list that get appended during the run, which then get pushed onto the wiki page, before the next vm is listed.

The only issue we are facing is that if any of these vms are deleted, then when the script is ran, the deleted vms are still present on the wiki page.

I thought of adding request.delete on the existing content on the wiki first, then running the rest of the script. However, I from what I've read about request.delete I think I would be deleting the wiki page, not the content within.

Any advice on what can be done to achieve this?

Here is the script:

resource_group_name = "vms-rg"
kv_url = "https://kv-pass-manager-xxxxxx.vault.azure.net/"
pat_secret_name = "User--WikiUpdateVMs"
organization = "org"
project = "project"
wiki_id = "12345"
wiki_url = f"https://dev.azure.com/{organization}/{project}/_apis/wiki/wikis/{project}.wiki/pages/{wiki_id}?includeContent=True&api-version=7.1-preview.1"

CREDENTIAL = DefaultAzureCredential(exclude_shared_token_cache_credential=True, exclude_visual_studio_code_credential=True, exclude_environment_credential=True, exclude_managed_identity_credential=True,
                                        exclude_powershell_credential=True, exclude_interactive_browser_credential=True)
subscription_id = credentials.get_azure_cli_credentials()[1]
subscription_name = SubscriptionClient(CREDENTIAL).subscriptions.get(subscription_id).display_name
print("Searching in Subscription:" , subscription_name)

compute_client = ComputeManagementClient(CREDENTIAL, subscription_id)

# Accessing the KeyVault credentials in accordance with Subscription that is set via ADO pipeline config
def get_or_set_secret(kv_url, secret_name, secret_value):
     secret_client = SecretClient(kv_url, CREDENTIAL)
     try:
         secret = secret_client.get_secret(secret_name)
         return secret.value
     except Exception as ex:
         secret_client.set_secret(secret_name, secret_value)
         return secret_value

# List the DebugVMs along with their information.
def list_debugvms():
    debug_vms = compute_client.virtual_machines.list(resource_group_name)
    vm_list = [ ]
    for vm in debug_vms:
        if vm.name == "vm-999999":
            continue
        json_string = vm.tags
        ownerEmail = json_string['OwnerEmail']
        ticket_number = vm.name.split("-")[1]
        date = datetime.datetime.strftime(vm.time_created, "%d-%m-%Y")
        print("virtual machine name:", vm.name , ", ticket number:" , ticket_number , ", Owner Email:" , ownerEmail , ", creation date:" , date)
        output = markdown.markdown(f"| {vm.name} | #{ticket_number} | {ownerEmail} | {date} |" , extensions=[TableExtension(use_align_attribute=True)])
        output_whout_para = output.strip('"<p""</p"')
        one_more = output_whout_para.strip('">""</p>"')
        vm_list.append(one_more)
        wiki_update(vm_list)
                         
# updating wiki page
def wiki_update(vm_list):
     pat = get_or_set_secret(kv_url, pat_secret_name, " ")
     authorization = base64.b64encode(f":{pat}".encode('ascii')).decode('ascii')
     basic_auth_value = f"Basic {authorization}"
     get_headers = {"Authorization": basic_auth_value} 
    
     get_response = requests.get(wiki_url, verify=True, headers=get_headers)

     if get_response.status_code == 200:
         existing_content = get_response.json()["content"]
         for token in vm_list:
             if token in existing_content:
                 # If the token is present, overwrite it with itself
                 new_content = {"content": existing_content}
             else:
                 # If the token is not present, append it to the end of the content
                 new_content = {"content": existing_content + "\n" + token}

             response_headers = get_response.headers
             etag = response_headers.get("ETag").replace('"', '')
             request_headers = {"Authorization": basic_auth_value, "content-type": "application/json", "If-Match": etag}
             response = requests.patch(wiki_url, verify=True, json=new_content, headers=request_headers)
             status_code = response.status_code
        
if __name__ == '__main__':
     list_debugvms()
0

There are 0 best solutions below