def main(argv): agent_id = None oms_cert_path = None oms_key_path = None endpoint = None gpg_keyring_path = None operation = None proxy_configuration_path = None test_mode = False state_directory = None working_directory = None workspace_id = None mock_powershelldsc_test = False # parse cmd line args try: opts, args = getopt.getopt(argv, "hrdw:a:c:k:e:f:s:p:g:t", [ "help", "register", "deregister", "workspaceid=", "agentid=", "certpath=", "keypath=", "endpoint=", "workingdirpath=", "statepath=", "proxyconfpath=", "gpgkeyringpath=", "mock_powershelldsc_test" ]) except getopt.GetoptError: print __file__ + "[--register, --deregister] -w <workspaceid> -a <agentid> -c <certhpath> -k <keypath> " \ "-e <endpoint> -f <workingdirpath> -s <statepath> -p <proxyconfpath> -g <gpgkeyringpath>" sys.exit(2) for opt, arg in opts: if opt == ("-h", "--help"): print __file__ + "[--register, --deregister] -w <workspaceid> -a <agentid> -c <certhpath> -k <keypath> " \ "-e <endpoint> -f <workingdirpath> -s <statepath> -p <proxyconfpath> -g <gpgkeyringpath>" sys.exit() elif opt in ("-r", "--register"): operation = REGISTER elif opt in ("-d", "--deregister"): operation = DEREGISTER elif opt in ("-w", "--workspaceid"): workspace_id = arg.strip() elif opt in ("-a", "--agentid"): agent_id = arg.strip() elif opt in ("-c", "--certpath"): oms_cert_path = arg.strip() elif opt in ("-k", "--keypath"): oms_key_path = arg.strip() elif opt in ("-e", "--endpoint"): endpoint = arg.strip() elif opt in ("-f", "--workingdirpath"): working_directory = arg.strip() elif opt in ("-p", "--proxyconfpath"): proxy_configuration_path = arg.strip() elif opt in ("-s", "--statepath"): state_directory = arg.strip() elif opt in ("-g", "--gpgkeyringpath"): gpg_keyring_path = arg.strip() elif opt in ("-t", "--test"): test_mode = True elif opt == "--mock_powershelldsc_test": # generate a dummy configuration file # does not do actual registration, just creates the resulting config file mock_powershelldsc_test = True if workspace_id is None or agent_id is None or oms_cert_path is None or oms_key_path is None \ or endpoint is None or gpg_keyring_path is None or proxy_configuration_path is None\ or working_directory is None or state_directory is None: print "Missing mandatory arguments." print "Use -h or --help for usage." sys.exit(1) else: if mock_powershelldsc_test is True: # Don't validate paths if we want to generate a dummy config file pass else: # validate that the cert and key exists if os.path.isfile(oms_cert_path) is False or os.path.isfile( oms_key_path) is False: raise Exception( "Certificate or key file doesn't exist. Are you using absolute path?" ) configuration.clear_config() configuration.set_config({ configuration.PROXY_CONFIGURATION_PATH: proxy_configuration_path, configuration.WORKER_VERSION: "LinuxAutoRegister", configuration.WORKING_DIRECTORY_PATH: "/var/opt/microsoft/omsagent/tmp" }) # build registration endpoint # example endpoint : agentsvc.azure-automation.net registration_endpoint = "https://" + workspace_id + "." + endpoint + "/accounts/" + workspace_id if "df-agentsvc" in registration_endpoint: registration_endpoint = "https://oaasagentsvcdf.test.azure-automation.net/accounts/" + workspace_id test_mode = True # rename to match oms concepts to automation machine_id = agent_id worker_group_name = socket.gethostname() + "_" + agent_id # action if operation == REGISTER: if mock_powershelldsc_test is True: # Don't do the actual registration in case we want only a dummy registration file # create a dummy response instead registration_response = \ {'jobRuntimeDataServiceUri': 'https://we-jobruntimedata-prod-su1.azure-automation.net', 'AccountId': '23216587-8f56-428c-9006-4c2f28c036f5'} cert_info = [ '', '', '959GG850526XC5JT35E269CZ69A55E1C7E1256JH' ] else: registration_response = register(registration_endpoint, worker_group_name, machine_id, oms_cert_path, oms_key_path, test_mode) cert_info = get_cert_info(oms_cert_path) create_worker_configuration_file( working_directory, registration_response["jobRuntimeDataServiceUri"], registration_endpoint, workspace_id, registration_response["AccountId"], worker_group_name, machine_id, oms_cert_path, oms_key_path, state_directory, gpg_keyring_path, proxy_configuration_path, test_mode, cert_info) elif operation == DEREGISTER: deregister(registration_endpoint, worker_group_name, machine_id, oms_cert_path, oms_key_path, test_mode) else: raise Exception( "No option specified, specify --register, --deregister or --help." )
import sys from optparse import OptionParser # append worker binary source path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from worker import configuration from worker import httpclientfactory from worker import linuxutil from worker import serializerfactory from worker import util json = serializerfactory.get_serializer(sys.version_info) configuration.clear_config() configuration.set_config({configuration.PROXY_CONFIGURATION_PATH: "/etc/opt/microsoft/omsagent/proxy.conf", configuration.WORKER_VERSION: "LinuxDIYRegister", configuration.WORKING_DIRECTORY_PATH: "/tmp"}) def get_ip_address(): try: return socket.gethostbyname(socket.gethostname()) except: return "127.0.0.1" def set_permission_recursive(permission, path): """Sets the permission for a specific path and it's child items recursively. Args: permission : string, linux permission (i.e 770).
import getopt import os import socket import subprocess import sys # append worker binary source path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # since we are using the worker httpclient, some configuration values are expected from worker import configuration configuration.delete_config() configuration.set_config({ configuration.WORKER_VERSION: "LinuxAutoRegister", configuration.WORKING_DIRECTORY_PATH: "/var/opt/microsoft/omsagent/tmp" }) from worker import CurlHttpClient from worker import simplejson as json REGISTER = "register" DEREGISTER = "deregister" def get_cert_info(certificate_path): """Gets certificate information by invoking OpenSSL (OMS agent dependency). Returns: A tuple containing the certificate's issuer, subject and thumbprint.
def main(argv): agent_id = None is_azure_vm = False vm_id = None oms_cert_path = None oms_key_path = None endpoint = None gpg_keyring_path = None operation = None proxy_configuration_path = None test_mode = False state_directory = None working_directory = None workspace_id = None mock_powershelldsc_test = False diy_account_id = None azure_resource_id = None # parse cmd line args try: opts, args = getopt.getopt(argv, "hrdw:a:c:k:e:f:s:p:g:y:i:v:zt", ["help", "register", "deregister", "workspaceid=", "agentid=", "certpath=", "keypath=", "endpoint=", "workingdirpath=", "statepath=", "proxyconfpath=", "gpgkeyringpath=", "diyaccountid=", "mock_powershelldsc_test=", "vmid=", "azureresourceid="]) except getopt.GetoptError: print __file__ + "[--register, --deregister] -w <workspaceid> -a <agentid> -c <certhpath> -k <keypath> " \ "-e <endpoint> -f <workingdirpath> -s <statepath> -p <proxyconfpath> -g <gpgkeyringpath>" \ "-y <diyaccountid> -i <vmid>" sys.exit(2) for opt, arg in opts: if opt == ("-h", "--help"): print __file__ + "[--register, --deregister] -w <workspaceid> -a <agentid> -c <certhpath> -k <keypath> " \ "-e <endpoint> -f <workingdirpath> -s <statepath> -p <proxyconfpath> -g <gpgkeyringpath>" \ "-y <diyaccountid> -i <vmid>" sys.exit() elif opt in ("-r", "--register"): operation = REGISTER elif opt in ("-d", "--deregister"): operation = DEREGISTER elif opt in ("-w", "--workspaceid"): workspace_id = arg.strip() elif opt in ("-a", "--agentid"): agent_id = arg.strip() elif opt in ("-c", "--certpath"): oms_cert_path = arg.strip() elif opt in ("-k", "--keypath"): oms_key_path = arg.strip() elif opt in ("-e", "--endpoint"): endpoint = arg.strip() elif opt in ("-f", "--workingdirpath"): working_directory = arg.strip() elif opt in ("-p", "--proxyconfpath"): proxy_configuration_path = arg.strip() elif opt in ("-s", "--statepath"): state_directory = arg.strip() elif opt in ("-g", "--gpgkeyringpath"): gpg_keyring_path = arg.strip() elif opt in ("-y", "--diyaccountid"): diy_account_id = arg.strip() elif opt in ("-z", "--azurevm"): is_azure_vm = True elif opt in ("-v", "--azureresourceid"): azure_resource_id = arg.strip() # Use the Resource ID from DSC resource as a backup. Overwrite it with metadata from IMDS when available elif opt in ("-i", "--vmid"): vm_id = arg.strip() # Use the VM ID from DSC resource as a backup. Overwrite it with metadata from IMDS when available elif opt in ("-t", "--test"): test_mode = True elif opt == "--mock_powershelldsc_test": # generate a dummy configuration file # does not do actual registration, just creates the resulting config file mock_powershelldsc_test = True if workspace_id is None or agent_id is None or oms_cert_path is None or oms_key_path is None \ or endpoint is None or gpg_keyring_path is None or proxy_configuration_path is None \ or working_directory is None or state_directory is None or vm_id is None: print "Missing mandatory arguments." print "Use -h or --help for usage." sys.exit(1) else: if mock_powershelldsc_test is True: # Don't validate paths if we want to generate a dummy config file pass else: # validate that the cert and key exists if os.path.isfile(oms_cert_path) is False or os.path.isfile(oms_key_path) is False: raise Exception("Certificate or key file doesn't exist. Are you using absolute path?") configuration.clear_config() configuration.set_config( {configuration.PROXY_CONFIGURATION_PATH: proxy_configuration_path, configuration.WORKER_VERSION: "LinuxAutoRegister", configuration.WORKING_DIRECTORY_PATH: "/var/opt/microsoft/omsagent/tmp"}) # build registration endpoint # example endpoint : agentsvc.azure-automation.net registration_endpoint = "https://" + workspace_id + "." + endpoint + "/accounts/" + workspace_id if "df-agentsvc" in registration_endpoint: registration_endpoint = "https://oaasagentsvcdf.test.azure-automation.net/accounts/" + workspace_id test_mode = True # rename to match oms concepts to automation machine_id = agent_id worker_group_name = get_hybrid_worker_group_name(agent_id=agent_id) # action if operation == REGISTER: if mock_powershelldsc_test is True: # Don't do the actual registration in case we want only a dummy registration file # create a dummy response instead registration_response = \ {'jobRuntimeDataServiceUri': 'https://we-jobruntimedata-prod-su1.azure-automation.net', 'AccountId': '23216587-8f56-428c-9006-4c2f28c036f5'} cert_info = ['', '', '959GG850526XC5JT35E269CZ69A55E1C7E1256JH'] else: registration_response, payload = register(registration_endpoint, worker_group_name, machine_id, oms_cert_path, oms_key_path, is_azure_vm, vm_id, azure_resource_id, test_mode) cert_info = linuxutil.get_cert_info(oms_cert_path) account_id = registration_response["AccountId"] if test_mode is False and diy_account_id is not None and diy_account_id != account_id: sys.stderr.write("Unable to create worker configuration. DIY Automation account differs from " "linked account.") sys.exit(-5) create_worker_configuration_file(working_directory, registration_response["jobRuntimeDataServiceUri"], registration_endpoint, workspace_id, account_id, worker_group_name, machine_id, oms_cert_path, oms_key_path, state_directory, gpg_keyring_path, proxy_configuration_path, test_mode, cert_info, is_azure_vm, payload["VirtualMachineId"]) elif operation == DEREGISTER: deregister(registration_endpoint, worker_group_name, machine_id, oms_cert_path, oms_key_path, test_mode) else: raise Exception("No option specified, specify --register, --deregister or --help.")
import ConfigParser import datetime import getopt import os import socket import subprocess import sys # append worker binary source path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # since we are using the worker httpclient, some configuration values are expected from worker import configuration configuration.delete_config() configuration.set_config({configuration.WORKER_VERSION: "LinuxAutoRegister", configuration.WORKING_DIRECTORY_PATH: "/var/opt/microsoft/omsagent/tmp"}) from worker import CurlHttpClient from worker import simplejson as json REGISTER = "register" DEREGISTER = "deregister" def get_cert_info(certificate_path): """Gets certificate information by invoking OpenSSL (OMS agent dependency). Returns: A tuple containing the certificate's issuer, subject and thumbprint. """ p = subprocess.Popen(["openssl", "x509", "-noout", "-in", certificate_path, "-fingerprint", "-sha1"],
import grp import pwd # append worker binary source path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from worker import configuration from worker import serializerfactory from worker import linuxutil from worker import diydirs json = serializerfactory.get_serializer(sys.version_info) configuration.clear_config() configuration.set_config({configuration.PROXY_CONFIGURATION_PATH: "/etc/opt/microsoft/omsagent/proxy.conf", configuration.WORKER_VERSION: "OMSUtil", configuration.WORKING_DIRECTORY_PATH: "/tmp"}) USERNAME_NXAUTOMATION = "nxautomation" GROUPNAME_NXAUTOMATION = "nxautomation" GROUPNAME_OMSAGENT = "omsagent" def initialize(): """Initializes the OMS environment. Meant to be executed everytime the resource's set method is invoked. Steps: - Sets omsagent group to nxautomation user (if needed). - Sets group read permission to MSFT keyring.gpg - Sets group read and execute to the OMS certificate folder. Args:
def main(argv): agent_id = None is_azure_vm = False vm_id = None oms_cert_path = None oms_key_path = None endpoint = None gpg_keyring_path = None operation = None proxy_configuration_path = None test_mode = False state_directory = None working_directory = None workspace_id = None mock_powershelldsc_test = False diy_account_id = None azure_resource_id = None # parse cmd line args try: opts, args = getopt.getopt(argv, "hrdw:a:c:k:e:f:s:p:g:y:i:v:zt", [ "help", "register", "deregister", "workspaceid=", "agentid=", "certpath=", "keypath=", "endpoint=", "workingdirpath=", "statepath=", "proxyconfpath=", "gpgkeyringpath=", "diyaccountid=", "mock_powershelldsc_test=", "vmid=", "azureresourceid=" ]) except getopt.GetoptError: print __file__ + "[--register, --deregister] -w <workspaceid> -a <agentid> -c <certhpath> -k <keypath> " \ "-e <endpoint> -f <workingdirpath> -s <statepath> -p <proxyconfpath> -g <gpgkeyringpath>" \ "-y <diyaccountid> -i <vmid>" sys.exit(2) for opt, arg in opts: if opt == ("-h", "--help"): print __file__ + "[--register, --deregister] -w <workspaceid> -a <agentid> -c <certhpath> -k <keypath> " \ "-e <endpoint> -f <workingdirpath> -s <statepath> -p <proxyconfpath> -g <gpgkeyringpath>" \ "-y <diyaccountid> -i <vmid>" sys.exit() elif opt in ("-r", "--register"): operation = REGISTER elif opt in ("-d", "--deregister"): operation = DEREGISTER elif opt in ("-w", "--workspaceid"): workspace_id = arg.strip() elif opt in ("-a", "--agentid"): agent_id = arg.strip() elif opt in ("-c", "--certpath"): oms_cert_path = arg.strip() elif opt in ("-k", "--keypath"): oms_key_path = arg.strip() elif opt in ("-e", "--endpoint"): endpoint = arg.strip() elif opt in ("-f", "--workingdirpath"): working_directory = arg.strip() elif opt in ("-p", "--proxyconfpath"): proxy_configuration_path = arg.strip() elif opt in ("-s", "--statepath"): state_directory = arg.strip() elif opt in ("-g", "--gpgkeyringpath"): gpg_keyring_path = arg.strip() elif opt in ("-y", "--diyaccountid"): diy_account_id = arg.strip() elif opt in ("-z", "--azurevm"): is_azure_vm = True elif opt in ("-v", "--azureresourceid"): azure_resource_id = arg.strip( ) # Use the Resource ID from DSC resource as a backup. Overwrite it with metadata from IMDS when available elif opt in ("-i", "--vmid"): vm_id = arg.strip( ) # Use the VM ID from DSC resource as a backup. Overwrite it with metadata from IMDS when available elif opt in ("-t", "--test"): test_mode = True elif opt == "--mock_powershelldsc_test": # generate a dummy configuration file # does not do actual registration, just creates the resulting config file mock_powershelldsc_test = True if workspace_id is None or agent_id is None or oms_cert_path is None or oms_key_path is None \ or endpoint is None or gpg_keyring_path is None or proxy_configuration_path is None \ or working_directory is None or state_directory is None or vm_id is None: print "Missing mandatory arguments." print "Use -h or --help for usage." sys.exit(1) else: if mock_powershelldsc_test is True: # Don't validate paths if we want to generate a dummy config file pass else: # validate that the cert and key exists if os.path.isfile(oms_cert_path) is False or os.path.isfile( oms_key_path) is False: raise Exception( "Certificate or key file doesn't exist. Are you using absolute path?" ) configuration.clear_config() configuration.set_config({ configuration.PROXY_CONFIGURATION_PATH: proxy_configuration_path, configuration.WORKER_VERSION: "LinuxAutoRegister", configuration.WORKING_DIRECTORY_PATH: "/var/opt/microsoft/omsagent/tmp" }) # build registration endpoint # example endpoint : agentsvc.azure-automation.net registration_endpoint = "https://" + workspace_id + "." + endpoint + "/accounts/" + workspace_id if "df-agentsvc" in registration_endpoint: registration_endpoint = "https://oaasagentsvcdf.test.azure-automation.net/accounts/" + workspace_id test_mode = True # rename to match oms concepts to automation machine_id = agent_id worker_group_name = get_hybrid_worker_group_name(agent_id=agent_id) # action if operation == REGISTER: if mock_powershelldsc_test is True: # Don't do the actual registration in case we want only a dummy registration file # create a dummy response instead registration_response = \ {'jobRuntimeDataServiceUri': 'https://we-jobruntimedata-prod-su1.azure-automation.net', 'AccountId': '23216587-8f56-428c-9006-4c2f28c036f5'} cert_info = [ '', '', '959GG850526XC5JT35E269CZ69A55E1C7E1256JH' ] else: # Update the metadata if possible platform_update_domain = "" tags = "" try: http_client_factory = httpclientfactory.HttpClientFactory( oms_cert_path, oms_key_path, test_mode) http_client = http_client_factory.create_http_client( sys.version_info) metadata = get_metadata_from_imds(http_client) if metadata is not None: try: vm_id = metadata["compute"]["vmId"] sub_id = metadata["compute"]["subscriptionId"] resource_group = metadata["compute"][ "resourceGroupName"] vm_name = metadata["compute"]["name"] azure_resource_id = "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualMachines/{2}".format( sub_id, resource_group, vm_name) platform_update_domain = metadata["compute"][ "platformUpdateDomain"] tags = metadata["compute"]["tags"] except KeyError: pass except: pass registration_response = register(registration_endpoint, worker_group_name, machine_id, oms_cert_path, oms_key_path, is_azure_vm, vm_id, azure_resource_id, test_mode, platform_update_domain, tags) cert_info = linuxutil.get_cert_info(oms_cert_path) account_id = registration_response["AccountId"] if test_mode is False and diy_account_id is not None and diy_account_id != account_id: sys.stderr.write( "Unable to create worker configuration. DIY Automation account differs from " "linked account.") sys.exit(-5) create_worker_configuration_file( working_directory, registration_response["jobRuntimeDataServiceUri"], registration_endpoint, workspace_id, account_id, worker_group_name, machine_id, oms_cert_path, oms_key_path, state_directory, gpg_keyring_path, proxy_configuration_path, test_mode, cert_info, is_azure_vm, vm_id) elif operation == DEREGISTER: deregister(registration_endpoint, worker_group_name, machine_id, oms_cert_path, oms_key_path, test_mode) else: raise Exception( "No option specified, specify --register, --deregister or --help." )