Пример #1
0
        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;
        }
Пример #2
0
        /// <summary>
        /// Initiates the asynchronous execution of the DescribeRouteTables operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the DescribeRouteTables 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 EndDescribeRouteTables
        ///         operation.</returns>
        public IAsyncResult BeginDescribeRouteTables(DescribeRouteTablesRequest request, AsyncCallback callback, object state)
        {
            var marshaller = new DescribeRouteTablesRequestMarshaller();
            var unmarshaller = DescribeRouteTablesResponseUnmarshaller.Instance;

            return BeginInvoke<DescribeRouteTablesRequest>(request, marshaller, unmarshaller,
                callback, state);
        }
Пример #3
0
 internal DescribeRouteTablesPaginator(IAmazonEC2 client, DescribeRouteTablesRequest request)
 {
     this._client  = client;
     this._request = request;
 }
Пример #4
0
 /// <summary>
 /// Paginator for DescribeRouteTables operation
 ///</summary>
 public IDescribeRouteTablesPaginator DescribeRouteTables(DescribeRouteTablesRequest request)
 {
     return(new DescribeRouteTablesPaginator(this.client, request));
 }
Пример #5
0
 IAsyncResult invokeDescribeRouteTables(DescribeRouteTablesRequest describeRouteTablesRequest, AsyncCallback callback, object state, bool synchronized)
 {
     IRequest irequest = new DescribeRouteTablesRequestMarshaller().Marshall(describeRouteTablesRequest);
     var unmarshaller = DescribeRouteTablesResponseUnmarshaller.GetInstance();
     AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
     Invoke(result);
     return result;
 }
Пример #6
0
 /// <summary>
 /// Initiates the asynchronous execution of the DescribeRouteTables operation.
 /// <seealso cref="Amazon.EC2.IAmazonEC2.DescribeRouteTables"/>
 /// </summary>
 /// 
 /// <param name="describeRouteTablesRequest">Container for the necessary parameters to execute the DescribeRouteTables 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
 ///         EndDescribeRouteTables operation.</returns>
 public IAsyncResult BeginDescribeRouteTables(DescribeRouteTablesRequest describeRouteTablesRequest, AsyncCallback callback, object state)
 {
     return invokeDescribeRouteTables(describeRouteTablesRequest, callback, state, false);
 }
