Add new IAM roles for the service account.
356801
def _add_iam_policy_binding(service_account, roles):
    """"""
    project_id = service_account["projectId"]
    email = service_account["email"]
    member_id = "serviceAccount:" + email

    policy = crm.projects().getIamPolicy(resource=project_id).execute()

    already_configured = True

    for role in roles:
        role_exists = False
        for binding in policy["bindings"]:
            if binding["role"] == role:
                if member_id not in binding["members"]:
                    binding["members"].append(member_id)
                    already_configured = False
                role_exists = True

        if not role_exists:
            already_configured = False
            policy["bindings"].append({
                "members": [member_id],
                "role": role,
            })

    if already_configured:
        # In some managed environments, an admin needs to grant the
        # roles, so only call setIamPolicy if needed.
        return

    result = crm.projects().setIamPolicy(
        resource=project_id, body={
            "policy": policy,
        }).execute()

    return result
975426
def create_iam_role(self, account):
        
        try:
            iam = self.session.client('iam')
            trust = get_template('vpc_flow_logs_iam_role_trust.json').render()
            policy = get_template('vpc_flow_logs_role_policy.json').render()

            newrole = iam.create_role(
                Path='/',
                RoleName=self.role_name,
                AssumeRolePolicyDocument=trust
            )['Role']['Arn']

            # Attach an inline policy to the role to avoid conflicts or hitting the Managed Policy Limit
            iam.put_role_policy(
                RoleName=self.role_name,
                PolicyName='VpcFlowPolicy',
                PolicyDocument=policy
            )

            self.log.debug('Created VPC Flow Logs role & policy for {}'.format(account.account_name))
            auditlog(
                event='vpc_flow_logs.create_iam_role',
                actor=self.ns,
                data={
                    'account': account.account_name,
                    'roleName': self.role_name,
                    'trustRelationship': trust,
                    'inlinePolicy': policy
                }
            )
            return newrole

        except Exception:
            self.log.exception('Failed creating the VPC Flow Logs role for {}.'.format(account))
1319968
def add_account(self, account):
        """"""
        serialized = account.serialize()
        section_items = flatten_dict(serialized)
        section_id = section_items['local_id']

        if not self.parser.has_section(section_id):
            self.parser.add_section(section_id)

        for key in sorted(section_items):
            self.parser.set(section_id, key, section_items[key])

        self.encrypt_account(id=section_id)

        return self
73533
def put(self):
        """"""
        cred_payload = utils.uni_to_str(json.loads(request.get_data()))
        return self.manager.update_credential(cred_payload)
986421
def assign(self, role):
        ''''''
        if role.owner_id != self.id:
            return self.roles.add(role)
45090
public CMASpaceMembership addRole(CMALink role) {
    if (role == null) {
      throw new IllegalArgumentException("Role cannot be null!");
    }

    if (roles == null) {
      roles = new ArrayList<CMALink>();
    }

    this.roles.add(role);
    return this;
  }
1198825
def add_to_inventory(self):
        """"""
        if self.lb_attrs:
            self.lb_attrs = self.consul.lb_details(
                    self.lb_attrs[A.loadbalancer.ID]
                    )
            host = self.lb_attrs['virtualIps'][0]['address']
            self.stack.add_lb_secgroup(self.name, [host], self.backend_port)
            self.stack.add_host(
                    host,
                    [self.name],
                    self.lb_attrs
                    )
339287
def auth_add(name, service, **kwargs):
    
    ctx = Context(**kwargs)
    ctx.execute_action('auth:group:members:add', **{
        'storage': ctx.repo.create_secure_service('storage'),
        'name': name,
        'service': service,
    })
83936
def add_service(self, zeroconf, service_type, name):
        """"""
        self.lock.acquire()
        try:
            self._internal_add(zeroconf, service_type, name)
        finally:
            self.lock.release()
94707
def add_user(self, user_name, role='user'):
        
        role_uri = self._get_role_uri(role=role)
        return self.api.put(path=role_uri, data={'username': user_name})
