コード例 #1
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(dict(
        group_name=dict(type='str', aliases=['name']),
        group_ids=dict(type='list', aliases=['ids']),
        filters=dict(type='dict')
    ))

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg="Package 'footmark' required for this module.")

    ecs = ecs_connect(module)

    group_ids = module.params['group_ids']
    name = module.params['group_name']

    changed = False
    result = []
    try:
        security_groups = ecs.get_all_security_groups(module.params)
        group_ids = []
        for sg in security_groups:
            if group_ids and sg.security_group_id not in group_ids:
                continue
            if name and sg.security_group_name != name:
                continue
            result.append(sg.read())
            group_ids.append(sg.id)
    except ECSResponseError as e:
        module.fail_json(msg='Error in get_all_security_groups: {0}'.format(e))

    module.exit_json(changed=changed, ids=group_ids, groups=result)
コード例 #2
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(dict(
        key_pair_name=dict(type='str'), aliases=["name"]),
        key_pair_finger_print=dict(type="str")
    )
    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg="Package 'footmark' required for this module.")

    filters = {}
    key_pair_name = module.params['key_pair_name']
    if key_pair_name:
        filters['key_pair_name'] = key_pair_name

    key_pair_finger_print = module.params['key_pair_finger_print']
    if key_pair_finger_print:
        filters['key_pair_finger_print'] = key_pair_finger_print

    changed = False
    key_pairs = []
    try:
        for key_pair in ecs_connect(module).describe_key_pairs(**filters):
            key_pairs.append(key_pair.get().read())

    except ECSResponseError as e:
        module.fail_json(msg='Error in describe_key_pairs: {0}'.format(e))

    module.exit_json(changed=changed, key_pairs=key_pairs)
コード例 #3
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']),
        name_prefix=dict(type='str'),
        tags=dict(type='dict', aliases=['instance_tags']),
        filters=dict(type='dict')
    )
    )
    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg='footmark required for the module ali_instance_facts')

    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 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
        instances.append(inst.read())
        instance_ids.append(inst.id)

    module.exit_json(changed=False, ids=instance_ids, instances=instances)
コード例 #4
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(group_name=dict(type='str', aliases=['name']),
             name_prefix=dict(type='str'),
             tags=dict(type='dict'),
             group_ids=dict(type='list', aliases=['ids']),
             filters=dict(type='dict')))

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg="Package 'footmark' required for this module.")

    ecs = ecs_connect(module)

    filters = module.params["filters"]
    if not filters:
        filters = {}

    group_ids = module.params['group_ids']
    if not group_ids:
        group_ids = []
    for key, value in list(filters.items()):
        if key in [
                "SecurityGroupIds", "security_group_ids", "security_group_ids"
        ] and isinstance(group_ids, list):
            for id in value:
                if id not in group_ids:
                    group_ids.append(id)
    if group_ids:
        filters["security_group_ids"] = group_ids

    name = module.params['group_name']
    name_prefix = module.params['name_prefix']
    if module.params['tags']:
        filters['tags'] = module.params['tags']

    changed = False
    groups = []
    ids = []
    try:
        for sg in ecs.describe_security_groups(**filters):
            if name and sg.security_group_name != name:
                continue
            if name_prefix and not str(
                    sg.security_group_name).startswith(name_prefix):
                continue
            groups.append(sg.get().read())
            ids.append(sg.id)
    except ECSResponseError as e:
        module.fail_json(
            msg='Error in describe_security_groups: {0}'.format(e))

    module.exit_json(changed=changed, ids=ids, groups=groups)
コード例 #5
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(
            alicloud_zone=dict(aliases=['zone_id', 'zone']),
            instance_type_ids=dict(type='list', aliases=["ids"]),
            instance_type_families=dict(type='list', aliases=["families"]),
            cpu_core_count=dict(type='int', aliases=["cpu_count"]),
            memory_size=dict(type='float', aliases=["memory"]),
        )
    )
    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg='footmark required for the module alicloud_instance_type_facts')

    ecs = ecs_connect(module)

    instance_types = []
    ids = []

    zone_id = module.params["alicloud_zone"]
    instance_type_ids = module.params["instance_type_ids"]
    instance_type_families = module.params["instance_type_families"]
    cpu_core_count = module.params["cpu_core_count"]
    memory_size = module.params["memory_size"]

    if zone_id:
        zones = ecs.describe_zones(zone_id=zone_id)
        families = [f for z in zones for resource in z.available_resources["resources_info"] for f in resource["instance_type_families"]["supported_instance_type_family"]]

        if instance_type_families:
            filter_families = [f for f in instance_type_families if f in families]
            if not filter_families:
                module.fail_json(msg="Instance type families {0} is not supported in the zone {1}. Expected instance type families: {2}.".format(instance_type_families, zone_id, families))
            families = filter_families

        families = list(set(families))
    else:
        families = [f.id for f in ecs.describe_instance_type_families() if not instance_type_families or f.id in instance_type_families]

    for family in families:
        for instance_type in ecs.describe_instance_types(instance_type_family=family):
            if cpu_core_count and instance_type.cpu_core_count != cpu_core_count:
                continue
            if memory_size and instance_type.memory_size != memory_size:
                continue
            if instance_type_ids and instance_type.id not in instance_type_ids:
                continue
            instance_types.append(get_instance_type_info(instance_type))
            ids.append(instance_type.id)

    module.exit_json(changed=False, instance_type_ids=ids, instance_types=instance_types,
                     total=len(instance_types))
コード例 #6
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(
            image_ids=dict(type='list', elements='str', aliases=['ids']),
            image_names=dict(type='list', elements='str', aliases=['names']),
        ))
    module = AnsibleModule(argument_spec=argument_spec)
    if HAS_FOOTMARK is False:
        module.fail_json(msg="Package 'footmark' required for this module.")

    image_ids = module.params['image_ids']
    image_names = module.params['image_names']
    result = []
    ids = []

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

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

    try:
        ecs = ecs_connect(module)
        if image_ids:
            image_id = ",".join(image_ids)
            for image in ecs.get_all_images(image_id=image_id):
                result.append(get_info(image))
                ids.append(image.image_id)

        elif image_names:
            for name in image_names:
                for image in ecs.get_all_images(image_name=name):
                    if image:
                        result.append(get_info(image))
                        ids.append(image.image_id)

        else:
            for image in ecs.get_all_images():
                result.append(get_info(image))
                ids.append(image.image_id)

        module.exit_json(changed=False,
                         image_ids=ids,
                         images=result,
                         total=len(result))

    except ECSResponseError as e:
        module.fail_json(msg='Error in describe images: %s' % str(e))
コード例 #7
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(state=dict(default='present', choices=['present', 'absent']),
             resource_ids=dict(type='list', elements='str', required=True),
             resource_type=dict(
                 type='str',
                 default='instance',
                 choices=['instance', 'disk', 'image', 'eni',
                          'securitygroup']),
             tags=dict(type='dict')))

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg='footmark required for the module ali_ecs_tag.')

    ecs_conn = ecs_connect(module)
    if module.params['resource_type'] == 'instance':
        resources = ecs_exists(module, ecs_conn)
    elif module.params['resource_type'] == 'disk':
        resources = disk_exists(module, ecs_conn)
    elif module.params['resource_type'] == 'image':
        resources = image_exists(module, ecs_conn)
    elif module.params['resource_type'] == 'eni':
        resources = eni_exists(module, ecs_conn)
    else:
        resources = sgroup_exists(module, ecs_conn)

    if not resources:
        module.fail_json(
            msg='No matching resource was found based on the IDS provided.')

    #Get values of variable
    tags = module.params['tags']

    if module.params['state'] == "present":
        ecs_changed = ecs_conn.tag_resources(
            resource_ids=module.params['resource_ids'],
            tags=tags,
            resource_type=module.params['resource_type'])
    else:
        ecs_changed = ecs_conn.untag_resources(
            resource_ids=module.params['resource_ids'],
            tags=tags,
            resource_type=module.params['resource_type'])

    result = []
    for resource in resources:
        result.append(resource.read()['tags'])

    module.exit_json(changed=ecs_changed, tags=result)
