Assume role (prior to deployment).
555579
def pre_deploy_assume_role(assume_role_config, context):
    """"""
    if isinstance(assume_role_config, dict):
        assume_role_arn = ''
        if assume_role_config.get('post_deploy_env_revert'):
            context.save_existing_iam_env_vars()
        if assume_role_config.get('arn'):
            assume_role_arn = assume_role_config['arn']
            assume_role_duration = assume_role_config.get('duration')
        elif assume_role_config.get(context.env_name):
            if isinstance(assume_role_config[context.env_name], dict):
                assume_role_arn = assume_role_config[context.env_name]['arn']  # noqa
                assume_role_duration = assume_role_config[context.env_name].get('duration')  # noqa pylint: disable=line-too-long
            else:
                assume_role_arn = assume_role_config[context.env_name]
                assume_role_duration = None
        else:
            LOGGER.info('Skipping assume-role; no role found for '
                        'environment %s...',
                        context.env_name)

        if assume_role_arn:
            context.env_vars = merge_dicts(
                context.env_vars,
                assume_role(
                    role_arn=assume_role_arn,
                    session_name=assume_role_config.get('session_name', None),
                    duration_seconds=assume_role_duration,
                    region=context.env_region,
                    env_vars=context.env_vars
                )
            )
    else:
        context.env_vars = merge_dicts(
            context.env_vars,
            assume_role(role_arn=assume_role_config,
                        region=context.env_region,
                        env_vars=context.env_vars)
        )
1250310
private void takeLeadership() {
    context.setLeader(context.getCluster().member().id());
    context.getClusterState().getRemoteMemberStates().forEach(m -> m.resetState(context.getLog()));
  }
188313
def cli(obj, role, scopes, delete):
    """"""
    client = obj['client']
    if delete:
        client.delete_perm(delete)
    else:
        if not role:
            raise click.UsageError('Missing option "--role".')
        if not scopes:
            raise click.UsageError('Missing option "--scope".')
        try:
            perm = client.create_perm(role, scopes)
        except Exception as e:
            click.echo('ERROR: {}'.format(e))
            sys.exit(1)
        click.echo(perm.id)
1298998
def create(cls, action, **kwargs):
        """"""
        role = kwargs.pop('role', None)
        if role:
            assert role.method == 'system_role'
            kwargs['role_name'] = role.value
        return super(ActionSystemRoles, cls).create(action, **kwargs)
898156
private void takeLeadership() {
    raft.setLeader(raft.getCluster().getMember().memberId());
    raft.getCluster().getRemoteMemberStates().forEach(m -> m.resetState(raft.getLog()));
  }
181333
def _cli_check_role(role):
    ''''''

    if role is None:
        return None

    role = role.lower()
    if not role in api.get_roles():
        errstr = "Role format '" + role + "' does not exist.\n"
        errstr += "For a complete list of roles, use the 'bse list-roles' command"
        raise RuntimeError(errstr)

    return role
1006029
def set_role(project_root, environment)
      roles = Bebox::Role.list(project_root)
      nodes = Bebox::Node.list(project_root, environment, 'nodes')
      node = choose_option(nodes, _('wizard.choose_node'))
      role = choose_option(roles, _('wizard.choose_role'))
      output = Bebox::Provision.associate_node_role(project_root, environment, node, role)
      ok _('wizard.node.role_set_success')
      return output
    end
613547
def role(ctx, dependency_name, driver_name, lint_name, provisioner_name,
         role_name, verifier_name, template):  # pragma: no cover
    
    command_args = {
        'dependency_name': dependency_name,
        'driver_name': driver_name,
        'lint_name': lint_name,
        'provisioner_name': provisioner_name,
        'role_name': role_name,
        'scenario_name': command_base.MOLECULE_DEFAULT_SCENARIO_NAME,
        'subcommand': __name__,
        'verifier_name': verifier_name,
    }

    if verifier_name == 'inspec':
        command_args['verifier_lint_name'] = 'rubocop'

    if verifier_name == 'goss':
        command_args['verifier_lint_name'] = 'yamllint'

    if verifier_name == 'ansible':
        command_args['verifier_lint_name'] = 'ansible-lint'

    if template is not None:
        command_args['template'] = template

    r = Role(command_args)
    r.execute()
1336556
def assume_role(role_arn, session_name=None, duration_seconds=None,
                region='us-east-1', env_vars=None):
    """"""
    if session_name is None:
        session_name = 'runway'
    assume_role_opts = {'RoleArn': role_arn,
                        'RoleSessionName': session_name}
    if duration_seconds:
        assume_role_opts['DurationSeconds'] = int(duration_seconds)
    boto_args = {}
    if env_vars:
        for i in ['aws_access_key_id', 'aws_secret_access_key',
                  'aws_session_token']:
            if env_vars.get(i.upper()):
                boto_args[i] = env_vars[i.upper()]

    sts_client = boto3.client('sts', region_name=region, **boto_args)
    LOGGER.info("Assuming role %s...", role_arn)
    response = sts_client.assume_role(**assume_role_opts)
    return {'AWS_ACCESS_KEY_ID': response['Credentials']['AccessKeyId'],
            'AWS_SECRET_ACCESS_KEY': response['Credentials']['SecretAccessKey'],  # noqa
            'AWS_SESSION_TOKEN': response['Credentials']['SessionToken']}
