Example #1
0
        public CreateDeploymentResponse DeployToStack(
            AmazonCodeDeployClient codeDeployClient,
            AmazonIdentityManagementServiceClient iamClient,
            AmazonAutoScalingClient autoScalingClient,
            Role role)
        {
            var deploymentGroupName = _stackName + "_" + BundleName;

            EnsureDeploymentGroupExistsForBundle(codeDeployClient, iamClient, autoScalingClient, role, deploymentGroupName);

            var deploymentResponse = codeDeployClient.CreateDeployment(new CreateDeploymentRequest
            {
                ApplicationName     = CodeDeployApplicationName,
                DeploymentGroupName = deploymentGroupName,
                Revision            = new RevisionLocation
                {
                    RevisionType = RevisionLocationType.S3,
                    S3Location   = new S3Location
                    {
                        Bucket     = Bucket,
                        Key        = FileName,
                        BundleType = BundleType.Zip,
                        ETag       = ETag
                    }
                }
            });

            return(deploymentResponse);
        }
Example #2
0
        /// <summary>
        /// Gets the deployment info
        /// </summary>
        /// <param name="deploymentID">A deployment ID associated with the applicable IAM user or AWS account.</param>
        /// <param name="settings">The <see cref="DeploySettings"/> used during the request to AWS.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async Task <DeploymentInfo> GetDeploymentInfo(string deploymentID, DeploySettings settings, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (String.IsNullOrEmpty(deploymentID))
            {
                throw new ArgumentNullException("deploymentID");
            }



            // Create Request
            AmazonCodeDeployClient client  = this.CreateClient(settings);
            GetDeploymentRequest   request = new GetDeploymentRequest();

            request.DeploymentId = deploymentID;



            // Check Response
            GetDeploymentResponse response = await client.GetDeploymentAsync(request, cancellationToken);

            if (response.HttpStatusCode == HttpStatusCode.OK)
            {
                _Log.Verbose("Successfully found deployment info '{0}'", deploymentID);
                return(response.DeploymentInfo);
            }
            else
            {
                _Log.Error("Failed to get deployment info '{0}'", deploymentID);
                return(null);
            }
        }
Example #3
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonCodeDeployConfig config = new AmazonCodeDeployConfig();

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

            ListDeploymentConfigsResponse resp = new ListDeploymentConfigsResponse();

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

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

                foreach (var obj in resp.DeploymentConfigsList)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
Example #4
0
        public static void DeleteStack(RegionEndpoint awsEndpoint, string stackName)
        {
            var codeDeployClient = new AmazonCodeDeployClient(awsEndpoint);
            var apps             = codeDeployClient.ListApplications().Applications.Where(name => name.StartsWith("HelloWorld"));

            foreach (var app in apps)
            {
                codeDeployClient.DeleteApplication(new DeleteApplicationRequest {
                    ApplicationName = app
                });
            }

            var cloudFormationClient = new AmazonCloudFormationClient(awsEndpoint);

            try
            {
                cloudFormationClient.DeleteStack(new DeleteStackRequest {
                    StackName = stackName
                });
                var testStackStatus = StackStatus.DELETE_IN_PROGRESS;
                while (testStackStatus == StackStatus.DELETE_IN_PROGRESS)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(10));
                    var stacksStatus =
                        cloudFormationClient.DescribeStacks(new DescribeStacksRequest {
                        StackName = stackName
                    });
                    testStackStatus = stacksStatus.Stacks.First(s => s.StackName == stackName).StackStatus;
                }
            }
            catch (AmazonCloudFormationException)
            {
            }
        }
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>

        public async Task <string> FunctionHandler(CodeDeployInvokeRequest input, ILambdaContext context)
        {
            String envId   = input.EnvironmentId;
            String appName = input.ApplicationName;

            AmazonCodeDeployClient client = new AmazonCodeDeployClient();

            var request = new CreateDeploymentRequest();

            request.ApplicationName     = appName;
            request.DeploymentGroupName = input.DeploymentGroup;
            request.Description         = "Testing Deployment created by Lambda";
            request.Revision            = new RevisionLocation()
            {
                RevisionType = Amazon.CodeDeploy.RevisionLocationType.S3,
                S3Location   = new S3Location()
                {
                    Bucket     = input.S3BucketName,
                    BucketType = Amazon.CodeDeploy.BundleType.Zip,
                    Key        = input.S3KeyName
                }
            };

            var response = await client.CreateDeploymentAsync(request);

            return(response.ToString());
        }