コード例 #8
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(vpc_id=dict(type='str'),
             group_ids=dict(type='list', aliases=['ids']),
             names=dict(type='list')))

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg="Package 'footmark' required for this module.")

    ecs = ecs_connect(module)

    vpc_id = module.params['vpc_id']
    group_ids = module.params['group_ids']
    names = module.params['names']

    changed = False
    result = []

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

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

    try:
        security_groups = ecs.get_all_security_groups(group_ids=group_ids,
                                                      vpc_id=vpc_id)
        group_ids = []
        for security_group in security_groups:
            result.append(get_group_detail(security_group))
            group_ids.append(security_group.id)

        if names:
            for name in names:
                security_groups = ecs.get_all_security_groups(name=name)
                for security_group in security_groups:
                    result.append(get_group_detail(security_group))
                    group_ids.append(security_group.id)

    except ECSResponseError as e:
        module.fail_json(msg='Error in get_all_security_groups: %s' % str(e))

    module.exit_json(changed=changed,
                     group_ids=group_ids,
                     security_groups=result,
                     total=len(result))
コード例 #9
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)
コード例 #10
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(
            alicloud_zone=dict(
                aliases=['acs_zone', 'ecs_zone', 'zone_id', '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 HAS_FOOTMARK is False:
        module.fail_json(
            msg='footmark required for the module alicloud_instance_facts')

    ecs = ecs_connect(module)

    instances = []
    instance_ids = []
    ids = module.params['instance_ids']
    names = module.params['instance_names']
    zone_id = module.params['alicloud_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(get_instance_info(inst))
                instance_ids.append(inst.id)
    else:
        for inst in ecs.get_all_instances(zone_id=zone_id, instance_ids=ids):
            instances.append(get_instance_info(inst))
            instance_ids.append(inst.id)

    module.exit_json(changed=False,
                     instance_ids=instance_ids,
                     instances=instances,
                     total=len(instances))
コード例 #11
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(
            eni_ids=dict(type='list', aliases=['ids']),
            name_prefix=dict(),
            tags=dict(type='dict'),
            filters=dict(type='dict'),
        ))
    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(msg='footmark required for the module ali_eni_facts')

    interfaces = []
    ids = []
    filters = module.params["filters"]
    if not filters:
        filters = {}
    eni_ids = module.params["eni_ids"]
    if not eni_ids:
        eni_ids = []
    for key, value in list(filters.items()):
        if str(key).startswith("NetworkInterfaceId") or \
                str(key).startswith("network_interface_id") or \
                str(key).startswith("network-interface-id"):
            if value not in eni_ids:
                eni_ids.append(value)
    if eni_ids:
        filters['network_interface_ids'] = eni_ids

    name_prefix = module.params["name_prefix"]
    if module.params['tags']:
        filters['tags'] = module.params['tags']

    try:
        for eni in ecs_connect(module).describe_network_interfaces(**filters):
            if name_prefix and not str(eni.name).startswith(name_prefix):
                continue
            interfaces.append(eni.read())
            ids.append(eni.id)

        module.exit_json(changed=False, ids=ids, interfaces=interfaces)
    except Exception as e:
        module.fail_json(
            msg=str("Unable to get network interfaces, error:{0}".format(e)))
コード例 #12
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(
            alicloud_zone=dict(
                aliases=['acs_zone', 'ecs_zone', 'zone_id', 'zone']),
            disk_ids=dict(type='list', aliases=['ids']),
            disk_names=dict(type='list', aliases=['names']),
        ))
    module = AnsibleModule(argument_spec=argument_spec)
    if HAS_FOOTMARK is False:
        module.fail_json(msg='footmark required for this module')

    ecs = ecs_connect(module)

    disks = []
    disk_ids = []
    ids = module.params['disk_ids']
    names = module.params['disk_names']
    zone_id = module.params['alicloud_zone']
    if ids and (not isinstance(ids, list) or len(ids)) < 1:
        module.fail_json(msg='disk_ids should be a list of disk id, aborting')

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

    if names:
        for name in names:
            for disk in ecs.get_all_volumes(zone_id=zone_id,
                                            volume_ids=ids,
                                            volume_name=name):
                disks.append(get_disk_info(disk))
                disk_ids.append(disk.id)
    else:
        for disk in ecs.get_all_volumes(zone_id=zone_id, volume_ids=ids):
            disks.append(get_disk_info(disk))
            disk_ids.append(disk.id)

    module.exit_json(changed=False,
                     disk_ids=disk_ids,
                     disks=disks,
                     total=len(disks))
コード例 #13
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(filters=dict(type='dict'),
             name_prefix=dict(type='str'),
             tags=dict(type='dict')))
    module = AnsibleModule(argument_spec=argument_spec)
    if HAS_FOOTMARK is False:
        module.fail_json(msg='footmark required for this module')

    ecs = ecs_connect(module)

    disks = []
    disk_ids = []

    filters = module.params['filters']
    if not filters:
        filters = {}

    name_prefix = module.params['name_prefix']
    tags = module.params['tags']

    for disk in ecs.describe_disks(**filters):
        if name_prefix and not str(disk.name).startswith(name_prefix):
            continue
        if tags:
            flag = False
            for key, value in list(tags.items()):
                if key in list(disk.tags.keys()) and value == disk.tags[key]:
                    flag = True
            if not flag:
                continue
        disks.append(disk.read())
        disk_ids.append(disk.id)

    module.exit_json(changed=False,
                     disk_ids=disk_ids,
                     disks=disks,
                     total=len(disks))
コード例 #14
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']),
             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 == '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)
コード例 #15
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(resource_group_id=dict(type='str', aliases=['group_id']),
             alicloud_zone=dict(type='str', aliases=['zone_id', 'zone']),
             state=dict(type='str',
                        default='present',
                        choices=['present', 'absent']),
             disk_id=dict(type='str', aliases=['vol_id', 'id']),
             disk_name=dict(type='str', aliases=['name']),
             disk_category=dict(type='str',
                                aliases=['disk_type', 'volume_type'],
                                choices=[
                                    'cloud', 'cloud_efficiency', 'cloud_ssd',
                                    'cloud_essd'
                                ],
                                default='cloud'),
             size=dict(type='int', aliases=['disk_size', 'volume_size']),
             disk_tags=dict(type='list', aliases=['tags']),
             snapshot_id=dict(type='str', aliases=['snapshot']),
             description=dict(type='str', aliases=['disk_description']),
             instance_id=dict(type='str', aliases=['instance']),
             delete_with_instance=dict(type='bool',
                                       aliases=['delete_on_termination'],
                                       default=False)))
    module = AnsibleModule(argument_spec=argument_spec)

    if not HAS_FOOTMARK:
        module.fail_json(msg="footmark required for the module ali_disk.")

    ecs = ecs_connect(module)
    state = module.params['state']

    instance_id = module.params['instance_id']
    disk_id = module.params['disk_id']
    zone_id = module.params['alicloud_zone']
    disk_name = module.params['disk_name']
    delete_with_instance = module.params['delete_with_instance']
    description = module.params['description']

    changed = False
    current_disk = None

    try:
        if disk_id:
            disks = ecs.get_all_volumes(zone_id=zone_id, volume_ids=[disk_id])
            if disks and len(disks) == 1:
                current_disk = disks[0]
        elif disk_name:
            disks = ecs.get_all_volumes(zone_id=zone_id, volume_name=disk_name)
            if disks:
                if len(disks) == 1:
                    current_disk = disks[0]
                else:
                    disk_ids = []
                    for d in disks:
                        disk_ids.append(d.id)
                    module.fail_json(
                        msg="There is too many disks match name '{0}', "
                        "please use disk_id or a new disk_name to specify a unique disk."
                        "Matched disk ids are: {1}".format(
                            disk_name, disk_ids))
    except ECSResponseError as e:
        module.fail_json(msg='Error in get_all_volumes: %s' % str(e))

    if state == 'absent':
        if not current_disk:
            module.fail_json(
                msg=
                "Please use disk_id or disk_name to specify one disk for detaching or deleting."
            )
        if instance_id:
            try:
                changed = current_disk.detach(instance_id)
                module.exit_json(changed=changed,
                                 disk_id=current_disk.id,
                                 disk_category=current_disk.category,
                                 disk_status=current_disk.status,
                                 instance_id=instance_id,
                                 disk=get_disk_detail(current_disk))
            except Exception as e:
                module.fail_json(
                    msg='Detaching disk {0} is failed, error: {1}'.format(
                        current_disk.id, e))

        try:
            changed = current_disk.delete()
            module.exit_json(changed=changed)
        except Exception as e:
            module.fail_json(
                msg='Deleting disk {0} is failed, error: {1}'.format(
                    current_disk.id, e))

    # state == present
    if not current_disk:
        disk_category = module.params['disk_category']
        size = module.params['size']
        disk_tags = module.params['disk_tags']
        snapshot_id = module.params['snapshot_id']
        client_token = "Ansible-Alicloud-%s-%s" % (hash(str(
            module.params)), str(time.time()))
        try:
            current_disk = ecs.create_disk(zone_id=zone_id,
                                           disk_name=disk_name,
                                           description=description,
                                           disk_category=disk_category,
                                           size=size,
                                           disk_tags=disk_tags,
                                           snapshot_id=snapshot_id,
                                           client_token=client_token)
            changed = True
        except Exception as e:
            module.fail_json(
                msg='Creating a new disk is failed, error: {0}'.format(e))

    else:
        try:
            if current_disk.name != disk_name \
                    or current_disk.description != description \
                    or current_disk.delete_with_instance != delete_with_instance:
                changed = current_disk.modify(
                    disk_name=disk_name,
                    description=description,
                    delete_with_instance=delete_with_instance)
        except Exception as e:
            module.fail_json(
                msg='Updating disk {0} attribute is failed, error: {1}'.format(
                    current_disk.id, e))

    if instance_id and current_disk and str(
            current_disk.status).lower() == "available":
        try:
            changed = current_disk.attach(
                instance_id=instance_id,
                delete_with_instance=delete_with_instance)
        except Exception as e:
            module.fail_json(
                msg='Attaching disk {0} to instance {1} is failed, error: {2}'.
                format(current_disk.id, instance_id, e))

    module.exit_json(changed=changed,
                     disk_id=current_disk.id,
                     disk_category=current_disk.category,
                     disk_status=current_disk.status,
                     instance_id=instance_id,
                     disk=get_disk_detail(current_disk))
