Build the NAT instance

@param {Object} imageId AMI image ID
@param {Array} zones Array of availability zones
@param {Object} params
@return {Object}
350341
function buildNatInstance(imageId, zones = [], { name = 'NatInstance' } = {}) {
  if (!imageId) {
    return {};
  }
  if (!Array.isArray(zones) || zones.length < 1) {
    return {};
  }

  return {
    [name]: {
      Type: 'AWS::EC2::Instance',
      DependsOn: 'InternetGatewayAttachment',
      Properties: {
        AvailabilityZone: {
          'Fn::Select': ['0', zones],
        },
        BlockDeviceMappings: [
          {
            DeviceName: '/dev/xvda',
            Ebs: {
              VolumeSize: 10,
              VolumeType: 'gp2',
              DeleteOnTermination: true,
            },
          },
        ],
        ImageId: imageId, // amzn-ami-vpc-nat-hvm-2018.03.0.20181116-x86_64-ebs
        InstanceType: 't2.micro',
        Monitoring: false,
        NetworkInterfaces: [
          {
            AssociatePublicIpAddress: true,
            DeleteOnTermination: true,
            Description: 'eth0',
            DeviceIndex: '0',
            GroupSet: [
              {
                Ref: 'NatSecurityGroup',
              },
            ],
            SubnetId: {
              Ref: `${PUBLIC_SUBNET}Subnet1`,
            },
          },
        ],
        SourceDestCheck: false, // required for a NAT instance
        Tags: [
          {
            Key: 'Name',
            Value: {
              'Fn::Join': [
                '-',
                [
                  {
                    Ref: 'AWS::StackName',
                  },
                  'nat',
                ],
              ],
            },
          },
        ],
      },
    },
  };
}
508075
function addImageToCells(imageId, range) {
    const model = {
      type: 'image',
      imageId,
      range,
    };
    this._media.push(new Image(this, model));
  }
