Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Azure Function Addition #9

Merged
merged 1 commit into from
Apr 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions PythonAZFunctionVMOperator/.env-template
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
SUBSCRIPTION_ID=your_subscription_id
TENANT_ID=your_tenant_id
CLIENT_ID=your_client_id
CLIENT_SECRET=your_client_secret
2 changes: 2 additions & 0 deletions PythonAZFunctionVMOperator/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.env
.DS_Store
46 changes: 46 additions & 0 deletions PythonAZFunctionVMOperator/README
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
### Author: [email protected]
### Version: 1.0
### Modified: April 14, 2023
##
#
Packages needed are in the requirements.txt file. Create a virtual environment and install with
pip install -r requirements.txt

Packages are:
azure-functions
azure-mgmt-compute
azure.common.credentials
azure-identity
python-dotenv

To create an App Registration in Azure, you can follow these steps:
1 Sign in to the Azure portal (https://portal.azure.com/).
2 In the search bar write 'App registrations', then, click on "App Registrations" under the "Services" section.
3 Click on "+ New registration"
4 Enter App Registration details, then click on the "Register" button to create the App Registration.
In the "Register an application" blade, enter the following details for your App Registration:
Name: Enter a unique name for your application.
Supported account types: Choose the appropriate account types for your application ('Accounts in this organizational directory only')
Then, click on the "Register" button to create the App Registration.
5 Note down Application (client) ID and Directory (tenant) ID
After the App Registration is created, note down the "Application (client) ID" and "Directory (tenant) ID" values, as they will be required in the .env credentials file.
6 Create a Client Secret by clicking the "Certificates & secrets" section in the App Registration blade,
then click on the "New client secret" button. Enter a description, select an expiration duration, and click on the "Add" button. Make sure to note down the client secret value (the ID is not needed) as it will be required in the .env credentials file.

Create the .env file and specify your Azure login credentials as noted in the App registration process. The file is included in .gitingore and a template is located at .env-template
vim .env

To authorize an app registration in Azure to perform the 'Microsoft.Compute/virtualMachines/*/action' actions, you need to grant the necessary permissions to the app registration at the appropriate scope. Here are the steps to do so:
1 Sign in to the Azure portal (https://portal.azure.com/).
2 Navigate to the resource group containing the virtual machine that you want to manage.
3 Click on the virtual machine name to open the virtual machine blade.
4 In the left-hand menu, click on 'Access control (IAM)'.
5 Click on the '+ Add' button to add a new role assignment.
6 In the 'Add role assignment' pane, select the 'Virtual Machine Contributor' or other appropriate role.
7 In the 'Assign access to' field, select 'User, group, or service principal'
8 Click on '+Select members' and search for the app registration name that you want to authorize.
9 In the 'Select' field, search for and select the name of an app registration.
10 Click on the 'Save' button to grant the permissions to the app registration.
#
##
###
45 changes: 45 additions & 0 deletions PythonAZFunctionVMOperator/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import sys
import os
from azure.mgmt.compute import ComputeManagementClient
from azure.identity import ClientSecretCredential
from dotenv import load_dotenv # Add dotenv module to read credentials

# Load credentials from .env file
load_dotenv()
subscription_id = os.getenv("SUBSCRIPTION_ID")
tenant_id = os.getenv("TENANT_ID")
client_id = os.getenv("CLIENT_ID")
client_secret = os.getenv("CLIENT_SECRET")

# Checking if the correct number of command-line arguments are provided
if len(sys.argv) != 4:
print("Usage: python3 operator.py <action> <resource_group> <vm_name>")
sys.exit(1)

def startdeallocate_vm(action, subscription_id, tenant_id, client_id, client_secret, resource_group_name, vm_name):
# Create credentials object
credentials = ClientSecretCredential(
tenant_id=tenant_id,
client_id=client_id,
client_secret=client_secret
)

# Create ComputeManagementClient - it includes begin_run_command
compute_client = ComputeManagementClient(credentials, subscription_id)
if action == "deallocate":
compute_client.virtual_machines.begin_deallocate(resource_group_name, vm_name)
return f"Virtual machine {vm_name} in resource group {resource_group_name} has been deallocated."
elif action == "start":
# Start the virtual machine
compute_client.virtual_machines.begin_start(resource_group_name, vm_name)
return f"Virtual machine {vm_name} in resource group {resource_group_name} has been started."
else:
# Handle unknown actions
return f"Unknown action. Virtual machine {vm_name} in resource group {resource_group_name} was not altered."

# Example usage
resource_group_name = sys.argv[2]
vm_name = sys.argv[3]

result = startdeallocate_vm(sys.argv[1], subscription_id, tenant_id, client_id, client_secret, resource_group_name, vm_name)
print(result)
17 changes: 17 additions & 0 deletions PythonAZFunctionVMOperator/install.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/bin/bash
# Get the directory containing the script
SCRIPT_DIR=$(dirname "$(readlink -f "$0")")
cd $SCRIPT_DIR
# Creat the .env file from the template
cp .env-template .env
# Create virtual environment
python3 -m venv ../azureFunctionsEnv
source ../azureFunctionsEnv/bin/activate && sleep 1
# Install packages
pip3 install --upgrade pip
pip3 install -r requirements.txt
cd ../azureFunctionsEnv
# Move the Function folder into the environment root folder
mv ../PythonAZFunctionVMOperator .
# Print an installation message
echo "Environment 'azureFunctionsEnv' was created and PythonAZFunctionVMOperator function was installed. Make sure to add the appropriate credentials to the .env file."
4 changes: 4 additions & 0 deletions PythonAZFunctionVMOperator/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
azure-functions
azure-mgmt-compute
azure-identity
python-dotenv