Esempio n. 1
0
    def delete(self):

        try:
            AWSRetry.jittered_backoff()(
                self.connection.delete_listener)(ListenerArn=self.listener)
        except (BotoCoreError, ClientError) as e:
            self.module.fail_json_aws(e)
Esempio n. 2
0
def call_method(client, module, method_name, parameters):
    result = {}
    changed = True
    if not module.check_mode:
        wait = module.params['wait']
        # TODO: stabilize by adding get_rds_method_attribute(method_name).extra_retry_codes
        method = getattr(client, method_name)
        try:
            if method_name == 'modify_db_instance':
                # check if instance is in an available state first, if possible
                if wait:
                    wait_for_status(client, module,
                                    module.params['db_instance_identifier'],
                                    method_name)
                result = AWSRetry.jittered_backoff(
                    catch_extra_error_codes=['InvalidDBInstanceState'])(
                        method)(**parameters)
            else:
                result = AWSRetry.jittered_backoff()(method)(**parameters)
        except (BotoCoreError, ClientError) as e:
            changed = handle_errors(module, e, method_name, parameters)

        if wait and changed:
            identifier = get_final_identifier(method_name, module)
            wait_for_status(client, module, identifier, method_name)
    return result, changed
Esempio n. 3
0
    def delete(self):
        """
        Delete elb
        :return:
        """

        try:
            AWSRetry.jittered_backoff()(self.connection.delete_load_balancer)(
                LoadBalancerArn=self.elb['LoadBalancerArn'])
        except (BotoCoreError, ClientError) as e:
            self.module.fail_json_aws(e)

        self.changed = True
Esempio n. 4
0
    def modify_security_groups(self):
        """
        Modify elb security groups to match module parameters
        :return:
        """

        try:
            AWSRetry.jittered_backoff()(self.connection.set_security_groups)(
                LoadBalancerArn=self.elb['LoadBalancerArn'],
                SecurityGroups=self.security_groups)
        except (BotoCoreError, ClientError) as e:
            self.module.fail_json_aws(e)

        self.changed = True
Esempio n. 5
0
    def delete(self):
        """
        Delete a listener rule

        :return:
        """

        try:
            AWSRetry.jittered_backoff()(
                self.connection.delete_rule)(RuleArn=self.rule['RuleArn'])
        except (BotoCoreError, ClientError) as e:
            self.module.fail_json_aws(e)

        self.changed = True
Esempio n. 6
0
    def modify_tags(self):
        """
        Modify elb tags

        :return:
        """

        try:
            AWSRetry.jittered_backoff()(self.connection.add_tags)(
                ResourceArns=[self.elb['LoadBalancerArn']], Tags=self.tags)
        except (BotoCoreError, ClientError) as e:
            self.module.fail_json_aws(e)

        self.changed = True
Esempio n. 7
0
    def delete_tags(self, tags_to_delete):
        """
        Delete elb tags

        :return:
        """

        try:
            AWSRetry.jittered_backoff()(self.connection.remove_tags)(
                ResourceArns=[self.elb['LoadBalancerArn']],
                TagKeys=tags_to_delete)
        except (BotoCoreError, ClientError) as e:
            self.module.fail_json_aws(e)

        self.changed = True
Esempio n. 8
0
    def create_elb(self):
        """
        Create a load balancer
        :return:
        """

        # Required parameters
        params = dict()
        params['Name'] = self.name
        params['Type'] = self.type

        # Other parameters
        if self.subnets is not None:
            params['Subnets'] = self.subnets
        if self.subnet_mappings is not None:
            params['SubnetMappings'] = self.subnet_mappings
        params['Scheme'] = self.scheme
        if self.tags:
            params['Tags'] = self.tags

        try:
            self.elb = AWSRetry.jittered_backoff()(
                self.connection.create_load_balancer)(
                    **params)['LoadBalancers'][0]
            self.changed = True
            self.new_load_balancer = True
        except (BotoCoreError, ClientError) as e:
            self.module.fail_json_aws(e)

        if self.wait:
            self.wait_for_status(self.elb['LoadBalancerArn'])
Esempio n. 9
0
    def modify(self):

        try:
            # Rules is not a valid parameter for modify_listener
            if 'Rules' in self.listener:
                self.listener.pop('Rules')
            AWSRetry.jittered_backoff()(
                self.connection.modify_listener)(**self.listener)
        except (BotoCoreError, ClientError) as e:
            if '"Order", must be one of: Type, TargetGroupArn' in str(e):
                self.module.fail_json(
                    msg="installed version of botocore does not support "
                    "multiple actions, please upgrade botocore to version "
                    "1.10.30 or higher")
            else:
                self.module.fail_json_aws(e)
