コード例 #1
0
ファイル: azure_rm.py プロジェクト: zhaxing2/ansible
    def __init__(self, args):
        self._args = args
        self._compute_client = None
        self._resource_client = None
        self._network_client = None

        self.debug = False
        if args.debug:
            self.debug = True

        self.credentials = self._get_credentials(args)
        if not self.credentials:
            self.fail("Failed to get credentials. Either pass as parameters, set environment variables, "
                      "or define a profile in ~/.azure/credentials.")

        if self.credentials.get('subscription_id', None) is None:
            self.fail("Credentials did not include a subscription_id value.")
        self.log("setting subscription_id")
        self.subscription_id = self.credentials['subscription_id']

        if self.credentials.get('client_id') is not None and \
           self.credentials.get('secret') is not None and \
           self.credentials.get('tenant') is not None:
            self.azure_credentials = ServicePrincipalCredentials(client_id=self.credentials['client_id'],
                                                                 secret=self.credentials['secret'],
                                                                 tenant=self.credentials['tenant'])
        elif self.credentials.get('ad_user') is not None and self.credentials.get('password') is not None:
            tenant = self.credentials.get('tenant')
            if tenant is not None:
                self.azure_credentials = UserPassCredentials(self.credentials['ad_user'], self.credentials['password'], tenant=tenant)
            else:
                self.azure_credentials = UserPassCredentials(self.credentials['ad_user'], self.credentials['password'])
        else:
            self.fail("Failed to authenticate with provided credentials. Some attributes were missing. "
                      "Credentials must include client_id, secret and tenant or ad_user and password.")
コード例 #2
0
ファイル: azurearm.py プロジェクト: arminsama/bos
def _determine_auth(**kwargs):
    '''
    Acquire Azure ARM Credentials
    '''
    if 'profile' in kwargs:
        azure_credentials = __salt__['config.option'](kwargs['profile'])
        kwargs.update(azure_credentials)

    service_principal_creds_kwargs = ['client_id', 'secret', 'tenant']
    user_pass_creds_kwargs = ['username', 'password']

    try:
        if kwargs.get('cloud_environment') and kwargs.get(
                'cloud_environment').startswith('http'):
            cloud_env = get_cloud_from_metadata_endpoint(
                kwargs['cloud_environment'])
        else:
            cloud_env_module = importlib.import_module(
                'msrestazure.azure_cloud')
            cloud_env = getattr(
                cloud_env_module,
                kwargs.get('cloud_environment', 'AZURE_PUBLIC_CLOUD'))
    except (AttributeError, ImportError, MetadataEndpointError):
        raise sys.exit(
            'The Azure cloud environment {0} is not available.'.format(
                kwargs['cloud_environment']))

    if set(service_principal_creds_kwargs).issubset(kwargs):
        if not (kwargs['client_id'] and kwargs['secret'] and kwargs['tenant']):
            raise SaltInvocationError(
                'The client_id, secret, and tenant parameters must all be '
                'populated if using service principals.')
        else:
            credentials = ServicePrincipalCredentials(
                kwargs['client_id'],
                kwargs['secret'],
                tenant=kwargs['tenant'],
                cloud_environment=cloud_env)
    elif set(user_pass_creds_kwargs).issubset(kwargs):
        if not (kwargs['username'] and kwargs['password']):
            raise SaltInvocationError(
                'The username and password parameters must both be '
                'populated if using username/password authentication.')
        else:
            credentials = UserPassCredentials(kwargs['username'],
                                              kwargs['password'],
                                              cloud_environment=cloud_env)
    else:
        raise SaltInvocationError(
            'Unable to determine credentials. '
            'A subscription_id with username and password, '
            'or client_id, secret, and tenant or a profile with the '
            'required parameters populated')

    if 'subscription_id' not in kwargs:
        raise SaltInvocationError('A subscription_id must be specified')

    subscription_id = salt.utils.stringutils.to_str(kwargs['subscription_id'])

    return credentials, subscription_id, cloud_env
