コード例 #1
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.DescribeInstanceStatusRequest();

            if (cmdletContext.Filter != null)
            {
                request.Filters = cmdletContext.Filter;
            }
            if (cmdletContext.IncludeAllInstance != null)
            {
                request.IncludeAllInstances = cmdletContext.IncludeAllInstance.Value;
            }
            if (cmdletContext.InstanceId != null)
            {
                request.InstanceIds = cmdletContext.InstanceId;
            }
            if (cmdletContext.MaxResult != null)
            {
                request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToServiceTypeInt32(cmdletContext.MaxResult.Value);
            }

            // 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);
        }
コード例 #2
0
 IAsyncResult invokeDescribeInstanceStatus(DescribeInstanceStatusRequest describeInstanceStatusRequest, AsyncCallback callback, object state, bool synchronized)
 {
     IRequest irequest = new DescribeInstanceStatusRequestMarshaller().Marshall(describeInstanceStatusRequest);
     var unmarshaller = DescribeInstanceStatusResponseUnmarshaller.GetInstance();
     AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
     Invoke(result);
     return result;
 }
コード例 #3
0
 /// <summary>
 /// Paginator for DescribeInstanceStatus operation
 ///</summary>
 public IDescribeInstanceStatusPaginator DescribeInstanceStatus(DescribeInstanceStatusRequest request)
 {
     return(new DescribeInstanceStatusPaginator(this.client, request));
 }
コード例 #4
0
 /// <summary>
 /// <para>Describes the status of one or more instances, including any scheduled events.</para> <para>Instance status has two main
 /// components:</para>
 /// <ul>
 /// <li> <para>System Status reports impaired functionality that stems from issues related to the systems that support an instance, such as
 /// such as hardware failures and network connectivity problems. This call reports such problems as impaired reachability.</para> </li>
 /// <li> <para>Instance Status reports impaired functionality that arises from problems internal to the instance. This call reports such
 /// problems as impaired reachability.</para> </li>
 /// 
 /// </ul>
 /// <para>Instance status provides information about four types of scheduled events for an instance that may require your attention:</para>
 /// <ul>
 /// <li> <para>Scheduled Reboot: When Amazon EC2 determines that an instance must be rebooted, the instances status returns one of two event
 /// codes: <c>system-reboot</c> or <c>instance-reboot</c> . System reboot commonly occurs if certain maintenance or upgrade operations require a
 /// reboot of the underlying host that supports an instance. Instance reboot commonly occurs if the instance must be rebooted, rather than the
 /// underlying host. Rebooting events include a scheduled start and end time.</para> </li>
 /// <li> <para>System Maintenance: When Amazon EC2 determines that an instance requires maintenance that requires power or network impact, the
 /// instance status is the event code <c>system-maintenance</c> . System maintenance is either power maintenance or network maintenance. For
 /// power maintenance, your instance will be unavailable for a brief period of time and then rebooted. For network maintenance, your instance
 /// will experience a brief loss of network connectivity. System maintenance events include a scheduled start and end time. You will also be
 /// notified by email if one of your instances is set for system maintenance. The email message indicates when your instance is scheduled for
 /// maintenance.</para> </li>
 /// <li> <para>Scheduled Retirement: When Amazon EC2 determines that an instance must be shut down, the instance status is the event code
 /// <c>instance-retirement</c> . Retirement commonly occurs when the underlying host is degraded and must be replaced. Retirement events include
 /// a scheduled start and end time. You will also be notified by email if one of your instances is set to retiring. The email message indicates
 /// when your instance will be permanently retired.</para> </li>
 /// <li> <para>Scheduled Stop: When Amazon EC2 determines that an instance must be shut down, the instances status returns an event code called
 /// <c>instance-stop</c> .
 /// Stop events include a scheduled start and end time. You will also be notified by email if one of your instances is set to stop. The
 /// email message indicates when your instance will be stopped.</para> </li>
 /// 
 /// </ul>
 /// <para>When your instance is retired, it will either be terminated (if its root device type is the instance-store) or stopped (if its root
 /// device type is an EBS volume). Instances stopped due to retirement will not be restarted, but you can do so manually. You can also avoid
 /// retirement of EBS-backed instances by manually restarting your instance when its event code is <c>instance-retirement</c> . This ensures
 /// that your instance is started on a different underlying host.</para>
 /// </summary>
 /// 
 /// <param name="describeInstanceStatusRequest">Container for the necessary parameters to execute the DescribeInstanceStatus service method on
 ///          AmazonEC2.</param>
 /// 
 /// <returns>The response from the DescribeInstanceStatus service method, as returned by AmazonEC2.</returns>
 /// 
 public DescribeInstanceStatusResponse DescribeInstanceStatus(DescribeInstanceStatusRequest describeInstanceStatusRequest)
 {
     IAsyncResult asyncResult = invokeDescribeInstanceStatus(describeInstanceStatusRequest, null, null, true);
     return EndDescribeInstanceStatus(asyncResult);
 }
コード例 #5
0
 /// <summary>
 /// Initiates the asynchronous execution of the DescribeInstanceStatus operation.
 /// <seealso cref="Amazon.EC2.IAmazonEC2.DescribeInstanceStatus"/>
 /// </summary>
 /// 
 /// <param name="describeInstanceStatusRequest">Container for the necessary parameters to execute the DescribeInstanceStatus 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
 ///         EndDescribeInstanceStatus operation.</returns>
 public IAsyncResult BeginDescribeInstanceStatus(DescribeInstanceStatusRequest describeInstanceStatusRequest, AsyncCallback callback, object state)
 {
     return invokeDescribeInstanceStatus(describeInstanceStatusRequest, callback, state, false);
 }
