Allow Lambda to manipuate EC2 ENIs for VPC support.
968301
def lambda_vpc_execution_statements():
    """"""
    return [
        Statement(
            Effect=Allow,
            Resource=['*'],
            Action=[
                ec2.CreateNetworkInterface,
                ec2.DescribeNetworkInterfaces,
                ec2.DeleteNetworkInterface,
            ]
        )
    ]
278927
def _default_options(p, blacklist=""):
    
    provider = p.add_argument_group(
        "provider", "AWS account information, defaults per the aws cli")

    if 'region' not in blacklist:
        provider.add_argument(
            "-r", "--region", action='append', default=[],
            dest='regions', metavar='REGION',
            help="AWS Region to target.  Can be used multiple times")
    provider.add_argument(
        "--profile",
        help="AWS Account Config File Profile to utilize")
    provider.add_argument("--assume", default=None, dest="assume_role",
                          help="Role to assume")
    provider.add_argument("--external-id", default=None, dest="external_id",
                          help="External Id to provide when assuming a role")

    config = p.add_argument_group(
        "config", "Policy config file(s) and policy selectors")
    # -c is deprecated.  Supported for legacy reasons
    config.add_argument("-c", "--config", help=argparse.SUPPRESS)
    config.add_argument("configs", nargs='*',
                        help="Policy configuration file(s)")
    config.add_argument("-p", "--policies", default=None, dest='policy_filter',
                        help="Only use named/matched policies")
    config.add_argument("-t", "--resource", default=None, dest='resource_type',
                        help="Only use policies with the given resource type")

    output = p.add_argument_group("output", "Output control")
    output.add_argument("-v", "--verbose", action="count", help="Verbose logging")
    if 'quiet' not in blacklist:
        output.add_argument("-q", "--quiet", action="count",
                            help="Less logging (repeatable, -qqq for no output)")
    else:
        output.add_argument("-q", "--quiet", action="count", help=argparse.SUPPRESS)
    output.add_argument("--debug", default=False, help=argparse.SUPPRESS,
                        action="store_true")

    if 'vars' not in blacklist:
        # p.add_argument('--vars', default=None,
        #               help='Vars file to substitute into policy')
        p.set_defaults(vars=None)

    if 'log-group' not in blacklist:
        p.add_argument(
            "-l", "--log-group", default=None,
            help="Cloudwatch Log Group to send policy logs")
    else:
        p.add_argument("--log-group", default=None, help=argparse.SUPPRESS)

    if 'output-dir' not in blacklist:
        p.add_argument("-s", "--output-dir", required=True,
                       help="[REQUIRED] Directory or S3 URL For policy output")

    if 'cache' not in blacklist:
        p.add_argument(
            "-f", "--cache", default="~/.cache/cloud-custodian.cache",
            help="Cache file (default %(default)s)")
        p.add_argument(
            "--cache-period", default=15, type=int,
            help="Cache validity in minutes (default %(default)i)")
    else:
        p.add_argument("--cache", default=None, help=argparse.SUPPRESS)
1104317
def conn_aws(cred, crid):
    """"""
    driver = get_driver(Provider.EC2)
    try:
        aws_obj = driver(cred['aws_access_key_id'],
                         cred['aws_secret_access_key'],
                         region=cred['aws_default_region'])
    except SSLError as e:
        abort_err("\r SSL Error with AWS: {}".format(e))
    except InvalidCredsError as e:
        abort_err("\r Error with AWS Credentials: {}".format(e))
    return {crid: aws_obj}
939081
def down_ec2(instance_id, region, access_key_id, secret_access_key):
    
    conn = connect_to_ec2(region, access_key_id, secret_access_key)
    # get the instance_id from the state file, and stop the instance
    instance = conn.stop_instances(instance_ids=instance_id)[0]
    while instance.state != "stopped":
        log_yellow("Instance state: %s" % instance.state)
        sleep(10)
        instance.update()
    log_green('Instance state: %s' % instance.state)
1207360
def cli(env):
    """"""

    account = env.client['Account']

    nas_accounts = account.getNasNetworkStorage(
        mask='eventCount,serviceResource[datacenter.name]')

    table = formatting.Table(['id', 'datacenter', 'size', 'server'])

    for nas_account in nas_accounts:
        table.add_row([
            nas_account['id'],
            utils.lookup(nas_account,
                         'serviceResource',
                         'datacenter',
                         'name') or formatting.blank(),
            formatting.FormattedItem(
                nas_account.get('capacityGb', formatting.blank()),
                "%dGB" % nas_account.get('capacityGb', 0)),
            nas_account.get('serviceResourceBackendIpAddress',
                            formatting.blank())])

    env.fout(table)
