Giter Club home page Giter Club logo

az.cli's Introduction

Az.Cli

PyPi Build Status master Build Status dev

This package is not officially maintained and developed by Microsoft - visit github.com/Azure/azure-cli for the official azure-cli.

Az.Cli is an easy-to-use Python interface that lets developers and administrators query Azure resources. The Python package is providing a way to interact with Azure using Python while sticking to a well-known concept of the Azure CLI.

exit_code, output, logs = az("group list")

If you are already familiar with the Azure CLI you should feel right at home using the Az.Cli Python packge API.

Usage

You can find a getting started guide here @markwarneke.me/2021-03-14-Query-Azure-Resources-Using-Python.

Install the package

pip install az.cli

Login using az login or sign in using a service principal.

Under the hood the package uses the ~/.azure folder to persist and retrieve config.

The az function returns a named tuple that allows you to retrieve the results easily.

AzResult = namedtuple('AzResult', ['exit_code', 'output', 'log'])
  • The error_code where 0 == success.

  • The output containing a python dictionary if the output from the 'az' command is expected as json format. Otherwise it will return the string returned by the command. This is useful when the output of the cli is specified, allowed values: json, jsonc, yaml, yamlc, table, tsv, none see https://learn.microsoft.com/en-us/cli/azure/format-output-azure-cli example, listing the resource groups as a table: az resource list --output table

  • On failure (error_code > 0) a log message is available in the log property as a string.

Example

from az.cli import az

# AzResult = namedtuple('AzResult', ['exit_code', 'output', 'log'])
exit_code, output, logs = az("group show -n test")

# On 0 (SUCCESS) print output, otherwise get info from `logs`
if exit_code == 0:
    print (output)
else:
    print(logs)

Interactive

You can run the command interactively to traverse the dictionary. Import the pacakge function from az.cli import az and run any query by executing the method az("<my command>") to invoke the Azure CLI command.

# cd src
# python3
from az.cli import az
# on Success, the `error_code` is 0 and the output contains the output
az("group list") # list return tuple (exit_code, output, log)
az("group list")[0] # 0
az("group list")[1] # print output
az("group list")[1][0]['id'] # enumerate the id of the first element in dictionary

# On Error, the `error_code` will be != 1 and the log is present
az("group show -n does-not-exsist") # list return tuple (exit_code, output, log)
az("group show -n does-not-exsist")[0] # 3
az("group show -n does-not-exsist")[2] # print the log

Programmatically Setting The Azure Config

To change the Azure context, the "session" in which you are logged in, the package relies on the stored credentials inside the ~/.azure folder by default. In order to change the context a simple change to the environment variable AZURE_CONFIG_DIR will point to a new context. This can easily be done in Python using the os.enviorn interface.

az login
mv ~/.azure/* ~/.azure-mw

az login --service-principal -u $id -p $p -t $t
# creates new ~/.azure folder

In Python the environment variable can be set using:

os.environ['AZURE_CONFIG_DIR'] = "<OTHER AZURE CONFIG DIR>"

Changing the AZURE_CONFIG_DIR environment variables is described in the docs to the Azure CLI environment variables. To demonstrate how to change the environment variable programmatically a small example:

from az.cli import az
import os

exit_code, output, logs = az("group list")
print (output)
# [{'id': '/subscriptions/...', 'location': 'westeurope',  'name': 'test1']

# Change the environment variable
os.environ['AZURE_CONFIG_DIR'] = '/Users/mark/.azure_mw'

exit_code, output, logs = az("group list")
print (output)
# [{'id': '/subscriptions/...', 'location': 'westeurope', 'name': 'test2']

How it works

The package is an easy-to-use abstraction on top of the official Microsoft Azure CLI. The official azure.cli.core library is simply wrapped in a funciton to execute Azure CLI commands using Python3. The package provides a function az the is based on the class AzCLI. It exposes the function to execute az commands and returns the results in a structured manner.

It has thus a similar API and usage to the shell version of the Azure CLI, but commands can be executed within Python, leveraging Pythons full potential.

Build

Local Development

  • install python3
  • install REQUIREMENTS.txt using make init

I recommend to use Python3 virtual environments.

# sets up environment
make env
# installs requirements
make init

Docker

To build the image run the following in order.

# Runs docker build & create
make create

Run

After the container is build & created you can run the az.cli interactivly.

# Run docker run
make run

Augmenting official Azure CLI Docker image

To those who want to use this wrapper with the official Azure CLI Docker image, then the quickest way is to mimic the following:

FROM mcr.microsoft.com/azure-cli:latest

ENV PATH="/venv/bin:${PATH}"

RUN : \
    && python3 -m venv --system-site-packages /venv \
    && pip install --disable-pip-version-check --no-cache-dir --no-dependencies az.cli

What that does is:

  • adds the virtual environment directory to the PATH environment variable
  • creates a virtual environment with access to the system site-packages directory
    • this is what --system-site-packages does
  • installs this project into that virtual environment without installing dependencies
    • as they are already in the original image
    • this is what --no-dependencies does

The --disable-pip-version-check option is set as it offers no tangible benefit to check Pip's version when building. The same goes for --no-cache-dir as the resulting image will be smaller due to Pip not having cached anything.

az.cli's People

Contributors

e-g-c avatar markwarneke avatar usrme avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.