Attach an IAM Instance Profile _profile_name_ to Role _role_name_.

    Args:
        role_name (str): Name of Role.
        profile_name (str): Name of Instance Profile.

    Returns:
        True upon successful completion.
15802
def attach_profile_to_role(client, role_name='forrest_unicorn_role', profile_name='forrest_unicorn_profile'):
    
    current_instance_profiles = resource_action(
        client,
        action='list_instance_profiles_for_role',
        log_format='Found Instance Profiles for %(RoleName)s.',
        RoleName=role_name)['InstanceProfiles']

    for profile in current_instance_profiles:
        if profile['InstanceProfileName'] == profile_name:
            LOG.info('Found Instance Profile attached to Role: %s -> %s', profile_name, role_name)
            break
    else:
        for remove_profile in current_instance_profiles:
            resource_action(
                client,
                action='remove_role_from_instance_profile',
                log_format='Removed Instance Profile from Role: '
                '%(InstanceProfileName)s -> %(RoleName)s',
                InstanceProfileName=remove_profile['InstanceProfileName'],
                RoleName=role_name)

        resource_action(
            client,
            action='add_role_to_instance_profile',
            log_format='Added Instance Profile to Role: '
            '%(InstanceProfileName)s -> %(RoleName)s',
            InstanceProfileName=profile_name,
            RoleName=role_name)

    return True
