Search code examples
pythonpython-3.xbashazureazure-cli2

Invalid Syntax : Azure CLI with Python


Thanks in advance, I'm trying to Update Azure VM. Eventually my code gets the certificate from Azure key vault and will save it in local certificate store. I've accomplished successfully using Azure CLI on Bash. code is present below

secret=$(az keyvault secret list-versions --vault-name aqrahyhkeyvault --name certificatename --query "[?attributes.enabled].id" --output tsv)

vm_secret=$(az vm secret format --secrets "$secret" --resource-group RAH-AQ --keyvault aqrahyhkeyvault --certificate-store My)

az vm update -g Archive-WSL -n win10new --set osProfile.secrets="$vm_secret"

I'm using the same command by wrapping it in Python as most of my code is in this format. But it is throwing invalid syntax error. I've tried every possible change with double quotes and shuffling it with no luck

import subprocess
import json

def Update_vm(vault_name,certificate_name,rscgroup_name):
    Secret_command=["az","keyvault","secret","list-versions","--vault-name",vault_name,"--name",certificate_name,"--query","[?attributes.enabled].id","--output","tsv"]
    create_vm=subprocess.run(Secret_command, stdout=subprocess.PIPE, stderr = subprocess.PIPE)
    print(create_vm.stdout)
    vm_secret=["az","vm","secret","format","--secrets",create_vm.stdout,"--resource-group",rscgroup_name,"--keyvault",vault_name,"--certificate-store","My"]
    vm_new_secret=subprocess.run(vm_secret, stdout=subprocess.PIPE, stderr = subprocess.PIPE)
    print(vm_new_secret.stdout)

    update_vm_cmd=["az","vm","update","-g",rscgroup_name,"-n",avm_name,"--set","osProfile.secrets"=vm_new_secret.stdout] //Error is present here saying invalid syntax
    vm_update=subprocess.run(update_vm_cmd, stdout=subprocess.PIPE, stderr = subprocess.PIPE)


if __name__=="__main__":
    rscgroup_name="vm-test-group"
    avm_name="testvm1"
    avm_image="Win2019Datacenter"
    avm_username="azuretest"
    avm_password="mypass"
    avm_size="Standard_D2_V3"
    vault_name = "aqrahkeyvault"
    certificate_name = "staticwebsite"

    Update_vm(vault_name,certificate_name,rscgroup_name)

Solution

  • I think it might be the way the string is formatted at "osProfile.secrets"=vm_new_secret.stdout Can you try the following instead?

    update_vm_cmd=["az","vm","update","-g",rscgroup_name,"-n",avm_name,"--set",f"osProfile.secrets={vm_new_secret.stdout}"]