76554
function buildNetworkAclEntry(
  name,
  CidrBlock,
  { Egress = false, Protocol = -1, RuleAction = 'allow', RuleNumber = 100 } = {},
) {
  const direction = Egress ? 'Egress' : 'Ingress';
  const cfName = `${name}${direction}${RuleNumber}`;
  return {
    [cfName]: {
      Type: 'AWS::EC2::NetworkAclEntry',
      Properties: {
        CidrBlock,
        NetworkAclId: {
          Ref: name,
        },
        Egress,
        Protocol,
        RuleAction,
        RuleNumber,
      },
    },
  };
}
815954
def create_primary_zone_by_upload(self, account_name, zone_name, bind_file):
        
        zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"}
        primary_zone_info = {"forceImport": True, "createType": "UPLOAD"}
        zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info}
        files = {'zone': ('', json.dumps(zone_data), 'application/json'),
                 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')}
        return self.rest_api_connection.post_multi_part("/v1/zones", files)
1173691
def get_image_id_by_name(self, ami_name, region='us-east-1'):
        
        image_details = None
        detail_query_attempts = 0

        while image_details is None:
            describe_cmd = "aws ec2 describe-images --filters 'Name=name,Values={}' --profile '{}' --region {}"\
                .format(ami_name, self.aws_project, region)
            res = subprocess.check_output(shlex.split(describe_cmd))

            print "describe command returned: {}".format(res)

            image_details = parse_image_json(res)
            if not image_details:
                if detail_query_attempts > 5:
                    print "Tried to get image details 5 times and failed, exiting"
                    raise Exception("Unable to get AMI image id from AWS using the image name")
                time.sleep(10)
                print "No images defined returned yet, will try another query"
                detail_query_attempts += 1

        image_id = image_details['ImageId']
        print "located image id: {}".format(image_id)
        return image_id
689834
function buildBastionAutoScalingGroup(numZones = 0, { name = 'BastionAutoScalingGroup' } = {}) {
  if (numZones < 1) {
    return {};
  }

  const zones = [];
  for (let i = 1; i <= numZones; i += 1) {
    zones.push({ Ref: `${PUBLIC_SUBNET}Subnet${i}` });
  }

  return {
    [name]: {
      Type: 'AWS::AutoScaling::AutoScalingGroup',
      CreationPolicy: {
        ResourceSignal: {
          Count: 1,
          Timeout: 'PT10M',
        },
      },
      Properties: {
        LaunchConfigurationName: {
          Ref: 'BastionLaunchConfiguration',
        },
        VPCZoneIdentifier: zones,
        MinSize: 1,
        MaxSize: 1,
        Cooldown: '300',
        DesiredCapacity: 1,
        Tags: [
          {
            Key: 'Name',
            Value: {
              'Fn::Join': [
                '-',
                [
                  {
                    Ref: 'AWS::StackName',
                  },
                  'bastion',
                ],
              ],
            },
            PropagateAtLaunch: true,
          },
        ],
      },
    },
  };
}
438221
def member_create(self, params, member_id):
        
        member_config = params.get('rsParams', {})
        server_id = params.pop('server_id', None)
        version = params.pop('version', self._version)
        proc_params = {'replSet': self.repl_id}
        proc_params.update(params.get('procParams', {}))
        if self.enable_ipv6:
            enable_ipv6_single(proc_params)
        # Make sure that auth isn't set the first time we start the servers.
        proc_params = self._strip_auth(proc_params)

        # Don't pass in auth_key the first time we start the servers.
        server_id = self._servers.create(
            name='mongod',
            procParams=proc_params,
            sslParams=self.sslParams,
            version=version,
            server_id=server_id
        )
        member_config.update({"_id": member_id,
                              "host": self._servers.hostname(server_id)})
        return member_config
965035
function Network(options) {
  if (!(this instanceof Network))
    return new Network(options);

  assert(!Network[options.type], 'Cannot create two networks.');

  this.type = options.type;
  this.seeds = options.seeds;
  this.magic = options.magic;
  this.port = options.port;
  this.checkpointMap = options.checkpointMap;
  this.lastCheckpoint = options.lastCheckpoint;
  this.checkpoints = [];
  this.halvingInterval = options.halvingInterval;
  this.genesis = options.genesis;
  this.genesisBlock = options.genesisBlock;
  this.pow = options.pow;
  this.block = options.block;
  this.bip30 = options.bip30;
  this.activationThreshold = options.activationThreshold;
  this.minerWindow = options.minerWindow;
  this.deployments = options.deployments;
  this.deploys = options.deploys;
  this.unknownBits = ~consensus.VERSION_TOP_MASK;
  this.keyPrefix = options.keyPrefix;
  this.addressPrefix = options.addressPrefix;
  this.requireStandard = options.requireStandard;
  this.rpcPort = options.rpcPort;
  this.minRelay = options.minRelay;
  this.feeRate = options.feeRate;
  this.maxFeeRate = options.maxFeeRate;
  this.selfConnect = options.selfConnect;
  this.requestMempool = options.requestMempool;
  this.time = new TimeData();

  this._init();
}
1138840
function(params) {

                corbel.validate.value('id', this.id);

                var options = params ? corbel.utils.clone(params) : {};

                var args = corbel.utils.extend(options, {
                    url: this._buildUriWithDomain(this.id),
                    method: corbel.request.method.GET,
                    query: params ? corbel.utils.serializeParams(params) : null
                });

                return this.request(args);

            }
949946
function(css, imageIndex){
    var urlVal = css.value[imageIndex];
    var image  = this._isSpriteImage(urlVal, imageIndex, css);
    var images = this.images;

    if (image){
      image = path.relative('./', image);
      image = image.replace(/\\+/g, '/');
      images[css.id] = image;
    }
  }
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
437305
public static void main(final String[] args) {
        /*-
         * use one of the pre-defined amis
         * (all amis are pre-defined in aws-mock-default.properties or aws-mock.properties)
         */
        String imageId = "ami-12345678";
        final int runCount = 10;

        List<Instance> startedInstances = runInstances(imageId, runCount);

        System.out.println("Started instances: ");

        for (Instance i : startedInstances) {
            System.out.println(i.getInstanceId() + " - " + i.getState().getName());
        }
    }
934923
def create_image(cloud, **kwargs):
    
    if cloud == 'ec2':
        return create_ami(**kwargs)

    if cloud == 'rackspace':
        return create_rackspace_image(**kwargs)

    if cloud == 'gce':
        return create_gce_image(**kwargs)
1275599
async function buildBastion(keyPairName, numZones = 0) {
  if (numZones < 1) {
    return {};
  }
  let publicIp = '0.0.0.0/0';
  try {
    publicIp = await getPublicIp();
    publicIp = `${publicIp}/32`;
  } catch (err) {
    console.error('Unable to discover public IP address:', err);
  }

  return Object.assign(
    {},
    buildBastionEIP(),
    buildBastionIamRole(),
    buildBastionInstanceProfile(),
    buildBastionSecurityGroup(publicIp),
    buildBastionLaunchConfiguration(keyPairName),
    buildBastionAutoScalingGroup(numZones),
  );
}
381065
function buildSubnet(name, position, zone, cidrBlock) {
  const cfName = `${name}Subnet${position}`;
  return {
    [cfName]: {
      Type: 'AWS::EC2::Subnet',
      Properties: {
        AvailabilityZone: zone,
        CidrBlock: cidrBlock,
        Tags: [
          {
            Key: 'Name',
            Value: {
              'Fn::Join': [
                '-',
                [
                  {
                    Ref: 'AWS::StackName',
                  },
                  name.toLowerCase(),
                  zone,
                ],
              ],
            },
          },
        ],
        VpcId: {
          Ref: 'VPC',
        },
      },
    },
  };
}
228447
function(params, callback) {
                getImageData = {};

                if (params) {
                    if (parseInt(params.imageId) > 0) {
                        getImageData.imageId = params.imageId;
                    }

                    if (typeof params.hashCode == 'string') {
                        getImageData.hashCode = params.hashCode;
                    }

                    if (parseInt(params.width) > 0) {
                        getImageData.width = params.width;
                    }

                    if (parseInt(params.height) > 0) {
                        getImageData.height = params.height;
                    }

                    if (parseInt(params.actual) > 0) {
                        getImageData.actual = params.actual;
                    }

                    if (parseInt(params.downloadable) > 0) {
                        getImageData.downloadable = params.downloadable;
                    }
                }

                httpRequest({
                    url: SERVICE_ADDRESSES.FILESERVER_ADDRESS + SERVICES_PATH.GET_IMAGE,
                    method: 'GET',
                    data: getImageData
                }, function(result) {
                    if (!result.hasError) {
                        var queryString = '?';
                        for (var i in params) {
                            queryString += i + '=' + params[i] + '&';
                        }
                        queryString = queryString.slice(0, -1);
                        var image = SERVICE_ADDRESSES.FILESERVER_ADDRESS + SERVICES_PATH.GET_IMAGE + queryString;
                        callback({
                            hasError: result.hasError,
                            result: image
                        });
                    }
                    else {
                        callback({
                            hasError: true
                        });
                    }
                });
            }
379659
function buildRoute(
  name,
  position,
  { NatGatewayId = null, GatewayId = null, InstanceId = null } = {},
) {
  const route = {
    Type: 'AWS::EC2::Route',
    Properties: {
      DestinationCidrBlock: '0.0.0.0/0',
      RouteTableId: {
        Ref: `${name}RouteTable${position}`,
      },
    },
  };

  if (NatGatewayId) {
    route.Properties.NatGatewayId = {
      Ref: NatGatewayId,
    };
  } else if (GatewayId) {
    route.Properties.GatewayId = {
      Ref: GatewayId,
    };
  } else if (InstanceId) {
    route.Properties.InstanceId = {
      Ref: InstanceId,
    };
  } else {
    throw new Error(
      'Unable to create route: either NatGatewayId, GatewayId or InstanceId must be provided',
    );
  }

  const cfName = `${name}Route${position}`;
  return {
    [cfName]: route,
  };
}