public AwsBootstrapNetworkInterfaceOptionsBuilder(int index, string subnetId) { _values = new InstanceNetworkInterfaceSpecification { DeviceIndex = index, SubnetId = subnetId }; _privateIps = new AwsBootstrapPrivateIpsOptionsBuilder(_values.PrivateIpAddresses); }
private void CreateAndLaunchInstance(AwsRegionLocations region) { // Get an Ec2Client for the current region var client = ec2Clients.GetOrAdd(region, r => AWSClientFactory.CreateAmazonEC2Client(credentials, region.ToAwsRegionEndpoint())); var securityGroupId = EnsureSecurityGroupExists(region); var availableSubnets = client.DescribeSubnets().Subnets.OrderByDescending(x => x.AvailableIpAddressCount); var networkSpecification = new InstanceNetworkInterfaceSpecification() { DeviceIndex = 0, SubnetId = availableSubnets.First().SubnetId, Groups = new List <string>() { securityGroupId }, AssociatePublicIpAddress = true }; var networkSpecifications = new List <InstanceNetworkInterfaceSpecification>() { networkSpecification }; var launchRequest = new RunInstancesRequest() { ImageId = GetAmiId(client, amiName), InstanceType = "t2.micro", MinCount = 1, MaxCount = 1, KeyName = keyPairName, NetworkInterfaces = networkSpecifications }; client.RunInstances(launchRequest); }
protected override void PostExecutionContextLoad(ExecutorContext context) { var cmdletContext = context as CmdletContext; if (this.AssociatePublicIp.HasValue) { if (cmdletContext.NetworkInterface == null) { // Else initialize the NetworkInterfaceSet property, // create an InstanceNetworkInterfaceSpecification with DeviceIndex 0 and // set the flag. var netInterface = new InstanceNetworkInterfaceSpecification { DeviceIndex = 0, AssociatePublicIpAddress = this.AssociatePublicIp.Value, SubnetId = cmdletContext.SubnetId, PrivateIpAddress = cmdletContext.PrivateIpAddress, }; if (cmdletContext.SecurityGroupId != null) { netInterface.Groups = cmdletContext.SecurityGroupId; } cmdletContext.NetworkInterface = new List <InstanceNetworkInterfaceSpecification> { netInterface }; // Set SubnetId and PrivateIpAddress to null as we have processed these parameters // at NIC level. cmdletContext.SubnetId = null; cmdletContext.PrivateIpAddress = null; cmdletContext.SecurityGroupId = null; } else { // Set the flag on the Network Interface with Deviceindex 0 if Network Interfaces are specified. var networkInterface0 = cmdletContext.NetworkInterface.SingleOrDefault( n => n.DeviceIndex == 0); if (networkInterface0 != null) { networkInterface0.AssociatePublicIpAddress = this.AssociatePublicIp.Value; } } } try { cmdletContext.UserData = AmazonEC2Helper.LoadUserData(this.UserData, this.UserDataFile, this.EncodeUserData); } catch (IOException e) { ThrowArgumentError("Error attempting to access UserDataFile.", UserDataFile, e); } }
public Instance CreateInstance(SecurityGroup securityGroup) { //Setup the network interface for the instance List <string> groups = new List <string>() { securityGroup.GroupId }; var eni = new InstanceNetworkInterfaceSpecification() { DeviceIndex = 0, SubnetId = Configuration.InstanceSubnetId, Groups = groups, AssociatePublicIpAddress = true }; List <InstanceNetworkInterfaceSpecification> enis = new List <InstanceNetworkInterfaceSpecification>() { eni }; //Setup the request for the new instance var launchRequest = new RunInstancesRequest() { ImageId = Configuration.InstanceImageId, InstanceType = Configuration.InstanceType, MinCount = 1, MaxCount = 1, KeyName = Configuration.InstanceKeyPairName, NetworkInterfaces = enis, }; //Request the new instance var launchResponse = EC2Client.RunInstances(launchRequest); var instance = launchResponse.Reservation.Instances.FirstOrDefault(); if (instance == null) { throw new Exception("Failed to create instance: " + launchResponse.HttpStatusCode); } Console.WriteLine("New instance created: " + instance.InstanceId); //Create a Name tag for the new instance var createTagsRequest = new CreateTagsRequest() { Resources = new[] { instance.InstanceId }.ToList(), Tags = new[] { new Tag("Name", Configuration.InstanceName) }.ToList() }; var createTagsResponse = EC2Client.CreateTags(createTagsRequest); return(instance); }
public bool request_spot(string instance_type, string availability_zone, string spot_price, string key_tag) { write_log(region + " に対してスポットリクエストを作成しています。"); int nn = setting_.getValueInt("common", "request_spot_width_of_minutes"); try { InstanceNetworkInterfaceSpecification instanceNetworkInterfaceSpecification = new InstanceNetworkInterfaceSpecification(); instanceNetworkInterfaceSpecification.DeviceIndex = 0; instanceNetworkInterfaceSpecification.SubnetId = subnet_ids[availability_zone]; instanceNetworkInterfaceSpecification.Groups.Add(security_group_id); instanceNetworkInterfaceSpecification.AssociatePublicIpAddress = true; LaunchSpecification launchSpecification = new LaunchSpecification(); launchSpecification.ImageId = image_id; launchSpecification.KeyName = Helper.build_name(setting_, key_tag); launchSpecification.InstanceType = InstanceType.FindValue(instance_type); launchSpecification.Placement = new SpotPlacement(region + availability_zone); launchSpecification.NetworkInterfaces.Add(instanceNetworkInterfaceSpecification); var client = get_client(); var spot_req = new RequestSpotInstancesRequest(); spot_req.SpotPrice = spot_price; spot_req.InstanceCount = 1; spot_req.Type = SpotInstanceType.OneTime; spot_req.ValidUntil = DateTime.Now.AddMinutes(nn); spot_req.LaunchSpecification = launchSpecification; var query_res = client.RequestSpotInstances(spot_req); spot_request_id = query_res.SpotInstanceRequests[0].SpotInstanceRequestId; } catch (Exception ex) { write_log("ERROR: " + ex.ToString()); return(false); } return(true); }
internal void LaunchServer(ref bool actionSucceeded, ref string actionMessage) { try { string keyPairPath = string.Empty; LaunchRequest.KeyPairName = $"KeyPair-{Guid.NewGuid().ToString()}"; while (!CreateKeyPair(LaunchRequest.KeyPairName, ref keyPairPath)) { LaunchRequest.KeyPairName = Guid.NewGuid().ToString(); } DescribeVpcsRequest vpcRequest = new DescribeVpcsRequest(); DescribeVpcsResponse vpcResponse = Ec2Client.DescribeVpcsAsync(vpcRequest).GetAwaiter().GetResult(); Vpc defaultVPC = vpcResponse.Vpcs.Find(x => x.IsDefault); //get the default vpc List <Filter> subnetFilter = new List <Filter>() { new Filter() { Name = "availability-zone", Values = new List <string>() { LaunchRequest.AvailabilityZone } }, new Filter() { Name = "vpc-id", Values = new List <string>() { defaultVPC.VpcId } } }; DescribeSubnetsRequest subnetRequest = new DescribeSubnetsRequest(); subnetRequest.Filters = subnetFilter; DescribeSubnetsResponse subnetResponse = Ec2Client.DescribeSubnetsAsync(subnetRequest).GetAwaiter().GetResult(); Subnet defaultSubnet = subnetResponse.Subnets.FirstOrDefault(); Filter SGFilter = new Filter { Name = "vpc-id", Values = new List <string>() { defaultVPC.VpcId } }; DescribeSecurityGroupsRequest SGrequest = new DescribeSecurityGroupsRequest(); SGrequest.Filters.Add(SGFilter); DescribeSecurityGroupsResponse SGresponse = Ec2Client.DescribeSecurityGroupsAsync(SGrequest).GetAwaiter().GetResult(); SecurityGroup defaultSG = SGresponse.SecurityGroups.FirstOrDefault(); InstanceNetworkInterfaceSpecification defaultENI = new InstanceNetworkInterfaceSpecification() { DeviceIndex = 0, SubnetId = defaultSubnet.SubnetId, Groups = new List <string>() { defaultSG.GroupId }, AssociatePublicIpAddress = true }; List <InstanceNetworkInterfaceSpecification> enis = new List <InstanceNetworkInterfaceSpecification>() { defaultENI }; EbsBlockDevice ebsBlockDevice = new EbsBlockDevice { VolumeSize = 10, VolumeType = GetActualStorageType(LaunchRequest.StorageType) }; BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping { DeviceName = "/dev/xvda" }; blockDeviceMapping.Ebs = ebsBlockDevice; var launchRequest = new RunInstancesRequest() { ImageId = GetImageID(LaunchRequest.AMIType), InstanceType = GetActualInstanceType(LaunchRequest.InstanceType), MinCount = LaunchRequest.NumOfInstances, MaxCount = LaunchRequest.NumOfInstances, KeyName = LaunchRequest.KeyPairName, Placement = new Placement(LaunchRequest.AvailabilityZone), NetworkInterfaces = enis, BlockDeviceMappings = new List <BlockDeviceMapping>() { blockDeviceMapping } }; RunInstancesResponse launchResponse = Ec2Client.RunInstancesAsync(launchRequest).GetAwaiter().GetResult(); List <String> instanceIds = new List <string>(); foreach (Instance instance in launchResponse.Reservation.Instances) { Console.WriteLine(instance.InstanceId); instanceIds.Add(instance.InstanceId); } actionSucceeded = true; actionMessage = $"The instance(s) are being launched. Please check the AWS Console to verify. {keyPairPath}"; } catch (Exception ex) { context.Logger.LogLine($"ServerOperationsHelper::LaunchServer {ex.Message}"); context.Logger.LogLine($"ServerOperationsHelper::LaunchServer {ex.StackTrace}"); actionSucceeded = false; actionMessage = $"Could not launch the server . Please contact your administrator."; } }
/// <summary> /// This function creates a spot instance request inside a VPC. It returns the request ID if successful, or sets the error /// code and message otherwise /// </summary> /// <param name="SubnetId">Id of the VPC subnet where the instances will be launched</param> /// <param name="AMI_ID">Id of the AMI that will be used as a base for the instances</param> /// <param name="SecurityGroupId">The name of the security group to be assigned to the instance(s)</param> /// <param name="KeyPairName">The name of the keypair to be assigned to the instance(s)</param> /// <param name="InstanceType">The type of the instance(s)</param> /// <param name="InstancePrice">The max price to pay for the instance(s)</param> /// <param name="InstanceCount">The number of instances to be launched</param> /// <param name="UserData">The user-data script that will be run as the instance(s) is(are) initialized</param> /// <returns>The list of Request Ids if successful</returns> public List <string> RequestVPCSpotInstances(string SubnetId, string AMI_ID, string SecurityGroupId, string KeyPairName, string InstanceType, double InstancePrice, int InstanceCount = 1, string UserData = "") { List <string> RequestIds = new List <string> (); // Initialize error values ErrorCode = 0; ErrorMessage = ""; // Create the list with security groups List <string> SecurityGroups = new List <string> () { SecurityGroupId }; // Create the network interface object (to connect with the VPC) var NetworkInterface = new InstanceNetworkInterfaceSpecification() { DeviceIndex = 0, SubnetId = SubnetId, Groups = SecurityGroups, AssociatePublicIpAddress = true }; List <InstanceNetworkInterfaceSpecification> NetworkInterfaces = new List <InstanceNetworkInterfaceSpecification> () { NetworkInterface }; // Create the launch specification LaunchSpecification launchSpecification = new LaunchSpecification() { ImageId = AMI_ID, InstanceType = InstanceType, KeyName = KeyPairName, SecurityGroups = SecurityGroups, NetworkInterfaces = NetworkInterfaces, UserData = Gadgets.Base64Encode(UserData) }; // Create the request object RequestSpotInstancesRequest spotRequest = new RequestSpotInstancesRequest() { SpotPrice = InstancePrice.ToString(), InstanceCount = InstanceCount, LaunchSpecification = launchSpecification }; // Request the instances try { var spotResponse = EC2client.RequestSpotInstances(spotRequest); // Check response for errors if (spotResponse.HttpStatusCode != HttpStatusCode.OK) { ErrorCode = Convert.ToInt32(spotResponse.HttpStatusCode); ErrorMessage = "Http Error [" + spotResponse.HttpStatusCode.ToString() + "]"; } else { foreach (SpotInstanceRequest request in spotResponse.SpotInstanceRequests) { RequestIds.Add(request.SpotInstanceRequestId); } } } catch (Exception ex) { ErrorCode = -1; ErrorMessage = ex.Message + "::" + ex.InnerException; } return(RequestIds); }
/// <summary> /// This function creates a set of instances into an EC2 VPC. It returns the Ids of the created instances if successful, or /// sets the error code and message otherwise /// </summary> /// <param name="regionEndpoint">Region where instances should be created</param> /// <param name="SubnetId">Id of the VPC subnet where the instances will be launched</param> /// <param name="AMI_ID">Id of the AMI that will be used as a base for the instances</param> /// <param name="SecurityGroupId">The name of the security group to be assigned to the instance(s)</param> /// <param name="KeyPairName">The name of the keypair to be assigned to the instance(s)</param> /// <param name="InstanceType">The type of the instance(s)</param> /// <param name="InstanceCount">The number of instances to be launched</param> /// <param name="UserData">The user-data script that will be run as the instance(s) is(are) initialized</param> /// <returns>The list of Instance Ids if successful</returns> public List <string> CreateVPCInstances(RegionEndpoint regionEndpoint, string SubnetId, string AMI_ID, string SecurityGroupId, string KeyPairName, string InstanceType, int InstanceCount = 1, string UserData = "") { List <string> InstanceIds = new List <string> (); // Initialize error values ErrorCode = 0; ErrorMessage = ""; // Create the list with security groups List <string> SecurityGroups = new List <string> () { SecurityGroupId }; // Create the network interface object (to connect with the VPC) var NetworkInterface = new InstanceNetworkInterfaceSpecification() { DeviceIndex = 0, SubnetId = SubnetId, Groups = SecurityGroups, AssociatePublicIpAddress = true }; List <InstanceNetworkInterfaceSpecification> NetworkInterfaces = new List <InstanceNetworkInterfaceSpecification> () { NetworkInterface }; // Create the request object var launchRequest = new RunInstancesRequest() { ImageId = AMI_ID, InstanceType = InstanceType, MinCount = InstanceCount, MaxCount = InstanceCount, KeyName = KeyPairName, NetworkInterfaces = NetworkInterfaces, UserData = Gadgets.Base64Encode(UserData) }; // Launch the instances try { var launchResponse = EC2client.RunInstances(launchRequest); // Check response for errors if (launchResponse.HttpStatusCode != HttpStatusCode.OK) { ErrorCode = Convert.ToInt32(launchResponse.HttpStatusCode); ErrorMessage = "Http Error [" + launchResponse.HttpStatusCode.ToString() + "]"; } else { List <Instance> createdInstances = launchResponse.Reservation.Instances; foreach (Instance instance in createdInstances) { InstanceIds.Add(instance.InstanceId); } } } catch (Exception ex) { ErrorCode = -1; ErrorMessage = ex.Message + "::" + ex.InnerException; } return(InstanceIds); }
// enumerate VPC security group and create a security group for EC2-VPC public void create_lunch_checkstatus_for_istance() { //Create an Amazon EC2 Client Using the the SDK var ec2Client = new AmazonEC2Client(); // enumerate VPC security group string secGroupName = "my-sample-sg-vpc"; SecurityGroup mySG = null; string vpcID = "vpc-7cdc5904"; Amazon.EC2.Model.Filter vpcFilter = new Amazon.EC2.Model.Filter { Name = "vpc-id", Values = new List <string>() { vpcID } }; var dsgRequest = new DescribeSecurityGroupsRequest(); dsgRequest.Filters.Add(vpcFilter); var dsgResponse = ec2Client.DescribeSecurityGroups(dsgRequest); List <SecurityGroup> mySGs = dsgResponse.SecurityGroups; foreach (SecurityGroup item in mySGs) { Console.WriteLine("Existing security group: " + item.GroupId); if (item.GroupName == secGroupName) { mySG = item; } } //create a security group for EC2-VPC if (mySG == null) { var newSGRequest = new CreateSecurityGroupRequest() { GroupName = secGroupName, Description = "My sample security group for EC2-VPC", VpcId = vpcID }; var csgResponse = ec2Client.CreateSecurityGroup(newSGRequest); Console.WriteLine(); Console.WriteLine("New security group: " + csgResponse.GroupId); List <string> Groups = new List <string>() { csgResponse.GroupId }; var newSgRequest = new DescribeSecurityGroupsRequest() { GroupIds = Groups }; var newSgResponse = ec2Client.DescribeSecurityGroups(newSgRequest); mySG = newSgResponse.SecurityGroups[0]; } //Create and initialize an IpPermission object. //iprange = the IP addresses of your local machine string ipRange = "0.0.0.0/0"; List <string> ranges = new List <string>() { ipRange }; var ipPermission = new IpPermission() { IpProtocol = "tcp", //The beginning and end of the port range. This example specifies a single port, 3389, which is used to communicate with Windows over RDP. //it should be changed if u launch a linux instance (use 22 insted ) FromPort = 3389, ToPort = 3389, IpRanges = ranges }; //Create and initialize an AuthorizeSecurityGroupIngressRequest object. var ingressRequest = new AuthorizeSecurityGroupIngressRequest(); ingressRequest.GroupId = mySG.GroupId; ingressRequest.IpPermissions.Add(ipPermission); //Pass the request object to the AuthorizeSecurityGroupIngress method, which returns an AuthorizeSecurityGroupIngressResponse object. var ingressResponse = ec2Client.AuthorizeSecurityGroupIngress(ingressRequest); Console.WriteLine("New RDP rule for: " + ipRange); //Create and initialize a network interface.for lunch enstance string subnetID = "subnet-048d6c59"; List <string> groups = new List <string>() { mySG.GroupId }; var eni = new InstanceNetworkInterfaceSpecification() { DeviceIndex = 0, SubnetId = subnetID, Groups = groups, AssociatePublicIpAddress = true }; List <InstanceNetworkInterfaceSpecification> enis = new List <InstanceNetworkInterfaceSpecification>() { eni }; string amiID = "ami-06a0d33fc8d328de0"; string keyPairName = "my-sample-key"; var launchRequest = new RunInstancesRequest() { ImageId = amiID, InstanceType = "m3.large", MinCount = 1, MaxCount = 1, KeyName = keyPairName, NetworkInterfaces = enis }; //launch RunInstancesResponse launchResponse = ec2Client.RunInstances(launchRequest); List <String> instanceIds = new List <string>(); foreach (Instance instance in launchResponse.Reservation.Instances) { Console.WriteLine(instance.InstanceId); instanceIds.Add(instance.InstanceId); } //check the status of the enstance var instanceRequest = new DescribeInstancesRequest(); instanceRequest.InstanceIds = new List <string>(); instanceRequest.InstanceIds.AddRange(instanceIds); var response = ec2Client.DescribeInstances(instanceRequest); Console.WriteLine(response.Reservations[0].Instances[0].State.Name); }
//############################################################################################ public string lunchInstance(IAmazonEC2 ec2, string ami, string subnetid, string Key, string insttype, List <string> secgroupid, bool publicip, string vpc, string NewSG, string privateIP, string Nametag, int rootDiskSize) //create new instance { RunInstancesResponse launchResponse; string subnetID = subnetid; // "subnet-2e107b76"; string amiID = ami; // "ami-c51e3eb6"; string keyPairName = Key; // "sirin-staging"; string itype = insttype; // "t2.small"; // List<string> groups = new List<string>() { "sg-9f90e2f9" }; List <string> groups = secgroupid; // new List<string>() { secgroupid }; if (NewSG.Length > 0) // create and add a new security group { try { //SG.GroupName = "AccessGP"; SecurityGroup SG = new SecurityGroup(); SG = CreateSecurityGroup(ec2, NewSG, vpc); groups.Add(SG.GroupId); } catch (Exception ex) { return(ex.Message + "\n" + ex.StackTrace); } } try { var eni = new InstanceNetworkInterfaceSpecification() { DeviceIndex = 0, SubnetId = subnetID, Groups = groups, AssociatePublicIpAddress = publicip }; if (privateIP.Length > 0) { eni.PrivateIpAddress = privateIP; // eni.PrivateIpAddress = "10.1.200.200"; } List <InstanceNetworkInterfaceSpecification> enis = new List <InstanceNetworkInterfaceSpecification>() { eni }; var launchRequest = new RunInstancesRequest() { ImageId = amiID, InstanceType = itype, MinCount = 1, MaxCount = 1, KeyName = keyPairName, NetworkInterfaces = enis // TagSpecifications = "protectorx" }; if (rootDiskSize != 0) { BlockDeviceMapping mapping = new BlockDeviceMapping { DeviceName = "/dev/sda1", Ebs = new EbsBlockDevice { VolumeType = VolumeType.Gp2, VolumeSize = rootDiskSize } }; List <BlockDeviceMapping> mappinglist; mappinglist = new List <BlockDeviceMapping>(); mappinglist.Add(mapping); launchRequest.BlockDeviceMappings = mappinglist; } // ------------------------- add tag ---------------------------------------------------- List <Amazon.EC2.Model.Tag> TagList; TagSpecification Tagspec; Amazon.EC2.Model.Tag EC2tag; //Amazon.EC2.Model.resorc EC2tag = new Amazon.EC2.Model.Tag(); EC2tag.Key = "Name"; EC2tag.Value = Nametag; //EC2tag.GetType TagList = new List <Amazon.EC2.Model.Tag>(); TagList.Add(EC2tag); // EC2tag(); Tagspec = new Amazon.EC2.Model.TagSpecification(); Tagspec.ResourceType = ResourceType.Instance; //TagSpecification(){ResourceType.Instance}; //Tagspec.Tags.OfType<Instance>; Tagspec.Tags = TagList; launchRequest.TagSpecifications.Add(Tagspec); //ec2.RunInstances(launchRequest); launchResponse = ec2.RunInstances(launchRequest); return("Done"); } catch (Exception ex) { return(ex.Message + "\n" + ex.StackTrace); } }