1000561
protected function insertRoleServiceAccess()
    {
        $rolesInZip = $this->package->getResourceFromZip('system/role.json');
        $imported = false;

        if (!empty($rolesInZip)) {
            try {
                foreach ($rolesInZip as $riz) {
                    $rsa = $riz['role_service_access_by_role_id'];
                    $role = Role::whereName($riz['name'])->first();
                    if (!empty($role) && !empty($rsa)) {
                        $newRoleId = $role->id;
                        $cleanedRsa = [];
                        foreach ($rsa as $r) {
                            $originId = $r['id'];
                            $this->fixCommonFields($r);
                            $newServiceId = $this->getNewServiceId($r['service_id']);

                            if (empty($newServiceId) && !empty($r['service_id'])) {
                                $this->log(
                                    'warning',
                                    'Skipping relation role_service_access_by_role_id with id ' .
                                    $originId .
                                    ' for Role ' .
                                    $riz['name'] .
                                    '. Service not found for ' .
                                    $r['service_id']
                                );
                                continue;
                            }

                            $r['service_id'] = $newServiceId;
                            $r['role_id'] = $newRoleId;

                            if ($this->isDuplicateRoleServiceAccess($r)) {
                                $this->log(
                                    'notice',
                                    'Skipping duplicate role_service_access relation with id ' . $originId . '.'
                                );
                                continue;
                            }

                            $cleanedRsa[] = $r;
                        }

                        if (!empty($cleanedRsa)) {
                            $roleUpdate = ['role_service_access_by_role_id' => $cleanedRsa];
                            $result =
                                ServiceManager::handleRequest(
                                    'system', Verbs::PATCH, 'role/' . $newRoleId, [], [], $roleUpdate, null, true, true
                                );
                            if ($result->getStatusCode() >= 300) {
                                throw ResponseFactory::createExceptionFromResponse($result);
                            }
                            $imported = true;
                        }
                    } elseif (!empty($rsa) && empty($role)) {
                        $this->log(
                            'warning',
                            'Skipping all Role Service Access for ' . $riz['name'] . ' No imported role found.'
                        );
                        \Log::debug('Skipped Role Service Access.', $riz);
                    } else {
                        $this->log('notice', 'No Role Service Access for role ' . $riz['name']);
                    }
                }
            } catch (\Exception $e) {
//                if ($e->getCode() === HttpStatusCodes::HTTP_FORBIDDEN) {
//                    $this->log(
//                        'error',
//                        'Failed to insert role service access records for roles. ' .
//                        $this->getErrorDetails($e)
//                    );
//                }
//                throw new InternalServerErrorException(
//                    'Failed to insert role service access records for roles. ' .
//                    $this->getErrorDetails($e)
//                );
                $this->throwExceptions($e, 'Failed to insert role service access records for roles');
            }
        }

        return $imported;
    }
1007833
def add_membership(self, user, role):
        
        targetGroup = AuthGroup.objects(role=role, creator=self.client).first()
        if not targetGroup:
            return False

        target = AuthMembership.objects(user=user, creator=self.client).first()
        if not target:
            target = AuthMembership(user=user, creator=self.client)

        if not role in [i.role for i in target.groups]:
            target.groups.append(targetGroup)
            target.save()
        return True
206688
protected function wizardAddUser()
    {
        // Required
        $this->validatePrompt('email', $this->text('E-mail'), 'user');
        $this->validatePrompt('password', $this->text('Password'), 'user');
        $this->validatePrompt('name', $this->text('Name'), 'user');

        // Optional
        $this->validatePrompt('role_id', $this->text('Role ID'), 'user', 0);
        $this->validatePrompt('store_id', $this->text('Store ID'), 'user', $this->config->get('store', 1));
        $this->validatePrompt('timezone', $this->text('Timezone'), 'user', $this->config->get('timezone', 'Europe/London'));
        $this->validatePrompt('status', $this->text('Status'), 'user', 0);
        $this->validatePrompt('data', $this->text('Data'), 'user');
        $this->setSubmittedJson('data');

        $this->validateComponent('user');
        $this->addUser();
    }
618904
def role_add(user, role):
    '''
    
    '''
    ret = {}

    ## validate roles
    roles = role.split(',')
    known_roles = role_list().keys()
    valid_roles = [r for r in roles if r in known_roles]
    log.debug(
        'rbac.role_add - roles=%s, known_roles=%s, valid_roles=%s',
        roles,
        known_roles,
        valid_roles,
    )

    ## update user roles
    if valid_roles:
        res = __salt__['cmd.run_all']('usermod -R "{roles}" {login}'.format(
            login=user,
            roles=','.join(set(role_get(user) + valid_roles)),
        ))
        if res['retcode'] > 0:
            ret['Error'] = {
                'retcode': res['retcode'],
                'message': res['stderr'] if 'stderr' in res else res['stdout']
            }
            return ret

    ## update return value
    active_roles = role_get(user)
    for r in roles:
        if r not in valid_roles:
            ret[r] = 'Unknown'
        elif r in active_roles:
            ret[r] = 'Added'
        else:
            ret[r] = 'Failed'

    return ret
741981
public function add()
    {
        $this->loadModel('User.Roles');
        $role = $this->Roles->newEntity();

        if ($this->request->data()) {
            $role = $this->Roles->patchEntity($role, $this->request->data(), ['fieldList' => 'name']);
            if ($this->Roles->save($role)) {
                $this->Flash->success(__d('user', 'Role successfully created.'));
            } else {
                $this->Flash->danger(__d('user', 'Role could not be created.'));
            }
        }

        $this->title(__d('user', 'Define New Role'));
        $this->set(compact('role'));
        $this->Breadcrumb
            ->push('/admin/user/manage')
            ->push(__d('user', 'Roles'), ['plugin' => 'User', 'controller' => 'roles', 'action' => 'index'])
            ->push(__d('user', 'Add new role'), '');
    }
76041
public function actionRoleAssign() : void
    {
        $username = $this->prompt('Username:', ['required' => true]);
        $user = $this->findModel($username);
        $roleName = $this->select('Role:', ArrayHelper::map($this->authManager->getRoles(), 'name', 'description'));
        $role = $this->authManager->getRole($roleName);
        $this->authManager->assign($role, $user->id);
        $this->log(true);
    }
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;
  }