コード例 #16
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(image_id=dict(),
             snapshot_id=dict(aliases=['snapshot']),
             description=dict(),
             image_name=dict(aliases=['name']),
             image_version=dict(aliases=['version']),
             disk_mapping=dict(type='list'),
             instance_id=dict(aliases=['instance']),
             status=dict(default='present',
                         choices=['present', 'absent'],
                         aliases=['state']),
             images_tags=dict(type='list', aliases=['tags']),
             launch_permission=dict(type='list'),
             wait=dict(default='no',
                       choices=[
                           'yes', 'no', 'Yes', 'No', "true", "false", "True",
                           "False"
                       ]),
             wait_timeout=dict(type='int', default='300')))
    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(
            msg='footmark required for the module alicloud_security_group.')

    ecs = ecs_connect(module)
    state = module.params['status']
    image_id = module.params['image_id']
    image_name = module.params['image_name']

    changed = False
    current_image = None

    try:
        if image_id:
            images = ecs.get_all_images(image_id=image_id)
            if images and len(images) == 1:
                current_image = images[0]
        elif image_name:
            images = ecs.get_all_images(image_name=image_name)
            if images:
                if len(images) == 1:
                    current_image = images[0]
                else:
                    images_ids = []
                    for i in images:
                        images_ids.append(i.id)
                    module.fail_json(
                        msg="There is too many images match name '{0}', "
                        "please use image_id or a new image_name to specify a unique image."
                        "Matched images ids are: {1}".format(
                            image_name, images_ids))
    except ECSResponseError as e:
        module.fail_json(msg='Error in get_all_images: %s' % str(e))

    if state == 'absent':
        if not current_image:
            module.fail_json(
                msg=
                "Please use valid image_id or image_name to specify one image for deleting."
            )

        try:
            changed = current_image.delete()
            module.exit_json(changed=changed,
                             image_id=current_image.id,
                             image=get_image_detail(current_image))
        except Exception as e:
            module.fail_json(
                msg='Deleting a image is failed, error: {0}'.format(e))

    if not current_image:
        snapshot_id = module.params['snapshot_id']
        image_version = module.params['image_version']
        description = module.params['description']
        disk_mapping = module.params['disk_mapping']
        instance_id = module.params['instance_id']
        images_tags = module.params['images_tags']
        wait = module.params['wait']
        wait_timeout = module.params['wait_timeout']
        launch_permission = module.params['launch_permission']

        try:
            # Calling create_image method
            changed, result, current_image = create_image(
                module=module,
                ecs=ecs,
                snapshot_id=snapshot_id,
                image_name=image_name,
                image_version=image_version,
                description=description,
                images_tags=images_tags,
                instance_id=instance_id,
                disk_mapping=disk_mapping,
                wait=wait,
                wait_timeout=wait_timeout,
                launch_permission=launch_permission)

            module.exit_json(changed=changed,
                             result=result,
                             image=get_image_detail(current_image))
        except Exception as e:
            module.fail_json(
                msg='Creating a new image is failed, error: {0}'.format(e))
