private static void UnmarshallResult(XmlUnmarshallerContext context, DescribeStacksResponse response)
        {
            int originalDepth = context.CurrentDepth;
            int targetDepth   = originalDepth + 1;

            if (context.IsStartOfDocument)
            {
                targetDepth += 2;
            }

            while (context.ReadAtDepth(originalDepth))
            {
                if (context.IsStartElement || context.IsAttribute)
                {
                    if (context.TestExpression("NextToken", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        response.NextToken = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("Stacks/member", targetDepth))
                    {
                        var unmarshaller = StackUnmarshaller.Instance;
                        var item         = unmarshaller.Unmarshall(context);
                        response.Stacks.Add(item);
                        continue;
                    }
                }
            }

            return;
        }
Esempio n. 2
0
        private void SetupStackStatusSequence(string stackName, IList <string> statuses)
        {
            var i = 0;

            _cloudFormationMock
            .Setup(x => x.DescribeStacksAsync(
                       It.Is <DescribeStacksRequest>(s => s.StackName == stackName),
                       It.IsAny <CancellationToken>())
                   )
            .Returns(() =>
            {
                var result = new DescribeStacksResponse
                {
                    Stacks = new List <Stack>
                    {
                        new Stack
                        {
                            StackStatus = statuses[i],
                            StackName   = stackName
                        }
                    }
                };

                i++;
                return(Task.FromResult(result));
            });
        }
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            DescribeStacksResponse response = new DescribeStacksResponse();

            context.Read();
            int targetDepth = context.CurrentDepth;

            while (context.ReadAtDepth(targetDepth))
            {
                if (context.IsStartElement)
                {
                    if (context.TestExpression("DescribeStacksResult", 2))
                    {
                        UnmarshallResult(context, response);
                        continue;
                    }

                    if (context.TestExpression("ResponseMetadata", 2))
                    {
                        response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context);
                    }
                }
            }

            return(response);
        }
        public static async Task DeleteStack(string stackName, Credentials credentials)
        {
            Console.WriteLine($"\nDeleting stack {stackName}...");

            try
            {
                await GetClient(credentials).DescribeStacksAsync(new DescribeStacksRequest {
                    StackName = stackName
                });
            }
            catch (AmazonCloudFormationException exc) when(exc.Message.Contains("does not exist"))
            {
                Console.WriteLine("Stack does not exist");
                return;
            }

            DescribeStacksResponse response = await GetClient(credentials).DescribeStacksAsync(new DescribeStacksRequest {
                StackName = stackName
            });

            Stack stack = response.Stacks.First();

            Console.WriteLine(stack.StackId);
            await GetClient(credentials).DeleteStackAsync(new DeleteStackRequest {
                StackName = stack.StackId
            });
            await WaitForStackStatus(stack.StackId, StackStatus.DELETE_COMPLETE, credentials);
        }