195175
function buildRole(options, roleName='LambdaCfnRole') {
  let role = {
    Resources: {}
  };

  role.Resources[roleName] = {
    Type: 'AWS::IAM::Role',
    Properties: {
      AssumeRolePolicyDocument: {
        Statement: [
          {
            Sid: '',
            Effect: 'Allow',
            Principal: {
              Service: 'lambda.amazonaws.com'
            },
            Action: 'sts:AssumeRole'
          },
          {
            Sid: '',
            Effect: 'Allow',
            Principal: {
              Service: 'events.amazonaws.com'
            },
            Action: 'sts:AssumeRole'
          }
        ]
      },
      Path: '/',
      Policies: [
        {
          PolicyName: 'basic',
          PolicyDocument: {
            Statement: [
              {
                Effect: 'Allow',
                Action: [
                  'logs:*'
                ],
                Resource: cf.join(['arn:aws:logs:*:', cf.accountId, ':*'])
              },
              {
                Effect: 'Allow',
                Action: [
                  'sns:Publish'
                ],
                Resource: cf.ref('ServiceAlarmSNSTopic')
              },
              {
                Effect: 'Allow',
                Action: [
                  'iam:SimulateCustomPolicy'
                ],
                Resource: '*'
              }
            ]
          }
        },
      ]
    }
  };

  if (options.eventSources && options.eventSources.webhook) {
    role.Resources[roleName].Properties.AssumeRolePolicyDocument.Statement.push({
      Sid: '',
      Effect: 'Allow',
      Principal: {
        Service: 'apigateway.amazonaws.com'
      },
      Action: 'sts:AssumeRole'
    });
  }

  if (options.statements) {
    statementValidation(options);

    role.Resources[roleName].Properties.Policies.push({
      PolicyName: options.name,
      PolicyDocument: {
        Statement: options.statements
      }
    });
  }

  return role;
}
707772
def _find_usage_vpcs(self):
        """"""
        # overall number of VPCs
        vpcs = self.conn.describe_vpcs()
        self.limits['VPCs']._add_current_usage(
            len(vpcs['Vpcs']),
            aws_type='AWS::EC2::VPC'
        )
973666
def vpc(self):
        
        if self.__vpc is None:
            self.__vpc = self.__aws_connect(vpc)
        return self.__vpc
1133323
function buildVpc(cidrBlock = '10.0.0.0/16', { name = 'VPC' } = {}) {
  return {
    [name]: {
      Type: 'AWS::EC2::VPC',
      Properties: {
        CidrBlock: cidrBlock,
        EnableDnsSupport: true,
        EnableDnsHostnames: true,
        InstanceTenancy: 'default',
        Tags: [
          {
            Key: 'Name',
            Value: {
              Ref: 'AWS::StackName',
            },
          },
        ],
      },
    },
  };
}
819175
def _modify_eni_properties(eni_id, properties=None, vm_=None):
    '''
    
    '''
    if not isinstance(properties, dict):
        raise SaltCloudException(
            'ENI properties must be a dictionary'
        )

    params = {'Action': 'ModifyNetworkInterfaceAttribute',
              'NetworkInterfaceId': eni_id}
    for k, v in six.iteritems(properties):
        params[k] = v

    result = aws.query(params,
                       return_root=True,
                       location=get_location(vm_),
                       provider=get_provider(),
                       opts=__opts__,
                       sigver='4')

    if isinstance(result, dict) and result.get('error'):
        raise SaltCloudException(
            'Could not change interface <{0}> attributes <\'{1}\'>'.format(
                eni_id, properties
            )
        )
    else:
        return result
87075
def start_accepting_passive_host_checks(self):
        
        # todo: #783 create a dedicated brok for global parameters
        if not self.my_conf.accept_passive_host_checks:
            self.my_conf.modified_attributes |= DICT_MODATTR["MODATTR_PASSIVE_CHECKS_ENABLED"].value
            self.my_conf.accept_passive_host_checks = True
            self.my_conf.explode_global_conf()
            self.daemon.update_program_status()
630909
def create_lambda_function( self,
                                bucket=None,
                                function_name=None,
                                handler=None,
                                s3_key=None,
                                description='Zappa Deployment',
                                timeout=30,
                                memory_size=512,
                                publish=True,
                                vpc_config=None,
                                dead_letter_config=None,
                                runtime='python2.7',
                                aws_environment_variables=None,
                                aws_kms_key_arn=None,
                                xray_tracing=False,
                                local_zip=None,
                                use_alb=False,
                            ):
        
        if not vpc_config:
            vpc_config = {}
        if not dead_letter_config:
            dead_letter_config = {}
        if not self.credentials_arn:
            self.get_credentials_arn()
        if not aws_environment_variables:
            aws_environment_variables = {}
        if not aws_kms_key_arn:
            aws_kms_key_arn = ''

        kwargs = dict(
            FunctionName=function_name,
            Runtime=runtime,
            Role=self.credentials_arn,
            Handler=handler,
            Description=description,
            Timeout=timeout,
            MemorySize=memory_size,
            Publish=publish,
            VpcConfig=vpc_config,
            DeadLetterConfig=dead_letter_config,
            Environment={'Variables': aws_environment_variables},
            KMSKeyArn=aws_kms_key_arn,
            TracingConfig={
                'Mode': 'Active' if self.xray_tracing else 'PassThrough'
            }
        )
        if local_zip:
            kwargs['Code'] = {
                'ZipFile': local_zip
            }
        else:
            kwargs['Code'] = {
                'S3Bucket': bucket,
                'S3Key': s3_key
            }

        response = self.lambda_client.create_function(**kwargs)

        resource_arn = response['FunctionArn']
        version = response['Version']

        # If we're using an ALB, let's create an alias mapped to the newly
        # created function. This allows clean, no downtime association when
        # using application load balancers as an event source.
        # See: https://github.com/Miserlou/Zappa/pull/1730
        #      https://github.com/Miserlou/Zappa/issues/1823
        if use_alb:
            self.lambda_client.create_alias(
                FunctionName=resource_arn,
                FunctionVersion=version,
                Name=ALB_LAMBDA_ALIAS,
            )

        if self.tags:
            self.lambda_client.tag_resource(Resource=resource_arn, Tags=self.tags)

        return resource_arn