コード例 #3
0
def get_conn(
    Client=ComputeManagementClient,  # pylint: disable=invalid-name
    ClientConfig=ComputeManagementClientConfiguration):  # pylint: disable=invalid-name
    '''
    Return a conn object for the passed VM data
    '''
    subscription_id = config.get_cloud_config_value('subscription_id',
                                                    get_configured_provider(),
                                                    __opts__,
                                                    search_global=False)

    username = config.get_cloud_config_value('username',
                                             get_configured_provider(),
                                             __opts__,
                                             search_global=False)

    password = config.get_cloud_config_value('password',
                                             get_configured_provider(),
                                             __opts__,
                                             search_global=False)

    credentials = UserPassCredentials(username, password)
    client = Client(
        ClientConfig(
            credentials,
            subscription_id=subscription_id,
        ))
    return client
コード例 #4
0
ファイル: pricing.py プロジェクト: reIMAGINE-Labs/trackit
def fetch_region_pricing(offer, region):
    now = datetime.utcnow()
    record = AzurePricing.query.filter(
        and_(AzurePricing.offer == offer,
             AzurePricing.region == region)).order_by(desc(
                 AzurePricing.date)).first()
    if record and record.date > now - azure_fetch_freq:
        return
    if not record:
        record = AzurePricing(offer=offer, region=region)
    try:
        azure_subscription_id = app.config['AZURE_SUBSCRIPTION_ID']
        azure_ad_username = app.config['AZURE_AD_USERNAME']
        azure_ad_password = app.config['AZURE_AD_PASSWORD']

        azure_credentials = UserPassCredentials(azure_ad_username,
                                                azure_ad_password)
        azure_commerce_client = UsageManagementClient(azure_credentials,
                                                      azure_subscription_id)

        azure_resource_client = ResourceManagementClient(
            azure_credentials, azure_subscription_id)
        azure_resource_client.providers.register('Microsoft.Commerce')
    except Exception, e:
        logging.error(
            "Error during azure UserPassCredentials instantiation in app.ms_azure.pricing.fetch_region_pricing"
        )
        global COMMERCE_CREDENTIALS_ERROR_EMAIL_SENT
        if not COMMERCE_CREDENTIALS_ERROR_EMAIL_SENT:
            azure_commerce_userpasscredentials_error_email(
                traceback.format_exc())
            COMMERCE_CREDENTIALS_ERROR_EMAIL_SENT = True
        return
コード例 #5
0
 def __init__(self, user, passwd, subscription_id, resource_group):
     self.subscription_id = subscription_id
     self.resource_group = resource_group
     self.dns_label_prefix = self.name_generator.haikunate()
     self.credentials = UserPassCredentials(user, passwd)
     self.client = ResourceManagementClient(self.credentials,
                                            self.subscription_id)
コード例 #6
0
def public_ip_creation(req):

    usr_mail = req.session['email']
    usr_pass = req.session['azure_pwd']
    subid = str(req.session['subid'])

    try:

        credentials = UserPassCredentials(usr_mail, usr_pass)
        network_client = NetworkManagementClient(credentials, subid)

        public_ip_parameter = {
            'location': req.POST['location'],
            'public_ip_allocation_method': 'Static',
            'public_ip_address_version': 'IPv4',
            'idle_timeout_in_minutes': 4  #value must be in between 4 to 30
        }

        res = network_client.public_ip_addresses.create_or_update(
            req.POST['resgroup'], req.POST['public_ip_name'],
            public_ip_parameter)

        res1 = res.result()

    except Exception as e:

        return HttpResponse(e)
    else:
        return HttpResponse("Your public ip address is " +
                            str(res1.ip_address))