コード例 #6
0
        /// <summary>
        /// Describes the status of one or more instances.
        /// 
        ///  
        /// <para>
        /// Instance status includes the following components:
        /// </para>
        ///  <ul> <li> 
        /// <para>
        /// <b>Status checks</b> - Amazon EC2 performs status checks on running EC2 instances
        /// to identify hardware and software issues. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-system-instance-status-check.html">Status
        /// Checks for Your Instances</a> and <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstances.html">Troubleshooting
        /// Instances with Failed Status Checks</a> in the <i>Amazon Elastic Compute Cloud User
        /// Guide</i>.
        /// </para>
        ///  </li> <li> 
        /// <para>
        /// <b>Scheduled events</b> - Amazon EC2 can schedule events (such as reboot, stop, or
        /// terminate) for your instances related to hardware issues, software updates, or system
        /// maintenance. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-instances-status-check_sched.html">Scheduled
        /// Events for Your Instances</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
        /// </para>
        ///  </li> <li> 
        /// <para>
        /// <b>Instance state</b> - You can manage your instances from the moment you launch them
        /// through their termination. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html">Instance
        /// Lifecycle</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
        /// </para>
        ///  </li> </ul>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the DescribeInstanceStatus service method.</param>
        /// 
        /// <returns>The response from the DescribeInstanceStatus service method, as returned by EC2.</returns>
        public DescribeInstanceStatusResponse DescribeInstanceStatus(DescribeInstanceStatusRequest request)
        {
            var marshaller = new DescribeInstanceStatusRequestMarshaller();
            var unmarshaller = DescribeInstanceStatusResponseUnmarshaller.Instance;

            return Invoke<DescribeInstanceStatusRequest,DescribeInstanceStatusResponse>(request, marshaller, unmarshaller);
        }