Esempio n. 10
0
def get_elb_listener(connection, module, elb_arn, listener_port):
    """
    Get an ELB listener based on the port provided. If not found, return None.

    :param connection: AWS boto3 elbv2 connection
    :param module: Ansible module
    :param elb_arn: ARN of the ELB to look at
    :param listener_port: Port of the listener to look for
    :return: boto3 ELB listener dict or None if not found
    """

    try:
        listener_paginator = connection.get_paginator('describe_listeners')
        listeners = (AWSRetry.jittered_backoff()(listener_paginator.paginate)(
            LoadBalancerArn=elb_arn).build_full_result())['Listeners']
    except (BotoCoreError, ClientError) as e:
        module.fail_json_aws(e)

    l = None

    for listener in listeners:
        if listener['Port'] == listener_port:
            l = listener
            break

    return l
Esempio n. 11
0
    def _get_elb_listener_rules(self):

        try:
            return AWSRetry.jittered_backoff()(self.connection.describe_rules)(
                ListenerArn=self.current_listener['ListenerArn'])['Rules']
        except (BotoCoreError, ClientError) as e:
            self.module.fail_json_aws(e)
Esempio n. 12
0
    def modify_elb_attributes(self):
        """
        Update Network ELB attributes if required

        :return:
        """

        update_attributes = []

        if self.cross_zone_load_balancing is not None and str(self.cross_zone_load_balancing).lower() != \
                self.elb_attributes['load_balancing_cross_zone_enabled']:
            update_attributes.append({
                'Key':
                'load_balancing.cross_zone.enabled',
                'Value':
                str(self.cross_zone_load_balancing).lower()
            })
        if self.deletion_protection is not None and str(
                self.deletion_protection).lower(
                ) != self.elb_attributes['deletion_protection_enabled']:
            update_attributes.append({
                'Key':
                'deletion_protection.enabled',
                'Value':
                str(self.deletion_protection).lower()
            })

        if update_attributes:
            try:
                AWSRetry.jittered_backoff()(
                    self.connection.modify_load_balancer_attributes)(
                        LoadBalancerArn=self.elb['LoadBalancerArn'],
                        Attributes=update_attributes)
                self.changed = True
            except (BotoCoreError, ClientError) as e:
                # Something went wrong setting attributes. If this ELB was created during this task, delete it to leave a consistent state
                if self.new_load_balancer:
                    AWSRetry.jittered_backoff()(
                        self.connection.delete_load_balancer)(
                            LoadBalancerArn=self.elb['LoadBalancerArn'])
                self.module.fail_json_aws(e)
Esempio n. 13
0
    def modify(self):
        """
        Modify a listener rule

        :return:
        """

        try:
            del self.rule['Priority']
            AWSRetry.jittered_backoff()(
                self.connection.modify_rule)(**self.rule)
        except (BotoCoreError, ClientError) as e:
            if '"Order", must be one of: Type, TargetGroupArn' in str(e):
                self.module.fail_json(
                    msg="installed version of botocore does not support "
                    "multiple actions, please upgrade botocore to version "
                    "1.10.30 or higher")
            else:
                self.module.fail_json_aws(e)

        self.changed = True
Esempio n. 14
0
 def wait(client, db_instance_id, waiter_name, extra_retry_codes):
     retry = AWSRetry.jittered_backoff(
         catch_extra_error_codes=extra_retry_codes)
     try:
         waiter = client.get_waiter(waiter_name)
     except ValueError:
         # using a waiter in ansible.module_utils.aws.waiters
         waiter = get_waiter(client, waiter_name)
     waiter.wait(WaiterConfig={
         'Delay': 60,
         'MaxAttempts': 60
     },
                 DBInstanceIdentifier=db_instance_id)
Esempio n. 15
0
    def get_elb_tags(self):
        """
        Get load balancer tags

        :return:
        """

        try:
            return AWSRetry.jittered_backoff()(self.connection.describe_tags)(
                ResourceArns=[self.elb['LoadBalancerArn']
                              ])['TagDescriptions'][0]['Tags']
        except (BotoCoreError, ClientError) as e:
            self.module.fail_json_aws(e)
Esempio n. 16
0
    def _get_elb_listeners(self):
        """
        Get ELB listeners

        :return:
        """

        try:
            listener_paginator = self.connection.get_paginator(
                'describe_listeners')
            return (AWSRetry.jittered_backoff()(listener_paginator.paginate)(
                LoadBalancerArn=self.elb_arn).build_full_result())['Listeners']
        except (BotoCoreError, ClientError) as e:
            self.module.fail_json_aws(e)
Esempio n. 17
0
def get_elb_listener_rules(connection, module, listener_arn):
    """
    Get rules for a particular ELB listener using the listener ARN.

    :param connection: AWS boto3 elbv2 connection
    :param module: Ansible module
    :param listener_arn: ARN of the ELB listener
    :return: boto3 ELB rules list
    """

    try:
        return AWSRetry.jittered_backoff()(
            connection.describe_rules)(ListenerArn=listener_arn)['Rules']
    except (BotoCoreError, ClientError) as e:
        module.fail_json_aws(e)
