/// <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 Instance LaunchNATInstance(IAmazonEC2 ec2Client, LaunchNATInstanceRequest request) { if (ec2Client == null) throw new ArgumentNullException("ec2Client"); if (request == null) throw new ArgumentNullException("request"); if (string.IsNullOrEmpty(request.SubnetId)) throw new InvalidOperationException("request.SubnetId is null"); if (string.IsNullOrEmpty(request.InstanceType)) throw new InvalidOperationException("request.InstanceType is null"); List<Filter> filters = new List<Filter>() { new Filter(){Name = "architecture", Values = new List<string>(){"x86_64"}}, new Filter(){Name = "name", Values = new List<string>(){"ami-vpc-nat-*.x86_64-ebs"}} }; DescribeImagesResponse imageResponse = ec2Client.DescribeImages(new DescribeImagesRequest() { Filters = filters }); var image = FindNATImage(ec2Client); 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.Reservation.Instances[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() { Resources = new List<string>() { instanceId }, Tags = new List<Tag>() { new Tag() { Key = "Name", Value = "NAT" } } }); var allocationId = ec2Client.AllocateAddress(new AllocateAddressRequest() { Domain = "vpc" }).AllocationId; ec2Client.AssociateAddress(new AssociateAddressRequest() { InstanceId = instanceId, AllocationId = allocationId }); var instance = ec2Client.DescribeInstances(new DescribeInstancesRequest() { InstanceIds = new List<string>() { instanceId } }).Reservations[0].Instances[0]; return instance; }
public M201602102132_CreateVPC(MigrationContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); _context = context; _client = CreateClient(); _cluster = _context.Settings.Cluster; _task = _cluster.GetTask("web"); }
public M201602102134_CreateEC2SecurityGroup(MigrationContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); _context = context; _client = CreateClient(); _cluster = _context.Settings.Cluster; _groupName = "securityGroup:" + _cluster.Name; }
public M201602102135_CreateEC2WebLoadBalancer(MigrationContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); _context = context; _client = CreateClient(); _ec2client = CreateEc2Client(); _cluster = _context.Settings.Cluster; _task = _cluster.GetTask("web"); }
public Ec2Terminator(string awsProfileName) { var creds = new StoredProfileAWSCredentials(awsProfileName); _client = AWSClientFactory.CreateAmazonEC2Client(creds); _instanceHandler = new Ec2InstanceHandler(_client); _tagHandler = new Ec2TagHandler(_client); _snapshotHandler = new Ec2SnapshotHandler(_client, _tagHandler); _securityGroupHandler = new Ec2SecurityGroupHandler(_client); }
//private Ec2SnapshotHandler _snapshotHandler; public Ec2Bootstrapper(string awsProfileName) { _awsProfileName = awsProfileName; var creds = new StoredProfileAWSCredentials(awsProfileName); _client = AWSClientFactory.CreateAmazonEC2Client(creds); _instanceHandler = new Ec2InstanceHandler(_client); _securityGroupHandler = new Ec2SecurityGroupHandler(_client); _tagHandler = new Ec2TagHandler(_client); _passwordHandler = new Ec2InstancePasswordHandler(_client); //_snapshotHandler = new Ec2SnapshotHandler(_client, _tagHandler); }
/// <summary> /// Find the current VPC NAT image in the region for the AmazonEC2 client. /// </summary> /// <param name="ec2Client">The ec2client used to look up the image.</param> /// <returns>The image</returns> public static Image FindNATImage(IAmazonEC2 ec2Client) { if (ec2Client == null) throw new ArgumentNullException("ec2Client"); List<Filter> filters = new List<Filter>() { new Filter(){Name = "architecture", Values = new List<string>(){"x86_64"}}, new Filter(){Name = "name", Values = new List<string>(){"ami-vpc-nat-*.x86_64-ebs"}} }; DescribeImagesResponse imageResponse = ec2Client.DescribeImages(new DescribeImagesRequest() { Filters = filters }); var image = imageResponse.Images.OrderByDescending(x => x.Name).FirstOrDefault(); return image; }
public static void Main(string[] args) { Ec2Client = AWSClientFactory.CreateAmazonEC2Client(); // Get a list of all of your Ec2 volumes var describeVolumesResponse = Ec2Client.DescribeVolumes(); var volumeIds = describeVolumesResponse.Volumes.Select(vr => vr.VolumeId).ToList(); // Delete any Snapshots older than 10 days DeleteOldSnapshots(volumeIds, 10); // Create a new Snapshot for each volume CreateNewSnapshots(volumeIds); Console.Read(); }
public AWSAvailabilityZone[] GetAvailabilityZones(IAmazonEC2 ec2Client = null) { var ret = new List<AWSAvailabilityZone>(); var ec2 = ec2Client ?? GetEC2Client(); // might be passed in by instances calls... var request = new DescribeAvailabilityZonesRequest(); var response = ec2.DescribeAvailabilityZones(request); foreach (var zone in response.AvailabilityZones) { var awsZone = new AWSAvailabilityZone() { Region = zone.RegionName, Name = zone.ZoneName, }; ret.Add(awsZone); } return ret.ToArray(); }
private static bool IsSubnetPublic(IAmazonEC2 ec2Client, string subnetID) { try { var describeRouteTablesRequest = new DescribeRouteTablesRequest(); var filter = new Filter { Name = "association.subnet-id" }; filter.Values.Add(subnetID); describeRouteTablesRequest.Filters.Add(filter); var regionRoutes = ec2Client.DescribeRouteTables(describeRouteTablesRequest); if (regionRoutes.RouteTables.Any(routeTable => routeTable.Routes.Any(route => route.DestinationCidrBlock == "0.0.0.0/0" && !string.IsNullOrEmpty(route.GatewayId) && route.GatewayId.StartsWith("igw-")))) { return true; } } catch (AmazonEC2Exception aex) { Logger.Log(LogLevel.Error, aex, $"AmazonEC2Exception in IsSubnetPublic() : {aex.Message}"); } return false; }
public AwsFacade() { _client = AWSClientFactory.CreateAmazonEC2Client(); }
public static Task <StopInstancesResponse> StopInstancesAsyncByIds(this IAmazonEC2 ec2Client, IEnumerable <string> instanceIds) { var stopRequest = new StopInstancesRequest(new List <string>(instanceIds)); return(ec2Client.StopInstancesAsync(stopRequest)); }
protected void Page_Load(object sender, EventArgs e) { // This client will default to US West (Oregon) AmazonDynamoDBClient client = new AmazonDynamoDBClient(); // Modify the client so that it accesses a different region. client.Config.RegionEndpoint = Amazon.RegionEndpoint.USEast1; StringBuilder sb = new StringBuilder(1024); using (StringWriter sr = new StringWriter(sb)) { try { ec2 = new AmazonEC2Client(); this.WriteEC2Info(); } 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("<br />"); sr.WriteLine("You can sign up for Amazon EC2 at http://aws.amazon.com/ec2"); sr.WriteLine("<br />"); sr.WriteLine("<br />"); } else { sr.WriteLine("Caught Exception: " + ex.Message); sr.WriteLine("<br />"); sr.WriteLine("Response Status Code: " + ex.StatusCode); sr.WriteLine("<br />"); sr.WriteLine("Error Code: " + ex.ErrorCode); sr.WriteLine("<br />"); sr.WriteLine("Error Type: " + ex.ErrorType); sr.WriteLine("<br />"); sr.WriteLine("Request ID: " + ex.RequestId); sr.WriteLine("<br />"); sr.WriteLine("<br />"); } this.ec2Placeholder.Text = sr.ToString(); } } sb = new StringBuilder(1024); using (StringWriter sr = new StringWriter(sb)) { try { s3 = new AmazonS3Client(); this.WriteS3Info(); } catch (AmazonS3Exception ex) { if (ex.ErrorCode != null && (ex.ErrorCode.Equals("InvalidAccessKeyId") || ex.ErrorCode.Equals("InvalidSecurity"))) { sr.WriteLine("The account you are using is not signed up for Amazon S3"); sr.WriteLine("<br />"); sr.WriteLine("You can sign up for Amazon S3 at http://aws.amazon.com/s3"); sr.WriteLine("<br />"); sr.WriteLine("<br />"); } else { sr.WriteLine("Caught Exception: " + ex.Message); sr.WriteLine("<br />"); sr.WriteLine("Response Status Code: " + ex.StatusCode); sr.WriteLine("<br />"); sr.WriteLine("Error Code: " + ex.ErrorCode); sr.WriteLine("<br />"); sr.WriteLine("Request ID: " + ex.RequestId); sr.WriteLine("<br />"); sr.WriteLine("<br />"); } this.s3Placeholder.Text = sr.ToString(); } } sb = new StringBuilder(1024); using (StringWriter sr = new StringWriter(sb)) { try { sdb = new AmazonSimpleDBClient(); this.WriteSimpleDBInfo(); } catch (AmazonSimpleDBException ex) { if (ex.ErrorCode != null && ex.ErrorCode.Equals("InvalidClientTokenId")) { sr.WriteLine("The account you are using is not signed up for Amazon SimpleDB."); sr.WriteLine("<br />"); sr.WriteLine("You can sign up for Amazon SimpleDB at http://aws.amazon.com/simpledb"); sr.WriteLine("<br />"); sr.WriteLine("<br />"); } else { sr.WriteLine("Exception Message: " + ex.Message); sr.WriteLine("<br />"); sr.WriteLine("Response Status Code: " + ex.StatusCode); sr.WriteLine("<br />"); sr.WriteLine("Error Code: " + ex.ErrorCode); sr.WriteLine("<br />"); sr.WriteLine("Error Type: " + ex.ErrorType); sr.WriteLine("<br />"); sr.WriteLine("Request ID: " + ex.RequestId); sr.WriteLine("<br />"); sr.WriteLine("<br />"); } this.sdbPlaceholder.Text = sr.ToString(); } } }
internal DescribeInstancesPaginator(IAmazonEC2 client, DescribeInstancesRequest request) { this._client = client; this._request = request; }
internal DescribeVpcEndpointServiceConfigurationsPaginator(IAmazonEC2 client, DescribeVpcEndpointServiceConfigurationsRequest request) { this._client = client; this._request = request; }
/// <summary> /// Class disposer (to implement IDisposable) /// </summary> public void Dispose() { try { if (EC2client != null) EC2client.Dispose (); } catch { } EC2client = null; }
public Ec2TagHandler(IAmazonEC2 client) { _client = client; }
internal DescribeManagedPrefixListsPaginator(IAmazonEC2 client, DescribeManagedPrefixListsRequest request) { this._client = client; this._request = request; }
internal ListImagesInRecycleBinPaginator(IAmazonEC2 client, ListImagesInRecycleBinRequest request) { this._client = client; this._request = request; }
internal DescribeInstanceCreditSpecificationsPaginator(IAmazonEC2 client, DescribeInstanceCreditSpecificationsRequest request) { this._client = client; this._request = request; }
internal DescribeIamInstanceProfileAssociationsPaginator(IAmazonEC2 client, DescribeIamInstanceProfileAssociationsRequest request) { this._client = client; this._request = request; }
protected void Page_Load(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(1024); using (StringWriter sr = new StringWriter(sb)) { try { ec2 = AWSClientFactory.CreateAmazonEC2Client(); this.WriteEC2Info(); } 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("<br />"); sr.WriteLine("You can sign up for Amazon EC2 at http://aws.amazon.com/ec2"); sr.WriteLine("<br />"); sr.WriteLine("<br />"); } else { sr.WriteLine("Caught Exception: " + ex.Message); sr.WriteLine("<br />"); sr.WriteLine("Response Status Code: " + ex.StatusCode); sr.WriteLine("<br />"); sr.WriteLine("Error Code: " + ex.ErrorCode); sr.WriteLine("<br />"); sr.WriteLine("Error Type: " + ex.ErrorType); sr.WriteLine("<br />"); sr.WriteLine("Request ID: " + ex.RequestId); sr.WriteLine("<br />"); sr.WriteLine("<br />"); } this.ec2Placeholder.Text = sr.ToString(); } } sb = new StringBuilder(1024); using (StringWriter sr = new StringWriter(sb)) { try { s3 = AWSClientFactory.CreateAmazonS3Client(); this.WriteS3Info(); } catch (AmazonS3Exception ex) { if (ex.ErrorCode != null && (ex.ErrorCode.Equals("InvalidAccessKeyId") || ex.ErrorCode.Equals("InvalidSecurity"))) { sr.WriteLine("The account you are using is not signed up for Amazon S3"); sr.WriteLine("<br />"); sr.WriteLine("You can sign up for Amazon S3 at http://aws.amazon.com/s3"); sr.WriteLine("<br />"); sr.WriteLine("<br />"); } else { sr.WriteLine("Caught Exception: " + ex.Message); sr.WriteLine("<br />"); sr.WriteLine("Response Status Code: " + ex.StatusCode); sr.WriteLine("<br />"); sr.WriteLine("Error Code: " + ex.ErrorCode); sr.WriteLine("<br />"); sr.WriteLine("Request ID: " + ex.RequestId); sr.WriteLine("<br />"); sr.WriteLine("<br />"); } this.s3Placeholder.Text = sr.ToString(); } } sb = new StringBuilder(1024); using (StringWriter sr = new StringWriter(sb)) { try { sdb = AWSClientFactory.CreateAmazonSimpleDBClient(); this.WriteSimpleDBInfo(); } catch (AmazonSimpleDBException ex) { if (ex.ErrorCode != null && ex.ErrorCode.Equals("InvalidClientTokenId")) { sr.WriteLine("The account you are using is not signed up for Amazon SimpleDB."); sr.WriteLine("<br />"); sr.WriteLine("You can sign up for Amazon SimpleDB at http://aws.amazon.com/simpledb"); sr.WriteLine("<br />"); sr.WriteLine("<br />"); } else { sr.WriteLine("Exception Message: " + ex.Message); sr.WriteLine("<br />"); sr.WriteLine("Response Status Code: " + ex.StatusCode); sr.WriteLine("<br />"); sr.WriteLine("Error Code: " + ex.ErrorCode); sr.WriteLine("<br />"); sr.WriteLine("Error Type: " + ex.ErrorType); sr.WriteLine("<br />"); sr.WriteLine("Request ID: " + ex.RequestId); sr.WriteLine("<br />"); sr.WriteLine("<br />"); } this.sdbPlaceholder.Text = sr.ToString(); } } }
internal DescribeVpcClassicLinkDnsSupportPaginator(IAmazonEC2 client, DescribeVpcClassicLinkDnsSupportRequest request) { this._client = client; this._request = request; }
internal DescribeCoipPoolsPaginator(IAmazonEC2 client, DescribeCoipPoolsRequest request) { this._client = client; this._request = request; }
internal DescribeTrafficMirrorFiltersPaginator(IAmazonEC2 client, DescribeTrafficMirrorFiltersRequest request) { this._client = client; this._request = request; }
internal DescribeSubnetsPaginator(IAmazonEC2 client, DescribeSubnetsRequest request) { this._client = client; this._request = request; }
public SecurityGroupService(IAmazonEC2 ec2Client) { _ec2Client = ec2Client; }
internal DescribeAddressesAttributePaginator(IAmazonEC2 client, DescribeAddressesAttributeRequest request) { this._client = client; this._request = request; }
/// <summary> /// Constructs an image importer to upload and convert virtual machine image /// or disk volumes for use with Amazon EC2. The importer will use the supplied /// clients for communicating with Amazon S3 and Amazon EC2. Note that the clients /// should be configured to use the same region and AWS account. /// </summary> /// <param name="s3Client">Client to use to upload artifacts to Amazon S3</param> /// <param name="ec2Client">Client to use to request image conversion in Amazon EC2</param> /// <param name="bucketName"> /// The name of the Amazon S3 bucket that will contain the uploaded image and manifest. If the bucket /// does not exist it will be created. /// </param> public DiskImageImporter(IAmazonS3 s3Client, IAmazonEC2 ec2Client, string bucketName) { S3Client = s3Client; EC2Client = ec2Client; BucketName = bucketName; }
/// <summary> /// This method will create a VPC, a public subnet, private subnet and a NAT EC2 instance to allow EC2 instances in the private /// subnet to establish outbound connections to the internet. /// </summary> /// <param name="ec2Client">The ec2client used to create the VPC</param> /// <param name="request">The properties used to create the VPC.</param> /// <returns>The response contains all the VPC objects that were created.</returns> public static LaunchVPCWithPublicAndPrivateSubnetsResponse LaunchVPCWithPublicAndPrivateSubnets(IAmazonEC2 ec2Client, LaunchVPCWithPublicAndPrivateSubnetsRequest request) { LaunchVPCWithPublicAndPrivateSubnetsResponse response = new LaunchVPCWithPublicAndPrivateSubnetsResponse(); LaunchVPCWithPublicSubnet(ec2Client, request, response); response.PrivateSubnet = ec2Client.CreateSubnet(new CreateSubnetRequest() { AvailabilityZone = request.PrivateSubnetAvailabilityZone ?? response.PublicSubnet.AvailabilityZone, CidrBlock = request.PrivateSubnetCiderBlock, VpcId = response.VPC.VpcId }).Subnet; WriteProgress(request.ProgressCallback, "Created private subnet {0}", response.PublicSubnet.SubnetId); WaitTillTrue(((Func<bool>)(() => (ec2Client.DescribeSubnets(new DescribeSubnetsRequest() { SubnetIds = new List<string>() { response.PrivateSubnet.SubnetId } }).Subnets.Count == 1)))); ec2Client.CreateTags(new CreateTagsRequest() { Resources = new List<string>() { response.PrivateSubnet.SubnetId }, Tags = new List<Tag>() { new Tag() { Key = "Name", Value = "Private" } } }); WriteProgress(request.ProgressCallback, "Launching NAT instance"); response.NATInstance = LaunchNATInstance(ec2Client, new LaunchNATInstanceRequest() { InstanceType = request.InstanceType, KeyName = request.KeyName, SubnetId = response.PublicSubnet.SubnetId }); WriteProgress(request.ProgressCallback, "NAT instance is available"); var defaultRouteTable = GetDefaultRouteTable(ec2Client, response.VPC.VpcId); if (defaultRouteTable == null) throw new AmazonEC2Exception("No default route table found for VPC"); ec2Client.CreateRoute(new CreateRouteRequest() { RouteTableId = defaultRouteTable.RouteTableId, DestinationCidrBlock = "0.0.0.0/0", InstanceId = response.NATInstance.InstanceId }); WriteProgress(request.ProgressCallback, "Added route to the NAT instance in the default route table"); if (request.ConfigureDefaultVPCGroupForNAT) { var defaultSecurityGroup = GetDefaultSecurityGroup(ec2Client, response.VPC.VpcId); var groupId = ec2Client.CreateSecurityGroup(new CreateSecurityGroupRequest() { VpcId = response.VPC.VpcId, GroupName = "NATGroup", Description = "Give EC2 Instances access through the NAT" }).GroupId; WriteProgress(request.ProgressCallback, "Created security group for NAT configuration"); IpPermission spec = new IpPermission { IpProtocol = "-1", IpRanges = new List<string>{ "0.0.0.0/0"}, UserIdGroupPairs = new List<UserIdGroupPair>() { new UserIdGroupPair() { GroupId = groupId } } }; ec2Client.AuthorizeSecurityGroupIngress(new AuthorizeSecurityGroupIngressRequest() { IpPermissions = new List<IpPermission>() { spec }, GroupId = defaultSecurityGroup.GroupId }); WriteProgress(request.ProgressCallback, "Added permission to the default security group {0} to allow traffic from security group {1}", defaultSecurityGroup.GroupId, groupId); response.NATSecurityGroup = ec2Client.DescribeSecurityGroups(new DescribeSecurityGroupsRequest() { GroupIds = new List<string>(){ groupId } }).SecurityGroups[0]; } return response; }
/// <summary> /// Find the Amazon machine image identified by the ImageDescriptor. /// </summary> /// <param name="ec2Client">The EC2 client used to search for the image.</param> /// <param name="descriptor">The descriptor used to identify the image.</param> /// <returns>The Amazon machine image.</returns> public static Image FindImage(IAmazonEC2 ec2Client, ImageDescriptor descriptor) { if (ec2Client == null) throw new ArgumentNullException("ec2Client"); if (descriptor == null) throw new ArgumentNullException("descriptor"); int retryCount = 1; Image image = null; do { var result = ec2Client.DescribeImages(new DescribeImagesRequest() { Owners = new List<string>() { "amazon" }, Filters = new List<Filter>() { new Filter(){Name = "name", Values = new List<string>(){descriptor.NamePrefix}} } }); if (result.Images.Count != 0) image = result.Images.OrderByDescending(x => x.Name).First(); else { // backing control file may be outdated, reload and try once more if (retryCount == 1) { LOGGER.InfoFormat("FindImage - DescribeImages call for image descriptor '{0}' (name prefix '{1}') yielded no results, assuming outdated control file and reloading", descriptor.DefinitionKey, descriptor.NamePrefix); LoadDefinitionsFromWeb(); } retryCount++; } } while (image == null && retryCount <= 2); if (image == null) LOGGER.InfoFormat("FindImage - failed to find valid AMI image for descriptor '{0}' (name prefix '{1}')", descriptor.DefinitionKey, descriptor.NamePrefix); return image; }
private static SecurityGroup GetDefaultSecurityGroup(IAmazonEC2 ec2Client, string vpcId) { var filters = new List<Filter>() { new Filter() { Name = "vpc-id", Values = new List<string>() { vpcId } }, new Filter() { Name = "group-name", Values = new List<string>() { "default" } } }; var response = ec2Client.DescribeSecurityGroups(new DescribeSecurityGroupsRequest() { Filters = filters }); if (response.SecurityGroups.Count != 1) return null; return response.SecurityGroups[0]; }
internal SearchTransitGatewayMulticastGroupsPaginator(IAmazonEC2 client, SearchTransitGatewayMulticastGroupsRequest request) { this._client = client; this._request = request; }
internal DescribeFastLaunchImagesPaginator(IAmazonEC2 client, DescribeFastLaunchImagesRequest request) { this._client = client; this._request = request; }
private static RouteTable GetDefaultRouteTable(IAmazonEC2 ec2Client, string vpcId) { var filters = new List<Filter>() { new Filter() { Name = "vpc-id", Values = new List<string>() { vpcId } }, new Filter() { Name = "association.main", Values = new List<string>() { "true" } } }; var response = ec2Client.DescribeRouteTables(new DescribeRouteTablesRequest() { Filters = filters }); if (response.RouteTables.Count != 1) return null; return response.RouteTables[0]; }
internal DescribeImportImageTasksPaginator(IAmazonEC2 client, DescribeImportImageTasksRequest request) { this._client = client; this._request = request; }
private static Instance WaitForInstanceToStartUp(IAmazonEC2 ec2Client, string instanceId) { var describeRequest = new DescribeInstancesRequest() { InstanceIds = new List<string>() { instanceId } }; for (int tries = 0; tries < 40; tries++) { AWSSDKUtils.Sleep(10 * 1000); var result = ec2Client.DescribeInstances(describeRequest); if (result.Reservations.Count != 1 && result.Reservations[0].Instances.Count != 1) return null; Instance instance = result.Reservations[0].Instances[0]; // Return the updated instance object if we're out of pending if (!instance.State.Name.Equals("pending")) { return instance; } } return null; }
internal DescribeTransitGatewayAttachmentsPaginator(IAmazonEC2 client, DescribeTransitGatewayAttachmentsRequest request) { this._client = client; this._request = request; }
internal DescribeLaunchTemplatesPaginator(IAmazonEC2 client, DescribeLaunchTemplatesRequest request) { this._client = client; this._request = request; }
internal DescribeNetworkInterfacePermissionsPaginator(IAmazonEC2 client, DescribeNetworkInterfacePermissionsRequest request) { this._client = client; this._request = request; }
public Ec2InstancePasswordHandler(IAmazonEC2 client) { _client = client; }
internal DescribeNetworkAclsPaginator(IAmazonEC2 client, DescribeNetworkAclsRequest request) { this._client = client; this._request = request; }
/// <summary> /// Deletes the image file artifacts associated with the specified conversion task. /// If the task is still active, ignoreActiveTask must be set true to enable artifact /// deletion, which will cause the task to fail. Use this option at your own risk. /// </summary> /// <param name="ec2Client"> /// Amazon EC2 client to use in the process. This should have been instantiated /// with credentials that have access to the conversion task and the region in /// which the import was performed. /// </param> /// <param name="s3Client"> /// Amazon S3 client to use use in the process. This should have been instantiated /// with credentials that have access to the bucket containing the image file artifacts /// and the region in which the bucket exists. /// </param> /// <param name="conversionTaskId"> /// The ID of the conversion task that used the image file /// </param> /// <param name="ignoreActiveTask"> /// If true the artifacts are deleted even if the conversion task is still in progress /// </param> /// <param name="progressCallback">Optional progress callback</param> public static void DeleteImageArtifacts(IAmazonEC2 ec2Client, ICoreAmazonS3 s3Client, string conversionTaskId, bool ignoreActiveTask, CleanupProgressCallback progressCallback) { if (string.IsNullOrEmpty(conversionTaskId)) throw new ArgumentException("Missing conversion task id", "conversionTaskId"); SendProgressNotification(progressCallback, "Inspecting conversion task", null); var request = new DescribeConversionTasksRequest(); request.ConversionTaskIds.Add(conversionTaskId); try { var response = ec2Client.DescribeConversionTasks(request); if (response.ConversionTasks.Count == 0) throw new ArgumentException("Invalid conversion task id", "conversionTaskId"); var conversionTask = response.ConversionTasks[0]; if (!ignoreActiveTask && conversionTask.State.Equals(ConversionTaskState.Active)) throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Import task '{0}' is still active.", conversionTaskId)); string manifestUrl = null; try { // At this time only one disk image per task if (conversionTask.IsSetImportInstance()) manifestUrl = conversionTask.ImportInstance.Volumes[0].Image.ImportManifestUrl; else if (conversionTask.IsSetImportVolume()) manifestUrl = conversionTask.ImportVolume.Image.ImportManifestUrl; } finally { if (string.IsNullOrEmpty(manifestUrl)) throw new ArgumentException("Unable to obtain import manifest url from conversion task instance."); } DeleteImageArtifacts(s3Client, manifestUrl, progressCallback); } catch (AmazonEC2Exception e) { throw new ArgumentException("Expected the id of a valid conversion task", "conversionTaskId", e); } }
internal DescribeSecurityGroupsPaginator(IAmazonEC2 client, DescribeSecurityGroupsRequest request) { this._client = client; this._request = request; }
internal DescribeVpcEndpointConnectionNotificationsPaginator(IAmazonEC2 client, DescribeVpcEndpointConnectionNotificationsRequest request) { this._client = client; this._request = request; }
internal GetAssociatedIpv6PoolCidrsPaginator(IAmazonEC2 client, GetAssociatedIpv6PoolCidrsRequest request) { this._client = client; this._request = request; }
public Ec2AmiLocator(string awsProfileName) { var creds = new StoredProfileAWSCredentials(awsProfileName); _client = AWSClientFactory.CreateAmazonEC2Client(creds); }
public TaskRunner(IAmazonECS ecs, IAmazonEC2 ec2, IRetrier retrier) { _ecs = ecs; _ec2 = ec2; _retrier = retrier; }
private void Initialize(RegionEndpoint regionEndpoint, string AWSAcessKey, string AWSSecretKey) { // Set configuration info AmazonEC2Config config = new AmazonEC2Config (); config.Timeout = new TimeSpan (1, 0, 0); config.ReadWriteTimeout = new TimeSpan (1, 0, 0); config.RegionEndpoint = regionEndpoint; // Create EC2 client EC2client = AWSClientFactory.CreateAmazonEC2Client ( AWSAcessKey, AWSSecretKey, config); }
/// <summary> /// Find the Amazon machine image identified by the ImageDescriptor. /// </summary> /// <param name="ec2Client">The EC2 client used to search for the image.</param> /// <param name="descriptor">The descriptor used to identify the image.</param> /// <returns>The Amazon machine image.</returns> public static Image FindImage(IAmazonEC2 ec2Client, ImageDescriptor descriptor) { AmazonEC2Config config = CreateConfigFromClient(ec2Client, descriptor); LoadDefinitionsFromWeb(config); int retryCount = 1; Image image = null; do { var result = ec2Client.DescribeImages(CreateDescribeImagesRequest(descriptor)); if (result.Images.Any()) image = result.Images.OrderByDescending(x => x.Name).First(); else { // backing control file may be outdated, reload and try once more if (retryCount == 1) { Logger.InfoFormat("FindImage - DescribeImages call for image descriptor '{0}' (name prefix '{1}') yielded no results, assuming outdated control file and reloading", descriptor.DefinitionKey, descriptor.NamePrefix); lock (LOCK_OBJECT) { ImageDefinitionsLoaded = false; } LoadDefinitionsFromWeb(config); } retryCount++; } } while (image == null && retryCount <= 2); if (image == null) Logger.InfoFormat("FindImage - failed to find valid AMI image for descriptor '{0}' (name prefix '{1}')", descriptor.DefinitionKey, descriptor.NamePrefix); return image; }
/// <summary> /// Constructs an image importer to upload and convert virtual machine image /// or disk volumes for use with Amazon EC2. /// </summary> /// <param name="credentials"> /// The AWS credentials of the account that will own the uploaded artifacts. /// </param> /// <param name="region"> /// The region to which the artifacts will be uploaded and EC2 conversion performed. /// </param> /// <param name="bucketName"> /// The name of the Amazon S3 bucket that will contain the uploaded image and manifest. If the bucket /// does not exist it will be created. /// </param> public DiskImageImporter(AWSCredentials credentials, RegionEndpoint region, string bucketName) { Region = region; BucketName = bucketName; EC2Client = new AmazonEC2Client(credentials, Region); S3Client = new AmazonS3Client(credentials, Region); }
internal DescribeLocalGatewaysPaginator(IAmazonEC2 client, DescribeLocalGatewaysRequest request) { this._client = client; this._request = request; }
public void SetUp() { AWSCredentials credentials = AmbientCredentials.GetCredentials(); Ec2Client = AWSClientFactory.CreateAmazonEC2Client(credentials); Service = new SecurityGroupService(Ec2Client); }
/// <summary> /// Deletes the image file artifacts associated with the specified conversion task. /// If the task is still active, ignoreActiveTask must be set true to enable artifact /// deletion, which will cause the task to fail. Use this option at your own risk. /// </summary> /// <param name="ec2Client"> /// Amazon EC2 client to use in the process. This should have been instantiated /// with credentials that have access to the conversion task and the region in /// which the import was performed. /// </param> /// <param name="s3Client"> /// Amazon S3 client to use use in the process. This should have been instantiated /// with credentials that have access to the bucket containing the image file artifacts /// and the region in which the bucket exists. /// </param> /// <param name="conversionTaskId"> /// The ID of the conversion task that used the image file /// </param> /// <param name="ignoreActiveTask"> /// If true the artifacts are deleted even if the conversion task is still in progress /// </param> /// <param name="progressCallback">Optional progress callback</param> public static void DeleteImageArtifacts(IAmazonEC2 ec2Client, ICoreAmazonS3 s3Client, string conversionTaskId, bool ignoreActiveTask, CleanupProgressCallback progressCallback) { if (string.IsNullOrEmpty(conversionTaskId)) { throw new ArgumentException("Missing conversion task id", "conversionTaskId"); } SendProgressNotification(progressCallback, "Inspecting conversion task", null); var request = new DescribeConversionTasksRequest(); request.ConversionTaskIds.Add(conversionTaskId); try { var response = ec2Client.DescribeConversionTasks(request); if (response.ConversionTasks.Count == 0) { throw new ArgumentException("Invalid conversion task id", "conversionTaskId"); } var conversionTask = response.ConversionTasks[0]; if (!ignoreActiveTask && conversionTask.State.Equals(ConversionTaskState.Active)) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Import task '{0}' is still active.", conversionTaskId)); } string manifestUrl = null; try { // At this time only one disk image per task if (conversionTask.IsSetImportInstance()) { manifestUrl = conversionTask.ImportInstance.Volumes[0].Image.ImportManifestUrl; } else if (conversionTask.IsSetImportVolume()) { manifestUrl = conversionTask.ImportVolume.Image.ImportManifestUrl; } } finally { if (string.IsNullOrEmpty(manifestUrl)) { throw new ArgumentException("Unable to obtain import manifest url from conversion task instance."); } } DeleteImageArtifacts(s3Client, manifestUrl, progressCallback); } catch (AmazonEC2Exception e) { throw new ArgumentException("Expected the id of a valid conversion task", "conversionTaskId", e); } }
internal DescribeEgressOnlyInternetGatewaysPaginator(IAmazonEC2 client, DescribeEgressOnlyInternetGatewaysRequest request) { this._client = client; this._request = request; }
internal DescribeSpotPriceHistoryPaginator(IAmazonEC2 client, DescribeSpotPriceHistoryRequest request) { this._client = client; this._request = request; }
/// <summary> /// Find the Amazon machine image identified by the version-independent key name. /// </summary> /// <param name="ec2Client">The EC2 client used to search for the image.</param> /// <param name="imageKey">The keyname used to identify the image.</param> /// <returns>The Amazon machine image.</returns> public static Image FindImage(IAmazonEC2 ec2Client, string imageKey) { ImageDescriptor descriptor = DescriptorFromKey(imageKey); if (descriptor != null) return FindImage(ec2Client, descriptor); else throw new ArgumentException("Image key '{0}' is not recognized.", imageKey); }
internal DescribeMovingAddressesPaginator(IAmazonEC2 client, DescribeMovingAddressesRequest request) { this._client = client; this._request = request; }
/// <summary> /// Returns the ImageDescriptor instance for a known key. /// </summary> /// <param name="key"> /// The version-independent key identifying the descriptor /// </param> /// <param name="ec2Client"> /// <para> /// Optional. Configured client object from which proxy settings, if needed, can be /// determined. If no client is supplied the application configuration will be /// inspected for proxy details. /// </para> /// <para> /// If a proxy is configured (either on the client or in the configuration file) it /// will be used when downloading the metadata file containing the key to filter /// mappings. /// </para> /// </param> /// <returns>Matching descriptor containing the name filter to search on</returns> public static ImageDescriptor DescriptorFromKey(string key, IAmazonEC2 ec2Client) { LoadDefinitionsFromWeb(ConfigFromClient(ec2Client)); return FindDescriptorWithKey(key); }
private Amazon.EC2.Model.DeleteTransitGatewayRouteTableResponse CallAWSServiceOperation(IAmazonEC2 client, Amazon.EC2.Model.DeleteTransitGatewayRouteTableRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Elastic Compute Cloud (EC2)", "DeleteTransitGatewayRouteTable"); try { #if DESKTOP return(client.DeleteTransitGatewayRouteTable(request)); #elif CORECLR return(client.DeleteTransitGatewayRouteTableAsync(request).GetAwaiter().GetResult()); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } }