Ensure that a org is present.

    name
        Name of the org to remove.

    profile
        Configuration profile used to connect to the Grafana instance.
        Default is 'grafana'.
163612
def absent(name, profile='grafana'):
    '''
    
    '''
    if isinstance(profile, string_types):
        profile = __salt__['config.option'](profile)

    ret = {'name': name, 'result': None, 'comment': None, 'changes': {}}
    org = __salt__['grafana4.get_org'](name, profile)

    if not org:
        ret['result'] = True
        ret['comment'] = 'Org {0} already absent'.format(name)
        return ret

    if __opts__['test']:
        ret['comment'] = 'Org {0} will be deleted'.format(name)
        return ret
    __salt__['grafana4.delete_org'](org['id'], profile=profile)

    ret['result'] = True
    ret['changes'][name] = 'Absent'
    ret['comment'] = 'Org {0} was deleted'.format(name)

    return ret
505524
def role_present(name, profile=None, **connection_args):
    ''''
    
    '''
    ret = {'name': name,
           'changes': {},
           'result': True,
           'comment': 'Role "{0}" already exists'.format(name)}

    # Check if role is already present
    role = __salt__['keystone.role_get'](name=name, profile=profile,
                                         **connection_args)

    if 'Error' not in role:
        return ret
    else:
        if __opts__.get('test'):
            ret['result'] = None
            ret['comment'] = 'Role "{0}" will be added'.format(name)
            return ret
        # Create role
        __salt__['keystone.role_create'](name, profile=profile,
                                         **connection_args)
        ret['comment'] = 'Role "{0}" has been added'.format(name)
        ret['changes']['Role'] = 'Created'
    return ret
449802
def _configHasProfile(self):
        

        for i, config_file in enumerate(self.config_files):
            if os.path.exists(config_file):
                with open(config_file) as f:
                    config_string = f.read()
                if "[pyradio]" in config_string:
                    if i == 0:
                        self.PROFILE_FROM_USER = True
                    return 1
        return 0
211531
def profile_associated(role_name, profile_name, region, key, keyid, profile):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    # The IAM module of boto doesn't return objects. Instead you need to grab
    # values through its properties. Sigh.
    try:
        profiles = conn.list_instance_profiles_for_role(role_name)
    except boto.exception.BotoServerError as e:
        log.debug(e)
        return False
    profiles = profiles.list_instance_profiles_for_role_response
    profiles = profiles.list_instance_profiles_for_role_result
    profiles = profiles.instance_profiles
    for profile in profiles:
        if profile.instance_profile_name == profile_name:
            return True
    return False
117378
def remove_profile(self):
        
        profile_name = self.profile_combo.currentText()
        # noinspection PyTypeChecker
        button_selected = QMessageBox.warning(
            None,
            'Remove Profile',
            self.tr('Remove %s.') % profile_name,
            QMessageBox.Ok,
            QMessageBox.Cancel
        )
        if button_selected == QMessageBox.Ok:
            self.profile_combo.removeItem(
                self.profile_combo.currentIndex()
            )
            self.minimum_needs.remove_profile(profile_name)
            self.select_profile(self.profile_combo.currentIndex())
1081546
def is_profile_configured(opts, provider, profile_name, vm_=None):
    '''
    
    '''
    # Standard dict keys required by all drivers.
    required_keys = ['provider']
    alias, driver = provider.split(':')

    # Most drivers need an image to be specified, but some do not.
    non_image_drivers = ['nova', 'virtualbox', 'libvirt', 'softlayer', 'oneandone', 'profitbricks']

    # Most drivers need a size, but some do not.
    non_size_drivers = ['opennebula', 'parallels', 'proxmox', 'scaleway',
                        'softlayer', 'softlayer_hw', 'vmware', 'vsphere',
                        'virtualbox', 'libvirt', 'oneandone', 'profitbricks']

    provider_key = opts['providers'][alias][driver]
    profile_key = opts['providers'][alias][driver]['profiles'][profile_name]

    # If cloning on Linode, size and image are not necessary.
    # They are obtained from the to-be-cloned VM.
    if driver == 'linode' and profile_key.get('clonefrom', False):
        non_image_drivers.append('linode')
        non_size_drivers.append('linode')
    elif driver == 'gce' and 'sourceImage' in six.text_type(vm_.get('ex_disks_gce_struct')):
        non_image_drivers.append('gce')

    # If cloning on VMware, specifying image is not necessary.
    if driver == 'vmware' and 'image' not in list(profile_key.keys()):
        non_image_drivers.append('vmware')

    if driver not in non_image_drivers:
        required_keys.append('image')
        if driver == 'vmware':
            required_keys.append('datastore')
    elif driver in ['linode', 'virtualbox']:
        required_keys.append('clonefrom')
    elif driver == 'nova':
        nova_image_keys = ['image', 'block_device_mapping', 'block_device', 'boot_volume']
        if not any([key in provider_key for key in nova_image_keys]) and not any([key in profile_key for key in nova_image_keys]):
            required_keys.extend(nova_image_keys)

    if driver not in non_size_drivers:
        required_keys.append('size')

    # Check if required fields are supplied in the provider config. If they
    # are present, remove it from the required_keys list.
    for item in list(required_keys):
        if item in provider_key:
            required_keys.remove(item)

    # If a vm_ dict was passed in, use that information to get any other configs
    # that we might have missed thus far, such as a option provided in a map file.
    if vm_:
        for item in list(required_keys):
            if item in vm_:
                required_keys.remove(item)

    # Check for remaining required parameters in the profile config.
    for item in required_keys:
        if profile_key.get(item, None) is None:
            # There's at least one required configuration item which is not set.
            log.error(
                "The required '%s' configuration setting is missing from "
                "the '%s' profile, which is configured under the '%s' alias.",
                item, profile_name, alias
            )
            return False

    return True