コード例 #7
0
def vpn_creation(req):

    usr_mail = req.session['email']
    usr_pass = req.session['azure_pwd']
    subid = str(req.session['subid'])

    try:

        credentials = UserPassCredentials(usr_mail, usr_pass)
        network_client = NetworkManagementClient(credentials, subid)
        resource_client = ResourceManagementClient(credentials, subid)

        res_obj = resource_client.resource_groups.get(req.POST['drop1'])

        vpn_parameter = {
            'location': res_obj.location,
            'address_space': {
                'address_prefixes': [req.POST['vpn_address']]
            }
        }

        network_client.virtual_networks.create_or_update(
            req.POST['drop1'], req.POST['vpn_name'], vpn_parameter)

    except Exception as e:

        return HttpResponse(e)
    else:
        return HttpResponse("Successfully Created")
コード例 #8
0
    def __init__(self):
        credentials = UserPassCredentials(CONF.azure.username,
                                          CONF.azure.password)
        LOG.info(_LI('Login with Azure username and password.'))
        self.resource = ResourceManagementClient(credentials,
                                                 CONF.azure.subscription_id)
        self.compute = ComputeManagementClient(credentials,
                                               CONF.azure.subscription_id)
        self.network = NetworkManagementClient(credentials,
                                               CONF.azure.subscription_id)
        try:
            self.resource.providers.register('Microsoft.Network')
            LOG.info(_LI("Register Microsoft.Network"))
            self.resource.providers.register('Microsoft.Compute')
            LOG.info(_LI("Register Microsoft.Compute"))
        except Exception as e:
            msg = six.text_type(e)
            ex = exception.ProviderRegisterFailure(reason=msg)
            LOG.exception(msg)
            raise ex

        try:
            self.resource.resource_groups.create_or_update(
                CONF.azure.resource_group, {'location': CONF.azure.location})
            LOG.info(_LI("Create/Update Resource Group"))
        except Exception as e:
            msg = six.text_type(e)
            ex = exception.ResourceGroupCreateFailure(reason=msg)
            LOG.exception(msg)
            raise ex
コード例 #9
0
ファイル: azurearm.py プロジェクト: haiya512/salt
def get_conn(Client=None, ClientConfig=None):
    '''
    Return a conn object for the passed VM data
    '''
    if Client is not None:
        Client = ComputeManagementClient
    if ClientConfig is not None:
        ClientConfig = ComputeManagementClientConfiguration

    subscription_id = config.get_cloud_config_value('subscription_id',
                                                    get_configured_provider(),
                                                    __opts__,
                                                    search_global=False)

    username = config.get_cloud_config_value('username',
                                             get_configured_provider(),
                                             __opts__,
                                             search_global=False)

    password = config.get_cloud_config_value('password',
                                             get_configured_provider(),
                                             __opts__,
                                             search_global=False)

    credentials = UserPassCredentials(username, password)
    client = Client(
        ClientConfig(
            credentials,
            subscription_id=subscription_id,
        ))
    return client
コード例 #10
0
    def get_credentials(self, auth_data):
        auths = auth_data.getAuthInfo(self.type)
        if not auths:
            raise Exception("No auth data has been specified to Azure.")
        else:
            auth = auths[0]

        if 'subscription_id' in auth and 'username' in auth and 'password' in auth:
            subscription_id = auth['subscription_id']

            if self.credentials and self.auth.compare(auth_data, self.type):
                return self.credentials, subscription_id
            else:
                self.auth = auth_data
                self.credentials = UserPassCredentials(auth['username'], auth['password'])
        elif 'subscription_id' in auth and 'client_id' in auth and 'secret' in auth and 'tenant' in auth:
            subscription_id = auth['subscription_id']

            if self.credentials and self.auth.compare(auth_data, self.type):
                return self.credentials, subscription_id
            else:
                self.auth = auth_data
                self.credentials = ServicePrincipalCredentials(client_id=auth['client_id'],
                                                               secret=auth['secret'],
                                                               tenant=auth['tenant'])
        else:
            raise Exception("No correct auth data has been specified to Azure: "
                            "subscription_id, username and password or"
                            "subscription_id, client_id, secret and tenant")

        return self.credentials, subscription_id