コード例 #17
0
ファイル: ali_eni.py プロジェクト: Rhealb/helium
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(
            eni_id=dict(type='str', aliases=['id']),
            instance_id=dict(type='str'),
            private_ip_address=dict(type='str', aliases=['private_ip']),
            vswitch_id=dict(type='str', aliases=['subnet_id']),
            description=dict(type='str'),
            name=dict(type='str'),
            security_groups=dict(type='list'),
            state=dict(default='present', choices=['present', 'absent']),
            attached=dict(default=None, type='bool')
        )
    )

    module = AnsibleModule(argument_spec=argument_spec,
                           required_if=([
                               ('attached', True, ['instance_id'])
                           ])
                           )

    if not HAS_FOOTMARK:
        module.fail_json(msg='footmark required for this module')

    ecs = ecs_connect(module)
    state = module.params.get("state")

    eni = uniquely_find_eni(ecs, module)

    changed = False
    if state == 'absent':
        if not eni:
            module.exit_json(changed=changed, interface={})
        try:
            changed = eni.delete()
            module.exit_json(changed=changed, interface={})
        except Exception as e:
            module.fail_json(msg="{0}".format(e))

    # when state is present
    group_ids = module.params.get("security_groups")
    name = module.params.get("name")
    description = module.params.get("description")
    if not eni:
        if not group_ids:
            module.fail_json(msg="'security_groups' is required when creating a new ENI")
        vswitch_id = module.params.get("vswitch_id")
        if not vswitch_id:
            module.fail_json(msg="'vswitch_id' is required when creating a new ENI")
        try:
            params = module.params
            params['security_group_id'] = group_ids[0]
            params['primary_ip_address'] = module.params.get("private_ip_address")
            params['network_interface_name'] = module.params.get("name")
            params['client_token'] = "Ansible-Alicloud-{0}-{1}".format(hash(str(module.params)), str(time.time()))
            eni = ecs.create_network_interface(params)
            changed = True
        except Exception as e:
            module.fail_json(msg="{0}".format(e))

    if not group_ids:
        group_ids = eni.security_group_ids["security_group_id"]
    if not name:
        name = eni.name
    if not description:
        description = eni.description
    try:
        if eni.modify(group_ids, name, description):
            changed = True
    except Exception as e:
        module.fail_json(msg="{0}".format(e))

    attached = module.params.get("attached")
    instance_id = module.params.get("instance_id")
    try:
        if attached is True:
            if not eni.instance_id:
                if eni.attach(instance_id):
                    changed = True
            elif eni.instance_id != instance_id and eni.detach(eni.instance_id) and eni.attach(instance_id):
                changed = True
        elif attached is False:
            if eni.detach(eni.instance_id):
                changed = True
    except Exception as e:
        module.fail_json(msg="{0}".format(e))

    module.exit_json(changed=changed, interface=eni.get().read())
コード例 #18
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(state=dict(default='present',
                        type='str',
                        choices=['present', 'absent']),
             group_name=dict(type='str', required=False, aliases=['name']),
             description=dict(type='str', required=False),
             vpc_id=dict(type='str'),
             group_tags=dict(type='list', aliases=['tags']),
             rules=dict(type='list'),
             rules_egress=dict(type='list'),
             group_id=dict(type='str')))

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(
            msg='footmark required for the module alicloud_security_group.')

    ecs = ecs_connect(module)

    state = module.params['state']
    group_name = module.params['group_name']
    description = module.params['description']
    vpc_id = module.params['vpc_id']
    group_id = module.params['group_id']
    group_tags = module.params['group_tags']

    changed = False
    group = None
    groups_by_name = []

    try:
        if group_id:
            security_groups = ecs.get_all_security_groups(group_ids=[group_id],
                                                          vpc_id=vpc_id)
        else:
            security_groups = ecs.get_all_security_groups(vpc_id=vpc_id)
    except ECSResponseError as e:
        module.fail_json(msg='Error in get_all_security_groups: %s' % str(e))

    if security_groups and len(security_groups) == 1:
        group = security_groups[0]

    group_ids_by_name = []
    group_ids = []
    if not group and group_name and security_groups:
        for cur in security_groups:
            if cur.name == group_name:
                group_ids_by_name.append(cur.id)
                groups_by_name.append(cur)

            group_ids.append(cur.id)

        if len(groups_by_name) == 1:
            group = groups_by_name[0]
        elif len(groups_by_name) > 1:
            module.fail_json(
                msg="There is too many security groups match name '{0}', "
                "please use group_id or a new group_name and vpc_id to specify a unique group."
                "Matched group ids are: {1}".format(group_name,
                                                    group_ids_by_name))

    if state == 'absent':
        if group:
            try:
                changed = group.delete()
                module.exit_json(changed=changed)
            except ECSResponseError as e:
                module.fail_json(
                    msg="Deleting security group {0} is failed. Error: {1}".
                    format(group.id, e))

        module.fail_json(
            changed=changed,
            msg=
            "Please specify a security group by using 'group_id' or 'group_name' "
            "and 'vpc_id', and expected group ids: {0}".format(group_ids))

    if not group:
        try:
            group = ecs.create_security_group(group_name=group_name,
                                              description=description,
                                              vpc_id=vpc_id,
                                              group_tags=group_tags)
            changed = True

        except ECSResponseError as e:
            module.fail_json(
                changed=changed,
                msg='Creating a security group is failed. Error: {0}'.format(
                    e))

    # validating rules if provided
    total_rules_count = 0
    inbound_rules = module.params['rules']
    if inbound_rules:
        total_rules_count = len(inbound_rules)

    outbound_rules = module.params['rules_egress']
    if outbound_rules:
        total_rules_count += len(outbound_rules)

    if total_rules_count > 100:
        module.fail_json(
            msg='more than 100 rules for authorization are not allowed')

    validate_format_sg_rules(module, inbound_rules, outbound_rules)

    if inbound_rules or outbound_rules:
        changed = authorize_security_group(module,
                                           ecs,
                                           group_id=group.id,
                                           inbound_rules=inbound_rules,
                                           outbound_rules=outbound_rules)

    module.exit_json(changed=changed,
                     group_id=group.id,
                     group=get_group_detail(group),
                     vpc_id=group.vpc_id)
コード例 #19
0
ファイル: ali_security_group.py プロジェクト: Rhealb/helium
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(state=dict(default='present',
                        type='str',
                        choices=['present', 'absent']),
             group_name=dict(type='str', required=False, aliases=['name']),
             description=dict(type='str', required=False),
             vpc_id=dict(type='str'),
             group_tags=dict(type='list', aliases=['tags']),
             rules=dict(type='list'),
             rules_egress=dict(type='list'),
             group_id=dict(type='str')))

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(
            msg='footmark required for the module ali_security_group.')

    ecs = ecs_connect(module)

    state = module.params['state']
    group_name = module.params['group_name']
    description = module.params['description']
    vpc_id = module.params['vpc_id']
    group_id = module.params['group_id']
    group_tags = module.params['group_tags']

    changed = False
    group = None

    try:
        if group_id:
            security_groups = ecs.get_all_security_groups()
            for sg in security_groups:
                if sg.security_group_id == group_id:
                    group = sg
    except ECSResponseError as e:
        module.fail_json(msg='Error in get_all_security_groups: %s' % str(e))

    if state == 'absent':
        if not group:
            module.exit_json(changed=changed, group={})
        try:
            module.exit_json(changed=group.delete(), group={})
        except ECSResponseError as e:
            module.fail_json(
                msg="Deleting security group {0} is failed. Error: {1}".format(
                    group.id, e))

    if not group:
        try:
            client_token = "Ansible-Alicloud-%s-%s" % (hash(str(
                module.params)), str(time.time()))
            group = ecs.create_security_group(group_name=group_name,
                                              description=description,
                                              vpc_id=vpc_id,
                                              group_tags=group_tags,
                                              client_token=client_token)
            changed = True

        except ECSResponseError as e:
            module.fail_json(
                changed=changed,
                msg='Creating a security group is failed. Error: {0}'.format(
                    e))

    # validating rules if provided
    total_rules_count = 0
    inbound_rules = module.params['rules']
    if inbound_rules:
        total_rules_count = len(inbound_rules)

    outbound_rules = module.params['rules_egress']
    if outbound_rules:
        total_rules_count += len(outbound_rules)

    if total_rules_count > 100:
        module.fail_json(
            msg='more than 100 rules for authorization are not allowed')

    validate_format_sg_rules(module, inbound_rules, outbound_rules)

    if inbound_rules or outbound_rules:
        if authorize_security_group(module,
                                    ecs,
                                    group_id=group.id,
                                    inbound_rules=inbound_rules,
                                    outbound_rules=outbound_rules):
            changed = True

    module.exit_json(changed=changed, group=group.get().read())
