Set the policies of an ELB listener.

    .. versionadded:: 2016.3.0

    CLI example:

    .. code-block:: Bash

        salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]"
332227
def set_listener_policy(name, port, policies=None, region=None, key=None,
                        keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    if not exists(name, region, key, keyid, profile):
        return True
    if policies is None:
        policies = []
    try:
        conn.set_lb_policies_of_listener(name, port, policies)
        log.info('Set policies %s on ELB %s listener %s', policies, name, port)
    except boto.exception.BotoServerError as e:
        log.info('Failed to set policy %s on ELB %s listener %s: %s',
                 policies, name, port, e.message,
                 exc_info_on_loglevel=logging.DEBUG)
        return False
    return True
816833
def configure_attributes(self, json_data):
        
        env = boto3.session.Session(profile_name=self.env, region_name=self.region)
        elbclient = env.client('elb')

        elb_settings = self.properties['elb']
        LOG.debug('Block ELB Settings Pre Configure Load Balancer Attributes:\n%s', pformat(elb_settings))

        # FIXME: Determine why 'job' is not being used
        # pylint: disable=unused-variable
        for job in json.loads(json_data)['job']:
            load_balancer_attributes = {
                'CrossZoneLoadBalancing': {
                    'Enabled': True
                },
                'AccessLog': {
                    'Enabled': False,
                },
                'ConnectionDraining': {
                    'Enabled': False,
                },
                'ConnectionSettings': {
                    'IdleTimeout': 60
                }
            }
            if elb_settings.get('connection_draining_timeout'):
                connection_draining_timeout = int(elb_settings['connection_draining_timeout'])
                LOG.info('Applying Custom Load Balancer Connection Draining Timeout: %d', connection_draining_timeout)
                load_balancer_attributes['ConnectionDraining'] = {
                    'Enabled': True,
                    'Timeout': connection_draining_timeout
                }
            if elb_settings.get('idle_timeout'):
                idle_timeout = int(elb_settings['idle_timeout'])
                LOG.info('Applying Custom Load Balancer Idle Timeout: %d', idle_timeout)
                load_balancer_attributes['ConnectionSettings'] = {'IdleTimeout': idle_timeout}
            if elb_settings.get('access_log'):
                access_log_bucket_name = elb_settings['access_log']['bucket_name']
                access_log_bucket_prefix = elb_settings['access_log']['bucket_prefix']
                access_log_emit_interval = int(elb_settings['access_log']['emit_interval'])
                LOG.info('Applying Custom Load Balancer Access Log: %s/%s every %d minutes', access_log_bucket_name,
                         access_log_bucket_prefix, access_log_emit_interval)
                load_balancer_attributes['AccessLog'] = {
                    'Enabled': True,
                    'S3BucketName': access_log_bucket_name,
                    'EmitInterval': access_log_emit_interval,
                    'S3BucketPrefix': access_log_bucket_prefix
                }

            LOG.info('Applying Load Balancer Attributes')
            LOG.debug('Load Balancer Attributes:\n%s', pformat(load_balancer_attributes))
            elbclient.modify_load_balancer_attributes(
                LoadBalancerName=self.app, LoadBalancerAttributes=load_balancer_attributes)
446236
def create_policy(name, policy_name, policy_type, policy, region=None,
                  key=None, keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    if not exists(name, region, key, keyid, profile):
        return False
    try:
        success = conn.create_lb_policy(name, policy_name, policy_type, policy)
        if success:
            log.info('Created policy %s on ELB %s', policy_name, name)
            return True
        else:
            log.error('Failed to create policy %s on ELB %s', policy_name, name)
            return False
    except boto.exception.BotoServerError as e:
        log.error('Failed to create policy %s on ELB %s: %s',
                  policy_name, name, e.message,
                  exc_info_on_loglevel=logging.DEBUG)
        return False
1007587
def send_message(self, options):
        
        if not options.get("save_policy"):
            raise ValueError("Only configuring save_policy is supported")
        if self.socket:
            self.socket.send(options)
        elif self._jupyter_agent:
            self._jupyter_agent.start()
            self._jupyter_agent.rm.update_user_file_policy(
                options["save_policy"])
        else:
            wandb.termerror(
                "wandb.init hasn't been called, can't configure run")
620139
def _generate_iam_invoke_role_policy(self):
        
        invoke_pol = {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Resource": ["*"],
                    "Action": ["lambda:InvokeFunction"]
                }
            ]
        }
        self.tf_conf['resource']['aws_iam_role_policy']['invoke_policy'] = {
            'name': self.resource_name + '-invoke',
            'role': '${aws_iam_role.invoke_role.id}',
            'policy': json.dumps(invoke_pol)
        }
292232
def policy(name, options = {}, &block)
      p = Sprinkle::Policy.new(name, options, &block)
      POLICIES << p
      p
    end
723490
def set_policy_threshold(zap_helper, policy_ids, threshold):
    """"""
    if not policy_ids:
        policy_ids = _get_all_policy_ids(zap_helper)

    with zap_error_handler():
        zap_helper.set_policy_alert_threshold(policy_ids, threshold)

    console.info('Set alert threshold to {0}.'.format(threshold))
