Search code examples
pythonazureazure-cli

How to run command from variable instead of those line in python?


I have below commands for run az aks command:

from azure.cli.core import get_default_cli
az_cli = get_default_cli()
res = az_cli.invoke(['login', '--service-principal', '-u', client_id, '-p', client_secret,'--tenant',tenant_id])
az_cli.invoke(['aks','command','invoke','--resource-group',resourcegroup,'--name',clustername,'--command','kubectl apply -f',outfile_final])

I want as below,

azcmd = "az login --service-principal -u " + client_id + " -p " + client_secret + " --tenant " + tenant_id

**res = az_cli.invoke([azcmd])**

but Above script is giving error like args should be a list or tuple, and 2nd error: enter image description here Is there anyways to run invoke with get input from variable.

Edit1: I'm applying deployment file as below:

namespace = "kubectl apply -f abc.yaml"

Solution

  • I tried in my environment and got below results:

    Initially I tried with same command and got same error:

    enter image description here

    I installed azure-cli module in my local machine, Also instead of using -

    res = az_cli.invoke([azcmd])
    

    You can add your azcmd inside ([ ])

    from  azure.cli.core  import  get_default_cli
    az_cli = get_default_cli()
    cmd=(['login', '--service-principal', '-u', client_id, '-p', client_secret,'--tenant',tenant_id])
    
    res=az_cli.invoke(cmd)
    

    Is there anyways to run invoke with get input from variable.

    With above code I can invoke with get input from variable.

    Console:

    enter image description here

    Reference: Authenticating Azure CLI with Python SDK - Stack Overflow by Jim Xu.