1# Copyright (c) 2015 Amazon.com, Inc. or its affiliates.  All Rights Reserved
2#
3# Permission is hereby granted, free of charge, to any person obtaining a
4# copy of this software and associated documentation files (the
5# "Software"), to deal in the Software without restriction, including
6# without limitation the rights to use, copy, modify, merge, publish, dis-
7# tribute, sublicense, and/or sell copies of the Software, and to permit
8# persons to whom the Software is furnished to do so, subject to the fol-
9# lowing conditions:
10#
11# The above copyright notice and this permission notice shall be included
12# in all copies or substantial portions of the Software.
13#
14# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
16# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
17# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
18# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
20# IN THE SOFTWARE.
21#
22
23import boto
24from boto.compat import json
25from boto.connection import AWSQueryConnection
26from boto.regioninfo import RegionInfo
27from boto.exception import JSONResponseError
28from boto.codedeploy import exceptions
29
30
31class CodeDeployConnection(AWSQueryConnection):
32    """
33    AWS CodeDeploy **Overview**
34    This is the AWS CodeDeploy API Reference. This guide provides
35    descriptions of the AWS CodeDeploy APIs. For additional
36    information, see the `AWS CodeDeploy User Guide`_.
37    **Using the APIs**
38    You can use the AWS CodeDeploy APIs to work with the following
39    items:
40
41
42    + Applications , which are unique identifiers that AWS CodeDeploy
43      uses to ensure that the correct combinations of revisions,
44      deployment configurations, and deployment groups are being
45      referenced during deployments. You can work with applications by
46      calling CreateApplication, DeleteApplication, GetApplication,
47      ListApplications, BatchGetApplications, and UpdateApplication to
48      create, delete, and get information about applications, and to
49      change information about an application, respectively.
50    + Deployment configurations , which are sets of deployment rules
51      and deployment success and failure conditions that AWS CodeDeploy
52      uses during deployments. You can work with deployment
53      configurations by calling CreateDeploymentConfig,
54      DeleteDeploymentConfig, GetDeploymentConfig, and
55      ListDeploymentConfigs to create, delete, and get information about
56      deployment configurations, respectively.
57    + Deployment groups , which represent groups of Amazon EC2
58      instances to which application revisions can be deployed. You can
59      work with deployment groups by calling CreateDeploymentGroup,
60      DeleteDeploymentGroup, GetDeploymentGroup, ListDeploymentGroups,
61      and UpdateDeploymentGroup to create, delete, and get information
62      about single and multiple deployment groups, and to change
63      information about a deployment group, respectively.
64    + Deployment instances (also known simply as instances ), which
65      represent Amazon EC2 instances to which application revisions are
66      deployed. Deployment instances are identified by their Amazon EC2
67      tags or Auto Scaling group names. Deployment instances belong to
68      deployment groups. You can work with deployment instances by
69      calling GetDeploymentInstance and ListDeploymentInstances to get
70      information about single and multiple deployment instances,
71      respectively.
72    + Deployments , which represent the process of deploying revisions
73      to deployment groups. You can work with deployments by calling
74      CreateDeployment, GetDeployment, ListDeployments,
75      BatchGetDeployments, and StopDeployment to create and get
76      information about deployments, and to stop a deployment,
77      respectively.
78    + Application revisions (also known simply as revisions ), which
79      are archive files that are stored in Amazon S3 buckets or GitHub
80      repositories. These revisions contain source content (such as
81      source code, web pages, executable files, any deployment scripts,
82      and similar) along with an Application Specification file (AppSpec
83      file). (The AppSpec file is unique to AWS CodeDeploy; it defines a
84      series of deployment actions that you want AWS CodeDeploy to
85      execute.) An application revision is uniquely identified by its
86      Amazon S3 object key and its ETag, version, or both. Application
87      revisions are deployed to deployment groups. You can work with
88      application revisions by calling GetApplicationRevision,
89      ListApplicationRevisions, and RegisterApplicationRevision to get
90      information about application revisions and to inform AWS
91      CodeDeploy about an application revision, respectively.
92    """
93    APIVersion = "2014-10-06"
94    DefaultRegionName = "us-east-1"
95    DefaultRegionEndpoint = "codedeploy.us-east-1.amazonaws.com"
96    ServiceName = "codedeploy"
97    TargetPrefix = "CodeDeploy_20141006"
98    ResponseError = JSONResponseError
99
100    _faults = {
101        "InvalidDeploymentIdException": exceptions.InvalidDeploymentIdException,
102        "InvalidDeploymentGroupNameException": exceptions.InvalidDeploymentGroupNameException,
103        "DeploymentConfigAlreadyExistsException": exceptions.DeploymentConfigAlreadyExistsException,
104        "InvalidRoleException": exceptions.InvalidRoleException,
105        "RoleRequiredException": exceptions.RoleRequiredException,
106        "DeploymentGroupAlreadyExistsException": exceptions.DeploymentGroupAlreadyExistsException,
107        "DeploymentConfigLimitExceededException": exceptions.DeploymentConfigLimitExceededException,
108        "InvalidNextTokenException": exceptions.InvalidNextTokenException,
109        "InvalidDeploymentConfigNameException": exceptions.InvalidDeploymentConfigNameException,
110        "InvalidSortByException": exceptions.InvalidSortByException,
111        "InstanceDoesNotExistException": exceptions.InstanceDoesNotExistException,
112        "InvalidMinimumHealthyHostValueException": exceptions.InvalidMinimumHealthyHostValueException,
113        "ApplicationLimitExceededException": exceptions.ApplicationLimitExceededException,
114        "ApplicationNameRequiredException": exceptions.ApplicationNameRequiredException,
115        "InvalidEC2TagException": exceptions.InvalidEC2TagException,
116        "DeploymentDoesNotExistException": exceptions.DeploymentDoesNotExistException,
117        "DeploymentLimitExceededException": exceptions.DeploymentLimitExceededException,
118        "InvalidInstanceStatusException": exceptions.InvalidInstanceStatusException,
119        "RevisionRequiredException": exceptions.RevisionRequiredException,
120        "InvalidBucketNameFilterException": exceptions.InvalidBucketNameFilterException,
121        "DeploymentGroupLimitExceededException": exceptions.DeploymentGroupLimitExceededException,
122        "DeploymentGroupDoesNotExistException": exceptions.DeploymentGroupDoesNotExistException,
123        "DeploymentConfigNameRequiredException": exceptions.DeploymentConfigNameRequiredException,
124        "DeploymentAlreadyCompletedException": exceptions.DeploymentAlreadyCompletedException,
125        "RevisionDoesNotExistException": exceptions.RevisionDoesNotExistException,
126        "DeploymentGroupNameRequiredException": exceptions.DeploymentGroupNameRequiredException,
127        "DeploymentIdRequiredException": exceptions.DeploymentIdRequiredException,
128        "DeploymentConfigDoesNotExistException": exceptions.DeploymentConfigDoesNotExistException,
129        "BucketNameFilterRequiredException": exceptions.BucketNameFilterRequiredException,
130        "InvalidTimeRangeException": exceptions.InvalidTimeRangeException,
131        "ApplicationDoesNotExistException": exceptions.ApplicationDoesNotExistException,
132        "InvalidRevisionException": exceptions.InvalidRevisionException,
133        "InvalidSortOrderException": exceptions.InvalidSortOrderException,
134        "InvalidOperationException": exceptions.InvalidOperationException,
135        "InvalidAutoScalingGroupException": exceptions.InvalidAutoScalingGroupException,
136        "InvalidApplicationNameException": exceptions.InvalidApplicationNameException,
137        "DescriptionTooLongException": exceptions.DescriptionTooLongException,
138        "ApplicationAlreadyExistsException": exceptions.ApplicationAlreadyExistsException,
139        "InvalidDeployedStateFilterException": exceptions.InvalidDeployedStateFilterException,
140        "DeploymentNotStartedException": exceptions.DeploymentNotStartedException,
141        "DeploymentConfigInUseException": exceptions.DeploymentConfigInUseException,
142        "InstanceIdRequiredException": exceptions.InstanceIdRequiredException,
143        "InvalidKeyPrefixFilterException": exceptions.InvalidKeyPrefixFilterException,
144        "InvalidDeploymentStatusException": exceptions.InvalidDeploymentStatusException,
145    }
146
147
148    def __init__(self, **kwargs):
149        region = kwargs.pop('region', None)
150        if not region:
151            region = RegionInfo(self, self.DefaultRegionName,
152                                self.DefaultRegionEndpoint)
153
154        if 'host' not in kwargs or kwargs['host'] is None:
155            kwargs['host'] = region.endpoint
156
157        super(CodeDeployConnection, self).__init__(**kwargs)
158        self.region = region
159
160    def _required_auth_capability(self):
161        return ['hmac-v4']
162
163    def batch_get_applications(self, application_names=None):
164        """
165        Gets information about one or more applications.
166
167        :type application_names: list
168        :param application_names: A list of application names, with multiple
169            application names separated by spaces.
170
171        """
172        params = {}
173        if application_names is not None:
174            params['applicationNames'] = application_names
175        return self.make_request(action='BatchGetApplications',
176                                 body=json.dumps(params))
177
178    def batch_get_deployments(self, deployment_ids=None):
179        """
180        Gets information about one or more deployments.
181
182        :type deployment_ids: list
183        :param deployment_ids: A list of deployment IDs, with multiple
184            deployment IDs separated by spaces.
185
186        """
187        params = {}
188        if deployment_ids is not None:
189            params['deploymentIds'] = deployment_ids
190        return self.make_request(action='BatchGetDeployments',
191                                 body=json.dumps(params))
192
193    def create_application(self, application_name):
194        """
195        Creates a new application.
196
197        :type application_name: string
198        :param application_name: The name of the application. This name must be
199            unique within the AWS user account.
200
201        """
202        params = {'applicationName': application_name, }
203        return self.make_request(action='CreateApplication',
204                                 body=json.dumps(params))
205
206    def create_deployment(self, application_name, deployment_group_name=None,
207                          revision=None, deployment_config_name=None,
208                          description=None,
209                          ignore_application_stop_failures=None):
210        """
211        Deploys an application revision to the specified deployment
212        group.
213
214        :type application_name: string
215        :param application_name: The name of an existing AWS CodeDeploy
216            application within the AWS user account.
217
218        :type deployment_group_name: string
219        :param deployment_group_name: The deployment group's name.
220
221        :type revision: dict
222        :param revision: The type of revision to deploy, along with information
223            about the revision's location.
224
225        :type deployment_config_name: string
226        :param deployment_config_name: The name of an existing deployment
227            configuration within the AWS user account.
228        If not specified, the value configured in the deployment group will be
229            used as the default. If the deployment group does not have a
230            deployment configuration associated with it, then
231            CodeDeployDefault.OneAtATime will be used by default.
232
233        :type description: string
234        :param description: A comment about the deployment.
235
236        :type ignore_application_stop_failures: boolean
237        :param ignore_application_stop_failures: If set to true, then if the
238            deployment causes the ApplicationStop deployment lifecycle event to
239            fail to a specific instance, the deployment will not be considered
240            to have failed to that instance at that point and will continue on
241            to the BeforeInstall deployment lifecycle event.
242        If set to false or not specified, then if the deployment causes the
243            ApplicationStop deployment lifecycle event to fail to a specific
244            instance, the deployment will stop to that instance, and the
245            deployment to that instance will be considered to have failed.
246
247        """
248        params = {'applicationName': application_name, }
249        if deployment_group_name is not None:
250            params['deploymentGroupName'] = deployment_group_name
251        if revision is not None:
252            params['revision'] = revision
253        if deployment_config_name is not None:
254            params['deploymentConfigName'] = deployment_config_name
255        if description is not None:
256            params['description'] = description
257        if ignore_application_stop_failures is not None:
258            params['ignoreApplicationStopFailures'] = ignore_application_stop_failures
259        return self.make_request(action='CreateDeployment',
260                                 body=json.dumps(params))
261
262    def create_deployment_config(self, deployment_config_name,
263                                 minimum_healthy_hosts=None):
264        """
265        Creates a new deployment configuration.
266
267        :type deployment_config_name: string
268        :param deployment_config_name: The name of the deployment configuration
269            to create.
270
271        :type minimum_healthy_hosts: dict
272        :param minimum_healthy_hosts: The minimum number of healthy instances
273            that should be available at any time during the deployment. There
274            are two parameters expected in the input: type and value.
275        The type parameter takes either of the following values:
276
277
278        + HOST_COUNT: The value parameter represents the minimum number of
279              healthy instances, as an absolute value.
280        + FLEET_PERCENT: The value parameter represents the minimum number of
281              healthy instances, as a percentage of the total number of instances
282              in the deployment. If you specify FLEET_PERCENT, then at the start
283              of the deployment AWS CodeDeploy converts the percentage to the
284              equivalent number of instances and rounds fractional instances up.
285
286
287        The value parameter takes an integer.
288
289        For example, to set a minimum of 95% healthy instances, specify a type
290            of FLEET_PERCENT and a value of 95.
291
292        """
293        params = {'deploymentConfigName': deployment_config_name, }
294        if minimum_healthy_hosts is not None:
295            params['minimumHealthyHosts'] = minimum_healthy_hosts
296        return self.make_request(action='CreateDeploymentConfig',
297                                 body=json.dumps(params))
298
299    def create_deployment_group(self, application_name,
300                                deployment_group_name,
301                                deployment_config_name=None,
302                                ec_2_tag_filters=None,
303                                auto_scaling_groups=None,
304                                service_role_arn=None):
305        """
306        Creates a new deployment group for application revisions to be
307        deployed to.
308
309        :type application_name: string
310        :param application_name: The name of an existing AWS CodeDeploy
311            application within the AWS user account.
312
313        :type deployment_group_name: string
314        :param deployment_group_name: The name of an existing deployment group
315            for the specified application.
316
317        :type deployment_config_name: string
318        :param deployment_config_name: If specified, the deployment
319            configuration name must be one of the predefined values, or it can
320            be a custom deployment configuration:
321
322        + CodeDeployDefault.AllAtOnce deploys an application revision to up to
323              all of the Amazon EC2 instances at once. The overall deployment
324              succeeds if the application revision deploys to at least one of the
325              instances. The overall deployment fails after the application
326              revision fails to deploy to all of the instances. For example, for
327              9 instances, deploy to up to all 9 instances at once. The overall
328              deployment succeeds if any of the 9 instances is successfully
329              deployed to, and it fails if all 9 instances fail to be deployed
330              to.
331        + CodeDeployDefault.HalfAtATime deploys to up to half of the instances
332              at a time (with fractions rounded down). The overall deployment
333              succeeds if the application revision deploys to at least half of
334              the instances (with fractions rounded up); otherwise, the
335              deployment fails. For example, for 9 instances, deploy to up to 4
336              instances at a time. The overall deployment succeeds if 5 or more
337              instances are successfully deployed to; otherwise, the deployment
338              fails. Note that the deployment may successfully deploy to some
339              instances, even if the overall deployment fails.
340        + CodeDeployDefault.OneAtATime deploys the application revision to only
341              one of the instances at a time. The overall deployment succeeds if
342              the application revision deploys to all of the instances. The
343              overall deployment fails after the application revision first fails
344              to deploy to any one instance. For example, for 9 instances, deploy
345              to one instance at a time. The overall deployment succeeds if all 9
346              instances are successfully deployed to, and it fails if any of one
347              of the 9 instances fail to be deployed to. Note that the deployment
348              may successfully deploy to some instances, even if the overall
349              deployment fails. This is the default deployment configuration if a
350              configuration isn't specified for either the deployment or the
351              deployment group.
352
353
354        To create a custom deployment configuration, call the create deployment
355            configuration operation.
356
357        :type ec_2_tag_filters: list
358        :param ec_2_tag_filters: The Amazon EC2 tags to filter on.
359
360        :type auto_scaling_groups: list
361        :param auto_scaling_groups: A list of associated Auto Scaling groups.
362
363        :type service_role_arn: string
364        :param service_role_arn: A service role ARN that allows AWS CodeDeploy
365            to act on the user's behalf when interacting with AWS services.
366
367        """
368        params = {
369            'applicationName': application_name,
370            'deploymentGroupName': deployment_group_name,
371        }
372        if deployment_config_name is not None:
373            params['deploymentConfigName'] = deployment_config_name
374        if ec_2_tag_filters is not None:
375            params['ec2TagFilters'] = ec_2_tag_filters
376        if auto_scaling_groups is not None:
377            params['autoScalingGroups'] = auto_scaling_groups
378        if service_role_arn is not None:
379            params['serviceRoleArn'] = service_role_arn
380        return self.make_request(action='CreateDeploymentGroup',
381                                 body=json.dumps(params))
382
383    def delete_application(self, application_name):
384        """
385        Deletes an application.
386
387        :type application_name: string
388        :param application_name: The name of an existing AWS CodeDeploy
389            application within the AWS user account.
390
391        """
392        params = {'applicationName': application_name, }
393        return self.make_request(action='DeleteApplication',
394                                 body=json.dumps(params))
395
396    def delete_deployment_config(self, deployment_config_name):
397        """
398        Deletes a deployment configuration.
399
400        A deployment configuration cannot be deleted if it is
401        currently in use. Also, predefined configurations cannot be
402        deleted.
403
404        :type deployment_config_name: string
405        :param deployment_config_name: The name of an existing deployment
406            configuration within the AWS user account.
407
408        """
409        params = {'deploymentConfigName': deployment_config_name, }
410        return self.make_request(action='DeleteDeploymentConfig',
411                                 body=json.dumps(params))
412
413    def delete_deployment_group(self, application_name,
414                                deployment_group_name):
415        """
416        Deletes a deployment group.
417
418        :type application_name: string
419        :param application_name: The name of an existing AWS CodeDeploy
420            application within the AWS user account.
421
422        :type deployment_group_name: string
423        :param deployment_group_name: The name of an existing deployment group
424            for the specified application.
425
426        """
427        params = {
428            'applicationName': application_name,
429            'deploymentGroupName': deployment_group_name,
430        }
431        return self.make_request(action='DeleteDeploymentGroup',
432                                 body=json.dumps(params))
433
434    def get_application(self, application_name):
435        """
436        Gets information about an application.
437
438        :type application_name: string
439        :param application_name: The name of an existing AWS CodeDeploy
440            application within the AWS user account.
441
442        """
443        params = {'applicationName': application_name, }
444        return self.make_request(action='GetApplication',
445                                 body=json.dumps(params))
446
447    def get_application_revision(self, application_name, revision):
448        """
449        Gets information about an application revision.
450
451        :type application_name: string
452        :param application_name: The name of the application that corresponds
453            to the revision.
454
455        :type revision: dict
456        :param revision: Information about the application revision to get,
457            including the revision's type and its location.
458
459        """
460        params = {
461            'applicationName': application_name,
462            'revision': revision,
463        }
464        return self.make_request(action='GetApplicationRevision',
465                                 body=json.dumps(params))
466
467    def get_deployment(self, deployment_id):
468        """
469        Gets information about a deployment.
470
471        :type deployment_id: string
472        :param deployment_id: An existing deployment ID within the AWS user
473            account.
474
475        """
476        params = {'deploymentId': deployment_id, }
477        return self.make_request(action='GetDeployment',
478                                 body=json.dumps(params))
479
480    def get_deployment_config(self, deployment_config_name):
481        """
482        Gets information about a deployment configuration.
483
484        :type deployment_config_name: string
485        :param deployment_config_name: The name of an existing deployment
486            configuration within the AWS user account.
487
488        """
489        params = {'deploymentConfigName': deployment_config_name, }
490        return self.make_request(action='GetDeploymentConfig',
491                                 body=json.dumps(params))
492
493    def get_deployment_group(self, application_name, deployment_group_name):
494        """
495        Gets information about a deployment group.
496
497        :type application_name: string
498        :param application_name: The name of an existing AWS CodeDeploy
499            application within the AWS user account.
500
501        :type deployment_group_name: string
502        :param deployment_group_name: The name of an existing deployment group
503            for the specified application.
504
505        """
506        params = {
507            'applicationName': application_name,
508            'deploymentGroupName': deployment_group_name,
509        }
510        return self.make_request(action='GetDeploymentGroup',
511                                 body=json.dumps(params))
512
513    def get_deployment_instance(self, deployment_id, instance_id):
514        """
515        Gets information about an Amazon EC2 instance as part of a
516        deployment.
517
518        :type deployment_id: string
519        :param deployment_id: The unique ID of a deployment.
520
521        :type instance_id: string
522        :param instance_id: The unique ID of an Amazon EC2 instance in the
523            deployment's deployment group.
524
525        """
526        params = {
527            'deploymentId': deployment_id,
528            'instanceId': instance_id,
529        }
530        return self.make_request(action='GetDeploymentInstance',
531                                 body=json.dumps(params))
532
533    def list_application_revisions(self, application_name, sort_by=None,
534                                   sort_order=None, s_3_bucket=None,
535                                   s_3_key_prefix=None, deployed=None,
536                                   next_token=None):
537        """
538        Lists information about revisions for an application.
539
540        :type application_name: string
541        :param application_name: The name of an existing AWS CodeDeploy
542            application within the AWS user account.
543
544        :type sort_by: string
545        :param sort_by: The column name to sort the list results by:
546
547        + registerTime: Sort the list results by when the revisions were
548              registered with AWS CodeDeploy.
549        + firstUsedTime: Sort the list results by when the revisions were first
550              used by in a deployment.
551        + lastUsedTime: Sort the list results by when the revisions were last
552              used in a deployment.
553
554
555        If not specified or set to null, the results will be returned in an
556            arbitrary order.
557
558        :type sort_order: string
559        :param sort_order: The order to sort the list results by:
560
561        + ascending: Sort the list results in ascending order.
562        + descending: Sort the list results in descending order.
563
564
565        If not specified, the results will be sorted in ascending order.
566
567        If set to null, the results will be sorted in an arbitrary order.
568
569        :type s_3_bucket: string
570        :param s_3_bucket: A specific Amazon S3 bucket name to limit the search
571            for revisions.
572        If set to null, then all of the user's buckets will be searched.
573
574        :type s_3_key_prefix: string
575        :param s_3_key_prefix: A specific key prefix for the set of Amazon S3
576            objects to limit the search for revisions.
577
578        :type deployed: string
579        :param deployed:
580        Whether to list revisions based on whether the revision is the target
581            revision of an deployment group:
582
583
584        + include: List revisions that are target revisions of a deployment
585              group.
586        + exclude: Do not list revisions that are target revisions of a
587              deployment group.
588        + ignore: List all revisions, regardless of whether they are target
589              revisions of a deployment group.
590
591        :type next_token: string
592        :param next_token: An identifier that was returned from the previous
593            list application revisions call, which can be used to return the
594            next set of applications in the list.
595
596        """
597        params = {'applicationName': application_name, }
598        if sort_by is not None:
599            params['sortBy'] = sort_by
600        if sort_order is not None:
601            params['sortOrder'] = sort_order
602        if s_3_bucket is not None:
603            params['s3Bucket'] = s_3_bucket
604        if s_3_key_prefix is not None:
605            params['s3KeyPrefix'] = s_3_key_prefix
606        if deployed is not None:
607            params['deployed'] = deployed
608        if next_token is not None:
609            params['nextToken'] = next_token
610        return self.make_request(action='ListApplicationRevisions',
611                                 body=json.dumps(params))
612
613    def list_applications(self, next_token=None):
614        """
615        Lists the applications registered within the AWS user account.
616
617        :type next_token: string
618        :param next_token: An identifier that was returned from the previous
619            list applications call, which can be used to return the next set of
620            applications in the list.
621
622        """
623        params = {}
624        if next_token is not None:
625            params['nextToken'] = next_token
626        return self.make_request(action='ListApplications',
627                                 body=json.dumps(params))
628
629    def list_deployment_configs(self, next_token=None):
630        """
631        Lists the deployment configurations within the AWS user
632        account.
633
634        :type next_token: string
635        :param next_token: An identifier that was returned from the previous
636            list deployment configurations call, which can be used to return
637            the next set of deployment configurations in the list.
638
639        """
640        params = {}
641        if next_token is not None:
642            params['nextToken'] = next_token
643        return self.make_request(action='ListDeploymentConfigs',
644                                 body=json.dumps(params))
645
646    def list_deployment_groups(self, application_name, next_token=None):
647        """
648        Lists the deployment groups for an application registered
649        within the AWS user account.
650
651        :type application_name: string
652        :param application_name: The name of an existing AWS CodeDeploy
653            application within the AWS user account.
654
655        :type next_token: string
656        :param next_token: An identifier that was returned from the previous
657            list deployment groups call, which can be used to return the next
658            set of deployment groups in the list.
659
660        """
661        params = {'applicationName': application_name, }
662        if next_token is not None:
663            params['nextToken'] = next_token
664        return self.make_request(action='ListDeploymentGroups',
665                                 body=json.dumps(params))
666
667    def list_deployment_instances(self, deployment_id, next_token=None,
668                                  instance_status_filter=None):
669        """
670        Lists the Amazon EC2 instances for a deployment within the AWS
671        user account.
672
673        :type deployment_id: string
674        :param deployment_id: The unique ID of a deployment.
675
676        :type next_token: string
677        :param next_token: An identifier that was returned from the previous
678            list deployment instances call, which can be used to return the
679            next set of deployment instances in the list.
680
681        :type instance_status_filter: list
682        :param instance_status_filter:
683        A subset of instances to list, by status:
684
685
686        + Pending: Include in the resulting list those instances with pending
687              deployments.
688        + InProgress: Include in the resulting list those instances with in-
689              progress deployments.
690        + Succeeded: Include in the resulting list those instances with
691              succeeded deployments.
692        + Failed: Include in the resulting list those instances with failed
693              deployments.
694        + Skipped: Include in the resulting list those instances with skipped
695              deployments.
696        + Unknown: Include in the resulting list those instances with
697              deployments in an unknown state.
698
699        """
700        params = {'deploymentId': deployment_id, }
701        if next_token is not None:
702            params['nextToken'] = next_token
703        if instance_status_filter is not None:
704            params['instanceStatusFilter'] = instance_status_filter
705        return self.make_request(action='ListDeploymentInstances',
706                                 body=json.dumps(params))
707
708    def list_deployments(self, application_name=None,
709                         deployment_group_name=None,
710                         include_only_statuses=None, create_time_range=None,
711                         next_token=None):
712        """
713        Lists the deployments under a deployment group for an
714        application registered within the AWS user account.
715
716        :type application_name: string
717        :param application_name: The name of an existing AWS CodeDeploy
718            application within the AWS user account.
719
720        :type deployment_group_name: string
721        :param deployment_group_name: The name of an existing deployment group
722            for the specified application.
723
724        :type include_only_statuses: list
725        :param include_only_statuses: A subset of deployments to list, by
726            status:
727
728        + Created: Include in the resulting list created deployments.
729        + Queued: Include in the resulting list queued deployments.
730        + In Progress: Include in the resulting list in-progress deployments.
731        + Succeeded: Include in the resulting list succeeded deployments.
732        + Failed: Include in the resulting list failed deployments.
733        + Aborted: Include in the resulting list aborted deployments.
734
735        :type create_time_range: dict
736        :param create_time_range: A deployment creation start- and end-time
737            range for returning a subset of the list of deployments.
738
739        :type next_token: string
740        :param next_token: An identifier that was returned from the previous
741            list deployments call, which can be used to return the next set of
742            deployments in the list.
743
744        """
745        params = {}
746        if application_name is not None:
747            params['applicationName'] = application_name
748        if deployment_group_name is not None:
749            params['deploymentGroupName'] = deployment_group_name
750        if include_only_statuses is not None:
751            params['includeOnlyStatuses'] = include_only_statuses
752        if create_time_range is not None:
753            params['createTimeRange'] = create_time_range
754        if next_token is not None:
755            params['nextToken'] = next_token
756        return self.make_request(action='ListDeployments',
757                                 body=json.dumps(params))
758
759    def register_application_revision(self, application_name, revision,
760                                      description=None):
761        """
762        Registers with AWS CodeDeploy a revision for the specified
763        application.
764
765        :type application_name: string
766        :param application_name: The name of an existing AWS CodeDeploy
767            application within the AWS user account.
768
769        :type description: string
770        :param description: A comment about the revision.
771
772        :type revision: dict
773        :param revision: Information about the application revision to
774            register, including the revision's type and its location.
775
776        """
777        params = {
778            'applicationName': application_name,
779            'revision': revision,
780        }
781        if description is not None:
782            params['description'] = description
783        return self.make_request(action='RegisterApplicationRevision',
784                                 body=json.dumps(params))
785
786    def stop_deployment(self, deployment_id):
787        """
788        Attempts to stop an ongoing deployment.
789
790        :type deployment_id: string
791        :param deployment_id: The unique ID of a deployment.
792
793        """
794        params = {'deploymentId': deployment_id, }
795        return self.make_request(action='StopDeployment',
796                                 body=json.dumps(params))
797
798    def update_application(self, application_name=None,
799                           new_application_name=None):
800        """
801        Changes an existing application's name.
802
803        :type application_name: string
804        :param application_name: The current name of the application that you
805            want to change.
806
807        :type new_application_name: string
808        :param new_application_name: The new name that you want to change the
809            application to.
810
811        """
812        params = {}
813        if application_name is not None:
814            params['applicationName'] = application_name
815        if new_application_name is not None:
816            params['newApplicationName'] = new_application_name
817        return self.make_request(action='UpdateApplication',
818                                 body=json.dumps(params))
819
820    def update_deployment_group(self, application_name,
821                                current_deployment_group_name,
822                                new_deployment_group_name=None,
823                                deployment_config_name=None,
824                                ec_2_tag_filters=None,
825                                auto_scaling_groups=None,
826                                service_role_arn=None):
827        """
828        Changes information about an existing deployment group.
829
830        :type application_name: string
831        :param application_name: The application name corresponding to the
832            deployment group to update.
833
834        :type current_deployment_group_name: string
835        :param current_deployment_group_name: The current name of the existing
836            deployment group.
837
838        :type new_deployment_group_name: string
839        :param new_deployment_group_name: The new name of the deployment group,
840            if you want to change it.
841
842        :type deployment_config_name: string
843        :param deployment_config_name: The replacement deployment configuration
844            name to use, if you want to change it.
845
846        :type ec_2_tag_filters: list
847        :param ec_2_tag_filters: The replacement set of Amazon EC2 tags to
848            filter on, if you want to change them.
849
850        :type auto_scaling_groups: list
851        :param auto_scaling_groups: The replacement list of Auto Scaling groups
852            to be included in the deployment group, if you want to change them.
853
854        :type service_role_arn: string
855        :param service_role_arn: A replacement service role's ARN, if you want
856            to change it.
857
858        """
859        params = {
860            'applicationName': application_name,
861            'currentDeploymentGroupName': current_deployment_group_name,
862        }
863        if new_deployment_group_name is not None:
864            params['newDeploymentGroupName'] = new_deployment_group_name
865        if deployment_config_name is not None:
866            params['deploymentConfigName'] = deployment_config_name
867        if ec_2_tag_filters is not None:
868            params['ec2TagFilters'] = ec_2_tag_filters
869        if auto_scaling_groups is not None:
870            params['autoScalingGroups'] = auto_scaling_groups
871        if service_role_arn is not None:
872            params['serviceRoleArn'] = service_role_arn
873        return self.make_request(action='UpdateDeploymentGroup',
874                                 body=json.dumps(params))
875
876    def make_request(self, action, body):
877        headers = {
878            'X-Amz-Target': '%s.%s' % (self.TargetPrefix, action),
879            'Host': self.region.endpoint,
880            'Content-Type': 'application/x-amz-json-1.1',
881            'Content-Length': str(len(body)),
882        }
883        http_request = self.build_base_http_request(
884            method='POST', path='/', auth_path='/', params={},
885            headers=headers, data=body)
886        response = self._mexe(http_request, sender=None,
887                              override_num_retries=10)
888        response_body = response.read().decode('utf-8')
889        boto.log.debug(response_body)
890        if response.status == 200:
891            if response_body:
892                return json.loads(response_body)
893        else:
894            json_body = json.loads(response_body)
895            fault_name = json_body.get('__type', None)
896            exception_class = self._faults.get(fault_name, self.ResponseError)
897            raise exception_class(response.status, response.reason,
898                                  body=json_body)
899
900