def create_security_groups(session, group_names, vpc_ids, descriptions):
    """Create Security groups."""
    _, status = EC2SecurityGroupManager(session.get_ec2_session()).\
        create_security_groups(group_names, vpc_ids, descriptions)

    print()
    print(status)
def list_security_groups(session, groups, long):
    """List All Security groups."""
    aok, err = EC2SecurityGroupManager(session.get_ec2_session()).\
        list_security_groups(groups, long)

    if not aok:
        print(err)
Example #3
0
def delete_rule(session, groups, egress_rule, ip_protocol, port_range,
                ipv4_cidr, ipv6_cidr, security_groups, icmp_type, icmp_code):
    """Delete Security Group Rules.

    Delete rules associated with (comma separated)
    groups. Can be group ids or group names of a mix of both'.

    Rules are selected for deletion based on a match of all
    of the above mentioned criteria.
    """
    from_port = None
    to_port = None
    wildcard = ('ignore', 'any')
    if port_range and port_range not in wildcard:
        parts = port_range.split(',')
        if parts[0] not in wildcard:
            from_port = parts[0]

        if len(parts) >= 2 and parts[1] not in wildcard:
            to_port = parts[1]

    _, status = EC2SecurityGroupRuleManager(
        EC2SecurityGroupManager(session.get_ec2_session())). \
        delete_rule(groups, egress_rule,
                    ip_protocol, from_port,
                    to_port, ipv4_cidr,
                    ipv6_cidr, security_groups,
                    icmp_type, icmp_code)

    print()
    print(status)
def delete_security_groups(session, groups):
    """Delete Security group.

    Delete security groups associated with (comma separated) groups.
    Can be group ids or group names of a mix of both'.
    """
    _, status = EC2SecurityGroupManager(session.get_ec2_session()).\
        delete_security_groups(groups)

    print()
    print(status)
Example #5
0
def create_rule(session, groups, egress_rule, ip_protocol, port_range,
                ipv4_cidr, ipv4_descriptions, ipv6_cidr, ipv6_descriptions,
                security_groups, security_group_descriptions, icmp_type,
                icmp_code):
    """Create Security Group Rules."""
    aok, from_port, to_port = util.str_range_to_int(port_range)

    if not aok:
        print(f'Invalid port range : {port_range}')
        return

    aok, status = EC2SecurityGroupRuleManager(
        EC2SecurityGroupManager(session.get_ec2_session())). \
        create_rule(groups, egress_rule,
                    ip_protocol, from_port,
                    to_port, ipv4_cidr, ipv4_descriptions,
                    ipv6_cidr, ipv6_descriptions,
                    security_groups, security_group_descriptions,
                    icmp_type, icmp_code)

    print()
    print(status)
Example #6
0
    def modify_instances(self, instances, security_groups,
                         source_dest_check_flag,
                         user_data, user_data_file,
                         project_name=None, instance_names=None,
                         iam_instance_profile_arn=None,
                         attach_iam_role=None,
                         sfunc=None):
        """Modify EC2 Instances."""
        modify_flag = False
        if security_groups:
            modify_flag = True
            security_groups, err =\
                EC2SecurityGroupManager(self.ec2_session).\
                validate_and_get_security_groups(security_groups)

            if err:
                return err

            security_groups = [group['GroupId'] for group in security_groups]

        if user_data:
            modify_flag = True
            user_data_file, err = self.\
                get_user_data_as_string(user_data_file)
            if err:
                return False, err

        if instance_names:
            modify_flag = True
            instance_names, err = util.convert_to_list(instance_names)
            if not instance_names:
                return False, err

        if attach_iam_role and \
                not iam_instance_profile_arn:
            return False, 'Require an iam instance profile arn'

        if attach_iam_role is not None:
            modify_flag = True

        if not modify_flag:
            return False, 'Nothing to modify'

        def default_status(status_str):
            print(status_str)

        if not sfunc:
            sfunc = default_status

        success_count = 0
        failure_count = 0
        index = 0
        user_data_file_template = user_data_file
        try:
            for inst in self.ec2_session.\
                    get_instances(instances, project_name,
                                  states='terminated', include_states=False):
                instance_name = None \
                    if not instance_names or index >= len(instance_names) \
                    else instance_names[index]
                if not instance_name:
                    tags = self.ec2_session.get_instance_tags(inst)
                    instance_name = tags.get('Name')
                if user_data:
                    user_data_file = \
                        self.update_user_data(user_data_file_template,
                                              instance_name)
                else:
                    user_data_file = None

                aok, err = self.\
                    ec2_session.modify_instance(inst, security_groups,
                                                source_dest_check_flag,
                                                user_data_file, instance_name,
                                                iam_instance_profile_arn,
                                                attach_iam_role,
                                                base64_encode=False,
                                                sfunc=sfunc)
                if not aok:
                    sfunc(err)
                    failure_count += 1
                else:
                    success_count += 1

                index += 1

            return self.ec2_session.get_status(success_count, failure_count)
        except ClientError as client_err:
            return False, str(client_err)
