Skip to content

Commit b606392

Browse files
DEVOPS-274 run commands using python
1 parent 88ed142 commit b606392

File tree

5 files changed

+126
-2
lines changed

5 files changed

+126
-2
lines changed

.gitignore

+2-2
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ ipython_config.py
9999
# This is especially recommended for binary packages to ensure reproducibility, and is more
100100
# commonly ignored for libraries.
101101
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102-
#poetry.lock
102+
poetry.lock
103103

104104
# pdm
105105
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
@@ -159,4 +159,4 @@ cython_debug/
159159
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160160
# and can be added to the global gitignore or merged into this file. For a more nuclear
161161
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
162-
#.idea/
162+
.idea/

README.md

+4
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,6 @@
11
# azure-runcommands-on-vm-vmss-with-python-sdk
22
Code to execute run commands on Azure VMs and VMSS using python sdks
3+
4+
5+
https://azuresdkdocs.blob.core.windows.net/$web/python/azure-mgmt-compute/32.0.0/azure.mgmt.compute.html#azure.mgmt.compute.ComputeManagementClient.virtual_machine_run_commands
6+

az_vm_runcommands.py

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import os
2+
import argparse
3+
from dotenv import load_dotenv
4+
from azure.mgmt.compute import ComputeManagementClient
5+
from azure.mgmt.compute.models import RunCommandInput
6+
from azure.identity import DefaultAzureCredential
7+
from resource_graph_query import run_azure_rg_query
8+
9+
def run_commands_on_vm(resource_group:str, subscription_id:str, vm_name:str):
10+
"""
11+
Execute run commands on Azure using Compute Management Client class
12+
:return:
13+
"""
14+
credential = DefaultAzureCredential()
15+
compute_mgmt_client = ComputeManagementClient(credential=credential, subscription_id=subscription_id)
16+
17+
# Define the command parameters
18+
run_command_parameters = RunCommandInput(
19+
command_id='RunShellScript',
20+
script=['sudo systemctl start jenkins']
21+
)
22+
23+
response = compute_mgmt_client.virtual_machines.begin_run_command(resource_group_name=resource_group,
24+
vm_name=vm_name,parameters=run_command_parameters)
25+
26+
result = response.result()
27+
print(result.value[0].message)
28+
29+
30+
def main():
31+
"""
32+
Execute program
33+
:return:
34+
"""
35+
load_dotenv()
36+
parser = argparse.ArgumentParser("Execute Run commands on an Azure VM")
37+
parser.add_argument("--subscription_name", help="Azuer Subscription name", required=True, type=str)
38+
parser.add_argument("--vm_name", help="Azure VM name",required=True, type=str)
39+
parser.add_argument("--resource_group", help="Azure resource group name", type=str, required=True)
40+
41+
args = parser.parse_args()
42+
43+
subscription_name =args.subscription_name
44+
vm_name = args.vm_name
45+
resource_group = args.resource_group
46+
47+
subscription_id = run_azure_rg_query(subscription_name=subscription_name)
48+
49+
run_commands_on_vm(subscription_id=subscription_id, resource_group=resource_group, vm_name=vm_name)
50+
51+
52+
if __name__ == "__main__":
53+
main()
54+

pyproject.toml

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
[tool.poetry]
2+
name = "azure-runcommands-on-vm-vmss-with-python-sdk"
3+
version = "0.1.0"
4+
description = ""
5+
authors = ["githubofkrishnadhas <[email protected]>"]
6+
readme = "README.md"
7+
8+
[tool.poetry.dependencies]
9+
python = "^3.11"
10+
azure-mgmt-compute = "^32.0.0"
11+
python-dotenv = "^1.0.1"
12+
azure-identity = "^1.17.1"
13+
azure-mgmt-resourcegraph = "^8.0.0"
14+
15+
16+
[build-system]
17+
requires = ["poetry-core"]
18+
build-backend = "poetry.core.masonry.api"

resource_graph_query.py

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
from azure.identity import DefaultAzureCredential
2+
import azure.mgmt.resourcegraph as arg
3+
import logging
4+
import os
5+
from dotenv import load_dotenv
6+
7+
def run_azure_rg_query(subscription_name: str):
8+
"""
9+
Run a resource graph query to get the subscription id of a subscription back
10+
:return: subscription_id str
11+
"""
12+
credential = DefaultAzureCredential()
13+
# Create Azure Resource Graph client and set options
14+
arg_client = arg.ResourceGraphClient(credential)
15+
16+
query = f"""
17+
resourcecontainers
18+
| where type == 'microsoft.resources/subscriptions' and name == '{subscription_name}'
19+
| project subscriptionId
20+
"""
21+
22+
print(f"query is {query}")
23+
24+
# Create query
25+
arg_query = arg.models.QueryRequest( query=query)
26+
27+
# Run query
28+
arg_result = arg_client.resources(arg_query)
29+
30+
# Show Python object
31+
# print(arg_result)
32+
subscription_id = arg_result.data[0]['subscriptionId']
33+
print(f"Subscription ID of {subscription_name} is : {subscription_id}")
34+
return subscription_id
35+
36+
def main():
37+
"""
38+
To test the script
39+
:return:
40+
"""
41+
load_dotenv()
42+
logging.info("ARG query being prepared......")
43+
run_azure_rg_query(subscription_name="TECH-ARCHITECTS-NONPROD")
44+
logging.info("ARG query Completed......")
45+
46+
47+
if __name__ == "__main__":
48+
main()

0 commit comments

Comments
 (0)