コード例 #11
0
def delstorage(req):

    mail = req.session['email']
    password = req.session['azure_pwd']
    subid = str(req.session['subid'])

    credentials = UserPassCredentials(mail, password)

    storage_client = StorageManagementClient(credentials, subid)
    resource_client = ResourceManagementClient(credentials, subid)

    lst_del_str = req.GET.getlist('abc')

    try:
        '''for rg in resource_client.resource_groups.list():
			for item in resource_client.resource_groups.list_resources(rg.name):

				if "Microsoft.Storage/storageAccounts" == item.type and item.name in lst_del_str:

					storage_client.storage_accounts.delete(rg.name,item.name)
		'''

        lst = lst_del_str[0].split(",")
        storage_client.storage_accounts.delete(lst[1], lst[0])

    except Exception as e:

        return HttpResponse(e)
    else:
        return HttpResponse("Successfully deleted")
コード例 #12
0
ファイル: azure_rm.py プロジェクト: Ineaweb/templateARM
    def __init__(self, args):
        self._args = args
        self._cloud_environment = None
        self._compute_client = None
        self._resource_client = None
        self._network_client = None

        self.debug = False
        if args.debug:
            self.debug = True

        self.credentials = self._get_credentials(args)
        if not self.credentials:
            self.fail("Failed to get credentials. Either pass as parameters, set environment variables, "
                      "or define a profile in ~/.azure/credentials.")

        # if cloud_environment specified, look up/build Cloud object
        raw_cloud_env = self.credentials.get('cloud_environment')
        if not raw_cloud_env:
            self._cloud_environment = azure_cloud.AZURE_PUBLIC_CLOUD  # SDK default
        else:
            # try to look up "well-known" values via the name attribute on azure_cloud members
            all_clouds = [x[1] for x in inspect.getmembers(azure_cloud) if isinstance(x[1], azure_cloud.Cloud)]
            matched_clouds = [x for x in all_clouds if x.name == raw_cloud_env]
            if len(matched_clouds) == 1:
                self._cloud_environment = matched_clouds[0]
            elif len(matched_clouds) > 1:
                self.fail("Azure SDK failure: more than one cloud matched for cloud_environment name '{0}'".format(raw_cloud_env))
            else:
                if not urlparse.urlparse(raw_cloud_env).scheme:
                    self.fail("cloud_environment must be an endpoint discovery URL or one of {0}".format([x.name for x in all_clouds]))
                try:
                    self._cloud_environment = azure_cloud.get_cloud_from_metadata_endpoint(raw_cloud_env)
                except Exception as e:
                    self.fail("cloud_environment {0} could not be resolved: {1}".format(raw_cloud_env, e.message))

        if self.credentials.get('subscription_id', None) is None:
            self.fail("Credentials did not include a subscription_id value.")
        self.log("setting subscription_id")
        self.subscription_id = self.credentials['subscription_id']

        if self.credentials.get('client_id') is not None and \
           self.credentials.get('secret') is not None and \
           self.credentials.get('tenant') is not None:
            self.azure_credentials = ServicePrincipalCredentials(client_id=self.credentials['client_id'],
                                                                 secret=self.credentials['secret'],
                                                                 tenant=self.credentials['tenant'],
                                                                 cloud_environment=self._cloud_environment)
        elif self.credentials.get('ad_user') is not None and self.credentials.get('password') is not None:
            tenant = self.credentials.get('tenant')
            if not tenant:
                tenant = 'common'
            self.azure_credentials = UserPassCredentials(self.credentials['ad_user'],
                                                         self.credentials['password'],
                                                         tenant=tenant,
                                                         cloud_environment=self._cloud_environment)
        else:
            self.fail("Failed to authenticate with provided credentials. Some attributes were missing. "
                      "Credentials must include client_id, secret and tenant or ad_user and password.")