1360585
def delete_role(name, region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    if not role_exists(name, region, key, keyid, profile):
        return True
    try:
        conn.delete_role(name)
        log.info('Deleted %s IAM role.', name)
        return True
    except boto.exception.BotoServerError as e:
        log.debug(e)
        log.error('Failed to delete %s IAM role.', name)
        return False
563359
def addUsersToRole(self, rolename, users):
        
        params = {
            "f" : "json",
            "rolename" : rolename,
            "users" : users
        }
        rURL = self._url + "/roles/addUsersToRole"
        return self._post(url=rURL, param_dict=params,
                             securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
1319211
def delete_role_policy(role_name, policy_name, region=None, key=None,
                       keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    _policy = get_role_policy(role_name, policy_name, region, key, keyid, profile)
    if not _policy:
        return True
    try:
        conn.delete_role_policy(role_name, policy_name)
        log.info('Successfully deleted policy %s for IAM role %s.',
                 policy_name, role_name)
        return True
    except boto.exception.BotoServerError as e:
        log.debug(e)
        log.error('Failed to delete policy %s for IAM role %s.',
                  policy_name, role_name)
        return False
721963
def conditionally_create_profile(role_name, service_type):
  
  # make instance profile if this service_type gets an instance profile
  if service_type not in INSTANCE_PROFILE_SERVICE_TYPES:
    print_if_verbose("service type: {} not eligible for instance profile".format(service_type))
    return

  instance_profile = get_instance_profile(role_name)
  if not instance_profile:
    print("Create instance profile: {}".format(role_name))
    if CONTEXT.commit:
      try:
        instance_profile = CLIENTS["iam"].create_instance_profile(InstanceProfileName=role_name)
      except ClientError as error:
        fail("Exception creating instance profile named: {} {}".format(role_name, sys.exc_info(), error))
  else:
    print_if_verbose("instance profile already exists: {}".format(role_name))
  # attach instance profile to role; test 'if instance_profile' because we drop through to here in a dry run
  if instance_profile and not instance_profile_contains_role(instance_profile, role_name):
    print("Add role: {} to instance profile: {}".format(role_name, role_name))
    if CONTEXT.commit:
      try:
        CLIENTS["iam"].add_role_to_instance_profile(InstanceProfileName=role_name, RoleName=role_name)
      except ClientError as error:
        fail("Exception adding role to instance profile: {} {}".format(role_name, sys.exc_info(), error))
  else:
    print_if_verbose("instance profile already contains role: {}".format(role_name))
785166
def update_role(u_name, newprivilege):
        '''
        
        '''
        entry = TabMember.update(
            role=newprivilege
        ).where(TabMember.user_name == u_name)
        try:
            entry.execute()
            return True
        except:
            return False
67131
public function attachRole($role)
    {
        if (! $this->hasRole($role->name)) {
            $this->roles()->attach($role);
        }
    }
804501
def get_instances_in_role(self, role, state_filter=None):
    
    self._check_role_name(role)
    instances = []
    
    for instance in self._get_instances(self._group_name_for_role(role), 
                                       state_filter):            
      instances.append(Instance(instance.id, instance.dns_name, 
                                instance.private_dns_name, 
                                instance.private_ip_address))
      
    return instances
1275138
public Policy addBucketIamMember(String bucketName, Role role, Identity identity) {
    // [START add_bucket_iam_member]
    // Initialize a Cloud Storage client
    Storage storage = StorageOptions.getDefaultInstance().getService();

    // Get IAM Policy for a bucket
    Policy policy = storage.getIamPolicy(bucketName);

    // Add identity to Bucket-level IAM role
    Policy updatedPolicy =
        storage.setIamPolicy(bucketName, policy.toBuilder().addIdentity(role, identity).build());

    if (updatedPolicy.getBindings().get(role).contains(identity)) {
      System.out.printf("Added %s with role %s to %s\n", identity, role, bucketName);
    }
    // [END add_bucket_iam_member]
    return updatedPolicy;
  }
698210
def role(self, role_name):
        
        field_name = self.name
        field_roles = {field_name: MLField.translate_role_name(role_name)}
        if field_roles:
            return _change_singleton_roles(self, field_roles, True)
        else:
            return self
172898
public synchronized void addRoleMapping(final String roleName) {
        HashMap<String, RoleMappingImpl> newRoles = new HashMap<String, RoleMappingImpl>(roleMappings);
        if (newRoles.containsKey(roleName) == false) {
            newRoles.put(roleName, new RoleMappingImpl(roleName));
            roleMappings = Collections.unmodifiableMap(newRoles);
        }
    }
857767
def name_build(self, name, is_policy=False, prefix=True):
        
        str = name

        # Add prefix
        if prefix:
            str = self.__role_name_prefix + str

        # Add policy suffix
        if is_policy:
            str = str + "-policy"

        return str
346396
def createRole(self, name, description):
        
        params = {
            "name" : name,
            "description" : description,
            "f" : "json"
        }
        url = self.root + "/createRole"
        return self._post(url=url,
                             param_dict=params,
                             securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
1033695
public boolean hasRoleForUser(String name, String role) {
        List<String> roles = getRolesForUser(name);

        boolean hasRole = false;
        for (String r : roles) {
            if (r.equals(role)) {
                hasRole = true;
                break;
            }
        }

        return hasRole;
    }
326642
def get_full_name(self, role, name):
        

        # An initial '.' indicates a partial name
        if name[0] == '.':
            # Find matches for the partial name in the string
            # containing all full names for this role
            ptrn = r'(?<= )[^,]*' + name + r'(?=,)'
            ml = re.findall(ptrn, self.rolnam[role])
            # Handle cases depending on the number of returned matches,
            # raising an error if exactly one match is not found
            if len(ml) == 0:
                raise KeyError('name matching %s not found' % name,
                               'name', len(ml))
            elif len(ml) > 1:
                raise KeyError('multiple names matching %s found' % name,
                               'name', len(ml))
            else:
                return ml[0]
        else:
            # The absence of an initial '.' indicates a full
            # name. Return the name if it is present in the inventory,
            # otherwise raise an error
            try:
                dom = IntersphinxInventory.roledomain[role]
            except KeyError:
                raise KeyError('role %s not found' % role, 'role', 0)
            if name in self.inv[dom]:
                return name
            else:
                raise KeyError('name %s not found' % name, 'name', 0)
796875
def create_role(name, policy_document=None, path=None, region=None, key=None,
                keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    if role_exists(name, region, key, keyid, profile):
        return True
    if not policy_document:
        policy_document = None
    try:
        conn.create_role(name, assume_role_policy_document=policy_document,
                         path=path)
        log.info('Created IAM role %s.', name)
        return True
    except boto.exception.BotoServerError as e:
        log.error(e)
        log.error('Failed to create IAM role %s.', name)
        return False
36969
def role_exists(name, region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    try:
        conn.get_role(name)
        return True
    except boto.exception.BotoServerError:
        return False