Esempio n. 5
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonCloudFormationConfig config = new AmazonCloudFormationConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonCloudFormationClient client = new AmazonCloudFormationClient(creds, config);

            DescribeStacksResponse resp = new DescribeStacksResponse();

            do
            {
                DescribeStacksRequest req = new DescribeStacksRequest
                {
                    NextToken = resp.NextToken
                };

                resp = client.DescribeStacks(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.Stacks)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
        public static async Task <string> GetStackOutputValue(string stackName, string key)
        {
            var client = new AmazonCloudFormationClient();
            DescribeStacksResponse describeStacksResponse = await client.DescribeStacksAsync(new DescribeStacksRequest { StackName = stackName });

            return(describeStacksResponse.Stacks.First().Outputs.First(output => output.OutputKey == key).OutputValue);
        }
        public static async Task <StackStatus> GetStackStatus(string stackName)
        {
            var client = new AmazonCloudFormationClient();
            DescribeStacksResponse describeStacksResponse = await client.DescribeStacksAsync(new DescribeStacksRequest { StackName = stackName });

            return(describeStacksResponse.Stacks.First().StackStatus);
        }
Esempio n. 8
0
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            DescribeStacksResponse response = new DescribeStacksResponse();

            context.Read();
            int targetDepth = context.CurrentDepth;

            while (context.ReadAtDepth(targetDepth))
            {
                if (context.TestExpression("NextToken", targetDepth))
                {
                    var unmarshaller = StringUnmarshaller.Instance;
                    response.NextToken = unmarshaller.Unmarshall(context);
                    continue;
                }
                if (context.TestExpression("Stacks", targetDepth))
                {
                    var unmarshaller = new ListUnmarshaller <Stack, StackUnmarshaller>(StackUnmarshaller.Instance);
                    response.Stacks = unmarshaller.Unmarshall(context);
                    continue;
                }
            }

            return(response);
        }
        /// <summary>
        /// <para> Returns the description for the specified stack; if no stack name was specified, then it returns the description for all the stacks
        /// created. </para>
        /// </summary>
        ///
        /// <param name="describeStacksRequest">Container for the necessary parameters to execute the DescribeStacks service method on
        ///           AmazonCloudFormation.</param>
        ///
        /// <returns>The response from the DescribeStacks service method, as returned by AmazonCloudFormation.</returns>
        ///
        public DescribeStacksResponse DescribeStacks(DescribeStacksRequest describeStacksRequest)
        {
            IRequest <DescribeStacksRequest> request  = new DescribeStacksRequestMarshaller().Marshall(describeStacksRequest);
            DescribeStacksResponse           response = Invoke <DescribeStacksRequest, DescribeStacksResponse> (request, this.signer, DescribeStacksResponseUnmarshaller.GetInstance());

            return(response);
        }
        public static DescribeStacksResponse Unmarshall(UnmarshallerContext context)
        {
            DescribeStacksResponse describeStacksResponse = new DescribeStacksResponse();

            describeStacksResponse.HttpResponse = context.HttpResponse;

            return(describeStacksResponse);
        }
Esempio n. 11
0
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            DescribeStacksResponse response = new DescribeStacksResponse();

            context.Read();

            UnmarshallResult(context, response);
            return(response);
        }
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            DescribeStacksResponse response = new DescribeStacksResponse();

            context.Read();

            response.DescribeStacksResult = DescribeStacksResultUnmarshaller.GetInstance().Unmarshall(context);

            return(response);
        }
Esempio n. 13
0
        static void WaitTillStackNotInProcess(string stackname)
        {
            DescribeStacksResponse response = null;

            do
            {
                Thread.Sleep(2000);
                response = Client.DescribeStacks(new DescribeStacksRequest
                {
                    StackName = stackname
                });
            } while (response.Stacks[0].StackStatus.Value.EndsWith("IN_PROGRESS"));
        }
Esempio n. 14
0
        void WaitTillStackNotInProcess(string stackname)
        {
            DescribeStacksResponse response = null;

            do
            {
                UtilityMethods.Sleep(TimeSpan.FromSeconds(2));
                response = Client.DescribeStacksAsync(new DescribeStacksRequest
                {
                    StackName = stackname
                }).Result;
            } while (response.Stacks[0].StackStatus.Value.EndsWith("IN_PROGRESS"));
        }
