|
| 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 | + |
0 commit comments