744853
def handle(self, *args, **options):
        """"""
        force = options.get('force')
        retire = options.get('retire')
        verbosity = int(options.get('verbosity'))

        users = get_user_model().objects.filter(is_superuser=True).order_by('date_joined')

        if not users.exists():
            self.stderr.write("Admin does not exist: create a superuser")
            exit(1)

        process_paths, descriptor_paths = [], []
        process_schemas, descriptor_schemas = [], []

        for finder in get_finders():
            process_paths.extend(finder.find_processes())
            descriptor_paths.extend(finder.find_descriptors())

        for proc_path in process_paths:
            process_schemas.extend(
                self.find_schemas(proc_path, schema_type=SCHEMA_TYPE_PROCESS, verbosity=verbosity))

        for desc_path in descriptor_paths:
            descriptor_schemas.extend(
                self.find_schemas(desc_path, schema_type=SCHEMA_TYPE_DESCRIPTOR, verbosity=verbosity))

        user_admin = users.first()
        self.register_descriptors(descriptor_schemas, user_admin, force, verbosity=verbosity)
        # NOTE: Descriptor schemas must be registered first, so
        #       processes can validate 'entity_descriptor_schema' field.
        self.register_processes(process_schemas, user_admin, force, verbosity=verbosity)

        if retire:
            self.retire(process_schemas)

        if verbosity > 0:
            self.stdout.write("Running executor post-registration hook...")
        manager.get_executor().post_register_hook(verbosity=verbosity)
535619
protected function beforeStart()
    {
        // If no explicit request was given (via Enlighten::setRequest), create one based on the current PHP globals
        if (empty($this->request)) {
            $this->setRequest(Request::extractFromEnvironment());
        }

        $this->bootstrapRouter();
    }
414531
def assume_role(credentials, account, role):
    """"""
    sts = boto3.client(
        'sts',
        aws_access_key_id=credentials['accessKeyId'],
        aws_secret_access_key=credentials['secretAccessKey'],
        aws_session_token=credentials['sessionToken'],
    )
    resp = sts.assume_role(
        RoleArn='arn:aws:sts::{}:role/{}'.format(account, role),
        RoleSessionName='fleece_assumed_role'
    )
    return {
        'accessKeyId': resp['Credentials']['AccessKeyId'],
        'secretAccessKey': resp['Credentials']['SecretAccessKey'],
        'sessionToken': resp['Credentials']['SessionToken'],
    }
388632
function askDeployNow() {
    if (this.abort) return null;
    const done = this.async();
    const prompts = [
        {
            type: 'confirm',
            name: 'deployNow',
            message: 'Would you like to deploy now?.',
            default: true
        }
    ];

    return this.prompt(prompts).then(props => {
        this.deployNow = props.deployNow;
        done();
    });
}
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
824485
def initiate(self, aspect=None, view=None, parent=None, officer=None):
        """"""

        def got_view(view):
            if view is None:
                return None
            return init(view)

        def init(view):
            self.view = view
            d = self.call_mro("init")
            d.addCallback(retrieve_reference)
            d.addCallback(update_reference)
            return d

        def retrieve_reference(_param):
            if callable(self._model_reference):
                context = self.make_context()
                return self._model_reference(self.source, context)
            return self._model_reference

        def update_reference(reference):
            self.reference = reference
            return self

        if officer is not None:
            self.officer = IOfficer(officer)
        self.aspect = IAspect(aspect) if aspect is not None else None
        if self._model_view is not None:
            if callable(self._model_view):
                context = self.make_context(view=view)
                d = self._model_view(None, context)
                return d.addCallback(got_view)
            return init(self._model_view)
        return init(view)
1179257
def cli(ctx, overwrite):
    """"""
    credentials_path = os.path.join(os.path.expanduser('~'), '.keep', '.credentials')
    if not os.path.exists(credentials_path):
        click.echo('You are not registered.')
        utils.register()
    else:
        utils.pull(ctx, overwrite)
599198
def add_role(ctx, role):
    """"""

    if role is None:
        log('Specify the role with --role')
        return
    if ctx.obj['username'] is None:
        log('Specify the username with --username')
        return

    change_user = ctx.obj['db'].objectmodels['user'].find_one({
        'name': ctx.obj['username']
    })
    if role not in change_user.roles:
        change_user.roles.append(role)
        change_user.save()
        log('Done')
    else:
        log('User already has that role!', lvl=warn)