Esempio n. 18
0
def convert_tg_name_to_arn(connection, module, tg_name):
    """
    Get ARN of a target group using the target group's name

    :param connection: AWS boto3 elbv2 connection
    :param module: Ansible module
    :param tg_name: Name of the target group
    :return: target group ARN string
    """

    try:
        response = AWSRetry.jittered_backoff()(
            connection.describe_target_groups)(Names=[tg_name])
    except (BotoCoreError, ClientError) as e:
        module.fail_json_aws(e)

    tg_arn = response['TargetGroups'][0]['TargetGroupArn']

    return tg_arn
Esempio n. 19
0
    def get_elb_attributes(self):
        """
        Get load balancer attributes

        :return:
        """

        try:
            attr_list = AWSRetry.jittered_backoff()(
                self.connection.describe_load_balancer_attributes)(
                    LoadBalancerArn=self.elb['LoadBalancerArn'])['Attributes']

            elb_attributes = boto3_tag_list_to_ansible_dict(attr_list)
        except (BotoCoreError, ClientError) as e:
            self.module.fail_json_aws(e)

        # Replace '.' with '_' in attribute key names to make it more Ansibley
        return dict(
            (k.replace('.', '_'), v) for k, v in elb_attributes.items())
Esempio n. 20
0
    def __init__(self, connection, connection_ec2, module):
        """

        :param connection: boto3 connection
        :param module: Ansible module
        """
        super(ApplicationLoadBalancer, self).__init__(connection, module)

        self.connection_ec2 = connection_ec2

        # Ansible module parameters specific to ALBs
        self.type = 'application'
        if module.params.get('security_groups') is not None:
            try:
                self.security_groups = AWSRetry.jittered_backoff()(
                    get_ec2_security_group_ids_from_names)(
                        module.params.get('security_groups'),
                        self.connection_ec2,
                        boto3=True)
            except ValueError as e:
                self.module.fail_json(msg=str(e),
                                      exception=traceback.format_exc())
            except (BotoCoreError, ClientError) as e:
                self.module.fail_json_aws(e)
        else:
            self.security_groups = module.params.get('security_groups')
        self.access_logs_enabled = module.params.get("access_logs_enabled")
        self.access_logs_s3_bucket = module.params.get("access_logs_s3_bucket")
        self.access_logs_s3_prefix = module.params.get("access_logs_s3_prefix")
        self.idle_timeout = module.params.get("idle_timeout")
        self.http2 = module.params.get("http2")

        if self.elb is not None and self.elb['Type'] != 'application':
            self.module.fail_json(
                msg=
                "The load balancer type you are trying to manage is not application. Try elb_network_lb module instead."
            )
Esempio n. 21
0
    def modify_elb_attributes(self):
        """
        Update Application ELB attributes if required

        :return:
        """

        update_attributes = []

        if self.access_logs_enabled is not None and str(
                self.access_logs_enabled).lower(
                ) != self.elb_attributes['access_logs_s3_enabled']:
            update_attributes.append({
                'Key':
                'access_logs.s3.enabled',
                'Value':
                str(self.access_logs_enabled).lower()
            })
        if self.access_logs_s3_bucket is not None and self.access_logs_s3_bucket != self.elb_attributes[
                'access_logs_s3_bucket']:
            update_attributes.append({
                'Key': 'access_logs.s3.bucket',
                'Value': self.access_logs_s3_bucket
            })
        if self.access_logs_s3_prefix is not None and self.access_logs_s3_prefix != self.elb_attributes[
                'access_logs_s3_prefix']:
            update_attributes.append({
                'Key': 'access_logs.s3.prefix',
                'Value': self.access_logs_s3_prefix
            })
        if self.deletion_protection is not None and str(
                self.deletion_protection).lower(
                ) != self.elb_attributes['deletion_protection_enabled']:
            update_attributes.append({
                'Key':
                'deletion_protection.enabled',
                'Value':
                str(self.deletion_protection).lower()
            })
        if self.idle_timeout is not None and str(
                self.idle_timeout
        ) != self.elb_attributes['idle_timeout_timeout_seconds']:
            update_attributes.append({
                'Key': 'idle_timeout.timeout_seconds',
                'Value': str(self.idle_timeout)
            })
        if self.http2 is not None and str(self.http2).lower(
        ) != self.elb_attributes['routing_http2_enabled']:
            update_attributes.append({
                'Key': 'routing.http2.enabled',
                'Value': str(self.http2).lower()
            })

        if update_attributes:
            try:
                AWSRetry.jittered_backoff()(
                    self.connection.modify_load_balancer_attributes)(
                        LoadBalancerArn=self.elb['LoadBalancerArn'],
                        Attributes=update_attributes)
                self.changed = True
            except (BotoCoreError, ClientError) as e:
                # Something went wrong setting attributes. If this ELB was created during this task, delete it to leave a consistent state
                if self.new_load_balancer:
                    AWSRetry.jittered_backoff()(
                        self.connection.delete_load_balancer)(
                            LoadBalancerArn=self.elb['LoadBalancerArn'])
                self.module.fail_json_aws(e)