Example #6
0
        public string Push(AmazonS3Client s3Client, AmazonCodeDeployClient codeDeployClient)
        {
            var zipFileName = string.Format("{0}.{1}.{2}.zip", ApplicationSetName, Version, BundleName);
            var tempPath    = Path.Combine(Path.GetTempPath(), zipFileName + "." + Guid.NewGuid() + ".zip");

            ZipFile.CreateFromDirectory(_bundleDirectory.FullName, tempPath, CompressionLevel.Optimal, false, Encoding.ASCII);

            var allTheBuckets = s3Client.ListBuckets(new ListBucketsRequest()).Buckets;

            if (!allTheBuckets.Exists(b => b.BucketName == Bucket))
            {
                s3Client.PutBucket(new PutBucketRequest {
                    BucketName = Bucket, UseClientRegion = true
                });
            }

            var putResponse = s3Client.PutObject(new PutObjectRequest
            {
                BucketName = Bucket,
                Key        = zipFileName,
                FilePath   = tempPath,
            });

            var registration = new RegisterApplicationRevisionRequest
            {
                ApplicationName = CodeDeployApplicationName,
                Description     = "Revision " + Version,
                Revision        = new RevisionLocation
                {
                    RevisionType = RevisionLocationType.S3,
                    S3Location   = new S3Location
                    {
                        Bucket     = Bucket,
                        BundleType = BundleType.Zip,
                        Key        = zipFileName,
                        Version    = Version
                    }
                }
            };

            try
            {
                codeDeployClient.RegisterApplicationRevision(registration);
            }
            catch (ApplicationDoesNotExistException)
            {
                codeDeployClient.CreateApplication(new CreateApplicationRequest {
                    ApplicationName = CodeDeployApplicationName
                });
                codeDeployClient.RegisterApplicationRevision(registration);
            }

            return(putResponse.ETag);
        }
Example #7
0
        public async Task <string> Handler(CodeDeployRequest request)
        {
            AmazonCodeDeployClient client = new AmazonCodeDeployClient();
            PutLifecycleEventHookExecutionStatusRequest req = new PutLifecycleEventHookExecutionStatusRequest();

            req.DeploymentId = request.DeploymentId;
            req.LifecycleEventHookExecutionId = request.LifecycleEventHookExecutionId;
            // SET STATUS TO Failed or Succeeded based on CUSTOM LOGIC
            req.Status = "Succeeded";
            await client.PutLifecycleEventHookExecutionStatusAsync(req);

            return("Go Serverless v1.0! Your function executed successfully!");
        }
Example #8
0
        /// <summary>
        /// Deploys an application revision through the specified deployment group.
        /// </summary>
        /// <param name="applicationName">The name of an AWS CodeDeploy application associated with the applicable IAM user or AWS account.</param>
        /// <param name="deploymentGroup">The name of the deployment group.</param>
        /// <param name="settings">The <see cref="DeploySettings"/> used during the request to AWS.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async Task <bool> CreateDeployment(string applicationName, string deploymentGroup, DeploySettings settings, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (String.IsNullOrEmpty(applicationName))
            {
                throw new ArgumentNullException("applicationName");
            }
            if (String.IsNullOrEmpty(deploymentGroup))
            {
                throw new ArgumentNullException("deploymentGroup");
            }



            // Create Request
            AmazonCodeDeployClient  client  = this.CreateClient(settings);
            CreateDeploymentRequest request = new CreateDeploymentRequest();

            request.ApplicationName     = applicationName;
            request.DeploymentGroupName = deploymentGroup;

            request.Revision = new RevisionLocation()
            {
                RevisionType = RevisionLocationType.S3,

                S3Location = new S3Location()
                {
                    BundleType = BundleType.Zip,

                    Bucket  = settings.S3Bucket,
                    Key     = settings.S3Key,
                    Version = settings.S3Version
                }
            };



            // Check Response
            CreateDeploymentResponse response = await client.CreateDeploymentAsync(request, cancellationToken);

            if (response.HttpStatusCode == HttpStatusCode.OK)
            {
                _Log.Verbose("Successfully deployed application '{0}'", applicationName);
                return(true);
            }
            else
            {
                _Log.Error("Failed to deploy application '{0}'", applicationName);
                return(false);
            }
        }
        protected IAmazonCodeDeploy CreateClient(AWSCredentials credentials, RegionEndpoint region)
        {
            var config = new AmazonCodeDeployConfig {
                RegionEndpoint = region
            };

            Amazon.PowerShell.Utils.Common.PopulateConfig(this, config);
            this.CustomizeClientConfig(config);
            var client = new AmazonCodeDeployClient(credentials, config);

            client.BeforeRequestEvent += RequestEventHandler;
            client.AfterResponseEvent += ResponseEventHandler;
            return(client);
        }