Пример #7
0
 /// <summary>
 /// <para>Describes one or more of your route tables.</para> <para>For more information about route tables, see <a
 /// href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Route_Tables.html" >Route Tables</a> in the <i>Amazon Virtual Private Cloud
 /// User Guide</i> .</para>
 /// </summary>
 /// 
 /// <param name="describeRouteTablesRequest">Container for the necessary parameters to execute the DescribeRouteTables service method on
 ///          AmazonEC2.</param>
 /// 
 /// <returns>The response from the DescribeRouteTables service method, as returned by AmazonEC2.</returns>
 /// 
 public DescribeRouteTablesResponse DescribeRouteTables(DescribeRouteTablesRequest describeRouteTablesRequest)
 {
     IAsyncResult asyncResult = invokeDescribeRouteTables(describeRouteTablesRequest, null, null, true);
     return EndDescribeRouteTables(asyncResult);
 }
        /// <summary>
        /// This method will create a VPC with a subnet that will have an internet gateway attached making instances available 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>
        /// <param name="response">The response contains all the VPC objects that were created.</param>
        private static void LaunchVPCWithPublicSubnet(AmazonEC2 ec2Client, LaunchVPCWithPublicSubnetRequest request, LaunchVPCWithPublicSubnetResponse response)
        {
            response.VPC = ec2Client.CreateVpc(new CreateVpcRequest()
            {
                CidrBlock = request.VPCCidrBlock,
                InstanceTenancy = request.InstanceTenancy
            }).CreateVpcResult.Vpc;
            WriteProgress(request.ProgressCallback, "Created vpc {0}", response.VPC.VpcId);

            var describeVPCRequest = new DescribeVpcsRequest() { VpcId = new List<string>() { response.VPC.VpcId } };
            WaitTillTrue(((Func<bool>)(() => ec2Client.DescribeVpcs(describeVPCRequest).DescribeVpcsResult.Vpc.Count == 1)));

            if(!string.IsNullOrEmpty(request.VPCName))
            {
                ec2Client.CreateTags(new CreateTagsRequest()
                {
                    ResourceId = new List<string>(){ response.VPC.VpcId},
                    Tag = new List<Tag>(){new Tag(){Key = "Name", Value = request.VPCName}}
                });
            }

            response.PublicSubnet = ec2Client.CreateSubnet(new CreateSubnetRequest()
            {
                AvailabilityZone = request.PublicSubnetAvailabilityZone,
                CidrBlock = request.PublicSubnetCiderBlock,
                VpcId = response.VPC.VpcId
            }).CreateSubnetResult.Subnet;
            WriteProgress(request.ProgressCallback, "Created public subnet {0}", response.PublicSubnet.SubnetId);

            WaitTillTrue(((Func<bool>)(() => (ec2Client.DescribeSubnets(new DescribeSubnetsRequest() { SubnetId = new List<string>() { response.PublicSubnet.SubnetId } }).DescribeSubnetsResult.Subnet.Count == 1))));

            ec2Client.CreateTags(new CreateTagsRequest()
            {
                ResourceId = new List<string>() { response.PublicSubnet.SubnetId },
                Tag = new List<Tag>() { new Tag() { Key = "Name", Value = "Public" } }
            });

            response.InternetGateway = ec2Client.CreateInternetGateway(new CreateInternetGatewayRequest()
            {
            }).CreateInternetGatewayResult.InternetGateway;
            WriteProgress(request.ProgressCallback, "Created internet gateway {0}", response.InternetGateway.InternetGatewayId);

            ec2Client.AttachInternetGateway(new AttachInternetGatewayRequest()
            {
                InternetGatewayId = response.InternetGateway.InternetGatewayId,
                VpcId = response.VPC.VpcId
            });
            WriteProgress(request.ProgressCallback, "Attached internet gateway to vpc");

            response.PublicSubnetRouteTable = ec2Client.CreateRouteTable(new CreateRouteTableRequest()
            {
                VpcId = response.VPC.VpcId
            }).CreateRouteTableResult.RouteTable;
            WriteProgress(request.ProgressCallback, "Created route table {0}", response.PublicSubnetRouteTable.RouteTableId);

            var describeRouteTableRequest = new DescribeRouteTablesRequest() { RouteTableId = new List<string>() { response.PublicSubnetRouteTable.RouteTableId } };
            WaitTillTrue(((Func<bool>)(() => (ec2Client.DescribeRouteTables(describeRouteTableRequest).DescribeRouteTablesResult.RouteTables.Count == 1))));

            ec2Client.CreateTags(new CreateTagsRequest()
            {
                ResourceId = new List<string>() { response.PublicSubnetRouteTable.RouteTableId },
                Tag = new List<Tag>() { new Tag() { Key = "Name", Value = "Public" } }
            });

            ec2Client.AssociateRouteTable(new AssociateRouteTableRequest()
            {
                RouteTableId = response.PublicSubnetRouteTable.RouteTableId,
                SubnetId = response.PublicSubnet.SubnetId
            });
            WriteProgress(request.ProgressCallback, "Associated route table to public subnet");

            ec2Client.CreateRoute(new CreateRouteRequest()
            {
                DestinationCidrBlock = "0.0.0.0/0",
                GatewayId = response.InternetGateway.InternetGatewayId,
                RouteTableId = response.PublicSubnetRouteTable.RouteTableId
            });
            WriteProgress(request.ProgressCallback, "Added route for internet gateway to route table {0}", response.PublicSubnetRouteTable.RouteTableId);

            response.PublicSubnetRouteTable = ec2Client.DescribeRouteTables(describeRouteTableRequest).DescribeRouteTablesResult.RouteTables[0];
        }