878800
def lock(instance_id, profile=None, **kwargs):
    '''
    

    '''
    conn = _auth(profile, **kwargs)
    return conn.lock(instance_id)
871528
def absent(name, auth=None, **kwargs):
    '''
    
    '''
    ret = {'name': name,
           'changes': {},
           'result': True,
           'comment': ''}

    kwargs = __utils__['args.clean_kwargs'](**kwargs)

    __salt__['keystoneng.setup_cloud'](auth)

    kwargs['name'] = name
    group = _common(kwargs)

    if group:
        if __opts__['test'] is True:
            ret['result'] = None
            ret['changes'] = {'id': group.id}
            ret['comment'] = 'Group will be deleted.'
            return ret

        __salt__['keystoneng.group_delete'](name=group)
        ret['changes']['id'] = group.id
        ret['comment'] = 'Deleted group'

    return ret
1204718
def absent(name, auth=None):
    '''
    

    '''
    ret = {'name': name,
           'changes': {},
           'result': True,
           'comment': ''}

    __salt__['neutronng.setup_clouds'](auth)

    subnet = __salt__['neutronng.subnet_get'](name=name)

    if subnet:
        if __opts__['test'] is True:
            ret['result'] = None
            ret['changes'] = {'id': subnet.id}
            ret['comment'] = 'Project will be deleted.'
            return ret

        __salt__['neutronng.subnet_delete'](name=subnet)
        ret['changes']['id'] = name
        ret['comment'] = 'Deleted subnet'

    return ret
469395
def validate(args, config):
    
    profile = args.profile
    if not args.profile:
        if os.environ.get('AWS_PROFILE'):
            args.profile = os.environ.get('AWS_PROFILE')
        else:
            args.profile = 'default'

    if args.assume_role:
        role_msg = "with assumed role: %s" % (args.assume_role,)
    elif config.has_option(args.profile, 'assumed_role_arn'):
        role_msg = "with assumed role: %s" % (
            config.get(args.profile, 'assumed_role_arn'))
    else:
        role_msg = ""
    logging.info('Validating credentials for profile: %s %s' %
                (profile, role_msg))
    reup_message = "Obtaining credentials for a new role or profile."

    try:
        key_id = config.get(profile, 'aws_access_key_id')
        access_key = config.get(profile, 'aws_secret_access_key')
    except NoSectionError:
        log_error_and_exit("Credentials session '[%s]' is missing. "
                           "You must add this section to your credentials file "
                           "along with your long term 'aws_access_key_id' and "
                           "'aws_secret_access_key'" % (profile,))
    except NoOptionError as e:
        log_error_and_exit(e)

    # get device from param, env var or config
    if not args.device:
        if os.environ.get('MFA_DEVICE'):
            args.device = os.environ.get('MFA_DEVICE')
        elif config.has_option(profile, 'aws_mfa_device'):
            args.device = config.get(profile, 'aws_mfa_device')
        else:
            log_error_and_exit('You must provide --device or MFA_DEVICE or set '
                               '"aws_mfa_device" in ".aws/credentials"')

    # get assume_role from param or env var
    if not args.assume_role:
        if os.environ.get('MFA_ASSUME_ROLE'):
            args.assume_role = os.environ.get('MFA_ASSUME_ROLE')
        elif config.has_option(profile, 'assume_role'):
            args.assume_role = config.get(profile, 'assume_role')

    # get duration from param, env var or set default
    if not args.duration:
        if os.environ.get('MFA_STS_DURATION'):
            args.duration = int(os.environ.get('MFA_STS_DURATION'))
        else:
            args.duration = 3600 if args.assume_role else 43200

    # If this is False, only refresh credentials if expired. Otherwise
    # always refresh.
    force_refresh = False

    # Validate presence of profile-term section
    if not config.has_section(profile):
        config.add_section(profile)
        force_refresh = True
    # Validate option integrity of profile section
    else:
        required_options = ['assumed_role',
                            'aws_access_key_id', 'aws_secret_access_key',
                            'aws_session_token', 'aws_security_token',
                            'expiration']
        try:
            short_term = {}
            for option in required_options:
                short_term[option] = config.get(profile, option)
        except NoOptionError:
            logging.warn("Your existing credentials are missing or invalid, "
                        "obtaining new credentials.")
            force_refresh = True

        try:
            current_role = config.get(profile, 'assumed_role_arn')
        except NoOptionError:
            current_role = None

        if args.force:
            logging.info("Forcing refresh of credentials.")
            force_refresh = True
        # There are not credentials for an assumed role,
        # but the user is trying to assume one
        elif current_role is None and args.assume_role:
            logging.info(reup_message)
            force_refresh = True
        # There are current credentials for a role and
        # the role arn being provided is the same.
        elif (current_role is not None and
                args.assume_role and current_role == args.assume_role):
            pass
        # There are credentials for a current role and the role
        # that is attempting to be assumed is different
        elif (current_role is not None and
              args.assume_role and current_role != args.assume_role):
            logging.info(reup_message)
            force_refresh = True
        # There are credentials for a current role and no role arn is
        # being supplied
        elif current_role is not None and args.assume_role is None:
            logging.info(reup_message)
            force_refresh = True

    should_refresh = True

    # Unless we're forcing a refresh, check expiration.
    if not force_refresh:
        exp = datetime.strptime(
            config.get(profile, 'expiration'), '%Y-%m-%d %H:%M:%S')
        diff = exp - datetime.utcnow()
        if diff.total_seconds() <= 0:
            logging.info("Your credentials have expired, renewing.")
        else:
            should_refresh = False
            logging.info(
                "Your credentials are still valid for %s seconds"
                " they will expire at %s"
                % (diff.total_seconds(), exp))

    if should_refresh:
        get_credentials(profile, args, config)