Example #10
0
        internal static string Deploy(string applicationName, string deploymentGroupName, string bucket, string key, string eTag, string version, string region = "")
        {
            try
            {
                S3Location location = new S3Location()
                {
                    Bucket     = bucket,
                    BundleType = BundleType.Zip,
                    ETag       = eTag,
                    Key        = key,
                    Version    = version
                };

                CreateDeploymentRequest request = new CreateDeploymentRequest()
                {
                    ApplicationName     = applicationName,
                    DeploymentGroupName = deploymentGroupName,
                    Revision            = new RevisionLocation()
                    {
                        S3Location   = location,
                        RevisionType = RevisionLocationType.S3
                    },
                };

                AmazonCodeDeployClient client = string.IsNullOrEmpty(region) ?
                                                new AmazonCodeDeployClient() :
                                                new AmazonCodeDeployClient(RegionEndpoint.GetBySystemName(region));

                Task <CreateDeploymentResponse> response = client.CreateDeploymentAsync(request);
                Task.WaitAll(new Task[] { response });


                string message = "Deployment Created: {0} \ndotnet codedeploy status --deployment-id {0}";
                if (!string.IsNullOrEmpty(region))
                {
                    message += " --region {1}";
                }

                Log.Information(message, response.Result.DeploymentId, region);
                return(response.Result.DeploymentId);
            }
            catch (System.Exception e)
            {
                Log.Error($"{e.GetBaseException().GetType().Name}: {e.Message}");
                return(null);
            }
        }
Example #11
0
        internal static GetDeploymentResponse GetDeployment(string deploymentId, string region)
        {
            try
            {
                GetDeploymentRequest request = new GetDeploymentRequest()
                {
                    DeploymentId = deploymentId
                };

                AmazonCodeDeployClient client = string.IsNullOrEmpty(region) ?
                                                new AmazonCodeDeployClient() :
                                                new AmazonCodeDeployClient(RegionEndpoint.GetBySystemName(region));

                Task <GetDeploymentResponse> response = client.GetDeploymentAsync(request);
                Task.WaitAll(new Task[] { response });

                return(response.Result);
            }
            catch (System.Exception e)
            {
                Log.Error($"{e.GetBaseException().GetType().Name}: {e.Message}");
                return(null);
            }
        }
