Exemplo n.º 1
0
        public IEnumerable<string> CreateInstances(string boostrapId, string imageId, int numberOfInstances, string securityGroupId)
        {
            const string userData = @"<powershell>
            netsh advfirewall firewall add rule name=""WinRM Public in"" protocol=TCP dir=in profile=any localport=5985 remoteip=any localip=any action=allow
            </powershell>";

            var runInstancesRequest = new RunInstancesRequest()
            {
                ImageId = imageId,
                InstanceType = "t2.micro",
                MinCount = numberOfInstances,
                MaxCount = numberOfInstances,
                KeyName = "ConDep",
                UserData = Convert.ToBase64String(Encoding.UTF8.GetBytes(userData)),
                NetworkInterfaces = new List<InstanceNetworkInterfaceSpecification>
                {
                    new InstanceNetworkInterfaceSpecification
                    {
                        AssociatePublicIpAddress = true,
                        DeviceIndex = 0,
                        SubnetId = "subnet-7eba6d1b",
                        Groups = new List<string>
                        {
                            securityGroupId
                        },
                        DeleteOnTermination = true,
                    }
                }
            };

            RunInstancesResponse runResponse = _client.RunInstances(runInstancesRequest);
            return runResponse.Reservation.Instances.Select(x => x.InstanceId);
        }
        public static Ec2Response StartServer(DeveloperOptions developerOptions)
        {
            try
            {
                var ec2Config = new AmazonEC2Config { AuthenticationRegion = developerOptions.RegionEndpont };

                var ec2Client = new AmazonEC2Client(
                    new BasicAWSCredentials(developerOptions.AccessKey, developerOptions.SecretAccessKey), ec2Config);

                var launchRequest = new RunInstancesRequest
                {
                    ImageId = developerOptions.AmiId,
                    InstanceType = developerOptions.InstanceType,
                    MinCount = 1,
                    MaxCount = 1,
                    KeyName = developerOptions.Ec2KeyPair,
                    SecurityGroupIds = new List<string> { developerOptions.SecurityGroupId }
                };
                var launchResponse = ec2Client.RunInstances(launchRequest);
                if (launchResponse.HttpStatusCode.Equals(HttpStatusCode.OK))
                {
                    while (true)
                    {
                        var instances = ec2Client.DescribeInstances();
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

            // TODO
            return null;
        }
Exemplo n.º 3
0
        public Reservation RunInstances(string vmImageId, string instanceType, string keyName, int numberOfInstances)
        {
            try
            {
                AWSModel.RunInstancesRequest request = new AWSModel.RunInstancesRequest();
                request.ImageId = vmImageId;
                if (!string.IsNullOrEmpty(instanceType))
                {
                    request.InstanceType = instanceType;
                }
                if (!string.IsNullOrEmpty(keyName))
                {
                    request.KeyName = keyName;
                }
                else
                {
                    request.KeyName = Settings.IaasKeyName;
                }
                request.MaxCount = numberOfInstances;
                AWSModel.RunInstancesResponse response = ec2.RunInstances(request);
                if (response != null)
                {
                    Reservation reservation = new Reservation();
                    reservation.ReservationId = response.RunInstancesResult.Reservation.ReservationId;
                    foreach (AWSModel.RunningInstance runningIns in response.RunInstancesResult.Reservation.RunningInstance)
                    {
                        if (reservation.Instances == null)
                        {
                            reservation.Instances = new List <Instance>();
                        }

                        Instance instance = ModelUtil.CreateInstance(runningIns);
                        reservation.Instances.Add(instance);
                    }
                    return(reservation);
                }
                return(null);
            }
            catch (WebException e)
            {
                throw new MonoscapeEC2Exception(e.Message, e);
            }
            catch (AmazonEC2Exception e)
            {
                throw new MonoscapeEC2Exception(e.Message, e);
            }
        }
        public void Run()
        {
            var amiId = ConfigurationManager.AppSettings["aws-imiId"];
            var keyPair = ConfigurationManager.AppSettings["aws-keyPair"];
            var groupSecurity = ConfigurationManager.AppSettings["aws-groupSecurity"];

            var groups = new List<string>() { groupSecurity };

            var launchRequest = new RunInstancesRequest
            {
                ImageId = amiId,
                InstanceType = InstanceType.M3Medium,
                MinCount = 1,
                MaxCount = 1,
                KeyName = keyPair,
                SecurityGroupIds = groups,

            };

            try
            {
                var launchResponse = client.Ec2Client.RunInstances(launchRequest);

                var instances = launchResponse.Reservation.Instances;

                foreach (var item in instances)
                {
                    instance.InstanceId = item.InstanceId;
                    instance.Instance = item;
                }

                FinishedSuccessfully = true;
            }
            catch (Exception ex)
            {
                Error = ex.Message;
            }
        }
Exemplo n.º 5
0
        public override Node CreateNode(string name, NodeSize size, NodeImage image, NodeLocation location, NodeAuth auth, NodeOptions options)
        {
            EC2NodeOptions ops = options as EC2NodeOptions;
            if (ops == null && options != null)
                throw new Exception ("Only EC2NodeOptions can be used as NodeOptions for creating EC2 Nodes.");
            else if (ops == null)
                ops = new EC2NodeOptions ();

            RunInstancesRequest request = new RunInstancesRequest () {
                InstanceType = size.Id,
                ImageId = image.Id,
                MinCount = 1,
                MaxCount = 1,
                KeyName = auth.UserName,
            };
            RunInstancesResponse response = Client.RunInstances (request);

            foreach (var i in response.RunInstancesResult.Reservation.RunningInstance) {
                return EC2Node.FromRunningInstance (i, this);
            }

            return null;
        }
        /// <summary>
        /// Launches the specified number of instances using an AMI for which you have permissions.
        /// 
        ///  
        /// <para>
        /// When you launch an instance, it enters the <code>pending</code> state. After the instance
        /// is ready for you, it enters the <code>running</code> state. To check the state of
        /// your instance, call <a>DescribeInstances</a>.
        /// </para>
        ///  
        /// <para>
        /// If you don't specify a security group when launching an instance, Amazon EC2 uses
        /// the default security group. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html">Security
        /// Groups</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
        /// </para>
        ///  
        /// <para>
        /// Linux instances have access to the public key of the key pair at boot. You can use
        /// this key to provide secure access to the instance. Amazon EC2 public images use this
        /// feature to provide secure access without passwords. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html">Key
        /// Pairs</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
        /// </para>
        ///  
        /// <para>
        /// You can provide optional user data when launching an instance. For more information,
        /// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html">Instance
        /// Metadata</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
        /// </para>
        ///  
        /// <para>
        /// If any of the AMIs have a product code attached for which the user has not subscribed,
        /// <code>RunInstances</code> fails.
        /// </para>
        ///  
        /// <para>
        /// T2 instance types can only be launched into a VPC. If you do not have a default VPC,
        /// or if you do not specify a subnet ID in the request, <code>RunInstances</code> fails.
        /// </para>
        ///  
        /// <para>
        /// For more information about troubleshooting, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_InstanceStraightToTerminated.html">What
        /// To Do If An Instance Immediately Terminates</a>, and <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html">Troubleshooting
        /// Connecting to Your Instance</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
        /// </para>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the RunInstances service method.</param>
        /// 
        /// <returns>The response from the RunInstances service method, as returned by EC2.</returns>
        public RunInstancesResponse RunInstances(RunInstancesRequest request)
        {
            var marshaller = new RunInstancesRequestMarshaller();
            var unmarshaller = RunInstancesResponseUnmarshaller.Instance;

            return Invoke<RunInstancesRequest,RunInstancesResponse>(request, marshaller, unmarshaller);
        }
Exemplo n.º 7
0
 IAsyncResult invokeRunInstances(RunInstancesRequest runInstancesRequest, AsyncCallback callback, object state, bool synchronized)
 {
     IRequest irequest = new RunInstancesRequestMarshaller().Marshall(runInstancesRequest);
     var unmarshaller = RunInstancesResponseUnmarshaller.GetInstance();
     AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
     Invoke(result);
     return result;
 }
Exemplo n.º 8
0
 /// <summary>
 /// <para>Launches the specified number of instances using an AMI for which you have permissions.</para> <para>When you launch an instance, it
 /// enters the <c>pending</c> state. After the instance is ready for you, it enters the <c>running</c> state. To check the state of your
 /// instance, call DescribeInstances.</para> <para>If you don't specify a security group when launching an instance, Amazon EC2 uses the default
 /// security group. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html" >Security
 /// Groups</a> in the <i>Amazon Elastic Compute Cloud User Guide</i> .</para> <para>Linux instances have access to the public key of the key
 /// pair at boot. You can use this key to provide secure access to the instance. Amazon EC2 public images use this feature to provide secure
 /// access without passwords. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html" >Key
 /// Pairs</a> in the <i>Amazon Elastic Compute Cloud User Guide</i> .</para> <para>You can provide optional user data when launching an
 /// instance. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html" >Instance
 /// Metadata</a> in the <i>Amazon Elastic Compute Cloud User Guide</i> .</para> <para>If any of the AMIs have a product code attached for which
 /// the user has not subscribed, <c>RunInstances</c> fails.</para>
 /// </summary>
 /// 
 /// <param name="runInstancesRequest">Container for the necessary parameters to execute the RunInstances service method on AmazonEC2.</param>
 /// 
 /// <returns>The response from the RunInstances service method, as returned by AmazonEC2.</returns>
 /// 
 public RunInstancesResponse RunInstances(RunInstancesRequest runInstancesRequest)
 {
     IAsyncResult asyncResult = invokeRunInstances(runInstancesRequest, null, null, true);
     return EndRunInstances(asyncResult);
 }
Exemplo n.º 9
0
		internal RunInstancesResponse RunInstances(RunInstancesRequest request)
        {
            var task = RunInstancesAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                ExceptionDispatchInfo.Capture(e.InnerException).Throw();
                return null;
            }
        }
Exemplo n.º 10
0
        /// <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;
        }
Exemplo n.º 11
0
        /// <summary>
        /// Creates (Runs) a new EC2 instance from the stored AMI image.
        /// </summary>
        /// <param name="imageId"></param>
        /// <param name="numberOfInstances"></param>
        /// <param name="keyName"></param>
        /// <param name="userData"></param>
        /// <param name="securityGroups"></param>
        /// <param name="availabilityZone">The AWS availability zone (us-east-1a, us-east-1b, us-east-1c, us-east-1d, eu-west-1a, eu-west-1b)</param>
        /// <returns>Returns a list of ALL instances not terminated, not just the ones started.</returns>
        public List<string> RunInstance(string imageId, int numberOfInstances, string keyName, string userData, string[] securityGroups, string availabilityZone)
        {
            var request = new RunInstancesRequest
                              {
                                  ImageId = imageId,
                                  MinCount = numberOfInstances,
                                  MaxCount = numberOfInstances,
                                  KeyName = keyName,
                                  UserData = userData,
                                  SecurityGroup = new List<string>(securityGroups)
                              };

            if (!string.IsNullOrEmpty(availabilityZone))
            {
                request.Placement = new Placement { AvailabilityZone = availabilityZone };
            }

            RunInstancesResponse response = Client.RunInstances(request);

            return response.RunInstancesResult.Reservation.RunningInstance.Select(runningInstance => runningInstance.InstanceId).ToList();
        }
Exemplo n.º 12
0
        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);
        }