Esempio n. 15
0
        DescribeStacksResponse GetStack(string stackName, string nextToken = null)
        {
            DescribeStacksResponse result = null;

            using (AmazonCloudFormationClient CFclient = new AmazonCloudFormationClient())
            {
                DescribeStacksRequest rq = new DescribeStacksRequest();
                rq.StackName = stackName;
                rq.NextToken = nextToken;
                result       = CFclient.DescribeStacks(rq);
            }

            return(result);
        }
        protected override async Task <bool> PerformActionAsync()
        {
            const int TIMESTAMP_WIDTH    = 20;
            const int STACK_NAME_WIDTH   = 30;
            const int STACK_STATUS_WIDTH = 20;

            this.Logger.WriteLine("Name".PadRight(STACK_NAME_WIDTH) + " " +
                                  "Status".PadRight(STACK_STATUS_WIDTH) + " " +
                                  "Created".PadRight(TIMESTAMP_WIDTH) + " " +
                                  "Last Modifed".PadRight(TIMESTAMP_WIDTH)
                                  );
            this.Logger.WriteLine($"{new string('-', STACK_NAME_WIDTH)} {new string('-', STACK_STATUS_WIDTH)} {new string('-', TIMESTAMP_WIDTH)} {new string('-', TIMESTAMP_WIDTH)}");

            var request = new DescribeStacksRequest();
            DescribeStacksResponse response = null;

            do
            {
                if (response != null)
                {
                    request.NextToken = response.NextToken;
                }

                try
                {
                    response = await this.CloudFormationClient.DescribeStacksAsync(request);
                }
                catch (Exception e)
                {
                    throw new LambdaToolsException("Error listing AWS Serverless applications: " + e.Message, LambdaToolsException.LambdaErrorCode.CloudFormationDescribeStack, e);
                }

                foreach (var stack in response.Stacks)
                {
                    if (stack.Tags.Any(x => string.Equals(x.Key, LambdaConstants.SERVERLESS_TAG_NAME)))
                    {
                        this.Logger.WriteLine(
                            stack.StackName.PadRight(STACK_NAME_WIDTH) + " " +
                            stack.StackStatus.ToString().PadRight(STACK_STATUS_WIDTH) + " " +
                            stack.CreationTime.ToString("g").PadRight(STACK_STATUS_WIDTH) + " " +
                            stack.LastUpdatedTime.ToString("g").PadRight(TIMESTAMP_WIDTH)
                            );
                    }
                }
            } while (!string.IsNullOrEmpty(response.NextToken));

            return(true);
        }
Esempio n. 17
0
        public async Task <DescribeStacksResponse> GetStackListPage(string nextToken = null)
        {
            DescribeStacksResponse response = null;

            if (nextToken != null)
            {
                var request = new DescribeStacksRequest()
                {
                    NextToken = nextToken
                };
                response = await client.DescribeStacksAsync(request);
            }
            else
            {
                response = await client.DescribeStacksAsync();
            }
            return(response);
        }
Esempio n. 18
0
        //private ListStackResourcesResponse ListStackResources(string stackName, AmazonCloudFormationClient cfClient, string nextToken = null)
        //{
        //    ListStackResourcesRequest lr = new ListStackResourcesRequest();
        //    lr.StackName = stackName;
        //    lr.NextToken = nextToken;
        //    ListStackResourcesResponse liveStackResources = cfClient.ListStackResources(lr);
        //    return liveStackResources;
        //}

        private void ProcessLiveStack(string stackName, AmazonCloudFormationClient cfClient, AmazonEC2Client ec2Client, RichTextBox rtb, CFStack stack)
        {
            Dictionary <string, string>   secGroupMap        = new Dictionary <string, string>();
            DescribeSecurityGroupsRequest secGroupRequestAll = new DescribeSecurityGroupsRequest();
            //Get all security group Id's and cf logicalId's (if any)
            DescribeSecurityGroupsResponse secGroupResponseAll = ec2Client.DescribeSecurityGroups(secGroupRequestAll);

            foreach (SecurityGroup sg in secGroupResponseAll.SecurityGroups)
            {
                string value = "none";
                foreach (Amazon.EC2.Model.Tag tag in sg.Tags)
                {
                    if (tag.Key.Contains("aws:cloudformation:logical-id"))
                    {
                        value = tag.Value;
                    }
                }
                secGroupMap.Add(sg.GroupId, value);
            }



            //Get Live Stack
            DescribeStacksRequest cfRequest = new DescribeStacksRequest();

            cfRequest.StackName = stackName;
            DescribeStacksResponse liveStack = cfClient.DescribeStacks(cfRequest);

            stack.Description = liveStack.Stacks[0].Description;

            //Get Stack Resouces
            //Need to use ListStackResourcesRequest to be able to get stacks with more than 100 resources
            ListStackResourcesRequest lr = new ListStackResourcesRequest();

            lr.StackName = stackName;
            ListStackResourcesResponse liveStackResources = cfClient.ListStackResources(lr);

            ProcessLiveStackResourcess(liveStackResources, stack, ec2Client, secGroupMap, stackName, cfClient);


            stack.Resources.Sort((a, b) => a.LogicalId.CompareTo(b.LogicalId));

            WriteOutput(stack, rtb, source1_CB.Text, templateOrStack1_TB.Text);
        }