コード例 #7
0
        /// <summary>
        /// Gets the data for EC2 Instances in a given Profile and Region.
        /// </summary>
        /// <param name="aprofile"></param>
        /// <param name="Region2Scan"></param>
        /// <returns></returns>
        public DataTable GetEC2Instances(string aprofile, string Region2Scan)
        {
            DataTable ToReturn = AWSTables.GetComponentTable("EC2");
            RegionEndpoint Endpoint2scan = RegionEndpoint.USEast1;
            Amazon.Runtime.AWSCredentials credential;
            credential = new Amazon.Runtime.StoredProfileAWSCredentials(aprofile);
            //Convert the Region2Scan to an AWS Endpoint.
            foreach (var aregion in RegionEndpoint.EnumerableAllRegions)
            {
                if (aregion.DisplayName.Equals(Region2Scan))
                {
                    Endpoint2scan = aregion;
                    continue;
                }
            }

            var ec2 = new Amazon.EC2.AmazonEC2Client(credential, Endpoint2scan);
            string accountid = GetAccountID(aprofile);
            var request = new DescribeInstanceStatusRequest();



            

            request.IncludeAllInstances = true;
            DescribeInstanceStatusResponse instatresponse = new DescribeInstanceStatusResponse();
            var indatarequest = new DescribeInstancesRequest();
            try
            {
                instatresponse = ec2.DescribeInstanceStatus(request);
            }
            catch (Exception ex)
            {
                string test = "";//Quepaso? 
            }

            //Get a list of the InstanceIDs.
            foreach (var instat in instatresponse.InstanceStatuses)
            {
                indatarequest.InstanceIds.Add(instat.InstanceId);
                indatarequest.InstanceIds.Sort();
            }

            DescribeInstancesResponse DescResult = ec2.DescribeInstances();
           
            int count = instatresponse.InstanceStatuses.Count();

            //Build data dictionary of instances
            Dictionary<String, Instance> Bunchadata = new Dictionary<string, Instance>();
            foreach (var urtburgle in DescResult.Reservations)
            {
                foreach (var instancedata in urtburgle.Instances)
                {
                    try { Bunchadata.Add(instancedata.InstanceId, instancedata); }
                    catch (Exception ex) {
                        var ff ="";//a duplicate??
                    };
                }
            }

            //Go through list of instances...
            foreach (var instat in instatresponse.InstanceStatuses)
            {
                
                string instanceid = instat.InstanceId;
                Instance thisinstance = new Instance();
                try
                {
                    thisinstance = Bunchadata[instanceid];
                }
                catch(Exception ex)
                {

                    continue;
                }
                DataRow thisinstancedatarow = ToReturn.NewRow();
                //Collect the datases
                string instancename = "";
                var status = instat.Status.Status;
                string AZ = instat.AvailabilityZone;
                var istate = instat.InstanceState.Name;

                string profile = aprofile;
                string myregion = Region2Scan;
                int eventnumber = instat.Events.Count();
                List<string> eventlist = new List<string>();
                var reservations = DescResult.Reservations;

                var myinstance = new Reservation();

                var atreq = new DescribeInstanceAttributeRequest();
                atreq.InstanceId = instanceid;
                atreq.Attribute = "disableApiTermination";
                var atresp = ec2.DescribeInstanceAttribute(atreq).InstanceAttribute;
                string TerminationProtection = atresp.DisableApiTermination.ToString();

                List<String> innies = new List<String>();
                foreach (Reservation arez in DescResult.Reservations)
                {
                    var checky = arez.Instances[0].InstanceId;
                    innies.Add(checky);
                    if (arez.Instances[0].InstanceId.Equals(instanceid))
                    {
                        myinstance = arez;
                    }
                }
                innies.Sort();

                List<string> tags = new List<string>();
                var loadtags = thisinstance.Tags.AsEnumerable();
                foreach (var atag in loadtags)
                {
                    tags.Add(atag.Key + ": " + atag.Value);
                    if (atag.Key.Equals("Name")) instancename = atag.Value;
                }

                Dictionary<string, string> taglist = new Dictionary<string, string>();
                foreach (var rekey in loadtags)
                {
                    taglist.Add(rekey.Key, rekey.Value);
                }

                if (eventnumber > 0)
                {
                    foreach (var anevent in instat.Events)
                    {
                        eventlist.Add(anevent.Description);
                    }
                }
                String platform = "";
                try { platform = thisinstance.Platform.Value; }
                catch { platform = "Linux"; }
                if (String.IsNullOrEmpty(platform)) platform = "Linux";


                String Priv_IP = "";
                try { Priv_IP = thisinstance.PrivateIpAddress; }
                catch { }
                if (String.IsNullOrEmpty(Priv_IP))
                {
                    Priv_IP = "?";
                }
                
                String disinstance = thisinstance.InstanceId;

                String publicIP = "";
                try { publicIP = thisinstance.PublicIpAddress; }
                catch { }
                if (String.IsNullOrEmpty(publicIP)) publicIP = "";

                

                String publicDNS = "";
                try { publicDNS = thisinstance.PublicDnsName; }
                catch { }
                if (String.IsNullOrEmpty(publicDNS)) publicDNS = "";

                string myvpcid = "";
                try
                { myvpcid = thisinstance.VpcId; }
                catch { }
                if (String.IsNullOrEmpty(myvpcid)) myvpcid = "";
                

                string mysubnetid = "";
                try { mysubnetid = thisinstance.SubnetId; }
                catch { }
                if (String.IsNullOrEmpty(mysubnetid)) mysubnetid = "";


                //Virtualization type (HVM, Paravirtual)
                string ivirtType = "";
                try
                { ivirtType = thisinstance.VirtualizationType; }
                catch { }
                if (String.IsNullOrEmpty(ivirtType)) ivirtType = "?";

                // InstanceType (m3/Large etc)
                String instancetype = "";
                try
                { instancetype = thisinstance.InstanceType.Value; }
                catch { }
                if (String.IsNullOrEmpty(instancetype)) instancetype = "?";


                //Test section to try to pull out AMI data
                string AMI = "";
                string AMIName = "";
                string AMIDesc = "";
                string AMILocation = "";
                string AMIState = "";
                try { AMI = thisinstance.ImageId; }
                catch { }
                if (string.IsNullOrEmpty(AMI)) AMI = "";
                else
                {
                    DescribeImagesRequest DIR = new DescribeImagesRequest();
                    DIR.ImageIds.Add(AMI);
                    var imresp = ec2.DescribeImages(DIR);
                    var idata = imresp.Images;
                    try {
                        if (idata.Count > 0)
                        {
                            AMIDesc = idata[0].Description;
                            AMIName = idata[0].Name;
                            AMILocation = idata[0].ImageLocation;
                            AMIState = idata[0].State;

                        }
                        else
                        {
                            AMIDesc = "na";
                            AMIName = "na";
                            AMILocation = "na";
                            AMIState = "na";
                        }
                        if (String.IsNullOrEmpty(AMIDesc)) { AMIDesc = ""; }
                        if (String.IsNullOrEmpty(AMIName)) { AMIName = ""; }
                    }
                    catch(Exception ex)
                    {
                        string whyforerror = ex.Message;
                    }
                 
                }

                //
                var SGs = thisinstance.SecurityGroups;
                List<string> SGids = new List<string>();
                List<String> SGNames = new List<string>();
                foreach (var wabbit in SGs)
                {
                    SGids.Add(wabbit.GroupId);
                    SGNames.Add(wabbit.GroupName);
                }



                //Add to table
                if (SGids.Count < 1) SGids.Add("NullOrEmpty");
                if (SGNames.Count < 1) SGNames.Add("");
                if (String.IsNullOrEmpty(SGids[0])) SGids[0] = "NullOrEmpty";
                if (String.IsNullOrEmpty(SGNames[0])) SGNames[0] = "";

                if (String.IsNullOrEmpty(instancename)) instancename = "";


                //EC2DetailsTable.Rows.Add(accountid, profile, myregion, instancename, instanceid, AMI, AMIDesc, AZ, platform, status, eventnumber, eventlist, tags, Priv_IP, publicIP, publicDNS, istate, ivirtType, instancetype, sglist);
                //Is list for Profile and Region, so can key off of InstanceID. In theory InstanceID is unique

                //Build our dictionary of values and keys for this instance  This is dependent on the table created by GetEC2DetailsTable()
                Dictionary<string, string> datafields = new Dictionary<string, string>();
                thisinstancedatarow["AccountID"] = accountid;
                thisinstancedatarow["Profile"] = profile;
                thisinstancedatarow["Region"] = myregion;
                thisinstancedatarow["InstanceName"] = instancename;
                thisinstancedatarow["InstanceID"] = instanceid;
                thisinstancedatarow["TerminationProtection"] = TerminationProtection;
                thisinstancedatarow["AMI"] = AMI;
                thisinstancedatarow["AMIState"] = AMIState;
                thisinstancedatarow["AMILocation"] = AMILocation;
                thisinstancedatarow["AMIDescription"] = AMIDesc;
                thisinstancedatarow["AvailabilityZone"] = AZ;
                thisinstancedatarow["Status"] = status;
                thisinstancedatarow["Events"] = eventnumber.ToString();
                thisinstancedatarow["EventList"] = List2String(eventlist);
                thisinstancedatarow["Tags"] = List2String(tags);
                thisinstancedatarow["PrivateIP"] = Priv_IP;
                thisinstancedatarow["PublicIP"] = publicIP;
                thisinstancedatarow["PublicDNS"] = publicDNS;
                thisinstancedatarow["PublicDNS"] = publicDNS;
                thisinstancedatarow["VPC"] = myvpcid;
                thisinstancedatarow["SubnetID"] = mysubnetid;
                thisinstancedatarow["InstanceState"] = istate.Value;
                thisinstancedatarow["VirtualizationType"] = ivirtType;
                thisinstancedatarow["InstanceType"] = instancetype;
                thisinstancedatarow["SecurityGroups"] = List2String(SGids);
                thisinstancedatarow["SGNames"] = List2String(SGNames);
                //Add this instance to the data returned.
                ToReturn.Rows.Add(thisinstancedatarow);


            }//End for of instances



            return ToReturn;
        }//EndGetEC2