110021
def remove_profile(project_root)
      # Choose a profile from the availables
      profiles = Bebox::Profile.list(project_root)
      # Get a profile if exist
      if profiles.count > 0
        profile = choose_option(profiles, _('wizard.choose_remove_profile'))
      else
        return error _('wizard.profile.no_deletion_profiles')
      end
      # Ask for deletion confirmation
      return warn(_('wizard.no_changes')) unless confirm_action?(_('wizard.profile.confirm_deletion'))
      # Profile deletion
      profile_name = profile.split('/').last
      profile_base_path = profile.split('/')[0...-1].join('/')
      profile = Bebox::Profile.new(profile_name, project_root, profile_base_path)
      output = profile.remove
      ok _('wizard.profile.deletion_success')
      return output
    end
85728
def get_profile(name=None, **kwargs):
    
    if isinstance(name, Profile):
        return name

    clazz = get_profile_class(name or 'default')
    return clazz(**kwargs)
689960
def set_instances(name, instances, test=False, region=None, key=None, keyid=None,
                         profile=None):
    '''
    
    '''
    ret = True
    current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)])
    desired = set(instances)
    add = desired - current
    remove = current - desired
    if test:
        return bool(add or remove)
    if remove:
        if deregister_instances(name, list(remove), region, key, keyid, profile) is False:
            ret = False
    if add:
        if register_instances(name, list(add), region, key, keyid, profile) is False:
            ret = False
    return ret
1021380
def getProfile(self, profile=None):
    '''
    
    '''
    if profile is None:
      # todo: what if the configuration `profile.default` does not exist?
      profile = self.config.get('DEFAULT', 'profile.default')
    if profile in self.profiles:
      return self.profiles[profile].init()
    for prof in self.profiles.values():
      if prof.name == profile:
        return prof.init()
    for prof in self.profiles.values():
      if prof.name.lower() == profile.lower():
        return prof.init()
    raise KeyError(profile)
368662
def exists(name=None, region=None, key=None, keyid=None, profile=None,
           vpc_id=None, vpc_name=None, group_id=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    group = _get_group(conn, name=name, vpc_id=vpc_id, vpc_name=vpc_name,
                       group_id=group_id, region=region, key=key, keyid=keyid,
                       profile=profile)
    if group:
        return True
    else:
        return False
179741
def set_default_org(self, name):
        
        org = self.get_org(name)
        self.unset_default_org()
        org.config["default"] = True
        self.set_org(org)
296351
def profile_name(org_vm, profile_inst, short=False):
    
    try:
        name_tuple = get_profile_name(org_vm, profile_inst)
    except Exception as ex:  # pylint: disable=broad-except
        print('GET_FULL_PROFILE_NAME exception %sm tuple=%r inst=%s' %
              (ex, name_tuple, profile_inst))
        return("UNKNOWN")
    if short:
        return "%s:%s" % (name_tuple[0], name_tuple[1])

    return "%s:%s:%s" % (name_tuple[0], name_tuple[1], name_tuple[2])