530845
def default_policy(policy='deny', direction='incoming'):
    
    if policy not in ['allow', 'deny', 'reject']:
        raise UFWError(('Unknown policy %s, valid values: '
                        'allow, deny, reject') % policy)

    if direction not in ['incoming', 'outgoing', 'routed']:
        raise UFWError(('Unknown direction %s, valid values: '
                        'incoming, outgoing, routed') % direction)

    output = subprocess.check_output(['ufw', 'default', policy, direction],
                                     universal_newlines=True,
                                     env={'LANG': 'en_US',
                                          'PATH': os.environ['PATH']})
    hookenv.log(output, level='DEBUG')

    m = re.findall("^Default %s policy changed to '%s'\n" % (direction,
                                                             policy),
                   output, re.M)
    if len(m) == 0:
        hookenv.log("ufw couldn't change the default policy to %s for %s"
                    % (policy, direction), level='WARN')
        return False
    else:
        hookenv.log("ufw default policy for %s changed to %s"
                    % (direction, policy), level='INFO')
        return True
349959
def set_interactive_policy(*, locals=None, banner=None, serve=None,
                           prompt_control=None):
    """"""
    policy = InteractiveEventLoopPolicy(
        locals=locals,
        banner=banner,
        serve=serve,
        prompt_control=prompt_control)
    asyncio.set_event_loop_policy(policy)
1104809
def execute_policy(self, scaling_group, policy):
        
        uri = "/%s/%s/policies/%s/execute" % (self.uri_base,
                utils.get_id(scaling_group), utils.get_id(policy))
        resp, resp_body = self.api.method_post(uri)
        return None
1332999
def create(name, availability_zones, listeners, subnets=None,
           security_groups=None, scheme='internet-facing',
           region=None, key=None, keyid=None,
           profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    if exists(name, region, key, keyid, profile):
        return True
    if isinstance(availability_zones, six.string_types):
        availability_zones = salt.utils.json.loads(availability_zones)

    if isinstance(listeners, six.string_types):
        listeners = salt.utils.json.loads(listeners)

    _complex_listeners = []
    for listener in listeners:
        _complex_listeners.append(listener_dict_to_tuple(listener))

    try:
        lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets,
                                       security_groups=security_groups, scheme=scheme,
                                       complex_listeners=_complex_listeners)
        if lb:
            log.info('Created ELB %s', name)
            return True
        else:
            log.error('Failed to create ELB %s', name)
            return False
    except boto.exception.BotoServerError as error:
        log.error('Failed to create ELB %s: %s: %s',
                  name, error.error_code, error.message,
                  exc_info_on_loglevel=logging.DEBUG)
        return False
843962
def policy(self, args):
        

        word = args[0]
        if word == 'reject':
            self.accepted_ports = None
            self.rejected_ports = []
            target = self.rejected_ports

        elif word == 'accept':
            self.accepted_ports = []
            self.rejected_ports = None
            target = self.accepted_ports

        else:
            raise RuntimeError("Don't understand policy word \"%s\"" % word)

        for port in args[1].split(','):
            if '-' in port:
                (a, b) = port.split('-')
                target.append(PortRange(int(a), int(b)))
            else:
                target.append(int(port))
1294297
def set_missing_value_policy(self, policy, target_attr_name=None):
        
        assert policy in MISSING_VALUE_POLICIES, \
            "Unknown policy: %s" % (policy,)
        for attr_name in self.data.attribute_names:
            if target_attr_name is not None and target_attr_name != attr_name:
                continue
            self.missing_value_policy[attr_name] = policy
631391
private void addPolicy(String pid, InputStream dsContent) throws GeneralException {
        LOG.info("Adding policy " + pid);

        String policy;

        try {
            policy = IOUtils.toString(dsContent);
            dsContent.close();
            m_policyIndex.addPolicy(pid, policy);
        } catch (IOException e) {
            throw new GeneralException("Error adding policy " + pid + " to policy index: " + e.getMessage(), e);
        } catch (PolicyIndexException e) {
            throw new GeneralException("Error adding policy " + pid + " to policy index: " + e.getMessage(), e);
        }


    }
924116
public function setPolicy(int $policy)
    {
        if (!($policy === Rule::ALLOW || $policy === Rule::DENY || $policy === Rule::INHERIT || $policy === Rule::NOINHERIT))
            throw new Exception("Policy must be either Rule::ALLOW, Rule::DENY, Rule::INHERIT or Rule::NOINHERIT");

        if ($policy === Rule::NOINHERIT && !empty($this->action))
            throw new Exception("Rule::NOINHERIT can not be used in combination with an action");

        if ($policy === Rule::NOINHERIT && !empty($this->role_id))
            throw new Exception("Rule::NOINHERIT can not be used in combination with a role");

        if ($policy !== $this->policy)
        {
            $this->policy = $policy;
            $this->changed = true;
        }
    }
550520
def _port_add_or_delete_policy(action, name, sel_type=None, protocol=None, port=None, sel_range=None):
    '''
    
    '''
    if action not in ['add', 'delete']:
        raise SaltInvocationError('Actions supported are "add" and "delete", not "{0}".'.format(action))
    if action == 'add' and not sel_type:
        raise SaltInvocationError('SELinux Type is required to add a policy')
    (protocol, port) = _parse_protocol_port(name, protocol, port)
    cmd = 'semanage port --{0} --proto {1}'.format(action, protocol)
    if sel_type:
        cmd += ' --type {0}'.format(sel_type)
    if sel_range:
        cmd += ' --range {0}'.format(sel_range)
    cmd += ' {0}'.format(port)
    return __salt__['cmd.run_all'](cmd)
863647
def add_policy(self, name, policy_type, cooldown, change=None,
            is_percent=False, desired_capacity=None, args=None):
        
        return self.manager.add_policy(self, name, policy_type, cooldown,
                change=change, is_percent=is_percent,
                desired_capacity=desired_capacity, args=args)