コード例 #13
0
def authenticate(req):

    msg = ""

    if 'email' in req.POST:
        email = req.POST['email']

        if email == "":
            return render(req, "validation_msg.html",
                          {"message": "Plase fill email"})
    else:
        msg = "email is missing"
        return render(req, 'validation_msg.html', {"message": msg})

    if 'password' in req.POST:
        password = req.POST['password']

        if password == "":
            msg = "password is missing"
            return render(req, 'validation_msg.html', {"message": msg})
    else:
        msg = "password is missing"
        return render(req, 'validation_msg.html', {"message": msg})

    if 'subid' in req.POST:
        subid = str(req.POST['subid'])

        if subid == "":
            msg = "subid is missing"
            return render(req, 'validation_msg.html', {"message": msg})
    else:
        msg = "subid is missing"
        return render(req, 'validation_msg.html', {"message": msg})

    try:
        req.session['email'] = email
        req.session['password'] = password
        req.session['subid'] = subid

        credentials = UserPassCredentials(email, password)
        resource_client = ResourceManagementClient(credentials, subid)

        msg += "Valid user!!!!"

        #fo = open("netrc","ab")
        #machine = "portal.azure.com"+email
        #str1 ="\nmachine "+machine+"\n"+"login "+email+"\n"+"password "+password

        #fo.write(str1)

        return render(req, 'validation_msg.html', {"message": msg})

    except Exception as e:

        msg += "EROOR: "
        msg += str(e)

        return render(req, 'validation_msg.html', {"message": msg})
コード例 #14
0
def get_credentials(config_data):

    return UserPassCredentials(

        config_data["username"],

        config_data["password"],

    )
コード例 #15
0
    def __init__(self, config: dict, channel=None):
        """INITIALIZE AZURE PROVIDER. USES AZURE PYTHON SDK TO PROVIDE EXECUTION RESOURCES
            ARGS:
             - :parm config (dict): Dictionary with all the config options.

            KWargs:
             - :param channel (None): A channel is not required for Azure.


        """
        self.config = self.read_configs(config)
        self.config_logger()

        if not _azure_enabled:
            raise OptionalModuleMissing(['azure'], "Azure Provider requires the azure module.")

        credentials = UserPassCredentials(self.config['username'], self.config['pass'])
        subscription_id = self.config['subscriptionId']

        self.resource_client = ResourceManagementClient(credentials, subscription_id)
        self.storage_client = StorageManagementClient(credentials, subscription_id)

        self.resource_group_name = 'my_resource_group'
        self.deployer = Deployer(subscription_id, self.resource_group_name, self.read_configs(config))

        self.channel = channel
        self.config = config
        self.sitename = config['site']
        self.current_blocksize = 0
        self.resources = {}
        self.instances = []

        self.config = config
        options = self.config["execution"]["block"]["options"]
        logger.warn("Options %s", options)
        self.instance_type = options.get("azure_template_file", "template.json")
        self.image_id = options["imageId"]
        self.key_name = options["keyName"]
        self.region = options.get("region", 'us-east-2')
        self.max_nodes = (
            self.config["execution"]["block"].get("maxBlocks", 1) * self.config["execution"]["block"].get("nodes", 1))

        try:
            self.initialize_boto_client()
        except Exception as e:
            logger.error("Site:[{0}] Failed to initialize".format(self))
            raise e

        try:
            self.statefile = self.config["execution"]["block"]["options"].get("stateFile", '.ec2site_{0}.json'.format(
                self.sitename))
            self.read_state_file(self.statefile)

        except Exception as e:
            self.create_vpc().id
            logger.info("No State File. Cannot load previous options. Creating new infrastructure")
            self.write_state_file()
コード例 #16
0
ファイル: main.py プロジェクト: tamcclur/azure-quick-attach
 def login(self):
     """Method to authenticate"""
     try:
         credentials = UserPassCredentials(userName, userPass)
         print('Authenticated Successfully.')
     except:
         print(
             'Either your AD login/password is incorrect, or you are using an MFA. \n'
             + 'MFA use with this script is not supported at this time')
         sys.exit(1)
     self.connecting_clients(credentials)