コード例 #8
0
        /// <summary>
        /// <para> Describes the status of an Amazon Elastic Compute Cloud (Amazon EC2) instance. Instance status provides information about two types
        /// of scheduled events for an instance that may require your attention: </para>
        /// <ul>
        /// <li> Scheduled Reboot: When Amazon EC2 determines that an instance must be rebooted, the instance's status will return one of two event
        /// codes: <c>system-reboot</c> or <c>instance-reboot</c> . System reboot commonly occurs if certain maintenance or upgrade operations require a
        /// reboot of the underlying host that supports an instance. Instance reboot commonly occurs if the instance must be rebooted, rather than the
        /// underlying host. Rebooting events include a scheduled start and end time. </li>
        /// <li> Scheduled Retirement: When Amazon EC2 determines that an instance must be shut down, the instance's status will return an event code
        /// called <c>instance-retirement</c> . Retirement commonly occurs when the underlying host is degraded and must be replaced. Retirement events
        /// include a scheduled start and end time. You're also notified by email if one of your instances is set to retiring. The email message
        /// indicates when your instance will be permanently retired. </li>
        /// 
        /// </ul>
        /// <para> If your instance is permanently retired, it will not be restarted. You can avoid retirement by manually restarting your instance
        /// when its event code is <c>instance-retirement</c> . This ensures that your instance is started on a healthy host. </para> <para>
        /// <c>DescribeInstanceStatus</c> returns information only for instances in the running state. </para> <para> You can filter the results to
        /// return information only about instances that match criteria you specify. For example, you could get information about instances in a
        /// specific Availability Zone. You can specify multiple values for a filter (e.g., more than one Availability Zone). An instance must match at
        /// least one of the specified values for it to be included in the results. </para> <para> You can specify multiple filters. An instance must
        /// match all the filters for it to be included in the results. 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: <c>*</c> 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> <para> The following filters are available: </para>
        /// <ul>
        /// <li> <c>availability-zone</c> - Filter on an instance's availability zone. </li>
        /// <li> <c>instance-state-name</c> - Filter on the intended state of the instance, e.g., running. </li>
        /// <li> <c>instance-state-code</c> - Filter on the intended state code of the instance, e.g., 16. </li>
        /// 
        /// </ul>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the DescribeInstanceStatus service method on
        /// AmazonEC2.</param>
        /// 
        /// <returns>The response from the DescribeInstanceStatus service method, as returned by AmazonEC2.</returns>
		public DescribeInstanceStatusResponse DescribeInstanceStatus(DescribeInstanceStatusRequest request)
        {
            var task = DescribeInstanceStatusAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                throw e.InnerException;
            }
        }
コード例 #9
0
        /// <summary>
        /// Initiates the asynchronous execution of the DescribeInstanceStatus operation.
        /// <seealso cref="Amazon.EC2.IAmazonEC2.DescribeInstanceStatus"/>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the DescribeInstanceStatus 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<DescribeInstanceStatusResponse> DescribeInstanceStatusAsync(DescribeInstanceStatusRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new DescribeInstanceStatusRequestMarshaller();
            var unmarshaller = DescribeInstanceStatusResponseUnmarshaller.GetInstance();
            var response = await Invoke<IRequest, DescribeInstanceStatusRequest, DescribeInstanceStatusResponse>(request, marshaller, unmarshaller, signer, cancellationToken)
                .ConfigureAwait(continueOnCapturedContext: false);
            return response;
        }
コード例 #10
0
ファイル: EC2.cs プロジェクト: koushikajay/Alfred
 public List<InstanceStatus> InstanceStatus(IEnumerable<string> instanceIds)
 {
     var request = new DescribeInstanceStatusRequest().WithInstanceId(instanceIds.ToArray());
     var response = this.client.DescribeInstanceStatus(request);
     return response.DescribeInstanceStatusResult.InstanceStatus;
 }
コード例 #11
0
 internal DescribeInstanceStatusPaginator(IAmazonEC2 client, DescribeInstanceStatusRequest request)
 {
     this._client  = client;
     this._request = request;
 }
コード例 #12
0
        /// <summary>
        ///     This method waits for all instances passed in to be marked as running in AWS. I assume
        ///     we can start using them once they are running :)
        /// </summary>
        /// <param name="ec2Client"></param>
        /// <param name="instanceIds"></param>
        private void WaitForInstancesToBeRunning(AmazonEC2Client ec2Client, List<string> instanceIds)
        {
            List<IsAgentReady> agentsThatAreReady =
                instanceIds.Select(instanceId => new IsAgentReady {InstanceID = instanceId, IsReady = false}).ToList();

            while (agentsThatAreReady.Any(x => x.IsReady == false))
            {
                foreach (string instanceId in instanceIds)
                {
                    //first check this isnt already ready
                    bool already = agentsThatAreReady.Any(x => x.InstanceID == instanceId && x.IsReady);

                    if (already) continue;
                    //get its status
                    var describeInstanceStatusRequest = new DescribeInstanceStatusRequest
                    {
                        InstanceIds = new List<string>
                        {
                            instanceId
                        }
                    };
                    DescribeInstanceStatusResponse response =
                        ec2Client.DescribeInstanceStatus(describeInstanceStatusRequest);
                    if (response.InstanceStatuses.Count > 0 &&
                        response.InstanceStatuses[0].InstanceState.Name == InstanceStateName.Running)
                    {
                        IsAgentReady agent = agentsThatAreReady.First(x => x.InstanceID == instanceId);
                        agent.IsReady = true;
                    }
                }
            }
        }
コード例 #13
0
 private void MakeSureAgentsCanBeUsed(AmazonEC2Client ec2Client, List<string> instanceIds)
 {
     List<IsAgentReady> agentsThatAreReady =
         instanceIds.Select(instanceId => new IsAgentReady {InstanceID = instanceId, IsReady = false}).ToList();
     while (agentsThatAreReady.Any(x => x.IsReady == false))
     {
         foreach (string instanceId in instanceIds)
         {
             bool already = agentsThatAreReady.Any(x => x.InstanceID == instanceId && x.IsReady);
             if (already) continue;
             var resquest = new DescribeInstanceStatusRequest
             {
                 InstanceIds = new List<string>
                 {
                     instanceId
                 }
             };
             DescribeInstanceStatusResponse response = ec2Client.DescribeInstanceStatus(resquest);
             if (response.InstanceStatuses.Count > 0 &&
                 response.InstanceStatuses[0].SystemStatus.Status == SummaryStatus.Ok &&
                 response.InstanceStatuses[0].Status.Status == SummaryStatus.Ok)
             {
                 IsAgentReady agent = agentsThatAreReady.First(x => x.InstanceID == instanceId);
                 agent.IsReady = true;
             }
         }
     }
 }