Exemplo n.º 13
0
        public void launch()
        {
            //instance started.
            if (string.IsNullOrEmpty(_instanceId) == false)
            {
                return;
            }

            try
            {
                RunInstancesRequest request = new RunInstancesRequest();

                request.ImageId = _amiId;
                request.MinCount = 1;
                request.MaxCount = 1;

                if (_defaultSecurityGroup == false)
                {
                    request.SecurityGroup.Add(_securityGroups);
                }
                else
                {
                    if(securitryGroupExistOnServer() == false)
                    {
                        createSecurityGroup();
                    }
                    request.SecurityGroup.Add(_securityGroups);
                }

                string keyPath = CAwsConfig.Instance.getKeyFilePath(_keyPairName);
                if (string.IsNullOrEmpty(keyPath) == true ||
                    File.Exists(keyPath) == false)
                {
                    if (keyExistOnServer() == false)
                    {
                        createKayPair();
                    }
                }
                request.KeyName = _keyPairName;

                RunInstancesResponse response = _service.RunInstances(request);
                if (response.IsSetRunInstancesResult())
                {
                    RunInstancesResult runInstancesResult = response.RunInstancesResult;
                    if (runInstancesResult.IsSetReservation())
                    {
                        if (runInstancesResult.Reservation.RunningInstance[0].IsSetInstanceId())
                        {
                            _instanceId = runInstancesResult.Reservation.RunningInstance[0].InstanceId;
                        }
                        if (runInstancesResult.Reservation.RunningInstance[0].IsSetPublicDnsName())
                        {
                            _publicDns = runInstancesResult.Reservation.RunningInstance[0].PublicDnsName;
                        }
                    }
                }

                if (string.IsNullOrEmpty(_instanceId) == true)
                    throw new Exception("No instance id is returned.");

                //return after the instance started up
                bool pending = true;
                while (pending == true)
                {
                    System.Threading.Thread.Sleep(5 * 1000);

                    DescribeInstancesRequest describeRequest = new DescribeInstancesRequest();
                    describeRequest.InstanceId.Add(_instanceId);
                    DescribeInstancesResponse describeResponse = _service.DescribeInstances(describeRequest);
                    DescribeInstancesResult describeResult = describeResponse.DescribeInstancesResult;

                    if (describeResult.Reservation.Count != 1)
                        throw new Exception("more than one instance with the same id");
                    if (describeResult.Reservation[0].RunningInstance.Count != 1)
                        throw new Exception("more than one running instance has the same id");

                    pending = describeResult.Reservation[0].RunningInstance[0].InstanceState.Name != "running";
                }
            }
            catch (AmazonEC2Exception ex)
            {
                throw new Exception("Caught Exception: " + ex.XML);
            }
        }