コード例 #17
0
 def __init__(self):
     self.credentials = UserPassCredentials(
         config.AD_LOGIN_USER,
         config.AD_LOGIN_PASS,
         resource="https://graph.windows.net"
     )
     self.tenant_id = config.AD_TENANT_ID
     self.client = GraphRbacManagementClient(
         self.credentials,
         self.tenant_id
     )
コード例 #18
0
    def __init__(self, cluster_id, cluster_name, config, plugin_config):
        self.config = config
        self.plugin_config = plugin_config

        #TODO: Deal with different auth types
        self.aad_credentials = UserPassCredentials(
            self.config.get("aadUsername"), self.config.get("aadPassword"))
        self.subscription_id = self.config.get('aadSubscriptionId')

        #TODO: check how to simplify that since clusters are unique to Azure
        self.hdi_cluster_name = self.config.get('hdiClusterName')
        self.hdi_cluster_rg = self.config.get('hdiResourceGroup')
コード例 #19
0
def main():

    credentials = UserPassCredentials(mailadmin,
                                      passwordadmin,
                                      resource="https://graph.windows.net")

    graphrbac_client = GraphRbacManagementClient(credentials, tenantid)

    param = UserUpdateParameters(password_profile=PasswordProfile(
        password=newpassword, force_change_password_next_login=False))

    user = graphrbac_client.users.update(mail, param)
コード例 #20
0
ファイル: azure.py プロジェクト: rantahar/libsubmit
    def __init__(self,
                 subscription_id,
                 username,
                 password,
                 label='azure',
                 template_file='template.json',
                 init_blocks=1,
                 min_blocks=0,
                 max_blocks=1,
                 nodes_per_block=1,
                 state_file=None):
        self.configure_logger()

        if not _azure_enabled:
            raise OptionalModuleMissing(
                ['azure'], "Azure Provider requires the azure module.")

        credentials = UserPassCredentials(username, password)

        self.resource_client = ResourceManagementClient(
            credentials, subscription_id)
        self.storage_client = StorageManagementClient(credentials,
                                                      subscription_id)

        self.resource_group_name = 'my_resource_group'
        self.deployer = Deployer(subscription_id, self.resource_group_name,
                                 self.read_configs(config))

        self.channel = channel
        self.config = config
        self.provisioned_blocks = 0
        self.resources = {}
        self.instances = []

        self.max_nodes = max_blocks * nodes_per_block

        try:
            self.initialize_boto_client()
        except Exception as e:
            logger.error("Azure '{}' failed to initialize.".format(self.label))
            raise e

        try:
            if state_file is None:
                state_file = '.azure_{}.json'.format(self.label)
            self.read_state_file(state_file)

        except Exception as e:
            self.create_vpc().id
            logger.info(
                "No State File. Cannot load previous options. Creating new infrastructure."
            )
            self.write_state_file()
コード例 #21
0
ファイル: azure_rm.py プロジェクト: titilambert/ansible
    def __init__(self, args):
        self._args = args
        self._compute_client = None
        self._resource_client = None
        self._network_client = None

        self.debug = False
        if args.debug:
            self.debug = True

        self.credentials = self._get_credentials(args)
        if not self.credentials:
            self.fail("Failed to get credentials. Either pass as parameters, set environment variables, "
                      "or define a profile in ~/.azure/credentials.")

        if self.credentials.get('subscription_id', None) is None:
            self.fail("Credentials did not include a subscription_id value.")
        self.log("setting subscription_id")
        self.subscription_id = self.credentials['subscription_id']

        if self.credentials.get('client_id') is not None and \
           self.credentials.get('secret') is not None and \
           self.credentials.get('tenant') is not None:
            self.azure_credentials = ServicePrincipalCredentials(client_id=self.credentials['client_id'],
                                                                 secret=self.credentials['secret'],
                                                                 tenant=self.credentials['tenant'])
        elif self.credentials.get('ad_user') is not None and \
             self.credentials.get('password') is not None and \
             self.credentials.get('client_id') is not None and \
             self.credentials.get('authority') is not None:
                # ADAL support
                # Default value for resource
                resource = self.credentials['resource']
                if resource is None:
                    resource = 'https://management.core.windows.net/'
                # Get context
                context = adal.AuthenticationContext(self.credentials['authority'])
                # Get token
                raw_token = context.acquire_token_with_username_password(resource,
                                                                         self.credentials['ad_user'],
                                                                         self.credentials['password'],
                                                                         self.credentials['client_id'])
                # From CamelCase to underscore
                token =  {}
                for key, value in raw_token.items():
                    token[re.sub( '(?<!^)(?=[A-Z])', '_', key).lower()] = value
                # Get azure credentials
                self.azure_credentials = BasicTokenAuthentication(token)
        elif self.credentials.get('ad_user') is not None and self.credentials.get('password') is not None:
            self.azure_credentials = UserPassCredentials(self.credentials['ad_user'], self.credentials['password'])
        else:
            self.fail("Failed to authenticate with provided credentials. Some attributes were missing. "
                      "Credentials must include client_id, secret and tenant or ad_user and password.")