コード例 #14
0
ファイル: EC2Manager.cs プロジェクト: SharpeRAD/Cake.AWS.EC2
            /// <summary>
            /// Describes the status of one or more instances. Instance status includes the following components:
            /// Status checks - Amazon EC2 performs status checks on running EC2 instances to identify hardware and software issues. For more information, see Status Checks
            /// for Your Instances and Troubleshooting Instances with Failed Status Checks in the Amazon Elastic Compute Cloud User Guide.
            /// Scheduled events - Amazon EC2 can schedule events (such as reboot, stop, or terminate) for your instances related to hardware issues, software updates, or system maintenance.
            /// For more information, see Scheduled Events for Your Instances in the Amazon Elastic Compute Cloud User Guide.
            /// Instance state - You can manage your instances from the moment you launch them through their termination. For more information, see Instance Lifecycle in the Amazon Elastic Compute Cloud User Guide.
            /// </summary>
            /// <param name="instances">A list of instance IDs to be stopped.</param>
            /// <param name="settings">The <see cref="EC2Settings"/> used during the request to AWS.</param>
            public IList<InstanceStatus> DescribeInstances(IList<string> instances, EC2Settings settings)
            {
                if ((instances == null) || (instances.Count == 0))
                {
                    throw new ArgumentNullException("instances");
                }



                //Create Request
                AmazonEC2Client client = this.CreateClient(settings);
                DescribeInstanceStatusRequest request = new DescribeInstanceStatusRequest();

                foreach (string instance in instances)
                {
                    request.InstanceIds.Add(instance);
                }



                //Check Response
                DescribeInstanceStatusResponse response = client.DescribeInstanceStatus(request);

                if (response.HttpStatusCode == HttpStatusCode.OK)
                {
                    _Log.Verbose("Successfully terminated instances '{0}'", string.Join(",", instances));
                    return response.InstanceStatuses;
                }
                else
                {
                    _Log.Error("Failed to terminate instances '{0}'", string.Join(",", instances));
                    return new List<InstanceStatus>();
                }
            }
コード例 #15
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.DescribeInstanceStatusRequest();

            if (cmdletContext.Filter != null)
            {
                request.Filters = cmdletContext.Filter;
            }
            if (cmdletContext.IncludeAllInstance != null)
            {
                request.IncludeAllInstances = cmdletContext.IncludeAllInstance.Value;
            }
            if (cmdletContext.InstanceId != null)
            {
                request.InstanceIds = cmdletContext.InstanceId;
            }

            // 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)
            {
                _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)
                {
                    request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToInt32(_emitLimit.Value);
                }

                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.InstanceStatuses.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 >= 1));


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


            return(null);
        }
コード例 #16
0
ファイル: AmazonEC2Client.cs プロジェクト: virajs/aws-sdk-net
		internal DescribeInstanceStatusResponse DescribeInstanceStatus(DescribeInstanceStatusRequest request)
        {
            var task = DescribeInstanceStatusAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                ExceptionDispatchInfo.Capture(e.InnerException).Throw();
                return null;
            }
        }
コード例 #17
0
ファイル: AmazonEC2Client.cs プロジェクト: aws/aws-sdk-net
        /// <summary>
        /// Initiates the asynchronous execution of the DescribeInstanceStatus operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the DescribeInstanceStatus 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 EndDescribeInstanceStatus
        ///         operation.</returns>
        public IAsyncResult BeginDescribeInstanceStatus(DescribeInstanceStatusRequest request, AsyncCallback callback, object state)
        {
            var marshaller = new DescribeInstanceStatusRequestMarshaller();
            var unmarshaller = DescribeInstanceStatusResponseUnmarshaller.Instance;

            return BeginInvoke<DescribeInstanceStatusRequest>(request, marshaller, unmarshaller,
                callback, state);
        }
コード例 #18
0
ファイル: AmazonEC2Client.cs プロジェクト: virajs/aws-sdk-net
        /// <summary>
        /// <para>Describes the status of one or more instances, including any scheduled events.</para> <para>Instance status has two main
        /// components:</para>
        /// <ul>
        /// <li> <para>System Status reports impaired functionality that stems from issues related to the systems that support an instance, such as
        /// such as hardware failures and network connectivity problems. This call reports such problems as impaired reachability.</para> </li>
        /// <li> <para>Instance Status reports impaired functionality that arises from problems internal to the instance. This call reports such
        /// problems as impaired reachability.</para> </li>
        /// 
        /// </ul>
        /// <para>Instance status provides information about four types of scheduled events for an instance that may require your attention:</para>
        /// <ul>
        /// <li> <para>Scheduled Reboot: When Amazon EC2 determines that an instance must be rebooted, the instances status returns one of two event
        /// codes: <c>system-reboot</c> or <c>instance-reboot</c> . System reboot commonly occurs if certain maintenance or upgrade operations require a
        /// reboot of the underlying host that supports an instance. Instance reboot commonly occurs if the instance must be rebooted, rather than the
        /// underlying host. Rebooting events include a scheduled start and end time.</para> </li>
        /// <li> <para>System Maintenance: When Amazon EC2 determines that an instance requires maintenance that requires power or network impact, the
        /// instance status is the event code <c>system-maintenance</c> . System maintenance is either power maintenance or network maintenance. For
        /// power maintenance, your instance will be unavailable for a brief period of time and then rebooted. For network maintenance, your instance
        /// will experience a brief loss of network connectivity. System maintenance events include a scheduled start and end time. You will also be
        /// notified by email if one of your instances is set for system maintenance. The email message indicates when your instance is scheduled for
        /// maintenance.</para> </li>
        /// <li> <para>Scheduled Retirement: When Amazon EC2 determines that an instance must be shut down, the instance status is the event code
        /// <c>instance-retirement</c> . Retirement commonly occurs when the underlying host is degraded and must be replaced. Retirement events include
        /// a scheduled start and end time. You will also be notified by email if one of your instances is set to retiring. The email message indicates
        /// when your instance will be permanently retired.</para> </li>
        /// <li> <para>Scheduled Stop: When Amazon EC2 determines that an instance must be shut down, the instances status returns an event code called
        /// <c>instance-stop</c> .
        /// Stop events include a scheduled start and end time. You will also be notified by email if one of your instances is set to stop. The
        /// email message indicates when your instance will be stopped.</para> </li>
        /// 
        /// </ul>
        /// <para>When your instance is retired, it will either be terminated (if its root device type is the instance-store) or stopped (if its root
        /// device type is an EBS volume). Instances stopped due to retirement will not be restarted, but you can do so manually. You can also avoid
        /// retirement of EBS-backed instances by manually restarting your instance when its event code is <c>instance-retirement</c> . This ensures
        /// that your instance is started on a different underlying host.</para>
        /// </summary>
        /// 
        /// <param name="describeInstanceStatusRequest">Container for the necessary parameters to execute the DescribeInstanceStatus service method on
        /// AmazonEC2.</param>
        /// 
        /// <returns>The response from the DescribeInstanceStatus 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<DescribeInstanceStatusResponse> DescribeInstanceStatusAsync(DescribeInstanceStatusRequest describeInstanceStatusRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new DescribeInstanceStatusRequestMarshaller();
            var unmarshaller = DescribeInstanceStatusResponseUnmarshaller.GetInstance();
            return Invoke<IRequest, DescribeInstanceStatusRequest, DescribeInstanceStatusResponse>(describeInstanceStatusRequest, marshaller, unmarshaller, signer, cancellationToken);
        }