Example #7
0
    def create_instances(self, image_name, instance_type, security_groups,
                         key_name, min_count=1, max_count=1, subnet_id=None,
                         user_data=False, user_data_file=None,
                         project_name=None, instance_name=None,
                         iam_instance_profile_arn=None,
                         base64_encode=False):
        """Create EC2 Instances."""
        if not key_name:
            return False, 'Require key_name'

        if not instance_type:
            return False, 'Require instance_type'

        if not min_count:
            return False, 'Require min_count'

        if not max_count:
            return False, 'Require max_count'

        security_groups, err =\
            EC2SecurityGroupManager(self.ec2_session).\
            validate_and_get_security_groups(security_groups)
        if err:
            return False, err
        security_groups = [group['GroupId'] for group in security_groups]

        image_id = self.ec2_session.\
            get_image_id_from_name(image_name)

        if not image_id:
            return False, f'Invalid Image Name : {image_name}'

        if instance_name:
            min_count = 1
            max_count = 1

        param_dict = {
            'ImageId': image_id,
            'InstanceType': instance_type,
            'KeyName': key_name,
            'MinCount': min_count,
            'MaxCount': max_count,
            'SecurityGroupIds': security_groups
        }

        if project_name:
            tag_spec = [
                {'ResourceType': 'instance',
                 'Tags': [{
                     'Key': 'Project',
                     'Value': project_name}]},
                {'ResourceType': 'volume',
                 'Tags': [{
                     'Key': 'Project',
                     'Value': project_name}]}
            ]
            param_dict['TagSpecifications'] = tag_spec

        if instance_name:
            instance_name_tag_dict = \
                {'Key': 'Name', 'Value': instance_name}
            tag_spec = param_dict.get('TagSpecifications', [])
            tags = None
            for tag in tag_spec:
                if tag['ResourceType'] == 'instance':
                    tags = tag['Tags']
                    break

            if not tags:
                tags = []
                tag_spec.append({'ResourceType': 'instance', 'Tags': tags})

            tags.append(instance_name_tag_dict)
            param_dict['TagSpecifications'] = tag_spec

        if subnet_id:
            param_dict['SubnetId'] = subnet_id

        if user_data:
            user_data_file, err = self.\
                get_user_data_as_string(user_data_file)
            user_data_file = self.update_user_data(user_data_file,
                                                   instance_name)
            if err:
                return False, err

            if base64_encode:
                user_data_file = \
                    util.get_base64_encoding(user_data_file)

            param_dict['UserData'] = user_data_file

        if iam_instance_profile_arn:
            param_dict['IamInstanceProfile'] = \
                {'Arn': iam_instance_profile_arn}

        try:
            instances = self.ec2_session.get_ec2_resource().\
                create_instances(**param_dict)

            return True, 'Success : InstanceIds : ' + \
                f'{[instance.id for instance in instances]}'
        except ClientError as client_error:
            return False, str(client_error)