Esempio n. 19
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonOpsWorksConfig config = new AmazonOpsWorksConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonOpsWorksClient client = new AmazonOpsWorksClient(creds, config);

            DescribeStacksResponse resp = new DescribeStacksResponse();
            DescribeStacksRequest  req  = new DescribeStacksRequest
            {
            };

            resp = client.DescribeStacks(req);
            CheckError(resp.HttpStatusCode, "200");

            foreach (var obj in resp.Stacks)
            {
                AddObject(obj);
            }
        }
Esempio n. 20
0
        public void GetStackByName()
        {
            // Arrange
            const string stackName = "three";
            var          response  = new DescribeStacksResponse
            {
                Stacks = new List <Stack>
                {
                    new Stack {
                        StackName = stackName
                    }
                }
            };

            CloudFormationMock.Setup(x => x.DescribeStacks(It.Is <DescribeStacksRequest>(y => y.StackName == stackName))).Returns(response);

            // Act
            var stack = StackService.GetStack("three");

            // Assert
            stack.StackName.Should().Be(stackName);
        }
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            DescribeStacksResponse response = new DescribeStacksResponse();

            while (context.Read())
            {
                if (context.IsStartElement)
                {
                    if (context.TestExpression("DescribeStacksResult", 2))
                    {
                        response.DescribeStacksResult = DescribeStacksResultUnmarshaller.GetInstance().Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("ResponseMetadata", 2))
                    {
                        response.ResponseMetadata = ResponseMetadataUnmarshaller.GetInstance().Unmarshall(context);
                    }
                }
            }


            return(response);
        }
        private static void UnmarshallResult(XmlUnmarshallerContext context, DescribeStacksResponse response)
        {
            int originalDepth = context.CurrentDepth;
            int targetDepth   = originalDepth + 1;

            if (context.IsStartOfDocument)
            {
                targetDepth += 2;
            }

            while (context.Read())
            {
                if (context.IsStartElement || context.IsAttribute)
                {
                    if (context.TestExpression("Stacks/member", targetDepth))
                    {
                        response.Stacks.Add(StackUnmarshaller.GetInstance().Unmarshall(context));

                        continue;
                    }
                    if (context.TestExpression("NextToken", targetDepth))
                    {
                        response.NextToken = StringUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                }
                else if (context.IsEndElement && context.CurrentDepth < originalDepth)
                {
                    return;
                }
            }



            return;
        }
Esempio n. 23
0
        public void GetAllStacks()
        {
            // Arrange
            var response = new DescribeStacksResponse
            {
                Stacks = new List <Stack>
                {
                    new Stack {
                        StackId = "one"
                    },
                    new Stack {
                        StackId = "two"
                    }
                }
            };

            CloudFormationMock.Setup(x => x.DescribeStacks()).Returns(response);

            // Act
            IEnumerable <Stack> stacks = StackService.GetAllStacks();

            // Assert
            stacks.Select(x => x.StackId).ShouldBeEquivalentTo(response.Stacks.Select(y => y.StackId));
        }
Esempio n. 24
0
        private static void UnmarshallResult(JsonUnmarshallerContext context, DescribeStacksResponse response)
        {
            int originalDepth = context.CurrentDepth;
            int targetDepth   = originalDepth + 1;

            while (context.Read())
            {
                if (context.TestExpression("Stacks", targetDepth))
                {
                    context.Read();
                    response.Stacks = new List <Stack>();
                    StackUnmarshaller unmarshaller = StackUnmarshaller.GetInstance();
                    while (context.Read())
                    {
                        JsonToken token = context.CurrentTokenType;
                        if (token == JsonToken.ArrayStart)
                        {
                            continue;
                        }
                        if (token == JsonToken.ArrayEnd)
                        {
                            break;
                        }
                        response.Stacks.Add(unmarshaller.Unmarshall(context));
                    }
                    continue;
                }

                if (context.CurrentDepth <= originalDepth)
                {
                    return;
                }
            }

            return;
        }
Esempio n. 25
0
        public IEnumerable <Stack> GetAllStacks()
        {
            DescribeStacksResponse response = _cloudFormationClient.DescribeStacks();

            return(response.Stacks);
        }
Esempio n. 26
0
        public async Task <string> FunctionHandler(S3EventNotification evnt, ILambdaContext context)
        {
            // S3 Client and the associated Call Variables
            IAmazonS3 S3Client = new AmazonS3Client();

            S3EventNotification.S3Entity s3Event = new S3EventNotification.S3Entity();
            GetObjectRequest             ParameterFileRequest  = new GetObjectRequest();
            GetObjectResponse            ParameterFileResponse = new GetObjectResponse();
            GetPreSignedUrlRequest       PresignedKeyRequest   = new GetPreSignedUrlRequest();
            GetObjectResponse            CommitInfoResponse    = new GetObjectResponse();

            // Cloudformation Client and associated Variables
            AmazonCloudFormationClient CloudformationClient  = new AmazonCloudFormationClient();
            List <Parameter>           Parameters            = new List <Parameter>();
            DescribeStacksRequest      CurrentStacksRequest  = new DescribeStacksRequest();
            DescribeStacksResponse     CurrentStacksResponse = new DescribeStacksResponse();

            // A flag to determine if I want to create a new stack or update an existing one
            bool newstack = new bool();

            // The name of the stack which will be generated by the deployment process.
            string TargetStackName;

            // The fixed file name values the deployment process will require. If all three files are not present no deployment will take place.
            string DeploymentFileName = "master.template";
            string ParameterFileName  = "Parameters.txt";
            string CommitInfoFileName = "commitinfo.txt";


            // Write details of the s3 event to my logger
            s3Event = evnt.Records?[0].S3;
            context.Logger.Log("S3 Cloudformation Template Upload Event Recieved. Processing potential deployment.");
            context.Logger.Log("Bucket: " + s3Event.Bucket.Name);
            context.Logger.Log("Key: " + s3Event.Object.Key);

            // Preform a check to make sure the filename matches the standard required.
            if (s3Event.Object.Key.EndsWith(DeploymentFileName))
            {
                context.Logger.Log("S3 Event corresponds to a properly formatted master.template CloudFormation document. Commencing deployment.");
            }
            else
            {
                context.Logger.Log("S3 Event does not match deployment requirements. Candidates for deployment must contain the primary CloudFormation template in a master.template file.");
                return("Impropper filename. No deployment processed");
            }

            // Display the commitinfo from the deployment
            string CommitInfoKeyName = s3Event.Object.Key.Replace(DeploymentFileName, CommitInfoFileName);

            context.Logger.Log($"Looking for accompanying commitinfo file: {CommitInfoKeyName}");
            try
            {
                CommitInfoResponse = await S3Client.GetObjectAsync(s3Event.Bucket.Name, CommitInfoKeyName);

                using (StreamReader reader = new StreamReader(CommitInfoResponse.ResponseStream))
                {
                    string contents = reader.ReadToEnd();
                    context.Logger.Log(contents);
                }
            }
            catch (Exception e)
            {
                context.Logger.Log(e.Message);
                context.Logger.Log("No commitinfo.txt file detected. Aborting Deployment");
                return("No accompanying commitinfo.txt. No deployment Processed");
            }

            // Get and set associated parameters
            string ParameterKeyName = s3Event.Object.Key.Replace(DeploymentFileName, ParameterFileName);

            context.Logger.Log($"Looking for accompanying parameter file: {ParameterKeyName}");
            try
            {
                ParameterFileResponse = await S3Client.GetObjectAsync(s3Event.Bucket.Name, ParameterKeyName);

                StreamReader reader    = new StreamReader(ParameterFileResponse.ResponseStream);
                string       paramline = reader.ReadLine();
                context.Logger.Log("Parameter file line being processed: " + paramline);
                while (!string.IsNullOrWhiteSpace(paramline))
                {
                    string[] paramstrings = paramline.Split(':');
                    if (paramstrings.Length == 2)
                    {
                        Parameters.Add(new Parameter()
                        {
                            ParameterKey   = paramstrings[0],
                            ParameterValue = paramstrings[1]
                        });
                    }
                    paramline = reader.ReadLine();
                    context.Logger.Log("Parameter file line being processed: " + paramline);
                }
            }
            catch (Exception e)
            {
                context.Logger.Log(e.Message);
                context.Logger.Log("No parameter file detected. Aborting Deployment.");
                return("No accompanying commitinfo.txt.No deployment Processed");
            }

            // The name of the stack will be based on the folder structure containing the master.template document.
            // As an example, a template deployed to the S3 key Knect/RCC/master.template would generate the stack Knect-RCC
            TargetStackName = s3Event.Object.Key.Replace("/", "-");
            TargetStackName = TargetStackName.Replace("-" + DeploymentFileName, "");
            context.Logger.Log("Cloudformation Stack Name: " + TargetStackName);

            // Gets a presigned url for the cloudformation client so it can access the master.template document.
            PresignedKeyRequest.BucketName = s3Event.Bucket.Name;
            PresignedKeyRequest.Key        = s3Event.Object.Key;
            PresignedKeyRequest.Expires    = DateTime.Now.AddMinutes(5);
            string PresignedS3Key = S3Client.GetPreSignedURL(PresignedKeyRequest);

            // If a stack with the target name already exists I want to update it. Otherwise I want to create a new stack.
            try
            {
                CurrentStacksRequest.StackName = TargetStackName;
                CurrentStacksResponse          = await CloudformationClient.DescribeStacksAsync(CurrentStacksRequest);

                context.Logger.Log("A stack for the target name already exists. The existing stack will be updated.");

                newstack = false;
            }
            catch
            {
                context.Logger.Log("No stack with the target name exists. A new stack will be created.");

                newstack = true;
            }

            foreach (Parameter param in Parameters)
            {
                context.Logger.Log($"Parameter is set Key: {param.ParameterKey} with value {param.ParameterValue}");
            }

            // If there is an existing stack I will update it. Otherwise I will create a new stack
            if (newstack == true)
            {
                // Create a new stack
                CreateStackRequest CreateStack = new CreateStackRequest();
                CreateStack.StackName   = TargetStackName;
                CreateStack.TemplateURL = PresignedS3Key;
                CreateStack.Parameters  = Parameters;
                CreateStack.Capabilities.Add("CAPABILITY_NAMED_IAM");

                await CloudformationClient.CreateStackAsync(CreateStack);

                return("A stack creation request was successfully generated");
            }
            else
            {
                UpdateStackRequest updatereq = new UpdateStackRequest();
                updatereq.StackName   = TargetStackName;
                updatereq.TemplateURL = PresignedS3Key;
                updatereq.Parameters  = Parameters;
                updatereq.Capabilities.Add("CAPABILITY_NAMED_IAM");

                await CloudformationClient.UpdateStackAsync(updatereq);

                return("A stack update request was successfully generated");
            }
        }
Esempio n. 27
0
        static void TestCfStack(EncryptionMaterials encryptionMaterials)
        {
            string bucket_Name  = QSS3BucketName;
            string templateName = QSS3KeyPrefix + TdwUtils.cfClassPathBastion.Replace("tdw_cf_template\\", "");
            string stack_name   = templateName.Replace("-", "");

            stack_name = stack_name.Replace(".template", "");
            //AmazonS3EncryptionClient s3Client = new AmazonS3EncryptionClient(encryptionMaterials);
            AmazonS3Client s3Client = new AmazonS3Client();

            GetObjectRequest getObjectRequest = new GetObjectRequest
            {
                BucketName = bucket_Name,
                Key        = templateName,
            };

            string data = null;

            using (GetObjectResponse getObjectResponse = s3Client.GetObject(getObjectRequest))
            {
                using (var stream = getObjectResponse.ResponseStream)
                    using (var reader = new StreamReader(stream))
                    {
                        data = reader.ReadToEnd();
                    }
            }

            Amazon.CloudFormation.AmazonCloudFormationClient cfClient = new AmazonCloudFormationClient();
            ValidateTemplateResponse templateResponse = cfClient.ValidateTemplate(new ValidateTemplateRequest()
            {
                TemplateBody = data
            });

            List <string>            capabilities       = templateResponse.Capabilities;
            string                   capabilitiesReason = templateResponse.CapabilitiesReason;
            string                   description        = templateResponse.Description;
            List <TemplateParameter> parameters         = templateResponse.Parameters;

            if (parameters.Any())
            {
                Console.WriteLine("  Parameters:");

                foreach (var p in parameters)
                {
                    Console.WriteLine("    {0} = {1}",
                                      p.ParameterKey, p.Description);
                }
            }

            //try
            //{
            //    DeleteStackRequest deleteRequest = new DeleteStackRequest() { StackName = stack_name };
            //    cfClient.DeleteStack(deleteRequest);
            //}
            //catch (Exception ex)
            //{
            //    ex = null;
            //}

            DescribeStacksResponse testForStackDescResp = new DescribeStacksResponse();

            try
            {
                testForStackDescResp = cfClient.DescribeStacks(new DescribeStacksRequest()
                {
                    StackName = stack_name
                });
            }
            catch (Exception ex)
            {
                testForStackDescResp = null;
            }

            if (testForStackDescResp == null)
            {
                List <string> CfCapabilities = new List <string>();
                CfCapabilities.Add("CAPABILITY_IAM");
                CreateStackRequest stackRequest = new CreateStackRequest()
                {
                    StackName = stack_name, TemplateBody = data, Capabilities = CfCapabilities
                };

                //stackRequest.Parameters.Add(new Parameter() { ParameterKey = "pDBPassword", ParameterValue = "LiverpoolFC" } );
                //stackRequest.Parameters.Add(new Parameter() { ParameterKey = "pNotifyEmail", ParameterValue = "*****@*****.**" });
                //stackRequest.Parameters.Add(new Parameter() { ParameterKey = "pEC2KeyPairBastion", ParameterValue = "BastionSshKvp" });
                //stackRequest.Parameters.Add(new Parameter() { ParameterKey = "pEC2KeyPair", ParameterValue = "Ec2SshKvp" });
                //stackRequest.Parameters.Add(new Parameter() { ParameterKey = "pSupportsConfig", ParameterValue = "Yes" });
                //stackRequest.Parameters.Add(new Parameter() { ParameterKey = "pAvailabilityZoneA", ParameterValue = "eu-west-1a" });
                //stackRequest.Parameters.Add(new Parameter() { ParameterKey = "pAvailabilityZoneB", ParameterValue = "eu-west-1b" });
                //stackRequest.Parameters.Add(new Parameter() { ParameterKey = "pVPCTenancy", ParameterValue = "default" });
                //stackRequest.Parameters.Add(new Parameter() { ParameterKey = "QSS3BucketName", ParameterValue = QSS3BucketName });
                //stackRequest.Parameters.Add(new Parameter() { ParameterKey = "QSS3KeyPrefix", ParameterValue = QSS3KeyPrefix });

                templateResponse = cfClient.ValidateTemplate(new ValidateTemplateRequest()
                {
                    TemplateBody = data
                });
                CreateStackResponse stackResponse = cfClient.CreateStack(stackRequest);
            }

            testForStackDescResp = cfClient.DescribeStacks(new DescribeStacksRequest());

            foreach (var stack in testForStackDescResp.Stacks)
            {
                Console.WriteLine("stack: {0}", stack.StackName);
                Console.WriteLine("  status: {0}", stack.StackStatus);
                Console.WriteLine("  created: {0}", stack.CreationTime);

                var ps = stack.Parameters;

                if (ps.Any())
                {
                    Console.WriteLine("  parameters:");

                    foreach (var p in ps)
                    {
                        Console.WriteLine("    {0} = {1}",
                                          p.ParameterKey, p.ParameterValue);
                    }
                }
            }
        }
Esempio n. 28
0
        //######################################################################



        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string searchItem = string.Empty;

            if (searchInstance_RB.Checked)
            {
                searchItem = "instance-id";
            }
            else if (searchName_RB.Checked)
            {
                searchItem = "tag:Name";
            }
            else if (searchPrivateIp_RB.Checked)
            {
                searchItem = "private-ip-address";
            }


            backgroundWorker1.ReportProgress(1, 1);
            DescribeInstancesResponse dir = new DescribeInstancesResponse();

            do
            {
                dir = GetInstances(BuildFilter(search_TB.Text, searchItem), dir.NextToken);
                Reservations.AddRange(dir.Reservations);
            } while (dir.NextToken != null);


            if (ColumnItems.Contains("Snapshots"))
            {
                foreach (Reservation reservation in Reservations)
                {
                    foreach (Instance instance in reservation.Instances)
                    {
                        string a = "";
                        foreach (InstanceBlockDeviceMapping mapping in instance.BlockDeviceMappings)
                        {
                            a += mapping.Ebs.VolumeId + ",";
                        }
                        a = a.Remove(a.Length - 1, 1);
                        DescribeSnapshotsResponse dsr = GetSnapshots(BuildFilter(a, "volume-id"));
                        Snapshots.AddRange(dsr.Snapshots);
                    }
                }
            }


            //if (ColumnItems.Contains("cloudformation:stack-name"))
            //{
            //    ListStacksResponse lsr = new ListStacksResponse();
            //    do
            //    {
            //        lsr = GetStackSummaries(lsr.NextToken);
            //        StackSummaries.AddRange(lsr.StackSummaries);
            //    } while (lsr.NextToken != null);
            //}


            if (ColumnItems.Contains(Properties.Settings.Default.StackNameTag) || ColumnItems.Contains("StackName"))
            {
                foreach (Reservation reservation in Reservations)
                {
                    foreach (Instance instance in reservation.Instances)
                    {
                        DescribeStacksResponse dstr = new DescribeStacksResponse();
                        string stackName            = Utils.GetEC2PropFromString("stackname", instance);
                        if (stackName != "")
                        {
                            dstr = GetStack(stackName, null);
                            Stacks.AddRange(dstr.Stacks);
                        }
                    }
                }
            }


            //if (ColumnItems.Contains("AMIs"))
            //{
            //    foreach (Reservation reservation in dir.Reservations)
            //    {
            //        string a = "";
            //        foreach (Instance instance in reservation.Instances)
            //        {
            //            a += instance.InstanceId + ",";
            //        }
            //        a = a.Remove(a.Length - 1, 1);
            //        DescribeImagesResponse dimr = GetAMIs(BuildFilter(a, "name"));
            //        AMIs.AddRange(dimr.Images);
            //    }
            //}

            e.Result = dir;
        }