Пример #9
0
        public object Execute(ExecutorContext context)
        {
            var cmdletContext      = context as CmdletContext;
            var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent;

            // create request and set iteration invariants
            var request = new Amazon.EC2.Model.DescribeRouteTablesRequest();

            if (cmdletContext.Filter != null)
            {
                request.Filters = cmdletContext.Filter;
            }
            if (cmdletContext.RouteTableId != null)
            {
                request.RouteTableIds = cmdletContext.RouteTableId;
            }

            // Initialize loop variants and commence piping
            System.String _nextToken      = null;
            int?          _emitLimit      = null;
            int           _retrievedSoFar = 0;

            if (AutoIterationHelpers.HasValue(cmdletContext.NextToken))
            {
                _nextToken = cmdletContext.NextToken;
            }
            if (cmdletContext.MaxResult.HasValue)
            {
                // The service has a maximum page size of 100. If the user has
                // asked for more items than page max, and there is no page size
                // configured, we rely on the service ignoring the set maximum
                // and giving us 100 items back. If a page size is set, that will
                // be used to configure the pagination.
                // We'll make further calls to satisfy the user's request.
                _emitLimit = cmdletContext.MaxResult;
            }
            var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken));

            var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);

            do
            {
                request.NextToken = _nextToken;
                if (_emitLimit.HasValue)
                {
                    int correctPageSize = Math.Min(100, _emitLimit.Value);
                    request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToInt32(correctPageSize);
                }

                CmdletOutput output;

                try
                {
                    var    response       = CallAWSServiceOperation(client, request);
                    object pipelineOutput = null;
                    if (!useParameterSelect)
                    {
                        pipelineOutput = cmdletContext.Select(response, this);
                    }
                    output = new CmdletOutput
                    {
                        PipelineOutput  = pipelineOutput,
                        ServiceResponse = response
                    };
                    int _receivedThisCall = response.RouteTables.Count;

                    _nextToken       = response.NextToken;
                    _retrievedSoFar += _receivedThisCall;
                    if (_emitLimit.HasValue)
                    {
                        _emitLimit -= _receivedThisCall;
                    }
                }
                catch (Exception e)
                {
                    if (_retrievedSoFar == 0 || !_emitLimit.HasValue)
                    {
                        output = new CmdletOutput {
                            ErrorResponse = e
                        };
                    }
                    else
                    {
                        break;
                    }
                }

                ProcessOutput(output);
            } while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken) && (!_emitLimit.HasValue || _emitLimit.Value >= 5));


            if (useParameterSelect)
            {
                WriteObject(cmdletContext.Select(null, this));
            }


            return(null);
        }
Пример #10
0
        public object Execute(ExecutorContext context)
        {
            var cmdletContext = context as CmdletContext;

            #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
            var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent;
            #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute

            // create request and set iteration invariants
            var request = new Amazon.EC2.Model.DescribeRouteTablesRequest();

            if (cmdletContext.Filter != null)
            {
                request.Filters = cmdletContext.Filter;
            }
            if (cmdletContext.MaxResult != null)
            {
                request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToServiceTypeInt32(cmdletContext.MaxResult.Value);
            }
            if (cmdletContext.RouteTableId != null)
            {
                request.RouteTableIds = cmdletContext.RouteTableId;
            }

            // Initialize loop variant and commence piping
            var _nextToken             = cmdletContext.NextToken;
            var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken));

            var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
            do
            {
                request.NextToken = _nextToken;

                CmdletOutput output;

                try
                {
                    var response = CallAWSServiceOperation(client, request);

                    object pipelineOutput = null;
                    if (!useParameterSelect)
                    {
                        pipelineOutput = cmdletContext.Select(response, this);
                    }
                    output = new CmdletOutput
                    {
                        PipelineOutput  = pipelineOutput,
                        ServiceResponse = response
                    };

                    _nextToken = response.NextToken;
                }
                catch (Exception e)
                {
                    output = new CmdletOutput {
                        ErrorResponse = e
                    };
                }

                ProcessOutput(output);
            } while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken));

            if (useParameterSelect)
            {
                WriteObject(cmdletContext.Select(null, this));
            }


            return(null);
        }
Пример #11
0
        /// <summary>
        /// <para>Describes one or more of your route tables.</para> <para>For more information about route tables, see <a href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Route_Tables.html">Route Tables</a> in the <i>Amazon Virtual Private Cloud
        /// User Guide</i> .</para>
        /// </summary>
        /// 
        /// <param name="describeRouteTablesRequest">Container for the necessary parameters to execute the DescribeRouteTables service method on
        /// AmazonEC2.</param>
        /// 
        /// <returns>The response from the DescribeRouteTables 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<DescribeRouteTablesResponse> DescribeRouteTablesAsync(DescribeRouteTablesRequest describeRouteTablesRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new DescribeRouteTablesRequestMarshaller();
            var unmarshaller = DescribeRouteTablesResponseUnmarshaller.GetInstance();
            return Invoke<IRequest, DescribeRouteTablesRequest, DescribeRouteTablesResponse>(describeRouteTablesRequest, marshaller, unmarshaller, signer, cancellationToken);
        }