140044
def _stop_ec2_instances(awsclient, ec2_instances, wait=True):
    
    if len(ec2_instances) == 0:
        return
    client_ec2 = awsclient.get_client('ec2')

    # get running instances
    running_instances = all_pages(
        client_ec2.describe_instance_status,
        {
            'InstanceIds': ec2_instances,
            'Filters': [{
                'Name': 'instance-state-name',
                'Values': ['pending', 'running']
            }]
        },
        lambda r: [i['InstanceId'] for i in r.get('InstanceStatuses', [])],
    )

    if running_instances:
        log.info('Stopping EC2 instances: %s', running_instances)
        client_ec2.stop_instances(InstanceIds=running_instances)

        if wait:
            # wait for instances to stop
            waiter_inst_stopped = client_ec2.get_waiter('instance_stopped')
            waiter_inst_stopped.wait(InstanceIds=running_instances)
823932
def cli(env):
    """"""
    mgr = SoftLayer.LoadBalancerManager(env.client)

    load_balancers = mgr.get_local_lbs()

    table = formatting.Table(['ID',
                              'VIP Address',
                              'Location',
                              'SSL Offload',
                              'Connections/second',
                              'Type'])

    table.align['Connections/second'] = 'r'

    for load_balancer in load_balancers:
        ssl_support = 'Not Supported'
        if load_balancer['sslEnabledFlag']:
            if load_balancer['sslActiveFlag']:
                ssl_support = 'On'
            else:
                ssl_support = 'Off'
        lb_type = 'Standard'
        if load_balancer['dedicatedFlag']:
            lb_type = 'Dedicated'
        elif load_balancer['highAvailabilityFlag']:
            lb_type = 'HA'
        table.add_row([
            'local:%s' % load_balancer['id'],
            load_balancer['ipAddress']['ipAddress'],
            load_balancer['loadBalancerHardware'][0]['datacenter']['name'],
            ssl_support,
            load_balancer['connectionLimit'],
            lb_type
        ])

    env.fout(table)
1362315
def _find_usage_networking_sgs(self):
        """"""
        logger.debug("Getting usage for EC2 VPC resources")
        sgs_per_vpc = defaultdict(int)
        rules_per_sg = defaultdict(int)
        for sg in self.resource_conn.security_groups.all():
            if sg.vpc_id is not None:
                sgs_per_vpc[sg.vpc_id] += 1
                rules_per_sg[sg.id] = len(sg.ip_permissions)
        # set usage
        for vpc_id, count in sgs_per_vpc.items():
            self.limits['Security groups per VPC']._add_current_usage(
                count,
                aws_type='AWS::EC2::VPC',
                resource_id=vpc_id,
            )
        for sg_id, count in rules_per_sg.items():
            self.limits['Rules per VPC security group']._add_current_usage(
                count,
                aws_type='AWS::EC2::SecurityGroupRule',
                resource_id=sg_id,
            )
699637
def up(ctx, instance_id):
    """"""
    session = create_session(ctx.obj['AWS_PROFILE_NAME'])
    ec2 = session.resource('ec2')
    try:
        instance = ec2.Instance(instance_id)
        instance.start()
    except botocore.exceptions.ClientError as e:
        click.echo("Invalid instance ID {0} ({1})".format(instance_id, e), err=True)
        sys.exit(2)
616279
def vsan_supported(service_instance):
    '''
    
    '''
    try:
        api_version = service_instance.content.about.apiVersion
    except vim.fault.NoPermission as exc:
        log.exception(exc)
        raise VMwareApiError('Not enough permissions. Required privilege: '
                             '{0}'.format(exc.privilegeId))
    except vim.fault.VimFault as exc:
        log.exception(exc)
        raise VMwareApiError(exc.msg)
    except vmodl.RuntimeFault as exc:
        log.exception(exc)
        raise VMwareRuntimeError(exc.msg)
    if int(api_version.split('.')[0]) < 6:
        return False
    return True