コード例 #19
0
        /// <summary>
        /// Initiates the asynchronous execution of the DescribeInstanceStatus operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the DescribeInstanceStatus 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<DescribeInstanceStatusResponse> DescribeInstanceStatusAsync(DescribeInstanceStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new DescribeInstanceStatusRequestMarshaller();
            var unmarshaller = DescribeInstanceStatusResponseUnmarshaller.Instance;

            return InvokeAsync<DescribeInstanceStatusRequest,DescribeInstanceStatusResponse>(request, marshaller, 
                unmarshaller, cancellationToken);
        }
コード例 #20
0
        public Dictionary<string, DataTable> ScanProfile(ScanRequest Request)
        {
            Dictionary<string, DataTable> ScanResults = new Dictionary<string, DataTable>();
            DataTable UserDetailsTable = GetUsersDetailsTable();
            DataTable EC2DetailsTable = GetEC2DetailsTable();
            DataTable S3DetailsTable = GetS3DetailsTable();
            string accountid = "";
            Amazon.Runtime.AWSCredentials credential;
            var aprofile = Request.Profile;
            var regions2process = Request.Regions;
            var SubmitResults = Request.ResultQueue;
            try
            {
                credential = new Amazon.Runtime.StoredProfileAWSCredentials(aprofile);
                //Try to get the AccountID ID//

                #region UserDetails
                var iam = new AmazonIdentityManagementServiceClient(credential);

                var myUserList = iam.ListUsers().Users;

                try
                {
                    accountid = myUserList[0].Arn.Split(':')[4];//Get the ARN and extract the AccountID ID
                    accountid = "ID: " + accountid;// Prefix added because Excel exsucks.
                }
                catch
                {
                    accountid = "?";
                }

                try // Send command to AWS to generate a Credential Report
                { var createcredreport = iam.GenerateCredentialReport(); }
                catch (Exception)
                { throw; }

                bool needreport = true;

                Amazon.IdentityManagement.Model.GetCredentialReportResponse credreport = new GetCredentialReportResponse();
                DateTime getreportstart = DateTime.Now;
                DateTime getreportfinish = DateTime.Now;
                while (needreport)
                {
                    try
                    {
                        credreport = iam.GetCredentialReport();
                        needreport = false;
                        getreportfinish = DateTime.Now;
                        var dif = getreportstart - getreportfinish;  //Just a check on how long it takes.

                        //Extract data from CSV Stream into DataTable
                        var streambert = credreport.Content;
                        streambert.Position = 0;
                        StreamReader sr = new StreamReader(streambert);
                        string myStringRow = sr.ReadLine();
                        if (myStringRow != null) myStringRow = sr.ReadLine();//Dump the header line
                        while (myStringRow != null)
                        {
                            var arow = myStringRow.Split(",".ToCharArray()[0]);

                            var newrow = new object[UserDetailsTable.Columns.Count];
                            newrow[0] = accountid;
                            newrow[1] = aprofile;
                            newrow[2] = ""; //UserID not in report. pull it later.
                            newrow[3] = arow[0];
                            newrow[4] = arow[1];
                            newrow[5] = arow[2];
                            newrow[6] = arow[3];
                            newrow[7] = arow[4];
                            newrow[8] = arow[5];
                            newrow[9] = arow[6];
                            newrow[10] = arow[7];
                            newrow[11] = arow[8];
                            newrow[12] = arow[9];
                            newrow[13] = arow[10];
                            newrow[14] = arow[11];
                            newrow[15] = arow[12];
                            newrow[16] = arow[13];
                            newrow[17] = arow[14];
                            newrow[18] = arow[15];
                            newrow[19] = arow[16];
                            newrow[20] = arow[17];
                            newrow[21] = arow[18];
                            newrow[22] = arow[19];
                            newrow[23] = arow[20];
                            newrow[24] = arow[21];
                            RawUsers.Rows.Add(newrow);
                            UserDetailsTable.Rows.Add(newrow);
                            myStringRow = sr.ReadLine();
                        }
                        sr.Close();
                        sr.Dispose();

                    }
                    catch (Exception ex)
                    {
                        string test = "";
                        //Deal with this later if necessary.
                    }
                }

                foreach (var auser in myUserList)//Fill in the userID.  Why?  because it exists.
                {
                    string auserid = auser.UserId;
                    string arn = auser.Arn;
                    string username = auser.UserName;
                    string policylist = "";
                    string aklist = "";
                    string groups = "";

                    ListAccessKeysRequest LAKREQ = new ListAccessKeysRequest();
                    LAKREQ.UserName = username;
                    ListAccessKeysResult LAKRES = iam.ListAccessKeys(LAKREQ);
                    foreach (var blivet in LAKRES.AccessKeyMetadata)
                    {
                        if (aklist.Length > 1) aklist += "\n";
                        aklist += blivet.AccessKeyId + "  :  " + blivet.Status;
                    }

                    ListAttachedUserPoliciesRequest LAUPREQ = new ListAttachedUserPoliciesRequest();
                    LAUPREQ.UserName = username;
                    ListAttachedUserPoliciesResult LAUPRES = iam.ListAttachedUserPolicies(LAUPREQ);
                    foreach (var apol in LAUPRES.AttachedPolicies)
                    {
                        if (policylist.Length > 1) policylist += "\n";
                        policylist += apol.PolicyName;
                    }

                    //Need to get policy and group info outta user
                    var groopsreq = new ListGroupsForUserRequest();
                    groopsreq.UserName = username;
                    ListGroupsForUserResult LG = iam.ListGroupsForUser(groopsreq);
                    foreach (var agroup in LG.Groups)
                    {
                        if (groups.Length > 1) groups += "\n";
                        groups += agroup.GroupName;
                    }

                    foreach (DataRow myrow in UserDetailsTable.Rows)
                    {
                        if (myrow["ARN"].Equals(arn))
                        {
                            myrow["UserID"] = auserid;
                            myrow["User-Policies"] = policylist;
                            myrow["Access-Keys"] = aklist;
                            myrow["Groups"] = groups;
                        }
                    }

                }
                #endregion

                #region S3Details
                try {

                AmazonS3Client S3Client = new AmazonS3Client(credential,Amazon.RegionEndpoint.USEast1);
                ListBucketsResponse response = S3Client.ListBuckets();
                foreach (S3Bucket abucket in response.Buckets)
                {

                    DataRow abucketrow = GetS3DetailsTable().NewRow();
                    var name = abucket.BucketName;

                    GetBucketLocationRequest gbr = new GetBucketLocationRequest();
                    gbr.BucketName=name;
                    GetBucketLocationResponse location = S3Client.GetBucketLocation(gbr);
                    var region = location.Location.Value;
                    if (region.Equals(""))region="us-east-1";
                    var pointy = RegionEndpoint.GetBySystemName(region);

                    //Build a config that references the buckets region.
                    AmazonS3Config S3C = new AmazonS3Config();
                    S3C.RegionEndpoint=pointy;
                    AmazonS3Client BS3Client = new AmazonS3Client(credential, S3C);

                    var createddate = abucket.CreationDate;
                    string owner = "";
                    string grants = "";
                    string tags = "";
                    string lastaccess = "";
                    string defaultpage = "";
                    string website = "";
                    //Now start pulling der einen data.

                    GetACLRequest GACR = new GetACLRequest();
                    GACR.BucketName = name;
                    var ACL = BS3Client.GetACL(GACR);
                    var grantlist = ACL.AccessControlList;
                    owner = grantlist.Owner.DisplayName;
                    foreach (var agrant in grantlist.Grants)
                    {
                        if (grants.Length > 1) grants += "\n";
                        var gName = agrant.Grantee.DisplayName;
                        var gType = agrant.Grantee.Type.Value;
                        var aMail = agrant.Grantee.EmailAddress;

                        if (gType.Equals("Group"))
                        {
                            grants +=  gType + " - " + agrant.Grantee.URI + " - " + agrant.Permission + " - " + aMail  ;
                        }
                        else
                        {
                            grants += gName + " - "+ agrant.Permission + " - " + aMail;
                        }
                    }

                    GetObjectMetadataRequest request = new GetObjectMetadataRequest();
                    request.BucketName = name;
                    GetObjectMetadataResponse MDresponse = BS3Client.GetObjectMetadata(request);
                    lastaccess = MDresponse.LastModified.ToString();
                    //defaultpage = MDresponse.WebsiteRedirectLocation;

                    GetBucketWebsiteRequest GBWReq = new GetBucketWebsiteRequest();
                    GBWReq.BucketName = name;
                    GetBucketWebsiteResponse GBWRes = BS3Client.GetBucketWebsite(GBWReq);

                    defaultpage = GBWRes.WebsiteConfiguration.IndexDocumentSuffix;

                    if (defaultpage != null)
                    {
                        website = @"http://" + name + @".s3-website-" + region + @".amazonaws.com/" + defaultpage;
                    }

                    //Amazon.S3.Model.req

                    abucketrow["AccountID"] = accountid;
                    abucketrow["Profile"] = aprofile;
                    abucketrow["Bucket"] = name;
                    abucketrow["Region"] = region;
                    abucketrow["CreationDate"] = createddate.ToString();
                    abucketrow["LastAccess"] = lastaccess;
                    abucketrow["Owner"] = owner;
                    abucketrow["Grants"] = grants;

                    abucketrow["WebsiteHosting"] = website;
                    abucketrow["Logging"] = "X";
                    abucketrow["Events"] = "X";
                    abucketrow["Versioning"] = "X";
                    abucketrow["LifeCycle"] = "X";
                    abucketrow["Replication"] = "X";
                    abucketrow["Tags"] = "X";
                    abucketrow["RequesterPays"] = "X";
                    S3DetailsTable.Rows.Add(abucketrow.ItemArray);
                }

                }
                catch(Exception ex)
                {

                    System.Windows.Forms.MessageBox.Show("S3 Failed!\n"+ex);
                }

                #endregion

                #region GetEC2Region

                //////////////////////////////////////////////////////////

                //Foreach aregion
                foreach (var aregion in regions2process)
                {
                    //Skip GovCloud and Beijing. They require special handling and I dont need em.
                    if (aregion == Amazon.RegionEndpoint.USGovCloudWest1) continue;
                    if (aregion == Amazon.RegionEndpoint.CNNorth1) continue;
                    var region = aregion;

                    regioncounter++;

                    //Try to get scheduled events on my Profile/aregion
                    var ec2 = AWSClientFactory.CreateAmazonEC2Client(credential, region);
                    var request = new DescribeInstanceStatusRequest();
                    request.IncludeAllInstances = true;
                    Dispatcher.Invoke(doupdatePbDelegate,
                       System.Windows.Threading.DispatcherPriority.Background,
                        new object[] { System.Windows.Controls.ProgressBar.ValueProperty, regioncounter });
                    var instatresponse = ec2.DescribeInstanceStatus(request);

                    var indatarequest = new DescribeInstancesRequest();

                    foreach (var instat in instatresponse.InstanceStatuses)
                    {

                        indatarequest.InstanceIds.Add(instat.InstanceId);
                    }
                    DescribeInstancesResult DescResult = ec2.DescribeInstances(indatarequest);

                    int count = instatresponse.InstanceStatuses.Count();

                    foreach (var instat in instatresponse.InstanceStatuses)
                    {
                        //Collect the datases
                        string instanceid = instat.InstanceId;
                        string instancename = "";
                        ProcessingLabel.Content = "Scanning -> Profile:" + aprofile + "    Region: " + region + "   Instance: " + instanceid;
                        Dispatcher.Invoke(doupdatePbDelegate,
                            System.Windows.Threading.DispatcherPriority.Background,
                            new object[] { System.Windows.Controls.ProgressBar.ValueProperty, regioncounter });

                        var status = instat.Status.Status;
                        string AZ = instat.AvailabilityZone;
                        var istate = instat.InstanceState.Name;

                        string profile = aprofile;
                        string myregion = region.ToString();
                        int eventnumber = instat.Events.Count();

                        string eventlist = "";
                        var urtburgle = DescResult.Reservations;

                        string tags = ""; // Holds the list of tags to print out.

                        var loadtags = (from t in DescResult.Reservations
                                        where t.Instances[0].InstanceId.Equals(instanceid)
                                        select t.Instances[0].Tags).AsEnumerable();

                        Dictionary<string, string> taglist = new Dictionary<string, string>();
                        foreach (var rekey in loadtags)
                        {
                            foreach (var kvp in rekey)
                            {
                                taglist.Add(kvp.Key, kvp.Value);
                            }
                        }

                        foreach (var atag in taglist)//Set instancename, and add value to combobox.
                        {
                            if (atag.Key.Equals("Name"))
                            {
                                instancename = atag.Value;
                            }
                            if (!TagFilterCombo.Items.Contains(atag.Key))
                            {
                                TagFilterCombo.Items.Add(atag.Key);
                            }
                            if (tags.Length > 1)
                            {
                                tags += "\n" + atag.Key + ":" + atag.Value;
                            }
                            else
                            {
                                tags += atag.Key + ":" + atag.Value;
                            }
                        }

                        if (eventnumber > 0)
                        {
                            foreach (var anevent in instat.Events)
                            {
                                eventlist += anevent.Description + "\n";
                            }
                        }

                        var platform = (from t in urtburgle
                                        where t.Instances[0].InstanceId.Equals(instanceid)
                                        select t.Instances[0].Platform).FirstOrDefault();
                        if (String.IsNullOrEmpty(platform)) platform = "Linux";

                        var Priv_IP = (from t in urtburgle
                                       where t.Instances[0].InstanceId.Equals(instanceid)
                                       select t.Instances[0].PrivateIpAddress).FirstOrDefault();
                        if (String.IsNullOrEmpty(Priv_IP)) Priv_IP = "?";

                        var publicIP = (from t in urtburgle
                                        where t.Instances[0].InstanceId.Equals(instanceid)
                                        select t.Instances[0].PublicIpAddress).FirstOrDefault();
                        if (String.IsNullOrEmpty(publicIP)) publicIP = "";

                        var publicDNS = (from t in urtburgle
                                         where t.Instances[0].InstanceId.Equals(instanceid)
                                         select t.Instances[0].PublicDnsName).FirstOrDefault();
                        if (String.IsNullOrEmpty(publicDNS)) publicDNS = "";

                        //Virtualization type (HVM, Paravirtual)
                        var ivirtType = (from t in urtburgle
                                         where t.Instances[0].InstanceId.Equals(instanceid)
                                         select t.Instances[0].VirtualizationType).FirstOrDefault();
                        if (String.IsNullOrEmpty(ivirtType)) ivirtType = "?";

                        // InstanceType (m3/Large etc)
                        var instancetype = (from t in urtburgle
                                            where t.Instances[0].InstanceId.Equals(instanceid)
                                            select t.Instances[0].InstanceType).FirstOrDefault();
                        if (String.IsNullOrEmpty(instancetype)) instancetype = "?";

                        var SGs = (from t in urtburgle
                                   where t.Instances[0].InstanceId.Equals(instanceid)
                                   select t.Instances[0].SecurityGroups);

                        string sglist = "";

                        if (SGs.Count() > 0)
                        {
                            foreach (var ansg in SGs.FirstOrDefault())
                            {
                                if (sglist.Length > 2) { sglist += "\n"; }
                                sglist += ansg.GroupName;
                            }
                        }
                        else
                        {
                            sglist = "_NONE!_";
                        }
                        //Add to table
                        if (String.IsNullOrEmpty(sglist)) sglist = "NullOrEmpty";

                        if (String.IsNullOrEmpty(instancename)) instancename = "";
                        string rabbit = accountid + profile + myregion + instancename + instanceid + AZ + status + eventnumber + eventlist + tags + Priv_IP + publicIP + publicDNS + istate + ivirtType + instancetype + sglist;

                        if(instancename.Contains("p1-job"))
                        {
                            string yup = "y";
                        }

                        EC2DetailsTable.Rows.Add(accountid, profile, myregion, instancename, instanceid, AZ, platform, status, eventnumber, eventlist, tags, Priv_IP, publicIP, publicDNS, istate, ivirtType, instancetype, sglist);

                    }

                }
                #endregion
                ScanResults.Add("EC2", EC2DetailsTable);
                ScanResults.Add("Users", UserDetailsTable);
                ScanResults.Add("S3", S3DetailsTable);

                return ScanResults;
            }
            catch (Exception ex)
            {
                //If we failed to connect with creds.

                string error = new string(ex.ToString().TakeWhile(c => c != '\n').ToArray());
                System.Windows.MessageBox.Show(error, Request.Profile.ToString() + " credentials failed to work.\n");
                //Try to flag the menu item so it no longer selectable, and maybe make she red.
                System.Windows.Controls.MenuItem Proot = (System.Windows.Controls.MenuItem)this.MainMenu.Items[1];
                foreach (System.Windows.Controls.MenuItem amenuitem in Proot.Items)
                {
                    if (amenuitem.Header.ToString() == aprofile.ToString())
                    {
                        amenuitem.IsCheckable = false;
                        amenuitem.IsChecked = false;
                        amenuitem.Background = Brushes.Red;
                        amenuitem.ToolTip = Request.Profile.ToString() + " credentials failed to work.\n";
                    }
                }

                ScanResults.Add("EC2", GetEC2DetailsTable());
                ScanResults.Add("Users", GetUsersDetailsTable());
                ScanResults.Add("S3", GetS3DetailsTable());

                return ScanResults;

            }
        }