Пример #12
0
		internal DescribeRouteTablesResponse DescribeRouteTables(DescribeRouteTablesRequest request)
        {
            var task = DescribeRouteTablesAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                ExceptionDispatchInfo.Capture(e.InnerException).Throw();
                return null;
            }
        }
Пример #13
0
        /// <summary>
        /// Initiates the asynchronous execution of the DescribeRouteTables operation.
        /// <seealso cref="Amazon.EC2.IAmazonEC2.DescribeRouteTables"/>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the DescribeRouteTables 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<DescribeRouteTablesResponse> DescribeRouteTablesAsync(DescribeRouteTablesRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new DescribeRouteTablesRequestMarshaller();
            var unmarshaller = DescribeRouteTablesResponseUnmarshaller.GetInstance();
            var response = await Invoke<IRequest, DescribeRouteTablesRequest, DescribeRouteTablesResponse>(request, marshaller, unmarshaller, signer, cancellationToken)
                .ConfigureAwait(continueOnCapturedContext: false);
            return response;
        }
Пример #14
0
        /// <summary>
        /// <para> Gives you information about your route tables. You can filter the results to return information only about tables that match criteria
        /// you specify. For example, you could get information only about a table associated with a particular subnet. You can specify multiple values
        /// for the filter. The table must match at least one of the specified values for it to be included in the results. </para> <para> You can
        /// specify multiple filters (e.g., the table has a particular route, and is associated with a particular subnet). The result includes
        /// information for a particular table only if it matches all your filters. If there's no match, no special message is returned; the response is
        /// simply empty. </para> <para> You can use wildcards with the filter values: an asterisk matches zero or more characters, and <c>?</c> matches
        /// exactly one character. You can escape special characters using a backslash before the character. For example, a value of <c>\*amazon\?\\</c>
        /// searches for the literal string <c>*amazon?\</c> .
        /// </para>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the DescribeRouteTables service method on
        /// AmazonEC2.</param>
        /// 
        /// <returns>The response from the DescribeRouteTables service method, as returned by AmazonEC2.</returns>
		public DescribeRouteTablesResponse DescribeRouteTables(DescribeRouteTablesRequest request)
        {
            var task = DescribeRouteTablesAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                throw e.InnerException;
            }
        }
        /// <summary>
        /// Describes one or more of your route tables. 
        /// 
        ///  
        /// <para>
        /// Each subnet in your VPC must be associated with a route table. If a subnet is not
        /// explicitly associated with any route table, it is implicitly associated with the main
        /// route table. This command does not return the subnet ID for implicit associations.
        /// </para>
        ///  
        /// <para>
        /// For more information about route tables, see <a href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Route_Tables.html">Route
        /// Tables</a> in the <i>Amazon Virtual Private Cloud User Guide</i>.
        /// </para>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the DescribeRouteTables service method.</param>
        /// 
        /// <returns>The response from the DescribeRouteTables service method, as returned by EC2.</returns>
        public DescribeRouteTablesResponse DescribeRouteTables(DescribeRouteTablesRequest request)
        {
            var marshaller = new DescribeRouteTablesRequestMarshaller();
            var unmarshaller = DescribeRouteTablesResponseUnmarshaller.Instance;

            return Invoke<DescribeRouteTablesRequest,DescribeRouteTablesResponse>(request, marshaller, unmarshaller);
        }
        /// <summary>
        /// Initiates the asynchronous execution of the DescribeRouteTables operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the DescribeRouteTables 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<DescribeRouteTablesResponse> DescribeRouteTablesAsync(DescribeRouteTablesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new DescribeRouteTablesRequestMarshaller();
            var unmarshaller = DescribeRouteTablesResponseUnmarshaller.Instance;

            return InvokeAsync<DescribeRouteTablesRequest,DescribeRouteTablesResponse>(request, marshaller, 
                unmarshaller, cancellationToken);
        }
Пример #17
0
 private Amazon.EC2.Model.DescribeRouteTablesResponse CallAWSServiceOperation(IAmazonEC2 client, Amazon.EC2.Model.DescribeRouteTablesRequest request)
 {
     Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Elastic Compute Cloud (EC2)", "DescribeRouteTables");
     try
     {
         #if DESKTOP
         return(client.DescribeRouteTables(request));
         #elif CORECLR
         return(client.DescribeRouteTablesAsync(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;
     }
 }