예제 #1
1
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(
            status=dict(default='present',
                        aliases=['state'],
                        choices=['present', 'absent', 'fetch']),
            cidr_block=dict(aliases=['cidr']),
            description=dict(),
            alicloud_zone=dict(
                aliases=['acs_zone', 'ecs_zone', 'zone_id', 'zone']),
            vpc_id=dict(),
            vswitch_name=dict(aliases=['name', 'subnet_name']),
            vswitch_ids=dict(aliases=['subnet_ids']),
            pagenumber=dict(type='int', default='1'),
            pagesize=dict(type='int', default='10'),
            is_default=dict(type='bool'),
        ))

    module = AnsibleModule(argument_spec=argument_spec)
    vpc = vpc_connect(module)

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

    if status == 'present':
        changed, vswitch = create_vswitch(module, vpc)
        module.exit_json(changed=changed,
                         vpc_id=vswitch['vpc_id'],
                         vswitch=vswitch,
                         vswitch_id=vswitch['id'])

    elif status == 'absent':
        vpc_id, vswitch_ids = delete_vswitch(module, vpc)

        module.exit_json(changed=True,
                         vpc_id=vpc_id,
                         vswitch_ids=vswitch_ids,
                         total_count=len(vswitch_ids))

    elif status == 'fetch':
        vswitches = retrieve_vswitches(module, vpc)
        vswitch_ids = []
        vpc_id = ""
        for vsw in vswitches:
            vswitch_ids.append(vsw['id'])
            vpc_id = vsw['vpc_id']
        module.exit_json(changed=False,
                         vpc_id=vpc_id,
                         vswitches=vswitches,
                         vswitch_ids=vswitch_ids,
                         total_count=len(vswitches))

    else:
        module.fail_json(
            msg='The expected state: {0}, {1} and {2}, but got {3}.'.format(
                "present", "absent", "fetch", status))