Example #12
0
        void EnsureDeploymentGroupExistsForBundle(AmazonCodeDeployClient codeDeployClient, AmazonIdentityManagementServiceClient iamClient, AmazonAutoScalingClient autoScalingClient, Role role, string deploymentGroupName)
        {
            var serviceRoleArn = role.Arn;

            if (TargetsAutoScalingDeploymentGroup)
            {
                var group =
                    autoScalingClient.DescribeAutoScalingGroups()
                    .AutoScalingGroups.FirstOrDefault(
                        asg => asg.Tags.Any(t => t.Key == "DeploymentRole" && t.Value == deploymentGroupName));

                if (group == null)
                {
                    throw new ApplicationException(
                              string.Format("Auto scaling group with DeploymentRole {0} does not exist.", deploymentGroupName));
                }

                try
                {
                    codeDeployClient.CreateDeploymentGroup(new CreateDeploymentGroupRequest
                    {
                        ApplicationName     = CodeDeployApplicationName,
                        DeploymentGroupName = deploymentGroupName,
                        ServiceRoleArn      = serviceRoleArn,
                        AutoScalingGroups   = new List <string> {
                            group.AutoScalingGroupName
                        }
                    });
                }
                catch (DeploymentGroupAlreadyExistsException)
                {
                    // reuse a previously created deployment group with the same name
                }
            }
            else
            {
                try
                {
                    Console.WriteLine("Will assume role {0} for deployment", serviceRoleArn);
                    codeDeployClient.CreateDeploymentGroup(new CreateDeploymentGroupRequest
                    {
                        ApplicationName     = CodeDeployApplicationName,
                        DeploymentGroupName = deploymentGroupName,
                        ServiceRoleArn      = serviceRoleArn,
                        Ec2TagFilters       = new List <EC2TagFilter>
                        {
                            new EC2TagFilter
                            {
                                Type  = EC2TagFilterType.KEY_AND_VALUE,
                                Key   = "DeploymentRole",
                                Value = deploymentGroupName
                            }
                        }
                    });
                }
                catch (DeploymentGroupAlreadyExistsException)
                {
                    // since this is EC2, we can reuse a previously created deployment group with the same name
                }
            }
        }
Example #13
0
        public Deployer(AwsConfiguration awsConfiguration)
        {
            _awsEndpoint             = awsConfiguration.AwsEndpoint;
            _bucket                  = awsConfiguration.Bucket;
            _assumeRoleTrustDocument = awsConfiguration.AssumeRoleTrustDocument;
            _iamRolePolicyDocument   = awsConfiguration.IamRolePolicyDocument;

            AWSCredentials credentials;

            if (isArn(awsConfiguration.RoleName))
            {
                var securityTokenServiceClient = new AmazonSecurityTokenServiceClient(awsConfiguration.AwsEndpoint);

                var assumeRoleResult = securityTokenServiceClient.AssumeRole(new AssumeRoleRequest
                {
                    RoleArn         = awsConfiguration.RoleName,
                    DurationSeconds = 3600,
                    RoleSessionName = "Net2User",
                    ExternalId      = Guid.NewGuid().ToString()
                });

                Credentials stsCredentials = assumeRoleResult.Credentials;

                SessionAWSCredentials sessionCredentials =
                    new SessionAWSCredentials(stsCredentials.AccessKeyId,
                                              stsCredentials.SecretAccessKey,
                                              stsCredentials.SessionToken);

                credentials = sessionCredentials;

                _role = new AssumedRole(assumeRoleResult.AssumedRoleUser);
            }
            else
            {
                credentials = awsConfiguration.Credentials ?? new EnvironmentAWSCredentials();
            }

            _codeDeployClient = new AmazonCodeDeployClient(
                credentials,
                new AmazonCodeDeployConfig {
                RegionEndpoint = awsConfiguration.AwsEndpoint,
                ProxyHost      = awsConfiguration.ProxyHost,
                ProxyPort      = awsConfiguration.ProxyPort
            });

            _cloudFormationClient = new AmazonCloudFormationClient(
                credentials,
                new AmazonCloudFormationConfig {
                RegionEndpoint = awsConfiguration.AwsEndpoint,
                ProxyHost      = awsConfiguration.ProxyHost,
                ProxyPort      = awsConfiguration.ProxyPort
            });

            _s3Client = new AmazonS3Client(
                credentials,
                new AmazonS3Config {
                RegionEndpoint = awsConfiguration.AwsEndpoint,
                ProxyHost      = awsConfiguration.ProxyHost,
                ProxyPort      = awsConfiguration.ProxyPort
            });

            _iamClient = new AmazonIdentityManagementServiceClient(
                credentials,
                new AmazonIdentityManagementServiceConfig  {
                RegionEndpoint = awsConfiguration.AwsEndpoint,
                ProxyHost      = awsConfiguration.ProxyHost,
                ProxyPort      = awsConfiguration.ProxyPort
            });

            _autoScalingClient = new AmazonAutoScalingClient(
                credentials,
                new AmazonAutoScalingConfig {
                RegionEndpoint = awsConfiguration.AwsEndpoint,
                ProxyHost      = awsConfiguration.ProxyHost,
                ProxyPort      = awsConfiguration.ProxyPort
            });
        }