コード例 #22
0
    def __init__(self,
                 resource_group_name,
                 template_path,
                 parameters,
                 user_email="*****@*****.**",
                 user_password="******",
                 subscription_id="0003c64e-455e-4794-8665-a59c04a8961b"):
        # region ---- Set instance fields ----
        self.resource_group_name = resource_group_name
        self.deployment_name = "taivo_python_deployment"
        self.template_path = template_path
        self.parameters = parameters

        self.credentials = UserPassCredentials(user_email, user_password)
        self.resource_client = ResourceManagementClient(
            self.credentials, subscription_id)
        self.compute_client = ComputeManagementClient(self.credentials,
                                                      subscription_id)
        self.network_client = NetworkManagementClient(self.credentials,
                                                      subscription_id)
        self.storage_client = StorageManagementClient(self.credentials,
                                                      subscription_id)

        # endregion

        # region ---- Set up logging ----
        LOG_FORMAT = '%(asctime)-15s [%(name)s] - %(message)s'
        LOG_LEVEL = logging.INFO
        formatter = logging.Formatter(LOG_FORMAT)

        ch = logging.StreamHandler()
        ch.setLevel(LOG_LEVEL)
        ch.setFormatter(formatter)

        self.log = logging.getLogger(__name__)
        self.log.setLevel(LOG_LEVEL)
        self.log.addHandler(ch)
        # endregion

        # region ---- Find if resource group exists ----
        already_exists = self.resource_client.resource_groups.check_existence(
            self.resource_group_name)
        if already_exists:
            self.log.info("Resource group already exists:")
            resources = self.resource_client.resource_groups.list_resources(
                self.resource_group_name)
            #for res in resources:
            #    self.log.info(Deployer.stringify_resource(res))
        else:
            self.log.info("Resource group does not exist yet.")
        # endregion
        pass
コード例 #23
0
    def __init__(self):
        self.credentials = ServicePrincipalCredentials(
            client_id=CLIENT_ID,
            secret=SECRET,
            tenant=TENANT,
        )

        self.cr = UserPassCredentials('*****@*****.**', 'Roshan@123')
        self.monitor_client = MonitorManagementClient(self.cr, subscription_id)
        self.compute_client = ComputeManagementClient(self.cr, subscription_id)
        self.network_client = NetworkManagementClient(self.cr, subscription_id)
        self.resource_client = ResourceManagementClient(
            self.cr, subscription_id)
コード例 #24
0
def azure_credentials():

    try:  # ServicePrincipalCredentials first
        credentials = ServicePrincipalCredentials(
            client_id=os.environ['AZURE_CLIENT_ID'],
            secret=os.environ['AZURE_CLIENT_SECRET'],
            tenant=os.environ['AZURE_TENANT_ID'])
    except KeyError:
        credentials = UserPassCredentials(
            username=os.environ['AZURE_USERNAME'],
            password=os.environ['AZURE_PASSWORD'])

    return credentials
