Ensures at least 1 security group is assigned if awsvpc_configuration
 is provided.
333203
def adjust_security_groups(options)
      return options unless options[:network_configuration] &&
                     options[:network_configuration][:awsvpc_configuration]

      awsvpc_conf = options[:network_configuration][:awsvpc_configuration]

      security_groups = awsvpc_conf[:security_groups]
      if [nil, '', 'nil'].include?(security_groups)
        security_groups = []
      end
      if security_groups.empty?
        fetch = Network::Fetch.new(network[:vpc])
        sg = fetch.security_group_id
        security_groups << sg
        security_groups.uniq!
      end

      # override security groups
      options[:network_configuration][:awsvpc_configuration][:security_groups] = security_groups
      options
    end
415101
def cache_security_group_exists(name, region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    return bool(describe_cache_security_groups(name=name, region=region, key=key, keyid=keyid,
                profile=profile))
663389
def validate_config(self, config):
        

        try:
            hosts = config['hosts']
        except KeyError:
            raise InvalidConfigurationError('hosts', "",
                                            reason=('hosts configuration '
                                                    'section is required'))

        for key in config.keys():
            if key not in default_allowed_keys:
                raise InvalidConfigurationError(key, config[key])

        bucket = False
        # optional configuration
        try:
            for key in config['aws'].keys():
                if key == 'bucket' and config['aws'][key] is not None:
                    bucket = True
                if key not in aws_allowed_keys:
                    raise InvalidConfigurationError(key, config['aws'][key])
        except KeyError:
            pass

        # optional configuration
        try:
            for key in config['logging'].keys():
                if key not in logging_allowed_keys:
                    raise InvalidConfigurationError(key, config['logging'][key])
        except KeyError:
            pass

        # optional configuration
        try:
            for key in config['repository'].keys():
                if key not in repository_allowed_keys:
                    raise InvalidConfigurationError(key, config['repository'][key])
        except KeyError:
            pass

        # required configuration
        if type(config['hosts']) is not list:
            raise InvalidConfigurationError('hosts', config['hosts'],
                                            reason="hosts must be a list")
        filename = False
        for host in config['hosts']:
            for key in host.keys():
                if key == 'filename' and host['filename'] is not None:
                    filename = True
                if key == 'jump_host' and host['jump_host'] is not None:
                    for jump_key in host['jump_host'].keys():
                        if jump_key not in jump_host_allowed_keys:
                            raise InvalidConfigurationError(key, host['jump_host'])
                if key not in host_allowed_keys:
                    raise InvalidConfigurationError(key, host[key])

        if bucket and filename:
            raise InvalidConfigurationError('bucket', config['aws']['bucket'],
                                            reason=('bucket configuration is'
                                                    'incompatible with filename'
                                                    'configuration in hosts'))
604831
def _use_consumer_group(self):
        """"""
        if self.config['api_version'] < (0, 9):
            return False
        elif self.config['group_id'] is None:
            return False
        elif not self._subscription.partitions_auto_assigned():
            return False
        return True
302486
def ec2_security_group_security_group_id(self, lookup, default=None):
    
    try:
      response = EFAwsResolver.__CLIENTS["ec2"].describe_security_groups(Filters=[{
        'Name':'group-name', 'Values':[lookup]
      }])
    except:
      return default
    if len(response["SecurityGroups"]) > 0:
      return response["SecurityGroups"][0]["GroupId"]
    else:
      return default
974635
public void setAdditionalSlaveSecurityGroups(java.util.Collection<String> additionalSlaveSecurityGroups) {
        if (additionalSlaveSecurityGroups == null) {
            this.additionalSlaveSecurityGroups = null;
            return;
        }

        this.additionalSlaveSecurityGroups = new com.amazonaws.internal.SdkInternalList<String>(additionalSlaveSecurityGroups);
    }
1131542
def wait_for_new_security_group
      old_group_name = @config['rds_security_group']
      update_status "Applying security group #{old_group_name}"+
        " to #{@new_instance.id}"
      @new_instance.wait_for {
        new_group = (db_security_groups.select do |group|
          group['DBSecurityGroupName'] == old_group_name
        end).first
        (new_group ? new_group['Status'] : 'Unknown') == 'active'
      }
    end
555346
def _security_group_present(name, description, vpc_id=None, vpc_name=None,
                            region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    ret = {'result': True, 'comment': '', 'changes': {}}
    exists = __salt__['boto_secgroup.exists'](name, region, key, keyid,
                                              profile, vpc_id, vpc_name)
    if not exists:
        if __opts__['test']:
            ret['comment'] = 'Security group {0} is set to be created.'.format(name)
            ret['result'] = None
            return ret
        created = __salt__['boto_secgroup.create'](name=name, description=description,
                                                   vpc_id=vpc_id, vpc_name=vpc_name,
                                                   region=region, key=key, keyid=keyid,
                                                   profile=profile)
        if created:
            ret['changes']['old'] = {'secgroup': None}
            sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
                                              keyid=keyid, profile=profile, vpc_id=vpc_id,
                                              vpc_name=vpc_name)
            ret['changes']['new'] = {'secgroup': sg}
            ret['comment'] = 'Security group {0} created.'.format(name)
        else:
            ret['result'] = False
            ret['comment'] = 'Failed to create {0} security group.'.format(name)
    else:
        ret['comment'] = 'Security group {0} present.'.format(name)
    return ret
895759
public function isAuthGroupConfigured() {
		$markerFile = $this->getPathMarkerFile();
		if ($this->_checkMarkerFile($markerFile)) {
			return true;
		}

		$authGroupsList = $this->getAuthGroupsList();
		if (empty($authGroupsList)) {
			return false;
		}

		foreach ($authGroupsList as $fieldName) {
			if (!$this->getConfig($fieldName)) {
				return false;
			}
		}

		return $this->_createMarkerFile($markerFile);
	}
342435
def portgroups_configured(name, dvs, portgroups):
    '''
    
    '''
    datacenter = _get_datacenter_name()
    log.info('Running state %s on DVS \'%s\', datacenter \'%s\'',
             name, dvs, datacenter)
    changes_required = False
    ret = {'name': name,
           'changes': {},
           'result': None,
           'comment': None}
    comments = []
    changes = {}
    changes_required = False

    try:
        #TODO portroups validation
        si = __salt__['vsphere.get_service_instance_via_proxy']()
        current_pgs = __salt__['vsphere.list_dvportgroups'](
            dvs=dvs, service_instance=si)
        expected_pg_names = []
        for pg in portgroups:
            pg_name = pg['name']
            expected_pg_names.append(pg_name)
            del pg['name']
            log.info('Checking pg \'%s\'', pg_name)
            filtered_current_pgs = \
                    [p for p in current_pgs if p.get('name') == pg_name]
            if not filtered_current_pgs:
                changes_required = True
                if __opts__['test']:
                    comments.append('State {0} will create a new portgroup '
                                    '\'{1}\' in DVS \'{2}\', datacenter '
                                    '\'{3}\''.format(name, pg_name, dvs,
                                                     datacenter))
                else:
                    __salt__['vsphere.create_dvportgroup'](
                        portgroup_dict=pg, portgroup_name=pg_name, dvs=dvs,
                        service_instance=si)
                    comments.append('Created a new portgroup \'{0}\' in DVS '
                                    '\'{1}\', datacenter \'{2}\''
                                    ''.format(pg_name, dvs, datacenter))
                log.info(comments[-1])
                changes.update({pg_name: {'new': pg}})
            else:
                # Porgroup already exists. Checking the config
                log.trace('Portgroup \'%s\' found in DVS \'%s\', datacenter '
                          '\'%s\'. Checking for any updates.',
                          pg_name, dvs, datacenter)
                current_pg = filtered_current_pgs[0]
                diff_dict = _get_diff_dict(current_pg, pg)

                if diff_dict:
                    changes_required = True
                    if __opts__['test']:
                        changes_strings = \
                                _get_changes_from_diff_dict(diff_dict)
                        log.trace('changes_strings = %s', changes_strings)
                        comments.append(
                            'State {0} will update portgroup \'{1}\' in '
                            'DVS \'{2}\', datacenter \'{3}\':\n{4}'
                            ''.format(name, pg_name, dvs, datacenter,
                                      '\n'.join(['\t{0}'.format(c) for c in
                                                 changes_strings])))
                    else:
                        __salt__['vsphere.update_dvportgroup'](
                            portgroup_dict=pg, portgroup=pg_name, dvs=dvs,
                            service_instance=si)
                        comments.append('Updated portgroup \'{0}\' in DVS '
                                        '\'{1}\', datacenter \'{2}\''
                                        ''.format(pg_name, dvs, datacenter))
                    log.info(comments[-1])
                    changes.update(
                        {pg_name: {'new':
                                   _get_val2_dict_from_diff_dict(diff_dict),
                                   'old':
                                   _get_val1_dict_from_diff_dict(diff_dict)}})
        # Add the uplink portgroup to the expected pg names
        uplink_pg = __salt__['vsphere.list_uplink_dvportgroup'](
            dvs=dvs, service_instance=si)
        expected_pg_names.append(uplink_pg['name'])
        # Remove any extra portgroups
        for current_pg in current_pgs:
            if current_pg['name'] not in expected_pg_names:
                changes_required = True
                if __opts__['test']:
                    comments.append('State {0} will remove '
                                    'the portgroup \'{1}\' from DVS \'{2}\', '
                                    'datacenter \'{3}\''
                                    ''.format(name, current_pg['name'], dvs,
                                              datacenter))
                else:
                    __salt__['vsphere.remove_dvportgroup'](
                        portgroup=current_pg['name'], dvs=dvs,
                        service_instance=si)
                    comments.append('Removed the portgroup \'{0}\' from DVS '
                                    '\'{1}\', datacenter \'{2}\''
                                    ''.format(current_pg['name'], dvs,
                                              datacenter))
                log.info(comments[-1])
                changes.update({current_pg['name']:
                                {'old': current_pg}})
        __salt__['vsphere.disconnect'](si)
    except salt.exceptions.CommandExecutionError as exc:
        log.exception('Encountered error')
        if si:
            __salt__['vsphere.disconnect'](si)
        if not __opts__['test']:
            ret['result'] = False
        ret.update({'comment': exc.strerror,
                    'result': False if not __opts__['test'] else None})
        return ret
    if not changes_required:
        # We have no changes
        ret.update({'comment': ('All portgroups in DVS \'{0}\', datacenter '
                                '\'{1}\' exist and are correctly configured. '
                                'Nothing to be done.'.format(dvs, datacenter)),
                    'result': True})
    else:
        ret.update({
            'comment': '\n'.join(comments),
            'changes': changes,
            'result': None if __opts__['test'] else True,
        })
    return ret
555980
public void setVpcSecurityGroupMemberships(java.util.Collection<String> vpcSecurityGroupMemberships) {
        if (vpcSecurityGroupMemberships == null) {
            this.vpcSecurityGroupMemberships = null;
            return;
        }

        this.vpcSecurityGroupMemberships = new com.amazonaws.internal.SdkInternalList<String>(vpcSecurityGroupMemberships);
    }
1020147
def _find_usage_security_groups(self):
        """"""
        num_groups = 0
        # If EC2-Classic isn't available (e.g., a new account)
        # this method will fail with:
        #   Code:    "InvalidParameterValue"
        #   Message: "Use of cache security groups is not permitted in
        #             this API version for your account."
        #   Type:    "Sender"
        try:
            paginator = self.conn.get_paginator(
                'describe_cache_security_groups')
            for page in paginator.paginate():
                for secgroup in page['CacheSecurityGroups']:
                    num_groups += 1
        except ClientError as ex:
            if ex.response['Error']['Code'] != 'InvalidParameterValue':
                raise ex
            logger.debug("caught ClientError checking ElastiCache security "
                         "groups (account without EC2-Classic?)")

        self.limits['Security Groups']._add_current_usage(
            num_groups,
            aws_type='WS::ElastiCache::SecurityGroup'
        )
194627
def _find_usage_security_groups(self):
        """"""
        vpc_count = 0

        paginator = self.conn.get_paginator('describe_db_security_groups')
        for page in paginator.paginate():
            for group in page['DBSecurityGroups']:
                if 'VpcId' in group and group['VpcId'] is not None:
                    vpc_count += 1
                self.limits['Max auths per security group']._add_current_usage(
                    len(group["EC2SecurityGroups"]) + len(group["IPRanges"]),
                    aws_type='AWS::RDS::DBSecurityGroup',
                    resource_id=group['DBSecurityGroupName']
                )

        self.limits['VPC Security Groups']._add_current_usage(
            vpc_count,
            aws_type='AWS::RDS::DBSecurityGroup',
        )
413372
def add_to_group(server_context, user_ids, group_id, container_path=None):
    
    return __make_security_group_api_request(server_context, 'addGroupMember.api', user_ids, group_id, container_path)
133941
def create_security_group
      aws_ec2 = ec2_obj

      name = nil

      loop do
        name = 'chef-workflow-' + (0..rand(10).to_i).map { rand(0..9).to_s }.join("")

        if_debug(3) do
          $stderr.puts "Seeing if security group name #{name} is taken"
        end

        break unless aws_ec2.security_groups.filter('group-name', [name]).first
        sleep 0.3
      end

      group = aws_ec2.security_groups.create(name)

      security_group_open_ports.each do |port|
        group.authorize_ingress(:tcp, port)
        group.authorize_ingress(:udp, port)
      end

      group.authorize_ingress(:tcp, (0..65535), group)
      group.authorize_ingress(:udp, (0..65535), group)

      # XXX I think the name should be enough, but maybe this'll cause a problem.
      File.binwrite(security_group_setting_path, Marshal.dump([name]))
      return [name]
    end
918483
public static void validateAwsConfiguration(Properties config) {
		if (config.containsKey(AWSConfigConstants.AWS_CREDENTIALS_PROVIDER)) {
			String credentialsProviderType = config.getProperty(AWSConfigConstants.AWS_CREDENTIALS_PROVIDER);

			// value specified for AWSConfigConstants.AWS_CREDENTIALS_PROVIDER needs to be recognizable
			CredentialProvider providerType;
			try {
				providerType = CredentialProvider.valueOf(credentialsProviderType);
			} catch (IllegalArgumentException e) {
				StringBuilder sb = new StringBuilder();
				for (CredentialProvider type : CredentialProvider.values()) {
					sb.append(type.toString()).append(", ");
				}
				throw new IllegalArgumentException("Invalid AWS Credential Provider Type set in config. Valid values are: " + sb.toString());
			}

			// if BASIC type is used, also check that the Access Key ID and Secret Key is supplied
			if (providerType == CredentialProvider.BASIC) {
				if (!config.containsKey(AWSConfigConstants.AWS_ACCESS_KEY_ID)
					|| !config.containsKey(AWSConfigConstants.AWS_SECRET_ACCESS_KEY)) {
					throw new IllegalArgumentException("Please set values for AWS Access Key ID ('" + AWSConfigConstants.AWS_ACCESS_KEY_ID + "') " +
						"and Secret Key ('" + AWSConfigConstants.AWS_SECRET_ACCESS_KEY + "') when using the BASIC AWS credential provider type.");
				}
			}
		}

		if (config.containsKey(AWSConfigConstants.AWS_REGION)) {
			// specified AWS Region name must be recognizable
			if (!AWSUtil.isValidRegion(config.getProperty(AWSConfigConstants.AWS_REGION))) {
				StringBuilder sb = new StringBuilder();
				for (Regions region : Regions.values()) {
					sb.append(region.getName()).append(", ");
				}
				throw new IllegalArgumentException("Invalid AWS region set in config. Valid values are: " + sb.toString());
			}
		}
	}
1174874
def apply_security_groups(name, security_groups, region=None, key=None,
                          keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    if isinstance(security_groups, six.string_types):
        security_groups = salt.utils.json.loads(security_groups)
    try:
        conn.apply_security_groups_to_lb(name, security_groups)
        log.info('Applied security_groups on ELB %s', name)
        return True
    except boto.exception.BotoServerError as e:
        log.debug(e)
        log.error('Failed to appply security_groups on ELB %s: %s',
                  name, e.message)
        return False