예제 #2
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(vpc_ids=dict(type='list', aliases=['ids']),
             vpc_name=dict(type='str', aliases=['name']),
             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.")

    filters = module.params['filters']
    if module.params['vpc_ids']:
        filters['vpc_ids'] = module.params['vpc_ids']
    name = module.params['vpc_name']

    try:
        vpcs = []
        ids = []
        for vpc in vpc_connect(module).get_all_vpcs(filters):
            if name and vpc.vpc_name != name:
                continue
            vpcs.append(vpc.read())
            ids.append(vpc.id)

        module.exit_json(changed=False, ids=ids, vpcs=vpcs)
    except Exception as e:
        module.fail_json(msg=str("Unable to get vpcs, error:{0}".format(e)))
예제 #3
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(dict(
        vrouter_id=dict(type='str', required=True, aliases=['id']),
        route_table_id=dict(type='str')
    )
    )
    module = AnsibleModule(argument_spec=argument_spec)

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

    result = []
    vrouter_id = module.params['vrouter_id']
    route_table_id = module.params['route_table_id']


    try:
        vpc_conn = vpc_connect(module)

        # list all route entries in vrouter
        if vrouter_id:
            vrouter_entries = vpc_conn.get_all_route_entries(router_id=vrouter_id, route_table_id=route_table_id)
            for vrouter_entry in vrouter_entries:
                result.append(get_info(vrouter_entry))
    except Exception as e:
        module.fail_json(msg="Unable to describe vrouter entries, and got an error: {0}.".format(e))

    module.exit_json(changed=False, vrouter_id=vrouter_id,  vroute_entries=result, total=len(result))
예제 #4
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(vswitch_name=dict(type='str', aliases=['name', 'subnet_name']),
             cidr_block=dict(type='str'),
             vswitch_ids=dict(type='list', aliases=['ids', 'subnet_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.")

    filters = module.params['filters']
    if module.params['vswitch_ids']:
        filters['vswitch_ids'] = module.params['vswitch_ids']
    name = module.params['vswitch_name']
    cidr_block = module.params['cidr_block']

    try:
        vswitches = []
        ids = []
        for vsw in vpc_connect(module).get_all_vswitches(filters):
            if name and vsw.vswitch_name != name:
                continue
            if cidr_block and vsw.cidr_block != cidr_block:
                continue
            vswitches.append(vsw.read())
            ids.append(vsw.id)

        module.exit_json(changed=False, ids=ids, vswitches=vswitches)
    except Exception as e:
        module.fail_json(
            msg=str("Unable to get vswitches, error:{0}".format(e)))
예제 #5
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(vswitch_name=dict(aliases=['name', 'subnet_name']),
             cidr_block=dict(),
             name_prefix=dict(),
             cidr_prefix=dict(),
             vswitch_ids=dict(type='list', aliases=['ids', 'subnet_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.")

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

    vswitch_ids = module.params['vswitch_ids']
    if not vswitch_ids:
        vswitch_ids = []
    for key, value in list(filters.items()):
        if key in ["VSwitchId", "vswitch_id", "vswitch-id"
                   ] and value not in vswitch_ids:
            vswitch_ids.append(value)

    name = module.params['vswitch_name']
    cidr_block = module.params['cidr_block']
    name_prefix = module.params['name_prefix']
    cidr_prefix = module.params['cidr_prefix']

    try:
        vswitches = []
        ids = []
        while True:
            if vswitch_ids:
                filters['vswitch_id'] = vswitch_ids[0]
                vswitch_ids.pop(0)
            for vsw in vpc_connect(module).describe_vswitches(**filters):
                if name and vsw.vswitch_name != name:
                    continue
                if cidr_block and vsw.cidr_block != cidr_block:
                    continue
                if name_prefix and not str(
                        vsw.vswitch_name).startswith(name_prefix):
                    continue
                if cidr_prefix and not str(
                        vsw.cidr_block).startswith(cidr_prefix):
                    continue
                vswitches.append(vsw.read())
                ids.append(vsw.id)
            if not vswitch_ids:
                break

        module.exit_json(changed=False, ids=ids, vswitches=vswitches)
    except Exception as e:
        module.fail_json(
            msg=str("Unable to get vswitches, error:{0}".format(e)))
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(
            eip_ids=dict(type='list', aliases=['ids']),
            name_prefix=dict(type='str'),
            ip_address_prefix=dict(type='str', aliases=['ip_prefix']),
            filters=dict(type='dict'),
            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_eip_facts')

    eips = []
    ids = []
    eip_ids = module.params["eip_ids"]
    if not eip_ids:
        eip_ids = []
    filters = module.params["filters"]
    if not filters:
        filters = {}
    new_filters = {}
    for key, value in list(filters.items()):
        if str(key).lower().replace("-", "").replace("_", "") == "allocationid" and value not in eip_ids:
            eip_ids.append(value)
            continue
        new_filters[key] = value

    name_prefix = module.params["name_prefix"]
    address_prefix = module.params["ip_address_prefix"]
    tags = module.params["tags"]

    try:
        for eip in vpc_connect(module).describe_eip_addresses(**new_filters):
            if name_prefix and not str(eip.name).startswith(name_prefix):
                continue
            if address_prefix and not str(eip.IpAddress).startswith(address_prefix):
                continue
            if eip_ids and eip.allocation_id not in eip_ids:
                continue
            if tags:
                flag = False
                for key, value in list(tags.items()):
                    if key in list(eip.tags.keys()) and value == eip.tags[key]:
                        flag = True
                if not flag:
                    continue
            eips.append(eip.read())
            ids.append(eip.id)

        module.exit_json(changed=False, ids=ids, eips=eips)
    except Exception as e:
        module.fail_json(msg=str("Unable to get eips, error:{0}".format(e)))
예제 #7
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(dict(
        vpc_ids=dict(type='list', aliases=['ids']),
        vpc_name=dict(aliases=['name']),
        name_prefix=dict(),
        cidr_prefix=dict(),
        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.")

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

    vpc_ids = module.params['vpc_ids']
    if vpc_ids:
        filter_vpc_id = filters['vpc_id']
        if filter_vpc_id and filter_vpc_id not in vpc_ids:
            vpc_ids.append(filter_vpc_id)

    name = module.params['vpc_name']
    name_prefix = module.params['name_prefix']
    cidr_prefix = module.params['cidr_prefix']

    try:
        vpcs = []
        ids = []
        while True:
            if vpc_ids:
                filters['vpc_id'] = vpc_ids[0]
                vpc_ids.pop(0)
            for vpc in vpc_connect(module).describe_vpcs(**filters):
                if name and vpc.vpc_name != name:
                    continue
                if name_prefix and not str(vpc.vpc_name).startswith(name_prefix):
                    continue
                if cidr_prefix and not str(vpc.cidr_block).startswith(cidr_prefix):
                    continue
                vpcs.append(vpc.read())
                ids.append(vpc.id)
            if not vpc_ids:
                break

        module.exit_json(changed=False, ids=ids, vpcs=vpcs)
    except Exception as e:
        module.fail_json(msg=str("Unable to get vpcs, error:{0}".format(e)))
예제 #8
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(alicloud_zone=dict(
            aliases=['acs_zone', 'ecs_zone', 'zone_id', 'zone']),
             vpc_id=dict(required=True, aliases=['id']),
             vswitch_ids=dict(type='list')))
    module = AnsibleModule(argument_spec=argument_spec)

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

    result = []
    zone_id = module.params['alicloud_zone']
    vpc_id = module.params['vpc_id']
    vswitch_ids = module.params['vswitch_ids']

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

    try:
        vpc_conn = vpc_connect(module)

        # list all vswitches by vswitch ids
        if vswitch_ids:
            for vswitch_id in vswitch_ids:
                vswitchs = vpc_conn.get_all_vswitches(vpc_id=vpc_id,
                                                      vswitch_id=vswitch_id,
                                                      zone_id=zone_id)
                if vswitchs and len(vswitchs) == 1:
                    result.append(get_info(vswitchs[0]))

        # list all vswitches in specified vpc
        else:
            vswitchs = vpc_conn.get_all_vswitches(vpc_id=vpc_id)
            vswitch_ids = []
            for vswitch in vswitchs:
                vswitch_ids.append(vswitch.vswitch_id)
                result.append(get_info(vswitch))
    except Exception as e:
        module.fail_json(
            msg=str("Unable to describe vswitch, error:{0}".format(e)))

    module.exit_json(changed=False,
                     vpc_id=vpc_id,
                     vswitch_ids=vswitch_ids,
                     vswitchs=result,
                     total=len(result))
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(state=dict(default='present', choices=['present', 'absent']),
             resource_ids=dict(type='list', required=True),
             resource_type=dict(type='str',
                                default='vpc',
                                choices=['vpc', 'vswitch', 'eip']),
             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_vpc_tag.')

    vpc_conn = vpc_connect(module)
    if module.params['resource_type'] == 'vpc':
        module.params['resource_type'] = 'VPC'
        resources = vpc_exists(module, vpc_conn)
    elif module.params['resource_type'] == 'vswitch':
        module.params['resource_type'] = 'VSWITCH'
        resources = vsw_exists(module, vpc_conn)
    else:
        module.params['resource_type'] = 'EIP'
        resources = eip_exists(module, vpc_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":
        changed = vpc_conn.tag_resources(
            resource_ids=module.params['resource_ids'],
            tags=tags,
            resource_type=module.params['resource_type'])
    else:
        changed = vpc_conn.un_tag_resources(
            resource_ids=module.params['resource_ids'],
            tags=tags,
            resource_type=module.params['resource_type'])

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

    module.exit_json(changed=changed, tags=result)
예제 #10
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(
            status=dict(default='present',
                        aliases=['state'],
                        choices=['present', 'absent', 'fetch']),
            cidr_block=dict(default='172.16.0.0/16', aliases=['cidr']),
            user_cidr=dict(),
            vpc_name=dict(aliases=['name']),
            description=dict(),
            vpc_id=dict(),
            pagenumber=dict(type='int', default='1'),
            pagesize=dict(type='int', default='10'),
            is_default=dict(type='bool'),
        ))

    module = AnsibleModule(argument_spec=argument_spec)
    vpc = vpc_connect(module)

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

    if status == 'present':
        changed, vpc = create_vpc(module, vpc)
        module.exit_json(changed=changed, vpc_id=vpc['id'], vpc=vpc)

    elif status == 'absent':
        vpc_id = module.params['vpc_id']
        changed = delete_vpc(module, vpc, vpc_id)
        module.exit_json(changed=changed, vpc_id=vpc_id)

    elif status == 'fetch':
        vpcs = retrieve_vpcs(module=module, vpc=vpc)
        vpc_ids = []
        for vpc in vpcs:
            vpc_ids.append(vpc['id'])
        module.exit_json(changed=False,
                         vpcs=vpcs,
                         vpc_ids=vpc_ids,
                         total_count=len(vpcs))

    else:
        module.fail_json(
            msg='The expected state: {0}, {1} and {2}, but got {3}.'.format(
                "present", "absent", "fetch", status))
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(dict(vpc_ids=dict(type='list', aliases=['ids'])))
    module = AnsibleModule(argument_spec=argument_spec)

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

    result = []
    vpc_ids = module.params['vpc_ids']

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

    try:
        vpc_conn = vpc_connect(module)

        # list all vpc's by ids
        if vpc_ids:
            for vpc_id in vpc_ids:
                vpcs = vpc_conn.get_all_vpcs(vpc_id=vpc_id)
                if vpcs and len(vpcs) == 1:
                    result.append(get_info(vpcs[0]))

        # list all vpc's in specified region
        else:
            vpcs = vpc_conn.get_all_vpcs()
            vpc_ids = []
            for vpc in vpcs:
                vpc_ids.append(vpc.vpc_id)
                result.append(get_info(vpc))
    except Exception as e:
        module.fail_json(
            msg=str("Unable to describe vpc, error:{0}".format(e)))

    module.exit_json(changed=False,
                     vpc_ids=vpc_ids,
                     vpcs=result,
                     total=len(result))
예제 #12
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(state=dict(type='str',
                        default='present',
                        choices=['present', 'absent']),
             ip_address=dict(type='str', aliases=['ip']),
             instance_id=dict(type='str', aliases=['device_id']),
             internet_charge_type=dict(
                 type='str',
                 default='PayByTraffic',
                 choices=['PayByTraffic', 'PayByBandwidth']),
             bandwidth=dict(type='int', default=5),
             reuse_existing_ip_allowed=dict(type='bool', default=False),
             release_on_disassociation=dict(type='bool', default=False),
             allow_reassociation=dict(type='bool', default=False),
             name=dict(type='str'),
             description=dict(type='str'),
             tags=dict(type='dict'),
             purge_tags=dict(type='bool', default=False)))

    module = AnsibleModule(argument_spec=argument_spec)

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

    vpc = vpc_connect(module)

    # set values
    state = module.params['state']
    instance_id = module.params['instance_id']
    ip_address = module.params['ip_address']

    eip, eips = find_eip(vpc, module, ip_address, instance_id)
    changed = False

    if state == 'absent':
        if not eip:
            module.exit_json(changed=changed, eip={})

        if ip_address and instance_id and eip.ip_address != ip_address:
            module.exit_json(changed=changed, eip=eip.get.read())

        release = module.params['release_on_disassociation']
        if instance_id:
            try:
                if unassociate_eip(eip, module, instance_id):
                    changed = True
                if not release:
                    module.exit_json(changed=changed, eip=eip.get().read())
            except Exception as e:
                module.fail_json(
                    msg="Disassociate EIP with instance {0} failed. Error: {1}"
                    .format(instance_id, e))
        else:
            release = True

        if release:
            try:
                changed = eip.release()
                module.exit_json(changed=changed, eip={})
            except Exception as e:
                module.fail_json(msg="{0}".format(e))

    # state == present
    if not eip:
        if module.params['reuse_existing_ip_allowed'] and len(eips) > 0:
            for e in eips:
                if str(e.status).lower() == "available":
                    eip = e
                    break
    if not eip:
        try:
            params = module.params
            params['client_token'] = "Ansible-Alicloud-%s-%s" % (hash(
                str(module.params)), str(time.time()))
            eip = vpc.allocate_eip_address(**params)
            changed = True
        except VPCResponseError as e:
            module.fail_json(
                msg='Unable to allocate an eip address, error: {0}'.format(e))

    # Modify EIP attribute
    name = module.params['name']
    description = module.params['description']
    bandwidth = module.params['bandwidth']
    if not name:
        name = eip.name
    if not description:
        description = eip.description
    if not bandwidth:
        bandwidth = eip.bandwidth

    try:
        if eip.modify(bandwidth, name, description):
            changed = True
    except VPCResponseError as e:
        module.fail_json(
            msg='Modify EIP attribute with an error {0}.'.format(e))

    tags = module.params['tags']
    if module.params['purge_tags']:
        if not tags:
            tags = eip.tags
        try:
            if eip.remove_tags(tags):
                changed = True
            module.exit_json(changed=changed, eip=eip.get().read())
        except Exception as e:
            module.fail_json(msg="{0}".format(e))

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

    # Associate instance
    if instance_id:
        if eip.instance_id and eip.instance_id != instance_id:
            if not module.params['allow_reassociation']:
                module.fail_json(
                    msg=
                    'Target EIP {0} has been associated. Please set allow_reassociation to ture to '
                    'associate the target instance {1}'.format(
                        eip.ip_address, instance_id))
            try:
                if unassociate_eip(eip, module, instance_id):
                    changed = True
            except Exception as e:
                module.fail_json(
                    msg="Unassociate EIP from instance {0} failed. Error: {1}".
                    format(instance_id, e))
        try:
            if eip.get().associate(instance_id=instance_id):
                changed = True
        except Exception as e:
            module.fail_json(
                msg="Associate EIP with instance {0} failed. Error: {1}".
                format(instance_id, e))
    module.exit_json(changed=changed, eip=eip.get().read())
예제 #13
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(dict(
        state=dict(default='present', choices=['present', 'absent']),
        destination_cidrblock=dict(type='str', aliases=['dest_cidrblock', 'cidr_block']),
        nexthop_type=dict(default='Instance', aliases=['hop_type'], choices=['Instance', 'Tunnel', 'HaVip', 'RouterInterface']),
        nexthop_id=dict(aliases=['hop_id']),
        router_id=dict(type='str', required=True),
    ))

    module = AnsibleModule(argument_spec=argument_spec)

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

    vpc = vpc_connect(module)

    # Get values of variable
    state = module.params['state']
    destination_cidrblock = module.params['destination_cidrblock']
    router_id = module.params['router_id']
    nexthop_id = module.params['nexthop_id']
    route_table_id = None

    changed = False
    route_entries = []
    route_entries_basic = []
    route_entry = None

    try:
        page = 1
        pagesize = 50
        while True:
            entries = vpc.get_all_route_entries(router_id=router_id, router_type='VRouter', pagenumber=page, pagesize=pagesize)
            if entries and len(entries) > 0:
                for entry in entries:
                    route_table_id = entry.route_table_id
                    route_entries.append(entry)
                    route_entries_basic.append(get_route_entry_basic(entry))

                    if destination_cidrblock and entry.destination_cidrblock == destination_cidrblock:
                        route_entry = entry

            if not entries or len(entries) < pagesize:
                break
            page += 1

    except VPCResponseError as e:
        module.fail_json(msg='Unable to retrieve route entries, error: {0}'.format(e))

    if state == 'present':
        if not route_entry:
            changed, route_entry = create_route_entry(module, vpc, route_table_id)

        module.exit_json(changed=changed, route_table_id=route_table_id, route_entry=get_route_entry_detail(route_entry),
                         destination_cidrblock=route_entry.destination_cidrblock)

    else:
        if route_entry:
            try:
                changed = vpc.delete_route_entry(route_table_id, destination_cidrblock=destination_cidrblock, nexthop_id=nexthop_id)
            except VPCResponseError as e:
                module.fail_json(msg='Unable to delete route entry, error: {0}'.format(e))
            module.exit_json(changed=changed, route_table_id=route_table_id, destination_cidrblock=destination_cidrblock)

        module.exit_json(changed=changed, msg="Please specify a route entry by using 'destination_cidrblock',"
                                              "and expected vpcs: {0}".format(route_entries_basic))
예제 #14
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(dict(
        state=dict(default="present", choices=["present", "absent", "restart"]),
        zone_id=dict(type='str', aliases=['alicloud_zone']),
        engine=dict(type='str', choices=['MySQL', 'SQLServer', 'PostgreSQL', 'PPAS', 'MariaDB']),
        engine_version=dict(type='str'),
        db_instance_net_type=dict(type='str', choices=["Internet", "Intranet"], aliases=['instance_net_type']),
        db_instance_name=dict(type='str', aliases=['description', 'name']),
        db_instance_id=dict(type='str', aliases=['id']),
        security_ip_list=dict(type='str', aliases=['security_ips']),
        pay_type=dict(type='str', choices=["PostPaid", "PrePaid"]),
        period=dict(type='int', choices=[1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 24, 36], default=1),
        connection_mode=dict(type='str', choices=["Standard", "Safe"]),
        vswitch_id=dict(type='str'),
        private_ip_address=dict(type='str'),
        tags=dict(type='dict'),
        purge_tags=dict(type='bool', default=False),
        auto_pay=dict(type='bool', aliases=['auto_renew']),
        connection_string_prefix=dict(type='str'),
        port=dict(type='str'),
        current_connection_string=dict(type='str'),
        db_instance_class=dict(type='str', aliases=['instance_class']),
        db_instance_storage=dict(type='int', aliases=['instance_storage'])
    ))
    modules = AnsibleModule(argument_spec=argument_spec)

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

    rds = rds_connect(modules)
    vpc = vpc_connect(modules)

    state = modules.params['state']
    vswitch_id = modules.params['vswitch_id']
    connection_string_prefix = modules.params['connection_string_prefix']
    port = modules.params['port']
    tags = modules.params['tags']
    current_connection_string = modules.params['current_connection_string']
    db_instance_description = modules.params['db_instance_name']
    modules.params['db_instance_description'] = db_instance_description
    db_instance_class = modules.params['db_instance_class']
    db_instance_storage = modules.params['db_instance_storage']
    db_instance_id = modules.params['db_instance_id']
    pay_type = modules.params['pay_type']
    used_time = modules.params['period']
    modules.params['period'] = 'Month'
    modules.params['used_time'] = str(used_time)

    if used_time > 9:
        modules.params['period'] = 'Year'
        if used_time == 12:
            modules.params['used_time'] = '1'
        elif used_time == 24:
            modules.params['used_time'] = '2'
        else:
            modules.params['used_time'] = '3'
    if pay_type:
        modules.params['pay_type'] = pay_type.capitalize()

    current_instance = None
    changed = False

    if vswitch_id:
        modules.params['instance_network_type'] = 'VPC'
        try:
            vswitch_obj = vpc.describe_vswitch_attributes(vswitch_id=vswitch_id)
            if vswitch_obj:
                modules.params['vpc_id'] = vswitch_obj.vpc_id
        except Exception as e:
            modules.fail_json(msg=str("Unable to get vswitch, error:{0}".format(e)))

    try:
        current_instance = get_instance(db_instance_id, db_instance_description, modules, rds)
    except Exception as e:
        modules.fail_json(msg=str("Unable to describe instance, error:{0}".format(e)))

    if state == 'absent':
        if current_instance:
            if current_connection_string:
                try:
                    changed = rds.release_instance_public_connection(current_connection_string=current_connection_string, db_instance_id=current_instance.id)
                    modules.exit_json(changed=changed, instances=current_instance.get().read())
                except Exception as e:
                    modules.fail_json(msg=str("Unable to release public connection string error: {0}".format(e)))
            try:
                current_instance.delete()
                modules.exit_json(changed=True, instances={})
            except Exception as e:
                modules.fail_json(msg=str("Unable to release instance error: {0}".format(e)))
        modules.fail_json(msg=str("Unable to operate your instance, please check your instance_id and try again!"))

    if state == 'restart':
        if current_instance:
            try:
                changed = current_instance.restart()
                modules.exit_json(changed=changed, instances=current_instance.get().read())
            except Exception as e:
                modules.fail_json(msg=str("Unable to restart instance error: {0}".format(e)))
        modules.fail_json(msg=str("Unable to restart your instance, please check your instance_id and try again!"))

    if not current_instance:
        try:
            modules.params['client_token'] = "Ansible-Alicloud-%s-%s" % (hash(str(modules.params)), str(time.time()))
            current_instance = rds.create_db_instance(**modules.params)
            modules.exit_json(changed=True, instances=current_instance.get().read())
        except Exception as e:
            modules.fail_json(msg=str("Unable to create rds instance error: {0}".format(e)))

    if connection_string_prefix and port:
        if current_connection_string:
            try:
                changed = current_instance.modify_db_instance_connection_string(current_connection_string=current_connection_string, connection_string_prefix=connection_string_prefix, port=port)
                modules.exit_json(changed=changed, instances=current_instance.get().read())
            except Exception as e:
                modules.fail_json(msg=str("Unable to modify current string error: {0}".format(e)))
        else:
            try:
                changed = current_instance.allocate_public_connection_string(connection_string_prefix=connection_string_prefix, port=port)
                modules.exit_json(changed=changed, instances=current_instance.get().read())
            except Exception as e:
                modules.fail_json(msg=str("Unable to allocate public connection error: {0}".format(e)))

    if db_instance_class or db_instance_storage:
        try:
            changed = current_instance.modify_instance_spec(db_instance_class=db_instance_class, db_instance_storage=db_instance_storage)
        except Exception as e:
            modules.fail_json(msg=str("Unable to modify instance spec: {0}".format(e)))

    if modules.params['purge_tags']:
        if not tags:
            tags = current_instance.tags
        try:
            if current_instance.remove_tags(tags):
                changed = True
            modules.exit_json(changed=changed, instances=current_instance.get().read())
        except Exception as e:
            modules.fail_json(msg="{0}".format(e))

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

    modules.exit_json(changed=changed, instances=current_instance.get().read())
예제 #15
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(
            state=dict(default='present',
                       choices=['present', 'absent', 'list']),
            cidr_block=dict(default='172.16.0.0/16', aliases=['cidr']),
            user_cidr=dict(),
            vpc_name=dict(aliases=['name']),
            description=dict(),
            vpc_id=dict(),
            is_default=dict(type='bool'),
        ))

    module = AnsibleModule(argument_spec=argument_spec)

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

    vpc_conn = vpc_connect(module)

    # Get values of variable
    state = module.params['state']
    vpc_id = module.params['vpc_id']
    is_default = module.params['is_default']
    vpc_name = module.params['vpc_name']
    description = module.params['description']
    cidr_block = module.params['cidr_block']
    user_cidr = module.params['user_cidr']

    if str(description).startswith('http://') or str(description).startswith(
            'https://'):
        module.fail_json(
            msg='description can not start with http:// or https://')
    if str(vpc_name).startswith('http://') or str(vpc_name).startswith(
            'https://'):
        module.fail_json(msg='vpc_name can not start with http:// or https://')

    changed = False
    vpc = None
    vpcs = []
    vpcs_basic = []
    vpcs_by_opts = []

    try:
        page = 1
        pagesize = 50
        while True:
            vpc_list = vpc_conn.get_all_vpcs(vpc_id=vpc_id,
                                             is_default=is_default,
                                             pagenumber=page,
                                             pagesize=pagesize)
            if vpc_list is not None and len(vpc_list) > 0:
                for curVpc in vpc_list:
                    vpcs.append(curVpc)
                    vpcs_basic.append(get_vpc_basic(curVpc))

                    if curVpc.id == vpc_id:
                        vpc = curVpc
                    if vpc_name and cidr_block:
                        if curVpc.name == vpc_name and curVpc.cidr_block == cidr_block:
                            vpcs_by_opts.append(curVpc)
                    elif vpc_name and curVpc.name == vpc_name:
                        vpcs_by_opts.append(curVpc)
                    elif cidr_block and curVpc.cidr_block == cidr_block:
                        vpcs_by_opts.append(curVpc)

            if vpc_list is None or len(vpc_list) < pagesize:
                break
            page += 1

    except VPCResponseError as e:
        module.fail_json(msg='Unable to retrieve vpc, error: {0}'.format(e))

    if not vpc and len(vpcs_by_opts) == 1:
        vpc = vpcs_by_opts[0]

    if len(vpcs_by_opts) > 1:
        vpcs = vpcs_by_opts

    if state == 'present':
        try:
            if not vpc:
                client_token = "Ansible-Alicloud-%s-%s" % (hash(
                    str(module.params)), str(time.time()))
                vpc = vpc_conn.create_vpc(cidr_block=cidr_block,
                                          user_cidr=user_cidr,
                                          vpc_name=vpc_name,
                                          description=description,
                                          client_token=client_token)
            else:
                vpc = vpc.update(name=vpc_name,
                                 description=description,
                                 user_cidr=user_cidr)
            changed = True
        except VPCResponseError as e:
            module.fail_json(
                msg='Unable to create or modify vpc, error: {0}'.format(e))

        module.exit_json(changed=changed,
                         vpc_id=vpc.id,
                         vpc=get_vpc_detail(vpc))

    elif state == 'absent':
        if vpc:
            try:
                changed = vpc.delete()
                module.exit_json(changed=changed, vpc_id=vpc.id)
            except VPCResponseError as ex:
                module.fail_json(
                    msg='Unable to delete vpc: {0}, error: {1}'.format(
                        vpc.id, ex))

        module.exit_json(
            changed=changed,
            msg=
            "Please specify a vpc by using 'vpc_id', 'vpc_name' or 'cidr_block',"
            "and expected vpcs: %s" % vpcs_basic)

    elif state == 'list':
        vpc_ids = []
        vpcs_detail = []
        if vpc:
            module.exit_json(changed=False,
                             vpcs=[get_vpc_detail(vpc)],
                             vpc_ids=[vpc.id],
                             total=1)

        for vpc in vpcs:
            vpc_ids.append(vpc.id)
            vpcs_detail.append(get_vpc_detail(vpc))
        module.exit_json(changed=False,
                         vpcs=vpcs_detail,
                         vpc_ids=vpc_ids,
                         total=len(vpcs))

    else:
        module.fail_json(
            msg='The expected state: {0}, {1} and {2}, but got {3}.'.format(
                "present", "absent", "list", state))
예제 #16
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(
            state=dict(default='present', choices=['present', 'absent']),
            cidr_block=dict(aliases=['cidr']),
            user_cidrs=dict(type='list'),
            vpc_name=dict(aliases=['name']),
            description=dict(),
            vpc_id=dict(aliases=['id']),
        ))

    module = AnsibleModule(argument_spec=argument_spec)

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

    vpc_conn = vpc_connect(module)

    # Get values of variable
    state = module.params['state']
    vpc_id = module.params['vpc_id']
    vpc_name = module.params['vpc_name']
    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://')
    if str(vpc_name).startswith('http://') or str(vpc_name).startswith(
            'https://'):
        module.fail_json(msg='vpc_name can not start with http:// or https://')

    changed = False
    vpc = None

    if vpc_id:
        try:
            vpc = vpc_conn.describe_vpc_attribute(vpc_id=vpc_id)
        except VPCResponseError as e:
            module.fail_json(
                msg='Retrieving vpc by id {0} got an error: {1}'.format(
                    vpc_id, e))

    if state == 'absent':
        if not vpc:
            module.exit_json(changed=changed, vpc={})

        try:
            module.exit_json(changed=vpc.delete(), vpc={})
        except VPCResponseError as ex:
            module.fail_json(
                msg='Unable to delete vpc {0}, error: {1}'.format(vpc.id, ex))

    if not vpc:
        params = module.params
        params['client_token'] = "Ansible-Alicloud-%s-%s" % (hash(
            str(module.params)), str(time.time()))
        try:
            vpc = vpc_conn.create_vpc(**params)
            module.exit_json(changed=True, vpc=vpc.get().read())
        except VPCResponseError as e:
            module.fail_json(msg='Unable to create vpc, error: {0}'.format(e))

    if not vpc_name:
        vpc_name = vpc.vpc_name
    if not description:
        description = vpc.description

    try:
        if vpc.modify(vpc_name, description):
            changed = True
        module.exit_json(changed=changed, vpc=vpc.get().read())
    except VPCResponseError as e:
        module.fail_json(
            msg='Unable to modify vpc {0}, error: {1}'.format(vpc_id, e))
예제 #17
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(
            state=dict(default='present', choices=['present', 'absent']),
            destination_cidrblock=dict(
                type='str', aliases=['dest_cidrblock', 'cidr_block']),
            nexthop_type=dict(
                default='Instance',
                aliases=['hop_type'],
                choices=['Instance', 'Tunnel', 'HaVip', 'RouterInterface']),
            nexthop_id=dict(aliases=['hop_id']),
            router_id=dict(type='str', required=True),
            name=dict(aliases=['route_entry_name']),
        ))

    module = AnsibleModule(argument_spec=argument_spec)

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

    vpc = vpc_connect(module)

    # Get values of variable
    state = module.params['state']
    destination_cidrblock = module.params['destination_cidrblock']
    router_id = module.params['router_id']
    nexthop_id = module.params['nexthop_id']
    name = module.params['name']
    route_table_id = None

    if str(name).startswith('http://') or str(name).startswith('https://'):
        module.fail_json(
            msg='router_entry_name can not start with http:// or https://')

    changed = False
    route_entry = None

    try:
        page = 1
        pagesize = 50
        while True:
            entries = vpc.get_all_route_entries(router_id=router_id,
                                                router_type='VRouter',
                                                pagenumber=page,
                                                pagesize=pagesize)
            if entries and len(entries) > 0:
                for entry in entries:
                    route_table_id = entry.route_table_id
                    if destination_cidrblock and entry.destination_cidrblock == destination_cidrblock:
                        route_entry = entry

            if not entries or len(entries) < pagesize:
                break
            page += 1

    except VPCResponseError as e:
        module.fail_json(
            msg='Unable to retrieve route entries, error: {0}'.format(e))

    if state == 'present':
        if not route_entry:
            changed, route_entry = create_route_entry(module, vpc,
                                                      route_table_id)
            module.exit_json(changed=changed,
                             route_entry=route_entry.get().read())
        try:
            changed = route_entry.modify(name)
            module.exit_json(changed=changed,
                             route_entry=route_entry.get().read())
        except VPCResponseError as e:
            module.fail_json(
                msg='Unable to modify route entry {0}, error: {1}'.format(
                    route_entry.id, e))

    else:
        if route_entry:
            try:
                changed = vpc.delete_route_entry(
                    route_table_id=route_table_id,
                    destination_cidrblock=destination_cidrblock,
                    nexthop_id=nexthop_id)
                module.exit_json(changed=changed, route_entry={})
            except VPCResponseError as e:
                module.fail_json(
                    msg='Unable to delete route entry, error: {0}'.format(e))

        module.exit_json(
            changed=changed,
            msg=
            "Please specify a route entry by using 'destination_cidrblock', and "
            "expected "
            "vpcs: {0}".format({
                "route_table_id":
                route_entry.route_table_id,
                "destination_cidrblock":
                route_entry.destination_cidrblock
            }))
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(state=dict(default='present', choices=['present', 'absent']),
             cidr_block=dict(type='str', required=True, aliases=['cidr']),
             user_cidrs=dict(type='list', elements='str'),
             name=dict(type='str', required=True, aliases=['vpc_name']),
             vpc_id=dict(type='str', aliases=['id']),
             multi_ok=dict(type='bool', default=False),
             description=dict(type='str'),
             recent=dict(type='bool', default=False),
             tags=dict(type='dict'),
             purge_tags=dict(type='bool', default=False)))

    module = AnsibleModule(argument_spec=argument_spec)

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

    vpc_conn = vpc_connect(module)

    # Get values of variable
    state = module.params['state']
    vpc_name = module.params['name']
    description = module.params['description']
    vpc_id = module.params['vpc_id']

    if str(description).startswith('http://') or str(description).startswith(
            'https://'):
        module.fail_json(
            msg='description can not start with http:// or https://')
    if str(vpc_name).startswith('http://') or str(vpc_name).startswith(
            'https://'):
        module.fail_json(msg='vpc_name can not start with http:// or https://')

    changed = False

    # Check if VPC exists
    vpc = vpc_exists(module, vpc_conn, vpc_id, vpc_name,
                     module.params['cidr_block'], module.params['multi_ok'],
                     module.params['recent'])

    if state == 'absent':
        if not vpc:
            module.exit_json(changed=changed, vpc={})

        try:
            module.exit_json(changed=vpc.delete(), vpc={})
        except VPCResponseError as ex:
            module.fail_json(
                msg='Unable to delete vpc {0}, error: {1}'.format(vpc.id, ex))

    if not vpc:
        params = module.params
        params['client_token'] = "Ansible-Alicloud-%s-%s" % (hash(
            str(module.params)), str(time.time()))
        params['vpc_name'] = vpc_name
        try:
            vpc = vpc_conn.create_vpc(**params)
            module.exit_json(changed=True, vpc=vpc.get().read())
        except VPCResponseError as e:
            module.fail_json(msg='Unable to create vpc, error: {0}'.format(e))

    if not description:
        description = vpc.description

    try:
        if vpc.modify(vpc_name, description):
            changed = True
    except VPCResponseError as e:
        module.fail_json(
            msg='Unable to modify vpc {0}, error: {1}'.format(vpc.id, e))

    tags = module.params['tags']
    if module.params['purge_tags']:
        if not tags:
            tags = vpc.tags
        try:
            if vpc.remove_tags(tags):
                changed = True
            module.exit_json(changed=changed, vpc=vpc.get().read())
        except Exception as e:
            module.fail_json(msg="{0}".format(e))

    if tags:
        try:
            if vpc.add_tags(tags):
                changed = True
        except Exception as e:
            module.fail_json(msg="{0}".format(e))
    module.exit_json(changed=changed, vpc=vpc.get().read())
예제 #19
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(state=dict(default="present",
                        choices=["present", "absent", "restart"],
                        alias=['status']),
             alicloud_zone=dict(type='str', aliases=['zone_id', 'zone']),
             engine=dict(type='str',
                         choices=["MySQL", "SQLServer", "PostgreSQL", "PPAS"]),
             engine_version=dict(type='str'),
             instance_net_type=dict(type='str',
                                    choices=["Internet", "Intranet"],
                                    aliases=['db_instance_net_type']),
             description=dict(type='str', aliases=['db_instance_description']),
             security_ips=dict(type='str'),
             instance_charge_type=dict(type='str',
                                       choices=["Postpaid", "Prepaid"]),
             period=dict(type='int', choices=range(1, 10).extend([12, 24,
                                                                  36])),
             connection_mode=dict(type='str', choices=["Performance",
                                                       "Safty"]),
             vpc_id=dict(type='str'),
             vswitch_id=dict(type='str'),
             private_ip_address=dict(type='str'),
             instance_id=dict(type='str', aliases=['db_instance_id']),
             tags=dict(type='str', aliases=['instance_tags']),
             page_size=dict(type='int', default=30, choices=[30, 50, 100]),
             page_number=dict(type='int', default=1),
             auto_renew_period=dict(type='int', choices=[1, 2, 3, 6, 12]),
             auto_renew=dict(type='bool'),
             public_connection_string_prefix=dict(type='str'),
             private_connection_string_prefix=dict(type='str'),
             dest_connection_string_prefix=dict(type='str'),
             dest_port=dict(type='str'),
             public_port=dict(type='str'),
             private_port=dict(type='int', choices=range(3001, 4000)),
             current_connection_string=dict(type='str'),
             instance_type=dict(type='str', aliases=['db_instance_class']),
             instance_storage=dict(type='int',
                                   aliases=['db_instance_storage'])))
    modules = AnsibleModule(argument_spec=argument_spec)

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

    rds = rds_connect(modules)
    vpc = vpc_connect(modules)

    state = modules.params['state']
    alicloud_zone = modules.params['alicloud_zone']
    engine = modules.params['engine']
    engine_version = modules.params['engine_version']
    instance_net_type = modules.params['instance_net_type']
    description = modules.params['description']
    security_ips = modules.params['security_ips']
    instance_charge_type = modules.params['instance_charge_type']
    period = modules.params['period']
    connection_mode = modules.params['connection_mode']
    vswitch_id = modules.params['vswitch_id']
    private_ip_address = modules.params['private_ip_address']
    instance_id = modules.params['instance_id']
    tags = modules.params['tags']
    page_size = modules.params['page_size']
    page_number = modules.params['page_number']
    auto_renew_period = modules.params['auto_renew_period']
    auto_renew = modules.params['auto_renew']
    public_connection_string_prefix = modules.params[
        'public_connection_string_prefix']
    private_connection_string_prefix = modules.params[
        'private_connection_string_prefix']
    public_port = modules.params['public_port']
    private_port = modules.params['private_port']
    current_connection_string = modules.params['current_connection_string']
    dest_connection_string_prefix = modules.params[
        'dest_connection_string_prefix']
    dest_port = modules.params['dest_port']
    instance_type = modules.params['instance_type']
    instance_storage = modules.params['instance_storage']

    vpc_id = None
    instance_network_type = 'Classic'
    current_instance = None
    changed = False
    if vswitch_id:
        instance_network_type = 'VPC'
        try:
            vswitch_obj = vpc.get_vswitch_attribute(vswitch_id)
            if vswitch_obj:
                vpc_id = vswitch_obj.vpc_id
        except Exception as e:
            modules.fail_json(
                msg=str("Unable to get vswitch, error:{0}".format(e)))
    if instance_id:
        try:
            current_instance = rds.describe_db_instance_attribute(instance_id)
        except Exception as e:
            modules.fail_json(
                msg=str("Unable to describe instance, error:{0}".format(e)))

    if state == 'absent':
        if current_instance:
            if current_connection_string:
                try:
                    changed = current_instance.release_public_connection_string(
                        current_connection_string)
                    modules.exit_json(changed=changed,
                                      instance=get_info(current_instance))
                except Exception as e:
                    modules.fail_json(msg=str(
                        "Unable to release public connection string error: {0}"
                        .format(e)))
            try:
                changed = current_instance.terminate()
                modules.exit_json(changed=changed,
                                  instance=get_info(current_instance))
            except Exception as e:
                modules.fail_json(
                    msg=str("Unable to release instance error: {0}".format(e)))
        modules.fail_json(msg=str(
            "Unable to operate your instance, please check your instance_id and try again!"
        ))
    if state == 'restart':
        if current_instance:
            try:
                changed = current_instance.restart()
                modules.exit_json(changed=changed,
                                  instance=get_info(current_instance))
            except Exception as e:
                modules.fail_json(
                    msg=str("Unable to restart instance error: {0}".format(e)))
        modules.fail_json(msg=str(
            "Unable to restart your instance, please check your instance_id and try again!"
        ))
    if not current_instance:
        try:
            client_token = "Ansible-Alicloud-%s-%s" % (hash(str(
                module.params)), str(time.time()))
            current_instance = rds.create_rds_instance(
                engine=engine,
                engine_version=engine_version,
                db_instance_class=instance_type,
                db_instance_storage=instance_storage,
                db_instance_net_type=instance_net_type,
                security_ip_list=security_ips,
                pay_type=instance_charge_type,
                client_token=client_token,
                instance_network_type=instance_network_type,
                period='Month',
                used_time=period,
                alicloud_zone=alicloud_zone,
                db_instance_description=description,
                connection_mode=connection_mode,
                vpc_id=vpc_id,
                vswitch_id=vswitch_id,
                private_ip_address=private_ip_address)
            instance_id = current_instance.dbinstance_id
        except Exception as e:
            modules.fail_json(
                msg=str("Unable to create rds instance error: {0}".format(e)))
    if auto_renew:
        try:
            changed = current_instance.modify_auto_renewal_attribute(
                duration=auto_renew_period, auto_renew=auto_renew)
        except Exception as e:
            modules.fail_json(msg=str(
                "Unable to modify rds instance auto renewal attribute error: {0}"
                .format(e)))
    if public_connection_string_prefix and public_port:
        try:
            changed = current_instance.allocate_public_connection_string(
                public_connection_string_prefix, public_port)
        except Exception as e:
            modules.fail_json(msg=str(
                "Unable to allocate public connection error: {0}".format(e)))
    if private_connection_string_prefix:
        try:
            changed = current_instance.allocate_private_connection_string(
                private_connection_string_prefix, private_port)
        except Exception as e:
            modules.fail_json(msg=str(
                "Unable to allocate private connection string error: {0}".
                format(e)))
    if current_connection_string:
        try:
            changed = current_instance.modify_connection_string(
                current_connection_string, dest_connection_string_prefix,
                dest_port)
        except Exception as e:
            modules.fail_json(
                msg=str("Unable to modify current connection string error: {0}"
                        .format(e)))
    # get newest instance
    try:
        current_instance = rds.describe_db_instance_attribute(instance_id)
    except Exception as e:
        modules.fail_json(
            msg=str("Unable to describe instance error: {0}".format(e)))
    modules.exit_json(changed=changed, instance=get_info(current_instance))
예제 #20
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(state=dict(default='present', choices=['present', 'absent']),
             cidr_block=dict(type='str', required=True),
             description=dict(type='str'),
             zone_id=dict(type='str',
                          aliases=['availability_zone', 'alicloud_zone']),
             vpc_id=dict(type='str', required=True),
             name=dict(type='str', aliases=['vswitch_name', 'subnet_name']),
             vswitch_id=dict(type='str', aliases=['subnet_id', 'id']),
             tags=dict(type='dict'),
             purge_tags=dict(type='bool', default=False)))

    module = AnsibleModule(argument_spec=argument_spec)

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

    vpc = vpc_connect(module)

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

    changed = False
    vswitch = vswitch_exists(vpc, module, vswitch_id, module.params['vpc_id'],
                             module.params['cidr_block'])

    if state == 'absent':
        if not vswitch:
            module.exit_json(changed=changed, vswitch={})
        try:
            changed = vswitch.delete()
            module.exit_json(changed=changed, vswitch={})
        except VPCResponseError as ex:
            module.fail_json(
                msg='Unable to delete vswitch: {0}, error: {1}'.format(
                    vswitch.id, ex))

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

    if str(vswitch_name).startswith('http://') or str(vswitch_name).startswith(
            'https://'):
        module.fail_json(
            msg='vswitch_name can not start with http:// or https://')

    if not vswitch:
        try:
            params = module.params
            params['client_token'] = "Ansible-Alicloud-{0}-{1}".format(
                hash(str(module.params)), str(time.time()))
            params['vswitch_name'] = vswitch_name
            vswitch = vpc.create_vswitch(**params)
            module.exit_json(changed=True, vswitch=vswitch.get().read())
        except VPCResponseError as e:
            module.fail_json(
                msg='Unable to create VSwitch, error: {0}'.format(e))

    if not vswitch_name:
        vswitch_name = vswitch.vswitch_name
    if not description:
        description = vswitch.description
    try:
        if vswitch.modify(name=vswitch_name, description=description):
            changed = True
    except VPCResponseError as e:
        module.fail_json(
            msg='Unable to modify vswitch attribute, error: {0}'.format(e))

    tags = module.params['tags']
    if module.params['purge_tags']:
        if not tags:
            tags = vswitch.tags
        try:
            if vswitch.remove_tags(tags):
                changed = True
            module.exit_json(changed=changed, vswitch=vswitch.get().read())
        except Exception as e:
            module.fail_json(msg="{0}".format(e))

    if tags:
        try:
            if vswitch.add_tags(tags):
                changed = True
        except Exception as e:
            module.fail_json(msg="{0}".format(e))
    module.exit_json(changed=changed, vswitch=vswitch.get().read())
예제 #21
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(
            state=dict(default='present',
                       choices=['present', 'absent', 'list']),
            cidr_block=dict(aliases=['cidr']),
            description=dict(),
            alicloud_zone=dict(aliases=['zone_id', 'zone']),
            vpc_id=dict(),
            vswitch_name=dict(aliases=['name', 'subnet_name']),
            vswitch_id=dict(aliases=['subnet_id']),
            is_default=dict(type='bool'),
        ))

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

    vpc = vpc_connect(module)

    # Get values of variable
    state = module.params['state']
    vpc_id = module.params['vpc_id']
    vswitch_id = module.params['vswitch_id']
    vswitch_name = module.params['vswitch_name']
    cidr_block = module.params['cidr_block']
    zone_id = module.params['alicloud_zone']
    is_default = module.params['is_default']
    description = module.params['description']

    changed = False
    vswitch = None
    vswitches = []
    vswitches_basic = []
    vswitches_by_opts = []

    try:
        page = 1
        pagesize = 50
        while True:
            vswitch_list = vpc.get_all_vswitches(vpc_id=vpc_id,
                                                 zone_id=zone_id,
                                                 is_default=is_default,
                                                 pagenumber=page,
                                                 pagesize=pagesize)
            if vswitch_list is not None and len(vswitch_list) > 0:
                for curVsw in vswitch_list:
                    vswitches.append(curVsw)
                    vswitches_basic.append(get_vswitch_basic(curVsw))

                    if curVsw.id == vswitch_id:
                        vswitch = curVsw
                    elif cidr_block and curVsw.cidr_block == cidr_block:
                        vswitch = curVsw

                    if vswitch_name and description:
                        if curVsw.name == vswitch_name and curVsw.description == description:
                            vswitches_by_opts.append(curVsw)
                    elif vswitch_name and curVsw.name == vswitch_name:
                        vswitches_by_opts.append(curVsw)
                    elif description and curVsw.description == description:
                        vswitches_by_opts.append(curVsw)

            if vswitch_list is None or len(vswitch_list) < pagesize:
                break
            page += 1

    except VPCResponseError as e:
        module.fail_json(
            msg='Unable to retrieve vswitch, error: {0}'.format(e))

    if not vswitch and len(vswitches_by_opts) == 1:
        vswitch = vswitches_by_opts[0]

    if len(vswitches_by_opts) > 1:
        vswitches = vswitches_by_opts

    if state == 'present':
        if not vswitch:
            changed, vswitch = create_vswitch(module, vpc)
        elif vswitch_name or description:
            try:
                vswitch = vswitch.update(name=vswitch_name,
                                         description=description)
                changed = True
            except VPCResponseError as e:
                module.fail_json(
                    msg='Unable to modify vswitch attribute, error: {0}'.
                    format(e))

        module.exit_json(changed=changed,
                         vpc_id=vswitch.vpc_id,
                         vswitch=get_vswitch_detail(vswitch),
                         vswitch_id=vswitch.id)

    elif state == 'absent':
        if vswitch:
            try:
                changed = vswitch.delete()
                module.exit_json(changed=changed, vswitch_id=vswitch.id)
            except VPCResponseError as ex:
                module.fail_json(
                    msg='Unable to delete vswitch: {0}, error: {1}'.format(
                        vswitch.id, ex))

        module.exit_json(
            changed=changed,
            msg=
            "Please specify a vswitch by using 'vswitch_id', 'vswitch_name' or "
            "'cidr_block', and expected vpcs: %s" % vswitches_basic)

    elif state == 'list':
        vswitch_ids = []
        vpc_ids = []
        vswitches_detail = []
        if vswitch:
            module.exit_json(changed=False,
                             vpc_ids=[vswitch.vpc_id],
                             vswitches=[get_vswitch_detail(vswitch)],
                             vswitch_ids=[vswitch.id],
                             total=1)

        for vsw in vswitches:
            vswitch_ids.append(vsw.id)
            vpc_ids.append(vsw.vpc_id)
            vswitches_detail.append(get_vswitch_detail(vsw))
        module.exit_json(changed=False,
                         vpc_id=vpc_ids,
                         vswitches=vswitches_detail,
                         vswitch_ids=vswitch_ids,
                         total=len(vswitches))

    else:
        module.fail_json(
            msg='The expected state: {0}, {1} and {2}, but got {3}.'.format(
                "present", "absent", "list", state))
예제 #22
0
def main():
    argument_spec = ecs_argument_spec()
    argument_spec.update(
        dict(state=dict(type='str',
                        default='present',
                        choices=['present', 'absent']),
             ip_address=dict(type='str', aliases=['ip']),
             instance_id=dict(type='str', aliases=['device_id']),
             internet_charge_type=dict(
                 type='str',
                 default='PayByBandwidth',
                 choices=['PayByTraffic', 'PayByBandwidth']),
             bandwidth=dict(type='int', default=5)))
    module = AnsibleModule(argument_spec=argument_spec)

    if HAS_FOOTMARK is False:
        module.fail_json(
            msg="Package 'footmark' required for the module alicloud_eip.")
    module = AnsibleModule(argument_spec=argument_spec)

    vpc = vpc_connect(module)

    # set values
    state = module.params['state']
    instance_id = module.params['instance_id']
    internet_charge_type = module.params['internet_charge_type']
    ip_address = module.params['ip_address']
    bandwidth = module.params['bandwidth']

    current = None
    changed = False
    if ip_address:
        eips = vpc.get_all_eip_addresses(ip_address=ip_address)
        if eips and len(eips) > 0:
            current = eips[0]

    if state == 'present':
        if not current:
            try:
                client_token = "Ansible-Alicloud-%s-%s" % (hash(
                    str(module.params)), str(time.time()))
                current = vpc.allocate_eip_address(
                    bandwidth=bandwidth,
                    internet_charge_type=internet_charge_type,
                    client_token=client_token)
                changed = True
            except VPCResponseError as e:
                module.fail_json(
                    msg='Unable to allocate an eip address, error: {0}'.format(
                        e))

        if bandwidth > 0 and bandwidth != int(current.bandwidth):
            try:
                changed = current.modify(bandwidth=bandwidth)
            except Exception as e:
                module.fail_json(
                    msg="Modify EIP bandwidth failed. Error: {0}".format(e))

        if instance_id and current.status == 'Available':
            try:
                changed = current.associate(instance_id=instance_id)
            except Exception as e:
                module.fail_json(
                    msg="Associate EIP with instance {0} failed. Error: {1}".
                    format(instance_id, e))
        module.exit_json(changed=changed,
                         ip_address=current.ip_address,
                         allocation_id=current.id,
                         instance_id=current.instance_id,
                         eip=get_eip(current))
    else:
        if instance_id:
            try:
                changed = current.disassociate(instance_id=instance_id)
                module.exit_json(changed=changed,
                                 ip_address=current.ip_address,
                                 allocation_d=current.id,
                                 eip=get_eip(current))
            except Exception as e:
                module.fail_json(
                    msg="Disassociate EIP with instance {0} failed. Error: {1}"
                    .format(instance_id, e))

        #release
        try:
            changed = current.release()
        except Exception as e:
            module.fail_json(
                msg="Disassociate EIP with instance {0} failed. Error: {1}".
                format(instance_id, e))
        module.exit_json(changed=changed)