def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(dict(
        name_prefix=dict(type='str'),
        tags=dict(type='dict', aliases=['instance_tags']),
        filters=dict(type='dict')
    )
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    if HAS_FOOTMARK is False:
        module.fail_json(msg=missing_required_lib('footmark'), exception=FOOTMARK_IMP_ERR)

    ecs = ecs_connect(module)

    instances = []
    instance_ids = []
    ids = []
    name_prefix = module.params['name_prefix']

    filters = module.params['filters']
    if not filters:
        filters = {}
    for key, value in list(filters.items()):
        if key in ["InstanceIds", "instance_ids", "instance-ids"] and isinstance(ids, list):
            for id in value:
                if id not in ids:
                    ids.append(value)
    if ids:
        filters['instance_ids'] = ids
    if module.params['tags']:
        filters['tags'] = module.params['tags']

    for inst in ecs.describe_instances(**filters):
        if name_prefix:
            if not str(inst.instance_name).startswith(name_prefix):
                continue
        volumes = ecs.describe_disks(instance_id=inst.id)
        setattr(inst, 'block_device_mappings', volumes)
        setattr(inst, 'user_data', inst.describe_user_data())
        instances.append(inst.read())
        instance_ids.append(inst.id)

    module.exit_json(changed=False, ids=instance_ids, instances=instances)
示例#2
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(dict(
        availability_zone=dict(aliases=['alicloud_zone']),
        instance_ids=dict(type='list', aliases=['ids']),
        instance_names=dict(type='list', aliases=['names']),
        instance_tags=dict(type='list', aliases=['tags']),
    )
    )
    module = AnsibleModule(argument_spec=argument_spec)
    if module._name == 'ali_instance_facts':
        module.deprecate("The 'ali_instance_facts' module has been renamed to 'ali_instance_info'", version='2.13')

    if HAS_FOOTMARK is False:
        module.fail_json(msg=missing_required_lib('footmark'), exception=FOOTMARK_IMP_ERR)

    ecs = ecs_connect(module)

    instances = []
    instance_ids = []
    ids = module.params['instance_ids']
    names = module.params['instance_names']
    zone_id = module.params['availability_zone']
    if ids and (not isinstance(ids, list) or len(ids) < 1):
        module.fail_json(msg='instance_ids should be a list of instances, aborting')

    if names and (not isinstance(names, list) or len(names) < 1):
        module.fail_json(msg='instance_ids should be a list of instances, aborting')

    if names:
        for name in names:
            for inst in ecs.get_all_instances(zone_id=zone_id, instance_ids=ids, instance_name=name):
                instances.append(inst.read())
                instance_ids.append(inst.id)
    else:
        for inst in ecs.get_all_instances(zone_id=zone_id, instance_ids=ids):
            instances.append(inst.read())
            instance_ids.append(inst.id)

    module.exit_json(changed=False, ids=instance_ids, instances=instances)
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(availability_zone=dict(aliases=['alicloud_zone']),
             instance_ids=dict(type='list', elements='str', aliases=['ids']),
             instance_names=dict(type='list',
                                 elements='str',
                                 aliases=['names']),
             name_prefix=dict(type='str'),
             tags=dict(type='dict', aliases=['instance_tags']),
             filters=dict(type='dict')))
    module = AnsibleModule(argument_spec=argument_spec)
    if module._name in ('ali_instance_facts',
                        'community.general.ali_instance_facts'):
        module.deprecate(
            "The 'ali_instance_facts' module has been renamed to 'ali_instance_info'",
            version='2.13')

    if HAS_FOOTMARK is False:
        module.fail_json(msg=missing_required_lib('footmark'),
                         exception=FOOTMARK_IMP_ERR)

    ecs = ecs_connect(module)

    instances = []
    instance_ids = []
    ids = module.params['instance_ids']
    name_prefix = module.params['name_prefix']
    names = module.params['instance_names']
    zone_id = module.params['availability_zone']
    if ids and (not isinstance(ids, list) or len(ids) < 1):
        module.fail_json(
            msg='instance_ids should be a list of instances, aborting')

    if names and (not isinstance(names, list) or len(names) < 1):
        module.fail_json(
            msg='instance_names should be a list of instances, aborting')

    filters = module.params['filters']
    if not filters:
        filters = {}
    if not ids:
        ids = []
    for key, value in list(filters.items()):
        if key in ["InstanceIds", "instance_ids", "instance-ids"
                   ] and isinstance(ids, list):
            for id in value:
                if id not in ids:
                    ids.append(value)
    if ids:
        filters['instance_ids'] = ids
    if module.params['tags']:
        filters['tags'] = module.params['tags']
    if zone_id:
        filters['zone_id'] = zone_id
    if names:
        filters['instance_name'] = names[0]

    for inst in ecs.describe_instances(**filters):
        if name_prefix:
            if not str(inst.instance_name).startswith(name_prefix):
                continue
        volumes = ecs.describe_disks(instance_id=inst.id)
        setattr(inst, 'block_device_mappings', volumes)
        setattr(inst, 'user_data', inst.describe_user_data())
        instances.append(inst.read())
        instance_ids.append(inst.id)

    module.exit_json(changed=False, ids=instance_ids, instances=instances)
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(security_groups=dict(type='list',
                                  elements='str',
                                  aliases=['group_ids']),
             availability_zone=dict(type='str',
                                    aliases=['alicloud_zone', 'zone_id']),
             instance_type=dict(type='str', aliases=['type']),
             image_id=dict(type='str', aliases=['image']),
             count=dict(type='int', default=1),
             count_tag=dict(type='str'),
             vswitch_id=dict(type='str', aliases=['subnet_id']),
             instance_name=dict(type='str', aliases=['name']),
             host_name=dict(type='str'),
             password=dict(type='str', no_log=True),
             internet_charge_type=dict(
                 type='str',
                 default='PayByBandwidth',
                 choices=['PayByBandwidth', 'PayByTraffic']),
             max_bandwidth_in=dict(type='int', default=200),
             max_bandwidth_out=dict(type='int', default=0),
             system_disk_category=dict(
                 type='str',
                 default='cloud_efficiency',
                 choices=['cloud_efficiency', 'cloud_ssd']),
             system_disk_size=dict(type='int', default=40),
             system_disk_name=dict(type='str'),
             system_disk_description=dict(type='str'),
             force=dict(type='bool', default=False),
             tags=dict(type='dict', aliases=['instance_tags']),
             purge_tags=dict(type='bool', default=False),
             state=dict(default='present',
                        choices=[
                            'present', 'running', 'stopped', 'restarted',
                            'absent'
                        ]),
             description=dict(type='str'),
             allocate_public_ip=dict(type='bool',
                                     aliases=['assign_public_ip'],
                                     default=False),
             instance_charge_type=dict(type='str',
                                       default='PostPaid',
                                       choices=['PrePaid', 'PostPaid']),
             period=dict(type='int', default=1),
             auto_renew=dict(type='bool', default=False),
             instance_ids=dict(type='list', elements='str'),
             auto_renew_period=dict(type='int', choices=[1, 2, 3, 6, 12]),
             key_name=dict(type='str', aliases=['keypair']),
             user_data=dict(type='str'),
             ram_role_name=dict(type='str'),
             spot_price_limit=dict(type='float'),
             spot_strategy=dict(
                 type='str',
                 default='NoSpot',
                 choices=['NoSpot', 'SpotWithPriceLimit', 'SpotAsPriceGo']),
             unique_suffix=dict(type='bool', default=False),
             period_unit=dict(type='str',
                              default='Month',
                              choices=['Month', 'Week']),
             dry_run=dict(type='bool', default=False),
             include_data_disks=dict(type='bool', default=True)))
    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg=missing_required_lib('footmark'),
                         exception=FOOTMARK_IMP_ERR)

    ecs = ecs_connect(module)
    host_name = module.params['host_name']
    state = module.params['state']
    instance_ids = module.params['instance_ids']
    count_tag = module.params['count_tag']
    count = module.params['count']
    instance_name = module.params['instance_name']
    force = module.params['force']
    zone_id = module.params['availability_zone']
    key_name = module.params['key_name']
    tags = module.params['tags']
    max_bandwidth_out = module.params['max_bandwidth_out']
    instance_charge_type = module.params['instance_charge_type']
    if instance_charge_type == "PrePaid":
        module.params['spot_strategy'] = ''
    changed = False

    instances = []
    if instance_ids:
        if not isinstance(instance_ids, list):
            module.fail_json(
                msg='The parameter instance_ids should be a list, aborting')
        instances = ecs.describe_instances(zone_id=zone_id,
                                           instance_ids=instance_ids)
        if not instances:
            module.fail_json(
                msg=
                "There are no instances in our record based on instance_ids {0}. "
                "Please check it and try again.".format(instance_ids))
    elif count_tag:
        instances = ecs.describe_instances(zone_id=zone_id,
                                           tags=eval(count_tag))
    elif instance_name:
        instances = ecs.describe_instances(zone_id=zone_id,
                                           instance_name=instance_name)

    ids = []
    if state == 'absent':
        if len(instances) < 1:
            module.fail_json(
                msg=
                'Please specify ECS instances that you want to operate by using '
                'parameters instance_ids, tags or instance_name, aborting')
        try:
            targets = []
            for inst in instances:
                if inst.status != 'stopped' and not force:
                    module.fail_json(
                        msg=
                        "Instance is running, and please stop it or set 'force' as True."
                    )
                targets.append(inst.id)
            if ecs.delete_instances(instance_ids=targets, force=force):
                changed = True
                ids.extend(targets)

            module.exit_json(changed=changed, ids=ids, instances=[])
        except Exception as e:
            module.fail_json(msg='Delete instance got an error: {0}'.format(e))

    if module.params['allocate_public_ip'] and max_bandwidth_out < 0:
        module.fail_json(
            msg=
            "'max_bandwidth_out' should be greater than 0 when 'allocate_public_ip' is True."
        )
    if not module.params['allocate_public_ip']:
        module.params['max_bandwidth_out'] = 0

    if state == 'present':
        if not instance_ids:
            if len(instances) > count:
                for i in range(0, len(instances) - count):
                    inst = instances[len(instances) - 1]
                    if inst.status != 'stopped' and not force:
                        module.fail_json(
                            msg=
                            "That to delete instance {0} is failed results from it is running, "
                            "and please stop it or set 'force' as True.".
                            format(inst.id))
                    try:
                        if inst.terminate(force=force):
                            changed = True
                    except Exception as e:
                        module.fail_json(
                            msg="Delete instance {0} got an error: {1}".format(
                                inst.id, e))
                    instances.pop(len(instances) - 1)
            else:
                try:
                    if re.search(r"-\[\d+,\d+\]-", host_name):
                        module.fail_json(
                            msg=
                            'Ordered hostname is not supported, If you want to add an ordered '
                            'suffix to the hostname, you can set unique_suffix to True'
                        )
                    new_instances = run_instance(module, ecs,
                                                 count - len(instances))
                    if new_instances:
                        changed = True
                        instances.extend(new_instances)
                except Exception as e:
                    module.fail_json(
                        msg="Create new instances got an error: {0}".format(e))

        # Security Group join/leave begin
        security_groups = module.params['security_groups']
        if security_groups:
            if not isinstance(security_groups, list):
                module.fail_json(
                    msg=
                    'The parameter security_groups should be a list, aborting')
            for inst in instances:
                existing = inst.security_group_ids['security_group_id']
                remove = list(set(existing).difference(set(security_groups)))
                add = list(set(security_groups).difference(set(existing)))
                for sg in remove:
                    if inst.leave_security_group(sg):
                        changed = True
                for sg in add:
                    if inst.join_security_group(sg):
                        changed = True
        # Security Group join/leave ends here

        # Attach/Detach key pair
        inst_ids = []
        for inst in instances:
            if key_name is not None and key_name != inst.key_name:
                if key_name == "":
                    if inst.detach_key_pair():
                        changed = True
                else:
                    inst_ids.append(inst.id)
        if inst_ids:
            changed = ecs.attach_key_pair(instance_ids=inst_ids,
                                          key_pair_name=key_name)

        # Modify instance attribute
        for inst in instances:
            if modify_instance(module, inst):
                changed = True
            if inst.id not in ids:
                ids.append(inst.id)

        # Modify instance charge type
        ids = []
        for inst in instances:
            if inst.instance_charge_type != instance_charge_type:
                ids.append(inst.id)
        if ids:
            params = {
                "instance_ids": ids,
                "instance_charge_type": instance_charge_type,
                "include_data_disks": module.params['include_data_disks'],
                "dry_run": module.params['dry_run'],
                "auto_pay": True
            }
            if instance_charge_type == 'PrePaid':
                params['period'] = module.params['period']
                params['period_unit'] = module.params['period_unit']

            if ecs.modify_instance_charge_type(**params):
                changed = True
                wait_for_instance_modify_charge(ecs, ids, instance_charge_type)

    else:
        if len(instances) < 1:
            module.fail_json(
                msg=
                'Please specify ECS instances that you want to operate by using '
                'parameters instance_ids, tags or instance_name, aborting')
        if state == 'running':
            try:
                targets = []
                for inst in instances:
                    if modify_instance(module, inst):
                        changed = True
                    if inst.status != "running":
                        targets.append(inst.id)
                    ids.append(inst.id)
                if targets and ecs.start_instances(instance_ids=targets):
                    changed = True
                    ids.extend(targets)
            except Exception as e:
                module.fail_json(
                    msg='Start instances got an error: {0}'.format(e))
        elif state == 'stopped':
            try:
                targets = []
                for inst in instances:
                    if inst.status != "stopped":
                        targets.append(inst.id)
                if targets and ecs.stop_instances(instance_ids=targets,
                                                  force_stop=force):
                    changed = True
                    ids.extend(targets)
                for inst in instances:
                    if modify_instance(module, inst):
                        changed = True
            except Exception as e:
                module.fail_json(
                    msg='Stop instances got an error: {0}'.format(e))
        elif state == 'restarted':
            try:
                targets = []
                for inst in instances:
                    if modify_instance(module, inst):
                        changed = True
                        targets.append(inst.id)
                if ecs.reboot_instances(instance_ids=targets,
                                        force_stop=module.params['force']):
                    changed = True
                    ids.extend(targets)
            except Exception as e:
                module.fail_json(
                    msg='Reboot instances got an error: {0}'.format(e))

    tags = module.params['tags']
    if module.params['purge_tags']:
        for inst in instances:
            if not tags:
                tags = inst.tags
            try:
                if inst.remove_tags(tags):
                    changed = True
            except Exception as e:
                module.fail_json(msg="{0}".format(e))
        module.exit_json(changed=changed,
                         instances=get_instances_info(ecs, ids))

    if tags:
        for inst in instances:
            try:
                if inst.add_tags(tags):
                    changed = True
            except Exception as e:
                module.fail_json(msg="{0}".format(e))
    module.exit_json(changed=changed, instances=get_instances_info(ecs, ids))
