public static async Task NameInstance(AmazonEC2Client ec2Client, string instanceId, string instanceName) { await ec2Client.CreateTagsAsync(new CreateTagsRequest { Resources = new List <string> { instanceId }, Tags = new List <Tag> { new Tag { Key = "Name", Value = instanceName } } }); Console.WriteLine($"Instance name: {instanceName}"); }
public async Task LaunchInstanceAsync(string imageId, int numberOfInstances = 1, int maxIdleTimeSec = 3600) { // Retrieve capabilities for the selected image. var tagResult = await _client.DescribeTagsAsync(new DescribeTagsRequest { Filters = { new Filter { Name = "resource-id", Values ={ imageId } }, new Filter { Name = "tag-key", Values ={ "maci" } } } }); var capabilities = tagResult.Tags.Single().Value.Split(',').Select(c => c.Trim()); var maxIdleTime = maxIdleTimeSec.ToString(); // Prepare launch script. var launchScript = _launchScript .Replace("{{Backend}}", _backend) .Replace("{{Capabilities}}", string.Join(" ", capabilities)) .Replace("{{MaxIdleTime}}", maxIdleTime); var encodedScript = Convert.ToBase64String(Encoding.UTF8.GetBytes(launchScript)); // Fetch the metadata of the image and prepare the block device mappings to delete the // volumes on termination. var describeImages = _client.DescribeImagesAsync(new DescribeImagesRequest { ImageIds = { imageId } }); var mappings = describeImages.Result.Images[0].BlockDeviceMappings; foreach (var mapping in mappings) { mapping.Ebs.DeleteOnTermination = true; } // Launch the instance. var instanceRequest = new RunInstancesRequest { ImageId = imageId, InstanceInitiatedShutdownBehavior = ShutdownBehavior.Terminate, InstanceType = new InstanceType(_instanceType), MinCount = 1, MaxCount = numberOfInstances, UserData = encodedScript, BlockDeviceMappings = mappings }; /* Provide SSH key? */ if (!string.IsNullOrEmpty(_keyName)) { instanceRequest.KeyName = _keyName; } /* Use security group? */ if (!string.IsNullOrEmpty(_securityGroup)) { instanceRequest.SecurityGroupIds.Add(_securityGroup); } var launchResult = await _client.RunInstancesAsync(instanceRequest); var instanceIds = launchResult.Reservation.Instances.Select(i => i.InstanceId).ToList(); var tags = new List <Tag> { new Tag("maci"), new Tag("maxIdleTime", maxIdleTime) }; await _client.CreateTagsAsync(new CreateTagsRequest(instanceIds, tags)); }
public Task <CreateTagsResponse> CreateTagsAsync(List <string> resourceIds, Dictionary <string, string> tags, CancellationToken cancellationToken = default(CancellationToken)) => _client.CreateTagsAsync(new CreateTagsRequest() { Resources = resourceIds, Tags = tags?.Select(x => new Tag(x.Key, x.Value))?.ToList(), }, cancellationToken).EnsureSuccessAsync();
public async void createEc2(String generatedUID, StringWriter sr, StringBuilder sb) { var bucketName = "magicec2" + RESOURCDE_POSTFIX; region = RegionEndpoint.USWest2; using (sr = new StringWriter(sb)) { sr.WriteLine("==========================================="); sr.WriteLine("Welcome to the MAGIC CREATE EC2!"); sr.WriteLine("==========================================="); string encodedString = ""; string userdata = Constants.ud_file_text_content.Replace("<bucket_name>", bucketName).Replace("<bucket_guid>", generatedUID) ; sr.WriteLine("\n" + userdata); string formattedString = userdata; sr.WriteLine("\n" + formattedString); encodedString = EncodeToBase64(formattedString); sr.WriteLine("\n" + encodedString); var ec2Client = new AmazonEC2Client(accessKeyId, secretAccessKey, region); try { // Get latest 2012 Base AMI // var imageId = ImageUtilities.FindImageAsync(ec2Client, ImageUtilities.U).Result.ImageId; var imageId = "ami-6e1a0117"; // Create an IAM role with a profile that the Instance will use to run commands against AWS var instanceProfileArn = CreateInstanceProfile(); sr.WriteLine("Created Instance Profile: {0}", instanceProfileArn); // Sleep for a little to make sure the profile is fully propagated. await Task.Delay(TimeSpan.FromMilliseconds(15000)); // Create key pair which will be used to demonstrate how get the Windows Administrator password. // var keyPair = ec2Client.CreateKeyPairAsync(new CreateKeyPairRequest { KeyName = bucketName }).Result.KeyPair; // sr.WriteLine("KeyPair Name: {0}", keyPair.KeyName); var runRequest = new RunInstancesRequest { ImageId = imageId, MinCount = 1, MaxCount = 1, KeyName = "magicec2636459158754457398", IamInstanceProfile = new IamInstanceProfileSpecification { Arn = instanceProfileArn }, InstanceType = InstanceType.T2Micro, // Add the region for the S3 bucket and the name of the bucket to create UserData = encodedString }; var instanceId = ec2Client.RunInstancesAsync(runRequest).Result.Reservation.Instances[0].InstanceId; sr.WriteLine("Launch Instance {0}", instanceId); // Create the name tag await ec2Client.CreateTagsAsync(new CreateTagsRequest { Resources = new List <string> { instanceId }, Tags = new List <Amazon.EC2.Model.Tag> { new Amazon.EC2.Model.Tag { Key = "Name", Value = "Processor" } } }); sr.WriteLine("Adding Name Tag to instance"); sr.WriteLine("Waiting for EC2 Instance to stop"); // The script put in the user data will shutdown the instance when it is complete. Wait // till the instance has stopped which signals the script is done so the instance can be terminated. Instance instance = null; var instanceDescribeRequest = new DescribeInstancesRequest { InstanceIds = new List <string> { instanceId } }; do { await Task.Delay(TimeSpan.FromMilliseconds(10000)); instance = ec2Client.DescribeInstancesAsync(instanceDescribeRequest).Result.Reservations[0].Instances[0]; if (instance.State.Name == "stopped") { // Demonstrate how to get the Administrator password using the keypair. var passwordResponse = ec2Client.GetPasswordDataAsync(new GetPasswordDataRequest { InstanceId = instanceId }); // Make sure we actually got a password if (passwordResponse.Result.PasswordData != null) { // var password = passwordResponse.Result.GetDecryptedPassword(keyPair.KeyMaterial); // sr.WriteLine("The Windows Administrator password is: {0}", password); } } } while (instance.State.Name == "pending" || instance.State.Name == "running"); /* * // Terminate instance * await ec2Client.TerminateInstancesAsync(new TerminateInstancesRequest * { * InstanceIds = new List<string>() { instanceId } * }); */ // Delete key pair created. // await ec2Client.DeleteKeyPairAsync(new DeleteKeyPairRequest { KeyName = keyPair.KeyName }); // var s3Client = new AmazonS3Client(); var listResponse = s3Client.ListObjectsAsync(new ListObjectsRequest { BucketName = BUCKET_NAME }); //AmazonS3Exception: The specified bucket does not exist Debug.WriteLine(listResponse.Result.ToString()); if (listResponse.Result.S3Objects.Count > 0) { sr.WriteLine("Found results file {0} in S3 bucket {1}", listResponse.Result.S3Objects[0].Key, bucketName); } // Delete bucket created for sample. // await AmazonS3Util.DeleteS3BucketWithObjectsAsync(s3Client, BUCKET_NAME); // sr.WriteLine("Deleted S3 bucket created for sample."); // DeleteInstanceProfile(); // sr.WriteLine("Delete Instance Profile created for sample."); // sr.WriteLine("Instance terminated, EXIT"); } 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); } } } // return sb.ToString(); }