コード例 #20
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(group_id=dict(type='str', aliases=['security_group_id']),
             alicloud_zone=dict(type='str', aliases=['zone_id', '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'),
             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'),
             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'),
             period=dict(type='int', default=1),
             auto_renew=dict(type='bool', default=False),
             instance_ids=dict(type='list'),
             sg_action=dict(type='str'),
             auto_renew_period=dict(type='int'),
             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="Package 'footmark' required for the module alicloud_instance."
        )

    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['alicloud_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 = []
    ips = []
    names = []
    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 is not '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
        sg_action = module.params['sg_action']

        if sg_action:
            action = sg_action.strip().lower()

            if action not in ('join', 'leave'):
                module.fail_json(
                    msg=
                    'To perform join_security_group or leave_security_group operation,'
                    'sg_action must be either join or leave respectively')

            security_group_id = module.params['group_id']
            for inst in instances:
                # Adding an Instance to a Security Group
                if action == 'join':
                    if security_group_id not in inst.security_group_ids[
                            'security_group_id']:
                        changed = inst.join_security_group(security_group_id)
                else:
                    if security_group_id in inst.security_group_ids[
                            'security_group_id']:
                        changed = inst.leave_security_group(security_group_id)

        # 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:
            update = False
            if instance_name and instance_name != inst.name:
                update = True
            else:
                name = inst.name
            if description and description != inst.description:
                update = True
            else:
                description = inst.description
            if host_name and host_name != inst.host_name:
                update = True
            else:
                host_name = inst.host_name
            if password:
                update = True

            if update:
                try:
                    changed = inst.modify(name=name,
                                          description=description,
                                          host_name=host_name,
                                          password=password)
                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)
                names.append(inst.name)
            ip = get_public_ip(inst)
            if ip not in ips:
                ips.append(ip)

        module.exit_json(changed=changed,
                         instance_ids=ids,
                         instance_ips=ips,
                         instance_names=names,
                         total=len(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:
                    changed = inst.start()
                    if changed:
                        ids.append(inst.id)
                        names.append(inst.name)
                        ips.append(get_public_ip(inst))

                module.exit_json(changed=changed,
                                 instance_ids=ids,
                                 instance_ips=ips,
                                 instance_names=names,
                                 total=len(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:
                    changed = inst.stop(force=force)
                    if changed:
                        ids.append(inst.id)
                        names.append(inst.name)
                        ips.append(get_public_ip(inst))

                module.exit_json(changed=changed,
                                 instance_ids=ids,
                                 instance_ips=ips,
                                 instance_names=names,
                                 total=len(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:
                    changed = inst.reboot(force=module.params['force'])
                    if changed:
                        ids.append(inst.id)
                        names.append(inst.name)
                        ips.append(get_public_ip(inst))

                module.exit_json(changed=changed,
                                 instance_ids=ids,
                                 instance_ips=ips,
                                 instance_names=names,
                                 total=len(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 is not 'stopped' and not force:
                        module.fail_json(
                            msg=
                            "Instance is running, and please stop it or set 'force' as True."
                        )
                    changed = inst.terminate(force=module.params['force'])

                module.exit_json(changed=changed)
            except Exception as e:
                module.fail_json(
                    msg='Delete instance got an error: {0}'.format(e))
コード例 #21
0
def main():
    if not HAS_FOOTMARK:
        module.fail_json(msg="footmark required for this module")

    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(group_id=dict(),
             alicloud_zone=dict(aliases=[
                 'zone_id', 'acs_zone', 'ecs_zone', 'zone', 'availability_zone'
             ]),
             status=dict(default='present',
                         aliases=['state'],
                         choices=['present', 'absent']),
             disk_id=dict(aliases=['vol_id', 'id']),
             disk_name=dict(aliases=['name']),
             disk_category=dict(aliases=['disk_type', 'volume_type']),
             size=dict(aliases=['disk_size', 'volume_size']),
             disk_tags=dict(type='list', aliases=['tags']),
             snapshot_id=dict(aliases=['snapshot']),
             description=dict(aliases=['disk_description']),
             instance_id=dict(aliases=['instance']),
             delete_with_instance=dict(aliases=['delete_on_termination'],
                                       default=None)))
    module = AnsibleModule(argument_spec=argument_spec)
    ecs = ecs_connect(module)
    status = module.params['status']

    instance_id = module.params['instance_id']
    disk_id = module.params['disk_id']

    if status == 'present':

        len_instance = 0
        len_disk = 0
        operation_flag = ''

        if instance_id:
            len_instance = len(instance_id.strip())

        if disk_id:
            len_disk = len(disk_id.strip())

        if not instance_id:
            if disk_id is None or len_disk == 0:
                operation_flag = 'present'
            elif disk_id is not None or len_disk > 0:
                operation_flag = 'detach'
        elif instance_id is not None or len_instance > 0:
            if disk_id is not None or len_disk > 0:
                operation_flag = 'attach'

        if operation_flag == '':
            module.fail_json(
                msg=
                'To attach disk: instance_id and disk_id both parameters are required.'
                ' To detach disk: only disk_id is to be set.'
                ' To create disk: disk_id and instance_id both are not to be sent.',
                instance_id=instance_id,
                disk_id=disk_id)

        if operation_flag == 'present':
            # create disk parameter values
            zone_id = module.params['alicloud_zone']
            disk_name = module.params['disk_name']
            description = module.params['description']
            disk_category = module.params['disk_category']
            size = module.params['size']
            disk_tags = module.params['disk_tags']
            snapshot_id = module.params['snapshot_id']
            # create disk parameter values end

            changed, result, disk_id, disk_dict = create_disk(
                module=module,
                ecs=ecs,
                zone_id=zone_id,
                disk_name=disk_name,
                description=description,
                disk_category=disk_category,
                size=size,
                disk_tags=disk_tags,
                snapshot_id=snapshot_id)

            module.exit_json(changed=changed,
                             disk_id=disk_id,
                             disk_category=disk_dict['category'],
                             disk_status=disk_dict['status'],
                             instance_id=instance_id,
                             disk=disk_dict)

        elif operation_flag == 'attach':

            delete_with_instance = module.params['delete_with_instance']

            changed, result, disk_dict = attach_disk(module, ecs, disk_id,
                                                     instance_id,
                                                     delete_with_instance)
            module.exit_json(changed=changed,
                             device=disk_dict['device'],
                             disk_id=disk_id,
                             disk_category=disk_dict['category'],
                             disk_status=disk_dict['status'],
                             instance_id=instance_id,
                             disk=disk_dict)

        elif operation_flag == 'detach':
            # performing operation detach disk from instance
            # instance_id is to be retreived in call

            changed, result, instance_id, disk_dict = detach_disk(
                module=module, ecs=ecs, disk_id=disk_id)
            module.exit_json(changed=changed,
                             disk_id=disk_id,
                             disk_category=disk_dict['category'],
                             disk_status=disk_dict['status'],
                             instance_id=instance_id,
                             disk=disk_dict)

    elif status == 'absent':
        # performing operation delete disk

        changed, result = delete_disk(module=module, ecs=ecs, disk_id=disk_id)
        module.exit_json(changed=changed, disk_id=disk_id)
コード例 #22
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(state=dict(default='present',
                        type='str',
                        choices=['present', 'absent']),
             group_name=dict(type='str', required=False, aliases=['name']),
             description=dict(type='str', required=False),
             vpc_id=dict(type='str'),
             group_tags=dict(type='list', aliases=['tags']),
             rules=dict(type='list'),
             rules_egress=dict(type='list'),
             group_id=dict(type='str')))

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(
            msg='footmark required for the module alicloud_security_group.')

    ecs = ecs_connect(module)

    state = module.params['state']
    group_name = module.params['group_name']
    description = module.params['description']
    vpc_id = module.params['vpc_id']
    group_id = module.params['group_id']
    group_tags = module.params['group_tags']

    changed = False
    group = None

    try:
        if group_id:
            security_groups = ecs.get_all_security_groups(group_ids=[group_id],
                                                          vpc_id=vpc_id,
                                                          name=group_name)
        else:
            security_groups = ecs.get_all_security_groups(vpc_id=vpc_id,
                                                          name=group_name)
    except ECSResponseError as e:
        module.fail_json(msg='Error in get_all_security_groups: %s' % str(e))

    group_ids = []
    if security_groups and len(security_groups) > 0:
        if group_id or len(security_groups) == 1:
            group = security_groups[0]
        else:
            for cur in security_groups:
                group_ids.append(cur.id)
            module.fail_json(
                msg=
                "There are several security group in our record based on name {0} or vpc {1}: {2}. "
                "Please specified one using 'id' and try again.".format(
                    group_name, vpc_id, group_ids))

    if state == 'absent':
        if not group:
            module.fail_json(
                changed=changed,
                msg=
                "Please specify a security group by using 'group_id' or 'group_name' "
                "and 'vpc_id' before deleting a security group.")
        try:
            module.exit_json(changed=group.delete())
        except ECSResponseError as e:
            module.fail_json(
                msg="Deleting security group {0} is failed. Error: {1}".format(
                    group.id, e))

    if not group:
        try:
            client_token = "Ansible-Alicloud-%s-%s" % (hash(str(
                module.params)), str(time.time()))
            group = ecs.create_security_group(group_name=group_name,
                                              description=description,
                                              vpc_id=vpc_id,
                                              group_tags=group_tags,
                                              client_token=client_token)
            changed = True

        except ECSResponseError as e:
            module.fail_json(
                changed=changed,
                msg='Creating a security group is failed. Error: {0}'.format(
                    e))

    # validating rules if provided
    total_rules_count = 0
    inbound_rules = module.params['rules']
    if inbound_rules:
        total_rules_count = len(inbound_rules)

    outbound_rules = module.params['rules_egress']
    if outbound_rules:
        total_rules_count += len(outbound_rules)

    if total_rules_count > 100:
        module.fail_json(
            msg='more than 100 rules for authorization are not allowed')

    validate_format_sg_rules(module, inbound_rules, outbound_rules)

    if inbound_rules or outbound_rules:
        changed = authorize_security_group(module,
                                           ecs,
                                           group_id=group.id,
                                           inbound_rules=inbound_rules,
                                           outbound_rules=outbound_rules)

    module.exit_json(changed=changed,
                     group_id=group.id,
                     group=get_group_detail(group),
                     vpc_id=group.vpc_id)
コード例 #23
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(dict(
        security_groups=dict(type='list', 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'),
        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="Package 'footmark' required for the module ali_instance.")

    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']
    tags = module.params['tags']
    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 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:
                    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))

        # Allocate instance public ip
        if module.params['allocate_public_ip']:
            for inst in instances:
                if inst.public_ip_address:
                    continue
                if inst.allocate_public_ip():
                    changed = True

        # start the stopped instances
        stopped = []
        for inst in instances:
            if inst.status == "stopped":
                stopped.append(inst.id)
        if stopped:
            if ecs.start_instances(instance_ids=stopped):
                changed = True

        # 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)
    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 tags or module.params['purge_tags']:
        for inst in instances:
            removed = {}
            if not tags:
                removed = inst.tags
            else:
                for key, value in inst.tags.items():
                    if key not in tags.keys():
                        removed[key] = value
            try:
                if inst.remove_tags(removed):
                    changed = True
            except Exception as e:
                module.fail_json(msg="{0}".format(e))

            if tags:
                try:
                    if inst.add_tags(tags):
                        changed = True
                except Exception as e:
                    module.fail_json(msg="{0}".format(e))

    module.exit_json(changed=changed, ids=ids, instances=get_instances_info(ecs, ids))
コード例 #24
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(state=dict(default='present',
                        type='str',
                        choices=['present', 'absent']),
             name=dict(type='str', required=True, aliases=['group_name']),
             description=dict(type='str'),
             vpc_id=dict(type='str'),
             security_group_id=dict(type='str', aliases=['id', 'group_id']),
             tags=dict(type='dict', aliases=['group_tags']),
             rules=dict(type='list', elements='dict'),
             rules_egress=dict(type='list', elements='dict'),
             purge_rules=dict(type='bool', default=True),
             purge_rules_egress=dict(type='bool', default=True),
             multi_ok=dict(type='bool', default=False),
             recent=dict(type='bool', default=False)))

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(
            msg='footmark is required for the module ali_security_group.')

    ecs = ecs_connect(module)

    state = module.params['state']
    security_group_id = module.params['security_group_id']
    group_name = module.params['name']
    if str(group_name).startswith('http://') or str(group_name).startswith(
            'https://'):
        module.fail_json(msg='Name can not start with http:// or https://')
    description = module.params['description']
    if str(description).startswith('http://') or str(description).startswith(
            'https://'):
        module.fail_json(
            msg='description can not start with http:// or https://')
    multi = module.params['multi_ok']
    recent = module.params['recent']

    if multi and recent:
        module.fail_json(
            msg='multi_ok and recent can not be True at the same time.')

    changed = False

    group = group_exists(ecs, module, module.params['vpc_id'], group_name,
                         security_group_id, multi, recent)

    if state == 'absent':
        if not group:
            module.exit_json(changed=changed, group={})
        try:
            module.exit_json(changed=group.delete(), group={})
        except ECSResponseError as e:
            module.fail_json(
                msg="Deleting security group {0} is failed. Error: {1}".format(
                    group.id, e))

    if not group:
        try:
            params = module.params
            params['security_group_name'] = group_name
            params['client_token'] = "Ansible-Alicloud-%s-%s" % (hash(
                str(module.params)), str(time.time()))
            group = ecs.create_security_group(**params)
            changed = True
        except ECSResponseError as e:
            module.fail_json(
                changed=changed,
                msg='Creating a security group is failed. Error: {0}'.format(
                    e))

    if not description:
        description = group.description
    if group.modify(name=group_name, description=description):
        changed = True

    # validating rules if provided
    ingress_rules = module.params['rules']
    if ingress_rules:
        direction = 'ingress'
        for rule in ingress_rules:
            validate_group_rule_keys(module, rule, direction)
        if module.params['purge_rules']:
            for existing in group.permissions:
                if existing['direction'] != direction:
                    continue
                if purge_rules(module, group, existing, ingress_rules,
                               direction):
                    changed = True
        for rule in ingress_rules:
            if group.authorize(rule, direction):
                changed = True

    egress_rules = module.params['rules_egress']
    if egress_rules:
        direction = 'egress'
        for rule in egress_rules:
            validate_group_rule_keys(module, rule, direction)
        if module.params['purge_rules_egress']:
            for existing in group.permissions:
                if existing['direction'] != direction:
                    continue
                if purge_rules(module, group, existing, egress_rules,
                               direction):
                    changed = True
        for rule in egress_rules:
            if group.authorize(rule, direction):
                changed = True

    module.exit_json(changed=changed, group=group.get().read())
コード例 #25
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(state=dict(default='present',
                        type='str',
                        choices=['present', 'absent']),
             group_name=dict(type='str', required=False, aliases=['name']),
             description=dict(type='str', required=False),
             vpc_id=dict(type='str'),
             tags=dict(type='dict', aliases=['group_tags']),
             rules=dict(type='list'),
             rules_egress=dict(type='list'),
             purge_rules=dict(type='bool', default=True),
             purge_rules_egress=dict(type='bool', default=True),
             group_id=dict(type='str', aliases=['id'])))

    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(
            msg='footmark is required for the module ali_security_group.')

    ecs = ecs_connect(module)

    state = module.params['state']
    group_name = module.params['group_name']
    group_id = module.params['group_id']

    changed = False
    group = None

    try:
        if group_id:
            group = ecs.describe_security_group_attribute(
                security_group_id=group_id)
    except ECSResponseError as e:
        module.fail_json(
            msg='Faild to describe security group {0}: {1}'.format(
                group_id, e))

    if state == 'absent':
        if not group:
            module.exit_json(changed=changed, group={})
        try:
            module.exit_json(changed=group.delete(), group={})
        except ECSResponseError as e:
            module.fail_json(
                msg="Deleting security group {0} is failed. Error: {1}".format(
                    group.id, e))

    if not group:
        try:
            params = module.params
            params['security_group_name'] = group_name
            params['client_token'] = "Ansible-Alicloud-%s-%s" % (hash(
                str(module.params)), str(time.time()))
            group = ecs.create_security_group(**params)
            changed = True
        except ECSResponseError as e:
            module.fail_json(
                changed=changed,
                msg='Creating a security group is failed. Error: {0}'.format(
                    e))

    if not group_name:
        group_name = group.security_group_name

    description = module.params['description']
    if not description:
        description = group.description
    if group.modify(name=group_name, description=description):
        changed = True

    # validating rules if provided
    ingress_rules = module.params['rules']
    if ingress_rules:
        direction = 'ingress'
        for rule in ingress_rules:
            validate_group_rule_keys(module, rule, direction)
        if module.params['purge_rules']:
            for existing in group.permissions:
                if existing['direction'] != direction:
                    continue
                if purge_rules(module, group, existing, ingress_rules,
                               direction):
                    changed = True
        for rule in ingress_rules:
            if group.authorize(rule, direction):
                changed = True

    egress_rules = module.params['rules_egress']
    if egress_rules:
        direction = 'egress'
        for rule in egress_rules:
            validate_group_rule_keys(module, rule, direction)
        if module.params['purge_rules_egress']:
            for existing in group.permissions:
                if existing['direction'] != direction:
                    continue
                if purge_rules(module, group, existing, egress_rules,
                               direction):
                    changed = True
        for rule in egress_rules:
            if group.authorize(rule, direction):
                changed = True

    module.exit_json(changed=changed, group=group.get().read())
コード例 #26
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(image_id=dict(type='str'),
             snapshot_id=dict(type='str', aliases=['snapshot']),
             description=dict(type='str'),
             image_name=dict(type='str', aliases=['name']),
             image_version=dict(type='str', aliases=['version']),
             disk_mapping=dict(type='list'),
             instance_id=dict(aliases=['instance']),
             state=dict(default='present',
                        choices=['present', 'absent'],
                        type='str'),
             wait=dict(default=False, type='bool'),
             wait_timeout=dict(type='int', default=300)))
    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(
            msg='footmark required for the module alicloud_security_group.')

    ecs = ecs_connect(module)
    state = module.params['state']
    image_id = module.params['image_id']
    image_name = module.params['image_name']

    changed = False
    current_image = None

    try:
        if image_id:
            images = ecs.get_all_images(image_id=image_id)
            if images and len(images) == 1:
                current_image = images[0]
        elif image_name and state == 'absent':
            images = ecs.get_all_images(image_name=image_name)
            if images:
                if len(images) == 1:
                    current_image = images[0]
                else:
                    images_ids = []
                    for i in images:
                        images_ids.append(i.id)
                    module.fail_json(
                        msg="There is too many images match name '{0}', "
                        "please use image_id or a new image_name to specify a unique image."
                        "Matched images ids are: {1}".format(
                            image_name, images_ids))
        elif state == 'absent':
            images = ecs.get_all_images()
            if images and len(images) > 0:
                current_image = images[0]

    except ECSResponseError as e:
        module.fail_json(msg='Error in get_all_images: %s' % str(e))

    if state == 'absent':
        if not current_image:
            module.fail_json(
                msg=
                "Please use valid image_id or image_name to specify one image for deleting."
            )

        try:
            changed_img = current_image.delete()
            module.exit_json(changed=changed_img,
                             image_id=current_image.id,
                             image=get_image_detail(current_image))
        except Exception as e:
            module.fail_json(
                msg='Deleting a image is failed, error: {0}'.format(e))
    if not current_image:
        snapshot_id = module.params['snapshot_id']
        image_version = module.params['image_version']
        description = module.params['description']
        disk_mapping = module.params['disk_mapping']
        instance_id = module.params['instance_id']
        wait = module.params['wait']
        wait_timeout = module.params['wait_timeout']

        try:
            # Calling create_image method
            client_token = "Ansible-Alicloud-%s-%s" % (hash(str(
                module.params)), str(time.time()))
            changed, image_id, results, request_id = create_image(
                module=module,
                ecs=ecs,
                snapshot_id=snapshot_id,
                image_name=image_name,
                image_version=image_version,
                description=description,
                instance_id=instance_id,
                disk_mapping=disk_mapping,
                client_token=client_token,
                wait=wait,
                wait_timeout=wait_timeout)
            images = ecs.get_all_images(image_id=image_id)
            if images:
                if len(images) == 1:
                    current_image = images[0]

            module.exit_json(changed=changed,
                             image_id=image_id,
                             image=get_image_detail(current_image))
        except Exception as e:
            module.fail_json(
                msg='Creating a new image is failed, error: {0}'.format(e))
コード例 #27
0
def main():
    if HAS_FOOTMARK is False:
        module.fail_json(msg='footmark required for this module')
    else:
        argument_spec = ecs_argument_spec()
        argument_spec.update(dict(
            group_id=dict(),
            alicloud_zone=dict(aliases=['acs_zone', 'ecs_zone', 'zone_id', 'zone']),
            instance_type=dict(aliases=['type']),
            image_id=dict(aliases=['image']),
            count=dict(type='int', default='1'),
            vswitch_id=dict(aliases=['subnet_id']),
            io_optimized=dict(type='bool', default=False),
            instance_name=dict(),
            internet_data=dict(type='dict'),
            host_name=dict(),
            password=dict(),
            system_disk=dict(type='dict'),
            disks=dict(type='list', aliases=['volumes']),
            force=dict(type='bool', default=False),
            instance_tags=dict(type='list', aliases=['tags']),
            status=dict(default='present', aliases=['state'], choices=['present', 'running', 'stopped', 'restarted',
                                                                       'absent', 'fetch', 'current']),
            description=dict(),
            allocate_public_ip=dict(type='bool', aliases=['assign_public_ip'], default=True),
            bind_eip=dict(),
            instance_charge_type=dict(default='PostPaid'),
            period=dict(type='int'),
            auto_renew=dict(type='bool', default=False),
            ids=dict(type='list', aliases=['id']),
            attributes=dict(type='list'),
            pagenumber=dict(type='int', default='1'),
            pagesize=dict(type='int', default='10'),
            vpc_id=dict(),
            instance_id=dict(type='list', aliases=['instance_ids']),
            sg_action=dict(),
            private_ip=dict(),
            auto_renew_period=dict(),
            wait=dict(default='no', choices=['yes', 'Yes', 'no', 'No', "True", "False", "true", "false"]),
            wait_timeout=dict(type='int', default='300')
        )
        )
        module = AnsibleModule(argument_spec=argument_spec)

        ecs = ecs_connect(module)
        tagged_instances = []
        status = module.params['status']

        if status == 'absent':
            instance_ids = module.params['instance_id']
            if not isinstance(instance_ids, list) or len(instance_ids) < 1:
                module.fail_json(msg='The parameter instance_ids should be a list, aborting')
            result = delete_instances(module=module, ecs=ecs, instance_ids=instance_ids)
            module.exit_json(changed=True, instance_ids=result, total_count=len(result))

        elif status in ('running', 'stopped', 'restarted'):
            instance_ids = module.params['instance_ids']
            instance_tags = module.params['instance_tags']
            if not (isinstance(instance_ids, list) or isinstance(instance_tags, list)):
                module.fail_json(
                    msg='running list needs to be a list of instances or set of tags to run: %s' % instance_ids)

            (changed, instance_dict_array, new_instance_ids) = startstop_instances(module, ecs, instance_ids, status,
                                                                                   instance_tags)
            (_, instance_dict_array, new_instance_ids) = get_instances(module, ecs, instance_ids)
            statuses = []
            for inst in instance_dict_array:
                statuses.append(str(inst["status"]))
            module.exit_json(changed=changed, instance_ids=new_instance_ids, instance_statuses=statuses,
                             total_count=len(new_instance_ids))

        elif status == 'present':
            # Join and leave security group is handled in state present
            # if sg_action parameter is absent then create new instance will begin
            # region Security Group join/leave begin
            sg_action = module.params['sg_action']
            attributes = module.params['attributes']

            if sg_action:
                action = sg_action.strip().lower()

                if action not in ('join', 'leave'):
                    module.fail_json(msg='To perform join_security_group or leave_security_group operation,'
                                         'sg_action must be either join or leave respectively')

                instance_ids = module.params['instance_id']
                security_group_id = module.params['group_id']

                if action == 'join':
                    # Adding an Instance to a Security Group
                    (changed, result, success_instance_ids, failed_instance_ids, security_group_id) = \
                        joinleave_security_group(module, ecs, action, instance_ids, security_group_id)
                else:
                    # Removing an Instance from a Security Group
                    (changed, result, success_instance_ids, failed_instance_ids, security_group_id) = \
                        joinleave_security_group(module, ecs, action, instance_ids, security_group_id)

                (_, instance_dict_array, new_instance_ids) = get_instances(module, ecs, instance_ids)
                statuses = []
                for inst in instance_dict_array:
                    statuses.append(str(inst["status"]))
                module.exit_json(changed=changed, group_id=security_group_id, instance_ids=success_instance_ids,
                                 failed_instance_ids=failed_instance_ids, instance_statuses=statuses,
                                 total_count=len(new_instance_ids))
            # region Security Group join/leave ends here

            elif attributes:
                # Modifying Instance Attributes
                changed, instance_ids, result = modify_instance(module, ecs, attributes)

                (_, instance_dict_array, new_instance_ids) = get_instances(module, ecs, instance_ids)
                statuses = []
                for inst in instance_dict_array:
                    statuses.append(str(inst["status"]))
                module.exit_json(changed=changed, instance_ids=instance_ids, instance_statuses=statuses,
                                 instances=instance_dict_array, total_count=len(instance_ids))
            else:
                # Create New Instance
                zone_id = module.params['alicloud_zone']
                image_id = module.params['image_id']
                instance_type = module.params['instance_type']
                group_id = module.params['group_id']
                io_optimized = module.params['io_optimized']
                vswitch_id = module.params['vswitch_id']
                instance_name = module.params['instance_name']
                description = module.params['description']
                internet_data = module.params['internet_data']
                host_name = module.params['host_name']
                password = module.params['password']
                system_disk = module.params['system_disk']
                disks = module.params['disks']
                count = module.params['count']
                allocate_public_ip = module.params['allocate_public_ip']
                bind_eip = module.params['bind_eip']
                instance_tags = module.params['instance_tags']
                period = module.params['period']
                auto_renew = module.params['auto_renew']
                instance_charge_type = module.params['instance_charge_type']
                ids = module.params['ids']
                private_ip = module.params['private_ip']
                auto_renew_period = module.params['auto_renew_period']
                wait = module.params['wait']
                wait_timeout = module.params['wait_timeout']

                changed, instance_list, result = create_instance(module=module, ecs=ecs, image_id=image_id,
                                                                 instance_type=instance_type, group_id=group_id, zone_id=zone_id,
                                                                 instance_name=instance_name, description=description,
                                                                 internet_data=internet_data, host_name=host_name, password=password,
                                                                 io_optimized=io_optimized, system_disk=system_disk, disks=disks,
                                                                 vswitch_id=vswitch_id, private_ip=private_ip, count=count,
                                                                 allocate_public_ip=allocate_public_ip, bind_eip=bind_eip,
                                                                 instance_charge_type=instance_charge_type, period=period,
                                                                 auto_renew=auto_renew, auto_renew_period=auto_renew_period,
                                                                 instance_tags=instance_tags, ids=ids, wait=wait, wait_timeout=wait_timeout)

                instances = []
                instance_ids = []
                statuses = []
                public_ips = []
                for inst in instance_list:
                    instances.append(get_instance_info(inst))
                    instance_ids.append(str(inst.instance_id))
                    statuses.append(str(inst.status))
                    public_ips.append(str(inst.public_ip))
                module.exit_json(changed=changed, instance_ids=instance_ids, instance_statuses=statuses,
                                 instance_ips=public_ips, instances=instances, total_count=len(instance_list))

        elif status == 'fetch':
            instance_ids = module.params['instance_ids']

            (changed, instance_dict_array, new_instance_ids) = get_instances(module, ecs, instance_ids)
            statuses = []
            public_ips = []
            for inst in instance_dict_array:
                statuses.append(str(inst["status"]))
                public_ips.append(str(inst["public_ip"]))
            module.exit_json(changed=changed, instance_ids=new_instance_ids, instance_statuses=statuses,
                             instance_ips=public_ips, instances=instance_dict_array, total_count=len(new_instance_ids))

        elif status == 'current':
            pagenumber = module.params['pagenumber']
            pagesize = module.params['pagesize']
            zone_id = module.params['alicloud_zone']

            (changed, result) = get_instance_status(module, ecs, zone_id, pagenumber, pagesize)

            instance_ids = []
            instance_statuses = []
            for inst in result.instance_statuses['instance_status']:
                instance_ids.append(str(inst["instance_id"]))
                instance_statuses.append(str.lower(str(inst["status"])))
            module.exit_json(changed=changed, instance_ids=instance_ids,
                             instance_statuses=instance_statuses, total_count=result.total_count)
コード例 #28
0
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', 'cloud_essd']),
             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=literal_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 host_name and 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
        keypair_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:
                    keypair_ids.append(inst.id)
        if keypair_ids:
            changed = ecs.attach_key_pair(instance_ids=keypair_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
        charge_type_ids = []
        for inst in instances:
            if inst.instance_charge_type != instance_charge_type:
                charge_type_ids.append(inst.id)
        if charge_type_ids:
            params = {
                "instance_ids": charge_type_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, charge_type_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))