示例#5
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(security_groups=dict(type='list'),
             availability_zone=dict(type='str', aliases=['alicloud_zone']),
             instance_type=dict(type='str', aliases=['type']),
             image_id=dict(type='str', aliases=['image']),
             count=dict(type='int', default=1),
             count_tag=dict(type='str'),
             vswitch_id=dict(type='str', aliases=['subnet_id']),
             instance_name=dict(type='str', aliases=['name']),
             host_name=dict(type='str'),
             password=dict(type='str', no_log=True),
             internet_charge_type=dict(
                 type='str',
                 default='PayByBandwidth',
                 choices=['PayByBandwidth', 'PayByTraffic']),
             max_bandwidth_in=dict(type='int', default=200),
             max_bandwidth_out=dict(type='int', default=0),
             system_disk_category=dict(
                 type='str',
                 default='cloud_efficiency',
                 choices=['cloud_efficiency', 'cloud_ssd']),
             system_disk_size=dict(type='int', default=40),
             system_disk_name=dict(type='str'),
             system_disk_description=dict(type='str'),
             force=dict(type='bool', default=False),
             instance_tags=dict(type='dict', aliases=['tags']),
             state=dict(default='present',
                        choices=[
                            'present', 'running', 'stopped', 'restarted',
                            'absent'
                        ]),
             description=dict(type='str'),
             allocate_public_ip=dict(type='bool',
                                     aliases=['assign_public_ip'],
                                     default=False),
             instance_charge_type=dict(type='str',
                                       default='PostPaid',
                                       choices=['PrePaid', 'PostPaid']),
             period=dict(type='int', default=1),
             auto_renew=dict(type='bool', default=False),
             instance_ids=dict(type='list'),
             auto_renew_period=dict(type='int', choices=[1, 2, 3, 6, 12]),
             key_name=dict(type='str', aliases=['keypair']),
             user_data=dict(type='str')))
    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg=missing_required_lib('footmark'),
                         exception=FOOTMARK_IMP_ERR)

    ecs = ecs_connect(module)
    state = module.params['state']
    instance_ids = module.params['instance_ids']
    count_tag = module.params['count_tag']
    count = module.params['count']
    instance_name = module.params['instance_name']
    force = module.params['force']
    zone_id = module.params['availability_zone']
    key_name = module.params['key_name']
    changed = False

    instances = []
    if instance_ids:
        if not isinstance(instance_ids, list):
            module.fail_json(
                msg='The parameter instance_ids should be a list, aborting')
        instances = ecs.get_all_instances(zone_id=zone_id,
                                          instance_ids=instance_ids)
        if not instances:
            module.fail_json(
                msg=
                "There are no instances in our record based on instance_ids {0}. "
                "Please check it and try again.".format(instance_ids))
    elif count_tag:
        instances = ecs.get_all_instances(zone_id=zone_id,
                                          instance_tags=eval(count_tag))
    elif instance_name:
        instances = ecs.get_all_instances(zone_id=zone_id,
                                          instance_name=instance_name)

    ids = []
    if state == 'present':
        if not instance_ids:
            if len(instances) > count:
                for i in range(0, len(instances) - count):
                    inst = instances[len(instances) - 1]
                    if inst.status != 'stopped' and not force:
                        module.fail_json(
                            msg=
                            "That to delete instance {0} is failed results from it is running, "
                            "and please stop it or set 'force' as True.".
                            format(inst.id))
                    try:
                        changed = inst.terminate(force=force)
                    except Exception as e:
                        module.fail_json(
                            msg="Delete instance {0} got an error: {1}".format(
                                inst.id, e))
                    instances.pop(len(instances) - 1)
            else:
                try:
                    new_instances = create_instance(module, ecs,
                                                    count - len(instances))
                    if new_instances:
                        changed = True
                        instances.extend(new_instances)
                except Exception as e:
                    module.fail_json(
                        msg="Create new instances got an error: {0}".format(e))

        # Security Group join/leave begin
        security_groups = module.params['security_groups']
        if not isinstance(security_groups, list):
            module.fail_json(
                msg='The parameter security_groups should be a list, aborting')
        if len(security_groups) > 0:
            for inst in instances:
                existing = inst.security_group_ids['security_group_id']
                remove = list(set(existing).difference(set(security_groups)))
                add = list(set(security_groups).difference(set(existing)))
                for sg in remove:
                    if inst.leave_security_group(sg):
                        changed = True
                for sg in add:
                    if inst.join_security_group(sg):
                        changed = True
        # Security Group join/leave ends here

        # Attach/Detach key pair
        inst_ids = []
        for inst in instances:
            if key_name is not None and key_name != inst.key_name:
                if key_name == "":
                    changed = inst.detach_key_pair()
                else:
                    inst_ids.append(inst.id)
        if inst_ids:
            changed = ecs.attach_key_pair(instance_ids=inst_ids,
                                          key_pair_name=key_name)

        # Modify instance attribute
        description = module.params['description']
        host_name = module.params['host_name']
        password = module.params['password']
        for inst in instances:
            if not instance_name:
                instance_name = inst.name
            if not description:
                description = inst.description
            if not host_name:
                host_name = inst.host_name
            try:
                if inst.modify(name=instance_name,
                               description=description,
                               host_name=host_name,
                               password=password):
                    changed = True
            except Exception as e:
                module.fail_json(
                    msg="Modify instance attribute {0} got an error: {1}".
                    format(inst.id, e))

            if inst.id not in ids:
                ids.append(inst.id)

        module.exit_json(changed=changed,
                         ids=ids,
                         instances=get_instances_info(ecs, ids))

    else:
        if len(instances) < 1:
            module.fail_json(
                msg=
                'Please specify ECS instances that you want to operate by using '
                'parameters instance_ids, instance_tags or instance_name, aborting'
            )
        force = module.params['force']
        if state == 'running':
            try:
                for inst in instances:
                    if inst.start():
                        changed = True
                        ids.append(inst.id)

                module.exit_json(changed=changed,
                                 ids=ids,
                                 instances=get_instances_info(ecs, ids))
            except Exception as e:
                module.fail_json(
                    msg='Start instances got an error: {0}'.format(e))
        elif state == 'stopped':
            try:
                for inst in instances:
                    if inst.stop(force=force):
                        changed = True
                        ids.append(inst.id)

                module.exit_json(changed=changed,
                                 ids=ids,
                                 instances=get_instances_info(ecs, ids))
            except Exception as e:
                module.fail_json(
                    msg='Stop instances got an error: {0}'.format(e))
        elif state == 'restarted':
            try:
                for inst in instances:
                    if inst.reboot(force=module.params['force']):
                        changed = True
                        ids.append(inst.id)

                module.exit_json(changed=changed,
                                 ids=ids,
                                 instances=get_instances_info(ecs, ids))
            except Exception as e:
                module.fail_json(
                    msg='Reboot instances got an error: {0}'.format(e))
        else:
            try:
                for inst in instances:
                    if inst.status != 'stopped' and not force:
                        module.fail_json(
                            msg=
                            "Instance is running, and please stop it or set 'force' as True."
                        )
                    if inst.terminate(force=module.params['force']):
                        changed = True

                module.exit_json(changed=changed, ids=[], instances=[])
            except Exception as e:
                module.fail_json(
                    msg='Delete instance got an error: {0}'.format(e))