コード例 #25
0
    def get_credentials(self, auth_method, **kwargs):
        if auth_method == 'Service Principal':
            credentials = ServicePrincipalCredentials(
                client_id=kwargs['client_id'],
                secret=kwargs['secret'],
                tenant=kwargs['tenant_id'])
        elif auth_method == 'User ID Password':
            credentials = UserPassCredentials(username=kwargs['user_id'],
                                              password=kwargs['password'])
        else:
            credentials = None

        return credentials
コード例 #26
0
    def __init__(self, config_file='/work/config.yaml'):
        """Set config file (default:/work/config.yaml)"""
        config_file = '/work/config.yaml'
        f = open(config_file)
        data = yaml.load(f)
        f.close()
        username = data['username']
        password = data['password']
        subscription_id = data['subscription_id']

        credentials = UserPassCredentials(username, password)

        self._computemanagement_client = ComputeManagementClient(
            credentials, subscription_id)
コード例 #27
0
def get_access_token(
    subscription_id=None,
    user=None,
    password=None,
    tenant=None,
    is_china=False,
    timeout=None):
    """
    Open Azure API session using AzureSDK and return Token

    :param subscription_id: Azure Subscription ID
    :type subscription_id: str
    :param user: UserName or Client ID
    :type user: str
    :param password: Password or Secret ID
    :type password: str
    :param tenant: Tenant ID
    :type tenant: str
    :param is_china: China Option
    :type is_china: bool

    :return: Token
    :rtype: dict

    """

    for field_name in ['subscription_id', 'user', 'password']:
        if locals().get(field_name, None) is None:
            raise AttributeError("field [%s] is required" % field_name)

    try:
        if not tenant:
            credentials = UserPassCredentials(user, password, china=is_china)
        else:
            credentials = ServicePrincipalCredentials(
                client_id=user, secret=password, tenant=tenant, china=is_china, timeout=timeout
            )
    except Exception as e:
        msg = 'Login Azure FAILED with message : %s' % str(e)
        logger.error(msg)
        raise AuthenticationError(msg)

    rm = ResourceManagementClient(credentials, subscription_id)
    if rm.config.generate_client_request_id:
        return credentials.token
    else:
        msg = 'login azure failed'
        logger.error(msg)
        raise AuthenticationError(msg)
コード例 #28
0
def network_content1(req):

    credentials = UserPassCredentials(req.session['email'],
                                      req.session['azure_pwd'])
    resource_client = ResourceManagementClient(credentials,
                                               str(req.session['subid']))

    lst = resource_client.resource_groups.list()

    lst_rg = []

    for item in lst:
        lst_rg.append(item.name)

    return render(req, "vertical_pilles.html", {"lst_rg": lst_rg})
コード例 #29
0
def lst_rg(req):

    lst_rg = []

    email = req.session['email']
    password = req.session['azure_pwd']
    subid = str(req.session['subid'])

    try:
        credentials = UserPassCredentials(email, password)
        resource_client = ResourceManagementClient(credentials, subid)
    except Exception as e:
        return HttpResponse(e)

    for item in resource_client.resource_groups.list():
        lst_rg.append(item.name)

    return render(req, 'lst_rg.html', {"lst_rg": lst_rg})
コード例 #30
0
    def __init__(self,
                 username=CONF.azure.username,
                 password=CONF.azure.password,
                 subscription_id=CONF.azure.subscription_id,
                 resource_group=CONF.azure.resource_group,
                 location=CONF.azure.location):

        credentials = UserPassCredentials(username, password)
        LOG.info(_LI('Login with Azure username and password.'))
        self.compute = ComputeManagementClient(credentials, subscription_id)
        self.resource = ResourceManagementClient(credentials, subscription_id)
        try:
            self.resource.resource_groups.create_or_update(
                CONF.azure.resource_group, {'location': location})
            LOG.info(_LI("Create/Update Resource Group"))
        except Exception as e:
            msg = six.text_type(e)
            ex = exception.VolumeBackendAPIException(reason=msg)
            LOG.exception(msg)
            raise ex