Exemplo n.º 14
0
        private async Task CreateInstanceAsync(CancellationToken? cancellationToken = null)
        {
            this.Logger.Log("Creating a new instance. AMI: {0}, size: {1}", this.Specification.Ami, this.Specification.Size.Name);
            var runInstanceRequest = new RunInstancesRequest()
            {
                ImageId = this.Specification.Ami,
                InstanceType = this.Specification.Size.Key,
                MinCount = 1,
                MaxCount = 1,
                KeyName = this.privateKeyPair.KeyName,
                SecurityGroups = new List<string>() { this.SecurityGroupName },
            };
            if (!string.IsNullOrWhiteSpace(this.Specification.AvailabilityZone))
            {
                runInstanceRequest.Placement = new Placement() { AvailabilityZone = this.Specification.AvailabilityZone };
            }

            var runResponse = await this.Client.RunInstancesAsync(runInstanceRequest);
            var instances = runResponse.Reservation.Instances;
            this.InstanceId = instances[0].InstanceId;
            this.Logger.Log("New instance created. Instance ID: {0}", this.InstanceId);

            await this.SetupInstanceAsync(cancellationToken);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Initiates the asynchronous execution of the RunInstances operation.
        /// <seealso cref="Amazon.EC2.IAmazonEC2.RunInstances"/>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the RunInstances operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
		public async Task<RunInstancesResponse> RunInstancesAsync(RunInstancesRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new RunInstancesRequestMarshaller();
            var unmarshaller = RunInstancesResponseUnmarshaller.GetInstance();
            var response = await Invoke<IRequest, RunInstancesRequest, RunInstancesResponse>(request, marshaller, unmarshaller, signer, cancellationToken)
                .ConfigureAwait(continueOnCapturedContext: false);
            return response;
        }
Exemplo n.º 16
0
 protected override void ProcessRecord()
 {
     AmazonEC2 client = base.GetClient();
     Amazon.EC2.Model.RunInstancesRequest request = new Amazon.EC2.Model.RunInstancesRequest();
     request.ImageId = this._ImageId;
     request.MinCount = this._MinCount;
     request.MaxCount = this._MaxCount;
     request.KeyName = this._KeyName;
     if (string.IsNullOrEmpty(this._SecurityGroup))
     {
         request.SecurityGroup.Add(this._SecurityGroup);
     }
     request.UserData = this._UserData;
     request.InstanceType = this._InstanceType;
     request.KernelId = this._KernelId;
     request.RamdiskId = this._RamdiskId;
     request.SubnetId = this._SubnetId;
     request.AdditionalInfo = this._AdditionalInfo;
     request.DisableApiTermination = this._DisableApiTermination;
     request.InstanceInitiatedShutdownBehavior = this._InstanceInitiatedShutdownBehavior;
     Amazon.EC2.Model.RunInstancesResponse response = client.RunInstances(request);
     base.WriteObject(response.RunInstancesResult.Reservation, true);
 }
        public List<string> AssignAgentIps(AmazonEC2Client ec2Client, TestSuite testSuite)
        {
            int requiredInstances = testSuite.Tests.Count(testToGiveIp => string.IsNullOrWhiteSpace(testToGiveIp.Agent));

            if (requiredInstances > 0)
            {
                var runInstancesRequest = new RunInstancesRequest
                {
                    ImageId = "ami-df844ba8",
                    InstanceType = "t1.micro",
                    MinCount = requiredInstances,
                    MaxCount = requiredInstances,
                    KeyName = "Fourth"
                };
                runInstancesRequest.SecurityGroups.Add("Controller");
                RunInstancesResponse runResponse = ec2Client.RunInstances(runInstancesRequest);
                List<Instance> instances = runResponse.Reservation.Instances;
                List<string> instanceIDs = instances.Select(item => item.InstanceId).ToList();
                WaitForInstancesToBeRunning(ec2Client, instanceIDs);
                var instancesRequest = new DescribeInstancesRequest {InstanceIds = instanceIDs};
                DescribeInstancesResponse statusResponse = ec2Client.DescribeInstances(instancesRequest);
                List<string> ipAddresses =
                    statusResponse.Reservations[0].Instances.Select(x => x.PublicIpAddress).ToList();
                //we now have our running instances and we need to assign the ips to our tests
                foreach (Test test in testSuite.Tests.Where(test => string.IsNullOrWhiteSpace(test.Agent)))
                {
                    //assign the first free Id
                    test.Agent = ipAddresses.First();
                    //then remove it from the list
                    ipAddresses.RemoveAt(0);
                }

                //now we need to make sure all instances are ready
                MakeSureAgentsCanBeUsed(ec2Client, instanceIDs);
                return instanceIDs;
            }
            return null;
        }
Exemplo n.º 18
0
        /// <summary>
        /// This function creates a set of instances into EC2 Classic. 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="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> CreateClassicInstances(RegionEndpoint regionEndpoint, 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 request object
            List<string> groups = new List<string> () { SecurityGroupId };
            var launchRequest = new RunInstancesRequest ()
            {
                ImageId          = AMI_ID,
                InstanceType     = InstanceType,
                MinCount         = InstanceCount,
                MaxCount         = InstanceCount,
                KeyName          = KeyPairName,
                SecurityGroupIds = groups,
                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;
        }
Exemplo n.º 19
0
        /// <summary>
        /// The RunInstances operation launches a specified number of instances.
        /// If Amazon EC2 cannot launch the minimum number AMIs you request, no instances
        /// launch. If there is insufficient capacity to launch the maximum number of AMIs
        /// you request, Amazon EC2 launches as many as possible to satisfy the requested
        /// maximum values.
        /// Every instance is launched in a security group. If you do not specify a
        /// security group at launch, the instances start in your default security group.
        /// For more information on creating security groups, see CreateSecurityGroup.
        /// An optional instance type can be specified. For information about instance
        /// types, see Instance Types.
        /// You can provide an optional key pair ID for each image in the launch request
        /// (for more information, see CreateKeyPair). All instances that are created from
        /// images that use this key pair will have access to the associated public key at
        /// boot. You can use this key to provide secure access to an instance of an image
        /// on a per-instance basis. Amazon EC2 public images use this feature to provide
        /// secure access without passwords.
        /// Important:
        /// Launching public images without a key pair ID will leave them inaccessible.
        /// The public key material is made available to the instance at boot time by
        /// placing it in the openssh_id.pub file on a logical device that is exposed to
        /// the instance as /dev/sda2 (the ephemeral store). The format of this file is
        /// suitable for use as an entry within ~/.ssh/authorized_keys (the OpenSSH
        /// format). This can be done at boot (e.g., as part of rc.local) allowing for
        /// secure access without passwords.
        /// Optional user data can be provided in the launch request. All instances that
        /// collectively comprise the launch request have access to this data For more
        /// information, see Instance Metadata.
        /// Note:
        /// If any of the AMIs have a product code attached for which the user has not
        /// subscribed, the RunInstances call will fail.
        /// Important:
        /// We strongly recommend using the 2.6.18 Xen stock kernel with the c1.medium and
        /// c1.xlarge instances. Although the default Amazon EC2 kernels will work, the new
        /// kernels provide greater stability and performance for these instance types. For
        /// more information about kernels, see Kernels, RAM Disks, and Block Device
        /// Mappings.
        /// 
        /// </summary>
        /// <param name="service">Instance of AmazonEC2 service</param>
        /// <param name="request">RunInstancesRequest request</param>
        public static void InvokeRunInstances(AmazonEC2 service, RunInstancesRequest request)
        {
            try 
            {
                RunInstancesResponse response = service.RunInstances(request);
                
                
                Console.WriteLine ("Service Response");
                Console.WriteLine ("=============================================================================");
                Console.WriteLine ();

                Console.WriteLine("        RunInstancesResponse");
                if (response.IsSetResponseMetadata())
                {
                    Console.WriteLine("            ResponseMetadata");
                    ResponseMetadata  responseMetadata = response.ResponseMetadata;
                    if (responseMetadata.IsSetRequestId())
                    {
                        Console.WriteLine("                RequestId");
                        Console.WriteLine("                    {0}", responseMetadata.RequestId);
                    }
                }
                if (response.IsSetRunInstancesResult())
                {
                    Console.WriteLine("            RunInstancesResult");
                    RunInstancesResult  runInstancesResult = response.RunInstancesResult;
                    if (runInstancesResult.IsSetReservation())
                    {
                        Console.WriteLine("                Reservation");
                        Reservation  reservation = runInstancesResult.Reservation;
                        if (reservation.IsSetReservationId())
                        {
                            Console.WriteLine("                    ReservationId");
                            Console.WriteLine("                        {0}", reservation.ReservationId);
                        }
                        if (reservation.IsSetOwnerId())
                        {
                            Console.WriteLine("                    OwnerId");
                            Console.WriteLine("                        {0}", reservation.OwnerId);
                        }
                        if (reservation.IsSetRequesterId())
                        {
                            Console.WriteLine("                    RequesterId");
                            Console.WriteLine("                        {0}", reservation.RequesterId);
                        }
                        List<String> groupNameList  =  reservation.GroupName;
                        foreach (String groupName in groupNameList)
                        {
                            Console.WriteLine("                    GroupName");
                            Console.WriteLine("                        {0}", groupName);
                        }
                        List<RunningInstance> runningInstanceList = reservation.RunningInstance;
                        foreach (RunningInstance runningInstance in runningInstanceList)
                        {
                            Console.WriteLine("                    RunningInstance");
                            if (runningInstance.IsSetInstanceId())
                            {
                                Console.WriteLine("                        InstanceId");
                                Console.WriteLine("                            {0}", runningInstance.InstanceId);
                            }
                            if (runningInstance.IsSetImageId())
                            {
                                Console.WriteLine("                        ImageId");
                                Console.WriteLine("                            {0}", runningInstance.ImageId);
                            }
                            if (runningInstance.IsSetInstanceState())
                            {
                                Console.WriteLine("                        InstanceState");
                                InstanceState  instanceState = runningInstance.InstanceState;
                                if (instanceState.IsSetCode())
                                {
                                    Console.WriteLine("                            Code");
                                    Console.WriteLine("                                {0}", instanceState.Code);
                                }
                                if (instanceState.IsSetName())
                                {
                                    Console.WriteLine("                            Name");
                                    Console.WriteLine("                                {0}", instanceState.Name);
                                }
                            }
                            if (runningInstance.IsSetPrivateDnsName())
                            {
                                Console.WriteLine("                        PrivateDnsName");
                                Console.WriteLine("                            {0}", runningInstance.PrivateDnsName);
                            }
                            if (runningInstance.IsSetPublicDnsName())
                            {
                                Console.WriteLine("                        PublicDnsName");
                                Console.WriteLine("                            {0}", runningInstance.PublicDnsName);
                            }
                            if (runningInstance.IsSetStateTransitionReason())
                            {
                                Console.WriteLine("                        StateTransitionReason");
                                Console.WriteLine("                            {0}", runningInstance.StateTransitionReason);
                            }
                            if (runningInstance.IsSetKeyName())
                            {
                                Console.WriteLine("                        KeyName");
                                Console.WriteLine("                            {0}", runningInstance.KeyName);
                            }
                            if (runningInstance.IsSetAmiLaunchIndex())
                            {
                                Console.WriteLine("                        AmiLaunchIndex");
                                Console.WriteLine("                            {0}", runningInstance.AmiLaunchIndex);
                            }
                            List<String> productCodeList  =  runningInstance.ProductCode;
                            foreach (String productCode in productCodeList)
                            {
                                Console.WriteLine("                        ProductCode");
                                Console.WriteLine("                            {0}", productCode);
                            }
                            if (runningInstance.IsSetInstanceType())
                            {
                                Console.WriteLine("                        InstanceType");
                                Console.WriteLine("                            {0}", runningInstance.InstanceType);
                            }
                            if (runningInstance.IsSetLaunchTime())
                            {
                                Console.WriteLine("                        LaunchTime");
                                Console.WriteLine("                            {0}", runningInstance.LaunchTime);
                            }
                            if (runningInstance.IsSetPlacement())
                            {
                                Console.WriteLine("                        Placement");
                                Placement  placement = runningInstance.Placement;
                                if (placement.IsSetAvailabilityZone())
                                {
                                    Console.WriteLine("                            AvailabilityZone");
                                    Console.WriteLine("                                {0}", placement.AvailabilityZone);
                                }
                            }
                            if (runningInstance.IsSetKernelId())
                            {
                                Console.WriteLine("                        KernelId");
                                Console.WriteLine("                            {0}", runningInstance.KernelId);
                            }
                            if (runningInstance.IsSetRamdiskId())
                            {
                                Console.WriteLine("                        RamdiskId");
                                Console.WriteLine("                            {0}", runningInstance.RamdiskId);
                            }
                            if (runningInstance.IsSetPlatform())
                            {
                                Console.WriteLine("                        Platform");
                                Console.WriteLine("                            {0}", runningInstance.Platform);
                            }
                        }
                    }
                }

            } 
            catch (AmazonEC2Exception ex) 
            {
                Console.WriteLine("Caught Exception: " + ex.Message);
                Console.WriteLine("Response Status Code: " + ex.StatusCode);
                Console.WriteLine("Error Code: " + ex.ErrorCode);
                Console.WriteLine("Error Type: " + ex.ErrorType);
                Console.WriteLine("Request ID: " + ex.RequestId);
                Console.WriteLine("XML: " + ex.XML);
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// <para>Launches the specified number of instances using an AMI for which you have permissions.</para> <para>When you launch an instance, it
        /// enters the <c>pending</c> state. After the instance is ready for you, it enters the <c>running</c> state. To check the state of your
        /// instance, call DescribeInstances.</para> <para>If you don't specify a security group when launching an instance, Amazon EC2 uses the default
        /// security group. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html">Security
        /// Groups</a> in the <i>Amazon Elastic Compute Cloud User Guide</i> .</para> <para>Linux instances have access to the public key of the key
        /// pair at boot. You can use this key to provide secure access to the instance. Amazon EC2 public images use this feature to provide secure
        /// access without passwords. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html">Key
        /// Pairs</a> in the <i>Amazon Elastic Compute Cloud User Guide</i> .</para> <para>You can provide optional user data when launching an
        /// instance. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html">Instance
        /// Metadata</a> in the <i>Amazon Elastic Compute Cloud User Guide</i> .</para> <para>If any of the AMIs have a product code attached for which
        /// the user has not subscribed, <c>RunInstances</c> fails.</para>
        /// </summary>
        /// 
        /// <param name="runInstancesRequest">Container for the necessary parameters to execute the RunInstances service method on AmazonEC2.</param>
        /// 
        /// <returns>The response from the RunInstances service method, as returned by AmazonEC2.</returns>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
		public Task<RunInstancesResponse> RunInstancesAsync(RunInstancesRequest runInstancesRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new RunInstancesRequestMarshaller();
            var unmarshaller = RunInstancesResponseUnmarshaller.GetInstance();
            return Invoke<IRequest, RunInstancesRequest, RunInstancesResponse>(runInstancesRequest, marshaller, unmarshaller, signer, cancellationToken);
        }
        /// <summary>
        /// This method will look up the current VPC NAT ami in the region and create an instance in the subnet specified.
        /// </summary>
        /// <param name="ec2Client">The ec2client used to create the NAT instance</param>
        /// <param name="request">The properties used to launch the NAT instance.</param>
        /// <returns></returns>
        public static RunningInstance LaunchNATInstance(AmazonEC2 ec2Client, LaunchNATInstanceRequest request)
        {
            if (ec2Client == null)
                throw new ArgumentNullException("ec2Client");
            if (request == null)
                throw new ArgumentNullException("request");
            if (string.IsNullOrEmpty(request.SubnetId))
                throw new ArgumentNullException("request.SubnetId");
            if (string.IsNullOrEmpty(request.InstanceType))
                throw new ArgumentNullException("request.InstanceType");

            List<Filter> filters = new List<Filter>()
            {
                new Filter(){Name = "architecture", Value = new List<string>(){"x86_64"}},
                new Filter(){Name = "name", Value = new List<string>(){"ami-vpc-nat-*.x86_64-ebs"}}
            };
            DescribeImagesResponse imageResponse = ec2Client.DescribeImages(new DescribeImagesRequest() { Filter = filters });
            var image = ImageUtilities.FindImage(ec2Client, ImageUtilities.VPC_NAT);
            if (image == null)
            {
                throw new AmazonEC2Exception("No NAT image found in this region");
            }

            RunInstancesRequest runRequest = new RunInstancesRequest()
            {
                InstanceType = request.InstanceType,
                KeyName = request.KeyName,
                ImageId = image.ImageId,
                MinCount = 1,
                MaxCount = 1,
                SubnetId = request.SubnetId
            };
            RunInstancesResponse runResponse = ec2Client.RunInstances(runRequest);
            string instanceId = runResponse.RunInstancesResult.Reservation.RunningInstance[0].InstanceId;
            // Can't associated elastic IP address until the instance is available
            WaitForInstanceToStartUp(ec2Client, instanceId);

            ModifyInstanceAttributeRequest modifyRequest = new ModifyInstanceAttributeRequest()
            {
                InstanceId = instanceId,
                Attribute = "sourceDestCheck",
                Value = "false"
            };
            ec2Client.ModifyInstanceAttribute(modifyRequest);

            ec2Client.CreateTags(new CreateTagsRequest()
            {
                ResourceId = new List<string>() { instanceId },
                Tag = new List<Tag>() { new Tag() { Key = "Name", Value = "NAT" } }
            });

            var allocationId = ec2Client.AllocateAddress(new AllocateAddressRequest() { Domain = "vpc" }).AllocateAddressResult.AllocationId;
            ec2Client.AssociateAddress(new AssociateAddressRequest() { InstanceId = instanceId, AllocationId = allocationId });

            var instance = ec2Client.DescribeInstances(new DescribeInstancesRequest() { InstanceId = new List<string>() { instanceId } }).DescribeInstancesResult.Reservation[0].RunningInstance[0];

            return instance;
        }
Exemplo n.º 22
0
 /// <summary>
 /// Initiates the asynchronous execution of the RunInstances operation.
 /// <seealso cref="Amazon.EC2.IAmazonEC2.RunInstances"/>
 /// </summary>
 /// 
 /// <param name="runInstancesRequest">Container for the necessary parameters to execute the RunInstances operation on AmazonEC2.</param>
 /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
 /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
 ///          procedure using the AsyncState property.</param>
 /// 
 /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndRunInstances
 ///         operation.</returns>
 public IAsyncResult BeginRunInstances(RunInstancesRequest runInstancesRequest, AsyncCallback callback, object state)
 {
     return invokeRunInstances(runInstancesRequest, callback, state, false);
 }
Exemplo n.º 23
0
        public static string GetServiceOutput()
        {
            var sb = new StringBuilder(1024);
            using (var sr = new StringWriter(sb))
            {
                var appConfig = ConfigurationManager.AppSettings;

                sr.WriteLine("===========================================");
                sr.WriteLine("Welcome to the AWS .NET SDK!");
                sr.WriteLine("===========================================");

                // Print the number of Amazon EC2 instances.
                var ec2 = AWSClientFactory.CreateAmazonEC2Client(
                    appConfig["AWSAccessKey"],
                    appConfig["AWSSecretKey"]//,
                    , new AmazonEC2Config().WithServiceURL("https://eu-west-1.ec2.amazonaws.com")
                    );

                var ec2Request = new RunInstancesRequest
                                     {
                                         KeyName = "FIQA",
                                         ImageId = ";" ,
                                         InstanceType = "m1.xlarge",
                                         MinCount = 1,
                                         MaxCount = 1,
                                         Placement = new Placement
                                             {
                                                 AvailabilityZone = "eu-west-1c"
                                             }
                                     };
                ec2Request.SecurityGroup.Add("FIQA");
                ec2Request.BlockDeviceMapping.Add(
                    new BlockDeviceMapping
                        {
                            DeviceName = "/dev/sda1",
                            Ebs = new EbsBlockDevice
                                      {
                                          VolumeSize = 200
                                      }
                        });
                try
                {
                    var ec2Response = ec2.RunInstances(ec2Request);
                    Console.WriteLine(ec2Response.ToXML());
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    //throw;
                }

                //var ec2Request = new DescribeInstancesRequest();

                //try
                //{
                //    var ec2Response = ec2.DescribeInstances(ec2Request);
                //    int numInstances = 0;
                //    numInstances = ec2Response.DescribeInstancesResult.Reservation.Count;
                //    sr.WriteLine("You have " + numInstances + " Amazon EC2 instance(s) running in the US-East (Northern Virginia) region.");

                //}
                //catch (AmazonEC2Exception ex)
                //{
                //    if (ex.ErrorCode != null && ex.ErrorCode.Equals("AuthFailure"))
                //    {
                //        sr.WriteLine("The account you are using is not signed up for Amazon EC2.");
                //        sr.WriteLine("You can sign up for Amazon EC2 at http://aws.amazon.com/ec2");
                //    }
                //    else
                //    {
                //        sr.WriteLine("Caught Exception: " + ex.Message);
                //        sr.WriteLine("Response Status Code: " + ex.StatusCode);
                //        sr.WriteLine("Error Code: " + ex.ErrorCode);
                //        sr.WriteLine("Error Type: " + ex.ErrorType);
                //        sr.WriteLine("Request ID: " + ex.RequestId);
                //        sr.WriteLine("XML: " + ex.XML);
                //    }
                //}
                //sr.WriteLine();

                //    // Print the number of Amazon SimpleDB domains.
                //    var sdb = AWSClientFactory.CreateAmazonSimpleDBClient(
                //        appConfig["AWSAccessKey"],
                //        appConfig["AWSSecretKey"]
                //        );
                //    var sdbRequest = new ListDomainsRequest();

                //    try
                //    {
                //        var sdbResponse = sdb.ListDomains(sdbRequest);

                //        if (sdbResponse.IsSetListDomainsResult())
                //        {
                //            int numDomains = 0;
                //            numDomains = sdbResponse.ListDomainsResult.DomainName.Count;
                //            sr.WriteLine("You have " + numDomains + " Amazon SimpleDB domain(s) in the US-East (Northern Virginia) region.");
                //        }
                //    }
                //    catch (AmazonSimpleDBException ex)
                //    {
                //        if (ex.ErrorCode != null && ex.ErrorCode.Equals("AuthFailure"))
                //        {
                //            sr.WriteLine("The account you are using is not signed up for Amazon SimpleDB.");
                //            sr.WriteLine("You can sign up for Amazon SimpleDB at http://aws.amazon.com/simpledb");
                //        }
                //        else
                //        {
                //            sr.WriteLine("Caught Exception: " + ex.Message);
                //            sr.WriteLine("Response Status Code: " + ex.StatusCode);
                //            sr.WriteLine("Error Code: " + ex.ErrorCode);
                //            sr.WriteLine("Error Type: " + ex.ErrorType);
                //            sr.WriteLine("Request ID: " + ex.RequestId);
                //            sr.WriteLine("XML: " + ex.XML);
                //        }
                //    }
                //    sr.WriteLine();

                //    // Print the number of Amazon S3 Buckets.
                //    var s3Client = AWSClientFactory.CreateAmazonS3Client(
                //        appConfig["AWSAccessKey"],
                //        appConfig["AWSSecretKey"]
                //        );

                //    try
                //    {
                //        ListBucketsResponse response = s3Client.ListBuckets();
                //        int numBuckets = 0;
                //        if (response.Buckets != null &&
                //            response.Buckets.Count > 0)
                //        {
                //            numBuckets = response.Buckets.Count;
                //        }
                //        sr.WriteLine("You have " + numBuckets + " Amazon S3 bucket(s) in the US Standard region.");
                //    }
                //    catch (AmazonS3Exception ex)
                //    {
                //        if (ex.ErrorCode != null && (ex.ErrorCode.Equals("InvalidAccessKeyId") ||
                //            ex.ErrorCode.Equals("InvalidSecurity")))
                //        {
                //            sr.WriteLine("Please check the provided AWS Credentials.");
                //            sr.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
                //        }
                //        else
                //        {
                //            sr.WriteLine("Caught Exception: " + ex.Message);
                //            sr.WriteLine("Response Status Code: " + ex.StatusCode);
                //            sr.WriteLine("Error Code: " + ex.ErrorCode);
                //            sr.WriteLine("Request ID: " + ex.RequestId);
                //            sr.WriteLine("XML: " + ex.XML);
                //        }
                //    }
                //    sr.WriteLine("Press any key to continue...");
            }
            return sb.ToString();
        }
Exemplo n.º 24
0
		public static RunningInstance launchInstance(this AmazonEC2Client ec2Client, string imageId, string instanceType, string securityGroup, string keyname)
		{
			"Launching Amazon EC2 Instance".info();
			var runInstancesRequest = new RunInstancesRequest();

			runInstancesRequest.ImageId = imageId;
			runInstancesRequest.MinCount = 1;
			runInstancesRequest.MaxCount = 1;
			runInstancesRequest.InstanceType = instanceType;
			runInstancesRequest.SecurityGroup.Add(securityGroup);
			runInstancesRequest.KeyName = keyname;
			var runningInstance =  ec2Client.RunInstances(runInstancesRequest)
											.RunInstancesResult
											.Reservation
											.RunningInstance.first();
			"Launched Image with ID: {0}".info(runningInstance.ImageId);
			return runningInstance;
		}
Exemplo n.º 25
0
        public Reservation RunInstances(string vmImageId, string instanceType, string keyName, int numberOfInstances)
        {
            try
            {
                AWSModel.RunInstancesRequest request = new AWSModel.RunInstancesRequest();
                request.ImageId = vmImageId;
                if (!string.IsNullOrEmpty(instanceType))
                    request.InstanceType = instanceType;
                if (!string.IsNullOrEmpty(keyName))
                    request.KeyName = keyName;
                else
                    request.KeyName = Settings.IaasKeyName;
                request.MaxCount = numberOfInstances;
                AWSModel.RunInstancesResponse response = ec2.RunInstances(request);
                if (response != null)
                {
                    Reservation reservation = new Reservation();
                    reservation.ReservationId = response.RunInstancesResult.Reservation.ReservationId;
                    foreach (AWSModel.RunningInstance runningIns in response.RunInstancesResult.Reservation.RunningInstance)
                    {
                        if (reservation.Instances == null)
                            reservation.Instances = new List<Instance>();

                        Instance instance = ModelUtil.CreateInstance(runningIns);
                        reservation.Instances.Add(instance);
                    }
                    return reservation;
                }
                return null;
            }
            catch (WebException e)
            {
                throw new MonoscapeEC2Exception(e.Message, e);
            }
            catch (AmazonEC2Exception e)
            {
                throw new MonoscapeEC2Exception(e.Message, e);
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Initiates the asynchronous execution of the RunInstances operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the RunInstances operation on AmazonEC2Client.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        /// 
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndRunInstances
        ///         operation.</returns>
        public IAsyncResult BeginRunInstances(RunInstancesRequest request, AsyncCallback callback, object state)
        {
            var marshaller = new RunInstancesRequestMarshaller();
            var unmarshaller = RunInstancesResponseUnmarshaller.Instance;

            return BeginInvoke<RunInstancesRequest>(request, marshaller, unmarshaller,
                callback, state);
        }
Exemplo n.º 27
0
        /// <summary>
        /// <para> The RunInstances operation launches a specified number of instances. </para> <para> If Amazon EC2 cannot launch the minimum number
        /// AMIs you request, no instances launch. If there is insufficient capacity to launch the maximum number of AMIs you request, Amazon EC2
        /// launches as many as possible to satisfy the requested maximum values. </para> <para> Every instance is launched in a security group. If you
        /// do not specify a security group at launch, the instances start in your default security group. For more information on creating security
        /// groups, see CreateSecurityGroup. </para> <para> An optional instance type can be specified. For information about instance types, see
        /// Instance Types. </para> <para> You can provide an optional key pair ID for each image in the launch request (for more information, see
        /// CreateKeyPair). All instances that are created from images that use this key pair will have access to the associated public key at boot. You
        /// can use this key to provide secure access to an instance of an image on a per-instance basis. Amazon EC2 public images use this feature to
        /// provide secure access without passwords. </para> <para><b>IMPORTANT:</b> Launching public images without a key pair ID will leave them
        /// inaccessible. The public key material is made available to the instance at boot time by placing it in the openssh_id.pub file on a logical
        /// device that is exposed to the instance as /dev/sda2 (the ephemeral store). The format of this file is suitable for use as an entry within
        /// ~/.ssh/authorized_keys (the OpenSSH format). This can be done at boot (e.g., as part of rc.local) allowing for secure access without
        /// passwords. Optional user data can be provided in the launch request. All instances that collectively comprise the launch request have access
        /// to this data For more information, see Instance Metadata. </para> <para><b>NOTE:</b> If any of the AMIs have a product code attached for
        /// which the user has not subscribed, the RunInstances call will fail. </para> <para><b>IMPORTANT:</b> We strongly recommend using the 2.6.18
        /// Xen stock kernel with the c1.medium and c1.xlarge instances. Although the default Amazon EC2 kernels will work, the new kernels provide
        /// greater stability and performance for these instance types. For more information about kernels, see Kernels, RAM Disks, and Block Device
        /// Mappings. </para>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the RunInstances service method on AmazonEC2.</param>
        /// 
        /// <returns>The response from the RunInstances service method, as returned by AmazonEC2.</returns>
		public RunInstancesResponse RunInstances(RunInstancesRequest request)
        {
            var task = RunInstancesAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                throw e.InnerException;
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Initiates the asynchronous execution of the RunInstances operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the RunInstances operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<RunInstancesResponse> RunInstancesAsync(RunInstancesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new RunInstancesRequestMarshaller();
            var unmarshaller = RunInstancesResponseUnmarshaller.Instance;

            return InvokeAsync<RunInstancesRequest,RunInstancesResponse>(request, marshaller, 
                unmarshaller, cancellationToken);
        }
        public void LaunchInstance(string instanceName, InstanceSize size, string metadata)
        {
            var ec2Client = new AmazonEC2Client(_awsCredentials);

            string instanceType = "t1.micro";
            // WEB: string imageId = "ami-a9da0ec0";
            // Compute: string imageId = "ami-443fe32d";
            string imageId = "ami-09d96e60";

            switch (size)
            {
                case InstanceSize.Medium:
                    instanceType = "t1.small";
                    break;

                case InstanceSize.Small:
                default:
                    instanceType = "t1.micro";
                    break;
            }

            var request = new RunInstancesRequest()
                .WithInstanceType(instanceType)
                .WithPlacement(new Placement().WithAvailabilityZone("us-east-1d"))
                .WithImageId(imageId)
                .WithMinCount(1)
                .WithMaxCount(1)
                .WithSecurityGroup("default")
                .WithKeyName("IgorTest3");

            if (!string.IsNullOrEmpty(metadata))
                request = request.WithUserData(Convert.ToBase64String(Encoding.UTF8.GetBytes(metadata)));

            var runInstancesResponse = ec2Client.RunInstances(request);

            var instances = runInstancesResponse.RunInstancesResult.Reservation.RunningInstance;
            var index = 0;
            foreach (var instance in instances)
            {
                var name = instanceName;

                if (instances.Count > 0)
                    instanceName = instanceName + index;

                var createTagsRequest = new CreateTagsRequest();
                createTagsRequest
                    .WithResourceId(instance.InstanceId)
                    .WithTag(new Tag().WithKey("Name")
                    .WithValue(name));
                ec2Client.CreateTags(createTagsRequest);

                index++;
            }

            /*
            string rsaPrivateKey;
            using (var reader = new StreamReader(@"C:\Dev\BlueMetal\CloudAbstractions\SecurityStorage\IgorKeyPair.pem"))
            {
                rsaPrivateKey = reader.ReadToEnd();
            }
            var result = ec2Client.GetPasswordData(
                        new GetPasswordDataRequest().WithInstanceId(instanceId))
                .GetPasswordDataResult;

            Console.WriteLine(result.GetDecryptedPassword(rsaPrivateKey));
            */

            /*
                        AmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client(
                          appConfig["AWSAccessKey"],
                          appConfig["AWSSecretKey"],
                          new AmazonEC2Config().WithServiceURL("https://eu-west-1.ec2.amazonaws.com")
                          );

                        DescribeInstancesRequest ec2Request = new DescribeInstancesRequest();
            */
        }