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))
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', 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'), 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))
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)
def main(): argument_spec = ecs_argument_spec() argument_spec.update( dict(load_balancer_name=dict(type='list', aliases=['name']), load_balancer_ids=dict(type='list', aliases=['ids']), name_prefix=dict(type='str'), 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.") lb_ids = module.params['load_balancer_ids'] if not lb_ids: lb_ids = [] name_prefix = module.params['name_prefix'] filters = module.params['filters'] if not filters: filters = {} for key, value in list(filters.items()): if key in ["LoadBalancerId", "load-balancer-id", "load_balancer_id" ] and value not in lb_ids: lb_ids.append(value) lbs = [] ids = [] names = [] try: slb = slb_connect(module) if len(lb_ids) > 0: for index in range(0, len(lb_ids), 10): ids_tmp = lb_ids[index:index + 10] if not ids_tmp: break filters['load_balancer_id'] = ",".join(ids_tmp) for lb in slb.describe_load_balancers(**filters): if name_prefix and not str( lb.load_balancer_name).startswith(name_prefix): continue lbs.append(lb.read()) ids.append(lb.load_balancer_id) names.append(lb.load_balancer_name) else: for lb in slb.describe_load_balancers(**filters): if name_prefix and not str( lb.load_balancer_name).startswith(name_prefix): continue lbs.append(lb.read()) ids.append(lb.load_balancer_id) names.append(lb.load_balancer_name) module.exit_json(changed=False, load_balancers=lbs, ids=ids, names=names) except Exception as e: module.fail_json( msg= "Unable to describe server load balancers, and got an error: {0}.". format(e))
def main(): argument_spec = ecs_argument_spec() argument_spec.update( dict( state=dict(default='present', choices=['present', 'absent']), db_name=dict(type='str'), db_instance_id=dict(type='str', required=True), account_name=dict(type='str', aliases=['name'], required=True), account_password=dict(type='str', aliases=['password']), account_privilege=dict(aliases=['privilege'], choices=['ReadOnly', 'ReadWrite']), description=dict(type='str'), account_type=dict(default='Normal', type='str', choices=['Normal', 'Super']), )) module = AnsibleModule(argument_spec=argument_spec) rds = rds_connect(module) if HAS_FOOTMARK is False: module.fail_json("Footmark required for this module") # Get values of variable state = module.params['state'] db_instance_id = module.params['db_instance_id'] account_name = module.params['account_name'] account_password = module.params['account_password'] account_privilege = module.params['account_privilege'] description = module.params['description'] account_type = module.params['account_type'] db_name = module.params['db_name'] account_list = [] current_account = None changed = False try: current_account_list = rds.list_account(db_instance_id, account_name) if len(current_account_list) == 1: current_account = current_account_list[0] except Exception as e: module.fail_json( msg=str("Unable to describe accounts, error:{0}".format(e))) if state == "absent": if current_account: if db_name: try: changed = current_account.revoke_privilege( db_instance_id, db_name) current_account = rds.list_account(db_instance_id, account_name)[0] module.exit_json(changed=True, account_name=account_name, account=get_info(current_account)) except Exception as e: module.fail_json(msg=str( "Unable to revoke privilege error:{0}".format(e))) try: changed = current_account.delete(db_instance_id) module.exit_json(changed=True, account_name=account_name, account=get_info(current_account)) except Exception as e: module.fail_json( msg=str("Unable to delete account error:{0}".format(e))) module.fail_json( msg= "There is no account to revoke database privilege or delete. Please specify an account using 'account_name', and try again." ) if account_password and current_account: try: changed = current_account.reset(db_instance_id, account_password) except Exception as e: module.fail_json(msg=str( "Unable to reset account password error:{0}".format(e))) if not current_account: try: current_account = rds.create_account(db_instance_id, account_name, account_password, description, account_type) except Exception as e: module.fail_json( msg=str("Unable to create account error:{0}".format(e))) if description and description != current_account.account_description: try: changed = current_account.modify_description( db_instance_id, description) current_account.account_description = description except Exception as e: module.fail_json(msg=str( "Unable to modify account description error:{0}".format(e))) if db_name: if account_privilege: try: changed = current_account.grant_privilege( db_instance_id, db_name, account_privilege) current_account = current_account_list[0] except Exception as e: module.fail_json( msg=str("Unable to grant privilege error:{0}".format(e))) else: module.fail_json( msg= "grant privilege failed. Please check your account_privilege and try again." ) module.exit_json(changed=changed, account_name=account_name, account=get_info(current_account))
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)
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']), state=dict(default='present', choices=['present', 'absent']), 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))
def main(): argument_spec = ecs_argument_spec() argument_spec.update( dict(domain_name=dict(type='str', aliases=['name'], required=True), group_name=dict(type='str'), lang=dict(type='str'), resource_group_id=dict(type='str'), remark=dict(type='str'), state=dict(default='present', choices=['present', 'absent']), user_client_ip=dict(type='str'))) module = AnsibleModule(argument_spec=argument_spec) if HAS_FOOTMARK is False: module.fail_json( msg='footmark required for the module ali_dns_domain.') dns_conn = dns_connect(module) # Get values of variable state = module.params['state'] domain_name = module.params['domain_name'] remark = module.params['remark'] group_name = module.params['group_name'] changed = False # Check if VPC exists dns = dns_exists(module, dns_conn, domain_name) if state == 'absent': if not dns: module.exit_json(changed=changed, dns={}) try: module.exit_json(changed=dns.delete(), dns={}) except DNSResponseError as ex: module.fail_json( msg='Unable to delete dns {0}, error: {1}'.format(dns.id, ex)) if not dns: params = module.params try: dns = dns_conn.add_domain(**params) if dns: changed = True except DNSResponseError as e: module.fail_json(msg='Unable to create dns, error: {0}'.format(e)) if domain_name and group_name: try: res = dns.change_domain_group(group_name=group_name, domain_name=domain_name) if res: changed = True except DNSResponseError as e: module.fail_json( msg='Unable to change domain group, error: {0}'.format(e)) if remark: try: res = dns.modify_remark(remark=remark) if res: changed = True except DNSResponseError as e: module.fail_json( msg='Unable to modify dns remark, error: {0}'.format(e)) module.exit_json(changed=changed, dns=dns.get().read())
def main(): argument_spec = ecs_argument_spec() argument_spec.update( dict( state=dict(default='present', choices=['present', 'absent', 'list']), 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 route_entry: module.fail_json( changed=changed, msg= "The specified route entry {0} has existed in route table {1}." .format(destination_cidrblock, route_table_id)) 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) elif state == 'absent': 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)) elif state == 'list': if route_entry: module.exit_json( changed=False, route_table_id=route_table_id, route_entries=[route_entry], destination_cidrblocks=[route_entry.destination_cidrblock], total=1) destination_cidrblocks = [] route_entries_detail = [] for entry in route_entries: destination_cidrblocks.append(entry.destination_cidrblock) route_entries_detail.append(get_route_entry_detail(entry)) module.exit_json(changed=False, route_table_id=route_table_id, route_entries=route_entries_detail, destination_cidrblocks=destination_cidrblocks, total=len(route_entries)) else: module.fail_json( msg='The expected state: {0}, {1} and {2}, but got {3}.'.format( "present", "absent", "list", state))
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', 'list']), 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_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))
def main(): argument_spec = ecs_argument_spec() argument_spec.update( dict(rule_id=dict(type='str'), launch_time=dict(type='str'), launch_expiration=dict(type='int', defalut=600, aliases=['expiration']), name=dict(type='str', aliases=['task_name']), description=dict(type='str'), recurrence_type=dict(type='str', choices=['Daily', 'Weekly', 'Monthly'], aliases=['type']), recurrence_value=dict(type='str', aliases=['value']), recurrence_endtime=dict(type='str', aliases=['endtime']), state=dict(type='str', default='present', choices=['present', 'absent']), enabled=dict(type='bool', default=True), id=dict(type='str', aliases=['task_id']))) module = AnsibleModule(argument_spec=argument_spec) if HAS_FOOTMARK is False: module.fail_json( msg="Package 'footmark' required for the module alicloud_ess_task." ) ess = ess_connect(module) state = module.params['state'] task_id = module.params['id'] task_name = module.params['name'] rule_id = module.params['rule_id'] launch_time = module.params['launch_time'] launch_expiration = module.params['launch_expiration'] recurrence_type = module.params['recurrence_type'] recurrence_value = module.params['recurrence_value'] recurrence_endtime = module.params['recurrence_endtime'] enabled = module.params['enabled'] description = module.params['description'] # Get scaling rule ari according rule ID rule_ari = None if rule_id: rules = ess.describe_rules(scaling_rule_ids=[rule_id]) rule_ari = rules[0].ari count = 0 if recurrence_type: count += 1 if recurrence_value: count += 1 if recurrence_endtime: count += 1 if count in (1, 2): module.fail_json( msg= "'recurrence_type', 'recurrence_value' and 'recurrence_endtime' must be specified or not at the same time" ) changed = False current = None all_tasks = [] if task_id or task_name: tasks = ess.describe_scheduled_tasks(scheduled_task_ids=[task_id], scheduled_task_names=[task_name], scaling_rule_aris=[rule_ari]) if tasks: if len(tasks) > 1: for task in tasks: all_tasks.append(task.id) module.fail_json( msg= "There are several scheduled tasks in our record based on name {0}: {1}. " "Please specified one using 'id' and try again.".format( task_name, all_tasks)) current = tasks[0] if state == 'present': if current is None: try: if not rule_id: module.exit_json( msg= "'rule_id': required field when state is present, aborting." ) if not rule_ari: module.exit_json( msg= "There is no scheduled task in our record based on rule id {0}, aborting." "Please check it and try again.".format(rule_id)) if not launch_time: module.exit_json( msg= "'launch_time': required field when state is present, aborting." ) current = ess.create_scheduled_task( scaling_rule_ari=rule_ari, launch_time=launch_time, name=task_name, description=description, launch_expiration_time=launch_expiration, recurrence_type=recurrence_type, recurrence_value=recurrence_value, recurrence_end_time=recurrence_endtime, task_enabled=enabled) changed = True except Exception as e: module.fail_json( msg="Create scheduled task got an error: {0}".format(e)) else: try: changed = current.modify( scaling_rule_ari=rule_ari, launch_time=launch_time, name=task_name, description=description, launch_expiration_time=launch_expiration, recurrence_type=recurrence_type, recurrence_value=recurrence_value, recurrence_end_time=recurrence_endtime, task_enabled=enabled) if changed: current = current.update(validate=True) except Exception as e: module.fail_json( msg="Modify scheduled rule got an error: {0}".format(e)) module.exit_json(changed=changed, id=current.id, name=current.name, task=get_details(current)) if current is None: if task_id or task_name: module.fail_json( msg= "There are no scheduled task in our record based on id {0} or name {1}. " "Please check it and try again.".format(task_id, task_name)) module.fail_json( msg= 'Please specify a scheduled task that you want to terminate by field id or name, aborting' ) try: module.exit_json(changed=current.terminate()) except Exception as e: module.fail_json( msg='Delete scheduled task {0} got an error: {1}'.format( current.id, e))
def main(): argument_spec = ecs_argument_spec() argument_spec.update(dict( internet_charge_type=dict(type='str', required=False, choices=['paybybandwidth', 'paybytraffic'], default='paybytraffic'), state=dict(type='str', required=True, choices=['present', 'absent', 'list']), load_balancer_name=dict(type='str', required=False, aliases=['name']), load_balancer_id=dict(type='str', required=False, aliases=['ecs_slb']), address_type=dict(type='str', required=False, default='internet', choices=['internet', 'intranet']), bandwidth=dict(type='int', required=False, default=1), vswitch_id=dict(type='str', required=False), load_balancer_status=dict(type='str', required=False, choices=['active', 'inactive']), master_zone_id=dict(type='str', required=False), slave_zone_id=dict(type='str', required=False) )) module = AnsibleModule(argument_spec=argument_spec) if HAS_FOOTMARK is False: module.fail_json(msg='footmark required for the module alicloud_slb_lb.') slb = slb_connect(module) state = module.params['state'] load_balancer_id = module.params['load_balancer_id'] load_balancer_name = module.params['load_balancer_name'] address_type = module.params['address_type'] vswitch_id = module.params['vswitch_id'] master_zone_id = module.params['master_zone_id'] slave_zone_id = module.params['slave_zone_id'] internet_charge_type = module.params['internet_charge_type'] load_balancer_status = module.params['load_balancer_status'] bandwidth = module.params['bandwidth'] res_objs = [] changed = False cur_slb = None if load_balancer_id and load_balancer_name: name_test = "" else: name_test = load_balancer_name res_objs = slb.describe_load_balancers(load_balancer_id=load_balancer_id, load_balancer_name=name_test) if len(res_objs) == 1: cur_slb = res_objs[0] if state == "absent": if cur_slb: changed = cur_slb.delete() module.exit_json(changed=changed, load_balancer_id=cur_slb.load_balancer_id) else: module.fail_json(msg="The specified load balancer is not exist. Please check your load_balancer_id or load_balancer_name and try again.") elif state == "present": if load_balancer_status and cur_slb: # set status changed = cur_slb.set_status(load_balancer_status) if changed: cur_slb.load_balancer_status = load_balancer_status module.exit_json(changed=changed, load_balancer=get_info(cur_slb), load_balancer_id=cur_slb.load_balancer_id) elif load_balancer_name and cur_slb: # set name changed = cur_slb.modify_name(load_balancer_name) if changed: cur_slb.load_balancer_name = load_balancer_name module.exit_json(changed=changed, load_balancer=get_info(cur_slb), load_balancer_id=cur_slb.load_balancer_id) elif (internet_charge_type or bandwidth) and cur_slb: # set spec changed = cur_slb.modify_spec(internet_charge_type=internet_charge_type, bandwidth=bandwidth) if changed: cur_slb.internet_charge_type = internet_charge_type cur_slb.bandwidth = bandwidth module.exit_json(changed=changed, load_balancer=get_info(cur_slb), load_balancer_id=cur_slb.load_balancer_id) elif not cur_slb: client_token = "Ansible-Alicloud-%s-%s" % (hash(str(module.params)), str(time.time())) res_obj = slb.create_load_balancer(load_balancer_name=load_balancer_name, address_type=address_type, vswitch_id=vswitch_id, internet_charge_type=internet_charge_type, master_zone_id=master_zone_id, slave_zone_id=slave_zone_id, bandwidth=bandwidth, client_token=client_token) changed = True module.exit_json(changed=changed, load_balancer=get_info(res_obj), load_balancer_id=res_obj.load_balancer_id) else: module.exit_json(changed=changed, load_balancer=get_info(cur_slb), load_balancer_id=cur_slb.load_balancer_id) elif state == "list": load_balancers = [] for res_obj in res_objs: load_balancers.append(get_info(res_obj)) module.exit_json(changed=True, load_balancers=load_balancers)
def main(): argument_spec = ecs_argument_spec() argument_spec.update( dict(state=dict(default='present', choices=['present', 'absent']), cidr_block=dict(required=True, aliases=['cidr']), user_cidrs=dict(type='list'), name=dict(required=True, aliases=['vpc_name']), multi_ok=dict(type='bool', default=False), description=dict(), 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'] 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_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())
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'), tags=dict(type='dict'), purge_tags=dict(type='bool', default=False))) 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) module.exit_json(changed=True, interface=eni.get().read()) 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)) tags = module.params['tags'] if module.params['purge_tags']: removed = {} if not tags: removed = eni.tags else: for key, value in list(eni.tags.items()): if key not in list(tags.keys()): removed[key] = value try: if eni.remove_tags(removed): changed = True except Exception as e: module.fail_json(msg="{0}".format(e)) if tags: try: if eni.add_tags(tags): 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())
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'), name_prefix=dict(type='str'), cidr_prefix=dict(type='str'), vswitch_ids=dict(type='list', aliases=['ids', 'subnet_ids']), filters=dict(type='dict'), tags=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'] tags = module.params['tags'] 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 if tags: flag = False for key, value in list(tags.items()): if key in list(vsw.tags.keys()) and value == vsw.tags[key]: flag = True if not flag: 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(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=eval(count_tag)) elif instance_name: instances = ecs.describe_instances(zone_id=zone_id, instance_name=instance_name) ids = [] if state == 'absent': if len(instances) < 1: module.fail_json( msg= 'Please specify ECS instances that you want to operate by using ' 'parameters instance_ids, tags or instance_name, aborting') try: targets = [] for inst in instances: if inst.status != 'stopped' and not force: module.fail_json( msg= "Instance is running, and please stop it or set 'force' as True." ) targets.append(inst.id) if ecs.delete_instances(instance_ids=targets, force=force): changed = True ids.extend(targets) module.exit_json(changed=changed, ids=ids, instances=[]) except Exception as e: module.fail_json(msg='Delete instance got an error: {0}'.format(e)) if module.params['allocate_public_ip'] and max_bandwidth_out < 0: module.fail_json( msg= "'max_bandwidth_out' should be greater than 0 when 'allocate_public_ip' is True." ) if not module.params['allocate_public_ip']: module.params['max_bandwidth_out'] = 0 if state == 'present': if not instance_ids: if len(instances) > count: for i in range(0, len(instances) - count): inst = instances[len(instances) - 1] if inst.status != 'stopped' and not force: module.fail_json( msg= "That to delete instance {0} is failed results from it is running, " "and please stop it or set 'force' as True.". format(inst.id)) try: if inst.terminate(force=force): changed = True except Exception as e: module.fail_json( msg="Delete instance {0} got an error: {1}".format( inst.id, e)) instances.pop(len(instances) - 1) else: try: if re.search(r"-\[\d+,\d+\]-", host_name): module.fail_json( msg= 'Ordered hostname is not supported, If you want to add an ordered ' 'suffix to the hostname, you can set unique_suffix to True' ) new_instances = run_instance(module, ecs, count - len(instances)) if new_instances: changed = True instances.extend(new_instances) except Exception as e: module.fail_json( msg="Create new instances got an error: {0}".format(e)) # Security Group join/leave begin security_groups = module.params['security_groups'] if security_groups: if not isinstance(security_groups, list): module.fail_json( msg= 'The parameter security_groups should be a list, aborting') for inst in instances: existing = inst.security_group_ids['security_group_id'] remove = list(set(existing).difference(set(security_groups))) add = list(set(security_groups).difference(set(existing))) for sg in remove: if inst.leave_security_group(sg): changed = True for sg in add: if inst.join_security_group(sg): changed = True # Security Group join/leave ends here # Attach/Detach key pair inst_ids = [] for inst in instances: if key_name is not None and key_name != inst.key_name: if key_name == "": if inst.detach_key_pair(): changed = True else: inst_ids.append(inst.id) if inst_ids: changed = ecs.attach_key_pair(instance_ids=inst_ids, key_pair_name=key_name) # Modify instance attribute for inst in instances: if modify_instance(module, inst): changed = True if inst.id not in ids: ids.append(inst.id) # Modify instance charge type ids = [] for inst in instances: if inst.instance_charge_type != instance_charge_type: ids.append(inst.id) if ids: params = { "instance_ids": ids, "instance_charge_type": instance_charge_type, "include_data_disks": module.params['include_data_disks'], "dry_run": module.params['dry_run'], "auto_pay": True } if instance_charge_type == 'PrePaid': params['period'] = module.params['period'] params['period_unit'] = module.params['period_unit'] if ecs.modify_instance_charge_type(**params): changed = True wait_for_instance_modify_charge(ecs, ids, instance_charge_type) else: if len(instances) < 1: module.fail_json( msg= 'Please specify ECS instances that you want to operate by using ' 'parameters instance_ids, tags or instance_name, aborting') if state == 'running': try: targets = [] for inst in instances: if modify_instance(module, inst): changed = True if inst.status != "running": targets.append(inst.id) ids.append(inst.id) if targets and ecs.start_instances(instance_ids=targets): changed = True ids.extend(targets) except Exception as e: module.fail_json( msg='Start instances got an error: {0}'.format(e)) elif state == 'stopped': try: targets = [] for inst in instances: if inst.status != "stopped": targets.append(inst.id) if targets and ecs.stop_instances(instance_ids=targets, force_stop=force): changed = True ids.extend(targets) for inst in instances: if modify_instance(module, inst): changed = True except Exception as e: module.fail_json( msg='Stop instances got an error: {0}'.format(e)) elif state == 'restarted': try: targets = [] for inst in instances: if modify_instance(module, inst): changed = True targets.append(inst.id) if ecs.reboot_instances(instance_ids=targets, force_stop=module.params['force']): changed = True ids.extend(targets) except Exception as e: module.fail_json( msg='Reboot instances got an error: {0}'.format(e)) tags = module.params['tags'] if module.params['purge_tags']: for inst in instances: if not tags: tags = inst.tags try: if inst.remove_tags(tags): changed = True except Exception as e: module.fail_json(msg="{0}".format(e)) module.exit_json(changed=changed, instances=get_instances_info(ecs, ids)) if tags: for inst in instances: try: if inst.add_tags(tags): changed = True except Exception as e: module.fail_json(msg="{0}".format(e)) module.exit_json(changed=changed, instances=get_instances_info(ecs, ids))
def main(): argument_spec = ecs_argument_spec() argument_spec.update( dict(state=dict(default='present', choices=['present', 'absent']), group_name=dict(type='str', required=True, aliases=['name']), new_group_name=dict(type='str'), comments=dict(type='str'), user_name=dict(type='str'))) module = AnsibleModule(argument_spec=argument_spec) if HAS_FOOTMARK is False: module.fail_json(msg='footmark required for this module.') ram_conn = ram_connect(module) # Get values of variable state = module.params['state'] group_name = module.params['group_name'] new_group_name = module.params['new_group_name'] comments = module.params['comments'] user_name = module.params['user_name'] changed = False # Check if user exists group = group_exists(module, ram_conn, group_name) if state == 'absent': if user_name: try: changed = group.remove_user(user_name=user_name) module.exit_json(changed=changed, group=group.read()) except Exception as e: module.fail_json( msg='Unable to remove user to group {0}, error: {1}'. format(group_name, e)) if not group: module.exit_json(changed=changed, group={}) try: module.exit_json(changed=group.delete(), group={}) except RAMResponseError as ex: module.fail_json( msg='Unable to delete group {0}, error: {1}'.format( group_name, ex)) if not group: try: group = ram_conn.create_group(**module.params) module.exit_json(changed=True, group=group.read()) except RAMResponseError as e: module.fail_json( msg='Unable to create group, error: {0}'.format(e)) if user_name: try: changed = group.add_user(user_name=user_name) except Exception as e: module.fail_json( msg='Unable to add user to group {0}, error: {1}'.format( group_name, e)) if comments or new_group_name: try: changed = group.update(comments=comments, new_group_name=new_group_name) except RAMResponseError as e: module.fail_json( msg='Unable to update comments, error: {0}'.format(e)) module.exit_json(changed=changed, group=group.read())
def main(): # if HAS_ECS is False: # module.fail_json("ecsutils required for this module") 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 # performing operation create disk 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)
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=list(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=list(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 ali_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))
def main(): argument_spec = ecs_argument_spec() argument_spec.update( dict(internet_charge_type=dict( type='str', required=False, choices=['paybybandwidth', 'paybytraffic'], default='paybytraffic'), state=dict(type='str', required=True, choices=['present', 'absent', 'running', 'stopped']), load_balancer_name=dict(type='str', required=False, aliases=['name']), load_balancer_id=dict(type='str', required=False, aliases=['id']), is_internet=dict(type='bool', required=False, default=True), bandwidth=dict(type='int', required=False, default=1), vswitch_id=dict(type='str', required=False, aliases=['subnet_id']), master_zone_id=dict(type='str', required=False), slave_zone_id=dict(type='str', required=False))) module = AnsibleModule(argument_spec=argument_spec) if HAS_FOOTMARK is False: module.fail_json( msg='footmark required for the module alicloud_slb_lb.') slb = slb_connect(module) state = module.params['state'] load_balancer_id = module.params['load_balancer_id'] load_balancer_name = module.params['load_balancer_name'] is_internet = module.params['is_internet'] vswitch_id = module.params['vswitch_id'] master_zone_id = module.params['master_zone_id'] slave_zone_id = module.params['slave_zone_id'] internet_charge_type = module.params['internet_charge_type'] bandwidth = module.params['bandwidth'] changed = False cur_slb = None if load_balancer_id and load_balancer_name: name_test = "" else: name_test = load_balancer_name res_objs = slb.describe_load_balancers(load_balancer_id=load_balancer_id, load_balancer_name=name_test) if len(res_objs) == 1: cur_slb = slb.describe_load_balancer_attribute(res_objs[0].id) if state == "present": if cur_slb: if load_balancer_name != cur_slb.name: changed = cur_slb.modify_name(load_balancer_name) if changed: cur_slb.load_balancer_name = load_balancer_name if internet_charge_type != cur_slb.internet_charge_type or \ (cur_slb.internet_charge_type == "paybybandwidth" and bandwidth != cur_slb.bandwidth): print(cur_slb.__dict__) print(cur_slb.internet_charge_type, cur_slb.bandwidth) changed = cur_slb.modify_spec( internet_charge_type=internet_charge_type, bandwidth=bandwidth) if changed: cur_slb.internet_charge_type = internet_charge_type cur_slb.bandwidth = bandwidth else: client_token = "Ansible-Alicloud-%s-%s" % (hash(str( module.params)), str(time.time())) address_type = "internet" if not is_internet: address_type = "intranet" cur_slb = slb.create_load_balancer( load_balancer_name=load_balancer_name, address_type=address_type, vswitch_id=vswitch_id, internet_charge_type=internet_charge_type, master_zone_id=master_zone_id, slave_zone_id=slave_zone_id, bandwidth=bandwidth, client_token=client_token) changed = True module.exit_json(changed=changed, load_balancer=get_info(cur_slb), load_balancer_id=cur_slb.id) if not cur_slb: module.fail_json( msg= "The specified load balancer is not exist. Please check your load_balancer_id or load_balancer_name and try again." ) if state == "absent": changed = cur_slb.delete() module.exit_json(changed=changed, load_balancer_id=cur_slb.load_balancer_id) if state == "running": if cur_slb.status != "active": changed = cur_slb.set_status("active") if changed: cur_slb.load_balancer_status = "active" module.exit_json(changed=changed, load_balancer=get_info(cur_slb), load_balancer_id=cur_slb.load_balancer_id) if state == "stopped": if cur_slb.status != "inactive": changed = cur_slb.set_status("inactive") if changed: cur_slb.load_balancer_status = "inactive" module.exit_json(changed=changed, load_balancer=get_info(cur_slb), load_balancer_id=cur_slb.load_balancer_id)
def main(): argument_spec = ecs_argument_spec() argument_spec.update(dict( name=dict(type=str, aliases=['group_name']), max_size=dict(type=int), min_size=dict(type=int), state=dict(type=str, default='present', choices=['present', 'active', 'inactive', 'absent']), id=dict(type=str, aliases=['group_id']), cooldown=dict(type=int, default=300, aliases=['default_cooldown']), removal_policies=dict(type=list, default=['OldestScalingConfiguration','OldestInstance']), load_balancer_ids=dict(type=list, aliases=['lb_ids']), db_instance_ids=dict(type=list, aliases=['db_ids']), vswitch_ids=dict(type=list, aliases=['subnet_ids']), configuration_id=dict(type=str, aliases=['scaling_configuration_id']) )) module = AnsibleModule(argument_spec=argument_spec) if HAS_FOOTMARK is False: module.fail_json(msg="Package 'footmark' required for the module ali_ess_group.") ess = ess_connect(module) state = module.params['state'] group_id = module.params['id'] group_name = module.params['name'] max_size = module.params['max_size'] min_size = module.params['min_size'] cooldown = module.params['cooldown'] removal_policies = module.params['removal_policies'] configuration_id = module.params['configuration_id'] changed = False current = None all_groups = [] if group_id or group_name: groups = ess.describe_groups(scaling_group_ids=[group_id], scaling_group_names=[group_name]) if groups: for group in groups: all_groups.append(group.id) if len(all_groups) > 1: module.fail_json(msg="There are several scaling group in our record based on name {0}: {1}. " "Please specified one using 'id' and try again.".format(group_name, all_groups)) current = groups[0] if state == 'present': if current is None: try: if max_size is None or max_size < 0 or max_size > 100: module.fail_json(msg="'max_size': required field when state is 'present' and its value range [0, 100]. " "Please check it and try again.") if min_size is None or min_size < 0 or min_size > 100: module.fail_json(msg="'min_size': required field when state is 'present' and its value range [0, 100]. " "Please check it and try again.") lb_ids = module.params['load_balancer_ids'] db_ids = module.params['db_instance_ids'] vsw_ids = module.params['vswitch_ids'] if lb_ids and not isinstance(lb_ids, list): module.fail_json(msg="Filed 'load_balancer_ids' should be a list, aborting.") if db_ids and not isinstance(db_ids, list): module.fail_json(msg="Filed 'db_instance_ids' should be a list, aborting.") if vsw_ids and not isinstance(vsw_ids, list): module.fail_json(msg="Filed 'vswitch_ids' should be a list, aborting.") current = ess.create_group(max_size=max_size, min_size=min_size, name=group_name, default_cooldown=cooldown, removal_policies=removal_policies, load_balancer_ids=lb_ids, db_instance_ids=db_ids, vswitch_ids=vsw_ids) changed = True except Exception as e: module.fail_json(msg="Create scaling group got an error: {0}".format(e)) # Modify scaling group attribute if group_name != current.name or max_size != current.max_size or min_size != current.min_size \ or configuration_id != current.configuration_id or cooldown != current.cooldown \ or removal_policies != current.removal_policies['removal_policy']: changed = current.modify(max_size=max_size, min_size=min_size, name=group_name, default_cooldown=cooldown, removal_policies=removal_policies, scaling_configuration_id=configuration_id) module.exit_json(changed=changed, id=current.id, name=current.name, configuration_id=current.configuration_id, group=get_details(current)) if current is None: if group_id or group_name: module.fail_json(msg="There are no scaling group in our record based on id {0} or name {1}. " "Please check it and try again.".format(group_id, group_name)) module.fail_json(msg='Please specify a scaling group that you want to operate by parameters id or name, aborting') if state == 'absent': try: module.exit_json(changed=current.terminate()) except Exception as e: module.fail_json(msg='Delete scaling group {0} got an error: {1}'.format(current.id, e)) if state == 'active': try: if str.lower(current.status) == 'inactive' or current.configuration_id != configuration_id: changed = current.enable(scaling_configuration_id=configuration_id) current = ess.describe_groups(scaling_group_ids=[group_id])[0] except Exception as e: module.fail_json(msg='Active scaling group {0} got an error: {1}.'.format(current.id, e)) elif state == 'inactive': try: if str.lower(current.status) == 'active': changed = current.disable() current = ess.describe_groups(scaling_group_ids=[group_id])[0] except Exception as e: module.fail_json(msg='Inactive scaling group {0} got an error: {1}.'.format(current.id, e)) module.exit_json(changed=changed, id=current.id, name=current.name, configuration_id=current.configuration_id, group=get_details(current))
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())
def main(): argument_spec = ecs_argument_spec() argument_spec.update(dict( listener_port=dict(type='int', required=True, choices=[i for i in range(1, 65536)], aliases=['frontend_port']), state=dict(type='str', required=True, choices=['present', 'absent', 'stopped', 'running']), load_balancer_id=dict(type='str', required=True, aliases=['id']), backend_server_port=dict(type='int', choices=[i for i in range(1, 65536)], aliases=['backend_port']), bandwidth=dict(type='int', choices=([i for i in range(1, 1001)]).append(-1)), sticky_session=dict(type='str', choices=['on', 'off']), protocol=dict(type='str', choices=['http', 'https', 'tcp', 'udp']), health_check=dict(type='str', default= 'on', choices=['on', 'off']), scheduler=dict(type='str', default='wrr', choices=['wrr', 'wlc']), sticky_session_type=dict(type='str', choices=['insert', 'server']), cookie_timeout=dict(type='str', choices=[i for i in range(1, 86401)]), cookie=dict(type='str'), health_check_domain=dict(type='str'), health_check_uri=dict(type='str', default='/'), health_check_connect_port=dict(type='int', choices=([i for i in range(1, 65536)]).append(-520)), healthy_threshold=dict(type='int', default=3, choices=[i for i in range(1, 11)]), unhealthy_threshold=dict(type='int', default=3, choices=[i for i in range(1, 11)]), health_check_timeout=dict(type='int', default=5, choices=[i for i in range(1, 51)]), health_check_interval=dict(type='int', default=2, choices=[i for i in range(1, 6)]), health_check_http_code=dict(type='str', default='http_2xx'), vserver_group_id=dict(type='str'), persistence_timeout=dict(type='int', default=0, choices=[i for i in range(0, 3601)]), server_certificate_id=dict(type='str'), health_check_type=dict(type='str', default='tcp', choice=['tcp', 'http']), )) module = AnsibleModule(argument_spec=argument_spec) if HAS_FOOTMARK is False: module.fail_json(msg='footmark required for the module alicloud_slb_listener.') slb = slb_connect(module) state = module.params['state'] load_balancer_id = module.params['load_balancer_id'] listener_port = module.params['listener_port'] backend_server_port = module.params['backend_server_port'] bandwidth = module.params['bandwidth'] sticky_session = module.params['sticky_session'] protocol = module.params['protocol'] health_check = module.params['health_check'] scheduler = module.params['scheduler'] sticky_session_type = module.params['sticky_session_type'] cookie_timeout = module.params['cookie_timeout'] cookie = module.params['cookie'] health_check_domain = module.params['health_check_domain'] health_check_uri = module.params['health_check_uri'] health_check_connect_port = module.params['health_check_connect_port'] healthy_threshold = module.params['healthy_threshold'] unhealthy_threshold = module.params['unhealthy_threshold'] health_check_timeout = module.params['health_check_timeout'] health_check_interval = module.params['health_check_interval'] health_check_http_code = module.params['health_check_http_code'] vserver_group_id = module.params['vserver_group_id'] server_certificate_id = module.params['server_certificate_id'] persistence_timeout = module.params['persistence_timeout'] health_check_type = module.params['health_check_type'] current_listener = slb.describe_load_balancer_listener_attribute(load_balancer_id, listener_port, protocol) changed = False if state == "present": if current_listener: changed = current_listener.set_attribute(load_balancer_id=load_balancer_id, bandwidth=bandwidth, sticky_session=sticky_session, protocol=protocol, health_check=health_check, scheduler=scheduler, sticky_session_type=sticky_session_type, cookie_timeout=cookie_timeout, cookie=cookie, health_check_domain=health_check_domain, health_check_uri=health_check_uri, health_check_connect_port=health_check_connect_port, healthy_threshold=healthy_threshold, unhealthy_threshold=unhealthy_threshold, health_check_timeout=health_check_timeout, health_check_interval=health_check_interval, health_check_http_code=health_check_http_code, vserver_group_id=vserver_group_id, server_certificate_id=server_certificate_id, persistence_timeout=persistence_timeout, health_check_type=health_check_type) module.exit_json(changed=changed, listener=get_info(current_listener.describe_attribute(load_balancer_id, protocol))) else: changed = slb.create_load_balancer_listener(load_balancer_id=load_balancer_id, listener_port=listener_port, backend_server_port=backend_server_port, bandwidth=bandwidth, sticky_session=sticky_session, protocol=protocol, health_check=health_check, scheduler=scheduler, sticky_session_type=sticky_session_type, cookie_timeout=cookie_timeout, cookie=cookie, health_check_domain=health_check_domain, health_check_uri=health_check_uri, health_check_connect_port=health_check_connect_port, healthy_threshold=healthy_threshold, unhealthy_threshold=unhealthy_threshold, health_check_timeout=health_check_timeout, health_check_interval=health_check_interval, health_check_http_code=health_check_http_code, vserver_group_id=vserver_group_id, server_certificate_id=server_certificate_id, persistence_timeout=persistence_timeout) new_current_listener = slb.describe_load_balancer_listener_attribute(load_balancer_id, listener_port, protocol) module.exit_json(changed=changed, listener=get_info(new_current_listener)) if not current_listener: module.fail_json(msg="The specified load balancer listener is not exist. Please check your load_balancer_id or listener_port and try again.") if state == "absent": changed = current_listener.delete(load_balancer_id) module.exit_json(changed=changed, listener=get_info(current_listener)) if state == "running": if current_listener.status == "stopped": # start changed = current_listener.start(load_balancer_id) module.exit_json(changed=changed, listener=get_info(current_listener.describe_attribute(load_balancer_id, protocol))) if state == "stopped": if current_listener.status == "running": # stop changed = current_listener.stop(load_balancer_id) module.exit_json(changed=changed, listener=get_info(current_listener.describe_attribute(load_balancer_id, protocol)))
def main(): argument_spec = ecs_argument_spec() argument_spec.update( dict( state=dict(type='str', default='present', choices=['present', 'absent']), cidr_block=dict(type='str'), description=dict(type='str'), availability_zone=dict(aliases=['alicloud_zone']), vpc_id=dict(type='str'), vswitch_name=dict(aliases=['name', 'subnet_name']), vswitch_id=dict(type='str', aliases=['subnet_id', 'id']), )) module = AnsibleModule(argument_spec=argument_spec, required_if=([('state', 'absent', ['vswitch_id'])])) 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_name = module.params['vswitch_name'] description = module.params['description'] changed = False vswitch = uniquely_find_vswitch(vpc, module) 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)) 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())) 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)) module.exit_json(changed=changed, vswitch=vswitch.get().read())
def main(): argument_spec = ecs_argument_spec() argument_spec.update(dict( group_id=dict(type='str', aliases=['scaling_group_id']), adjustment_type=dict(type='str', aliases=['type'], choices=['QuantityChangeInCapacity', 'PercentChangeInCapacity', 'TotalCapacity']), adjustment_value=dict(type='int', aliases=['value']), name=dict(type='str', aliases=['rule_name']), cooldown=dict(type='int'), state=dict(type='str', default='present', choices=['present', 'absent']), id=dict(type='str', aliases=['rule_id']) )) module = AnsibleModule(argument_spec=argument_spec) if HAS_FOOTMARK is False: module.fail_json(msg="Package 'footmark' required for the module ali_ess_rule.") ess = ess_connect(module) state = module.params['state'] rule_id = module.params['id'] rule_name = module.params['name'] scaling_group = module.params['group_id'] adjustment_type = module.params['adjustment_type'] adjustment_value = module.params['adjustment_value'] cooldown = module.params['cooldown'] changed = False current = None all_rules = [] if rule_id or rule_name: rules = ess.describe_rules(scaling_group_id=scaling_group, scaling_rule_ids=[rule_id], scaling_rule_names=[rule_name]) if rules: if len(rules) > 1: for r in rules: all_rules.append(r.id) module.fail_json(msg="There are several scaling rules in our record based on name {0}: {1}. " "Please specified one using 'id' and try again.".format(rule_name, all_rules)) current = rules[0] if state == 'present': if current is None: try: if not scaling_group: module.exit_json(msg="'group_id': required field when state is present, aborting.") if not adjustment_type: module.exit_json(msg="'adjustment_type': required field when state is present, aborting.") if not adjustment_value: module.exit_json(msg="'adjustment_value': required field when state is present, aborting.") current = ess.create_rule(scaling_group_id=scaling_group, adjustment_type=adjustment_type, adjustment_value=adjustment_value, name=rule_name, cooldown=cooldown) changed = True except Exception as e: module.fail_json(msg="Create scaling rule got an error: {0}".format(e)) else: try: changed = current.modify(adjustment_type=adjustment_type, adjustment_value=adjustment_value, name=rule_name, cooldown=cooldown) if changed: current = current.update(validate=True) except Exception as e: module.fail_json(msg="Modify scaling rule got an error: {0}".format(e)) module.exit_json(changed=changed, id=current.id, name=current.name, group_id=current.group_id, rule=get_details(current)) if current is None: if rule_id or rule_name: module.fail_json(msg="There are no scaling rule in our record based on id {0} or name {1}. " "Please check it and try again.".format(rule_id, rule_name)) module.fail_json(msg='Please specify a scaling rule that you want to terminate by parameters id or name, aborting') try: module.exit_json(changed=current.terminate()) except Exception as e: module.fail_json(msg='Delete scaling rule {0} got an error: {1}'.format(current.id, e))
def main(): argument_spec = ecs_argument_spec() argument_spec.update( dict(security_groups=dict(type='list'), availability_zone=dict(type='str', aliases=['alicloud_zone']), instance_type=dict(type='str', aliases=['type']), image_id=dict(type='str', aliases=['image']), count=dict(type='int', default=1), count_tag=dict(type='str'), vswitch_id=dict(type='str', aliases=['subnet_id']), instance_name=dict(type='str', aliases=['name']), host_name=dict(type='str'), password=dict(type='str', no_log=True), internet_charge_type=dict( type='str', default='PayByBandwidth', choices=['PayByBandwidth', 'PayByTraffic']), max_bandwidth_in=dict(type='int', default=200), max_bandwidth_out=dict(type='int', default=0), system_disk_category=dict( type='str', default='cloud_efficiency', choices=['cloud_efficiency', 'cloud_ssd']), system_disk_size=dict(type='int', default=40), system_disk_name=dict(type='str'), system_disk_description=dict(type='str'), force=dict(type='bool', default=False), instance_tags=dict(type='dict', aliases=['tags']), state=dict(default='present', choices=[ 'present', 'running', 'stopped', 'restarted', 'absent' ]), description=dict(type='str'), allocate_public_ip=dict(type='bool', aliases=['assign_public_ip'], default=False), instance_charge_type=dict(type='str', default='PostPaid', choices=['PrePaid', 'PostPaid']), period=dict(type='int', default=1), auto_renew=dict(type='bool', default=False), instance_ids=dict(type='list'), auto_renew_period=dict(type='int', choices=[1, 2, 3, 6, 12]), key_name=dict(type='str', aliases=['keypair']), user_data=dict(type='str'))) module = AnsibleModule(argument_spec=argument_spec) if HAS_FOOTMARK is False: module.fail_json(msg=missing_required_lib('footmark'), exception=FOOTMARK_IMP_ERR) ecs = ecs_connect(module) state = module.params['state'] instance_ids = module.params['instance_ids'] count_tag = module.params['count_tag'] count = module.params['count'] instance_name = module.params['instance_name'] force = module.params['force'] zone_id = module.params['availability_zone'] key_name = module.params['key_name'] changed = False instances = [] if instance_ids: if not isinstance(instance_ids, list): module.fail_json( msg='The parameter instance_ids should be a list, aborting') instances = ecs.get_all_instances(zone_id=zone_id, instance_ids=instance_ids) if not instances: module.fail_json( msg= "There are no instances in our record based on instance_ids {0}. " "Please check it and try again.".format(instance_ids)) elif count_tag: instances = ecs.get_all_instances(zone_id=zone_id, instance_tags=eval(count_tag)) elif instance_name: instances = ecs.get_all_instances(zone_id=zone_id, instance_name=instance_name) ids = [] if state == 'present': if not instance_ids: if len(instances) > count: for i in range(0, len(instances) - count): inst = instances[len(instances) - 1] if inst.status != 'stopped' and not force: module.fail_json( msg= "That to delete instance {0} is failed results from it is running, " "and please stop it or set 'force' as True.". format(inst.id)) try: changed = inst.terminate(force=force) except Exception as e: module.fail_json( msg="Delete instance {0} got an error: {1}".format( inst.id, e)) instances.pop(len(instances) - 1) else: try: new_instances = create_instance(module, ecs, count - len(instances)) if new_instances: changed = True instances.extend(new_instances) except Exception as e: module.fail_json( msg="Create new instances got an error: {0}".format(e)) # Security Group join/leave begin security_groups = module.params['security_groups'] if not isinstance(security_groups, list): module.fail_json( msg='The parameter security_groups should be a list, aborting') if len(security_groups) > 0: for inst in instances: existing = inst.security_group_ids['security_group_id'] remove = list(set(existing).difference(set(security_groups))) add = list(set(security_groups).difference(set(existing))) for sg in remove: if inst.leave_security_group(sg): changed = True for sg in add: if inst.join_security_group(sg): changed = True # Security Group join/leave ends here # Attach/Detach key pair inst_ids = [] for inst in instances: if key_name is not None and key_name != inst.key_name: if key_name == "": changed = inst.detach_key_pair() else: inst_ids.append(inst.id) if inst_ids: changed = ecs.attach_key_pair(instance_ids=inst_ids, key_pair_name=key_name) # Modify instance attribute description = module.params['description'] host_name = module.params['host_name'] password = module.params['password'] for inst in instances: if not instance_name: instance_name = inst.name if not description: description = inst.description if not host_name: host_name = inst.host_name try: if inst.modify(name=instance_name, description=description, host_name=host_name, password=password): changed = True except Exception as e: module.fail_json( msg="Modify instance attribute {0} got an error: {1}". format(inst.id, e)) if inst.id not in ids: ids.append(inst.id) module.exit_json(changed=changed, ids=ids, instances=get_instances_info(ecs, ids)) else: if len(instances) < 1: module.fail_json( msg= 'Please specify ECS instances that you want to operate by using ' 'parameters instance_ids, instance_tags or instance_name, aborting' ) force = module.params['force'] if state == 'running': try: for inst in instances: if inst.start(): changed = True ids.append(inst.id) module.exit_json(changed=changed, ids=ids, instances=get_instances_info(ecs, ids)) except Exception as e: module.fail_json( msg='Start instances got an error: {0}'.format(e)) elif state == 'stopped': try: for inst in instances: if inst.stop(force=force): changed = True ids.append(inst.id) module.exit_json(changed=changed, ids=ids, instances=get_instances_info(ecs, ids)) except Exception as e: module.fail_json( msg='Stop instances got an error: {0}'.format(e)) elif state == 'restarted': try: for inst in instances: if inst.reboot(force=module.params['force']): changed = True ids.append(inst.id) module.exit_json(changed=changed, ids=ids, instances=get_instances_info(ecs, ids)) except Exception as e: module.fail_json( msg='Reboot instances got an error: {0}'.format(e)) else: try: for inst in instances: if inst.status != 'stopped' and not force: module.fail_json( msg= "Instance is running, and please stop it or set 'force' as True." ) if inst.terminate(force=module.params['force']): changed = True module.exit_json(changed=changed, ids=[], instances=[]) except Exception as e: module.fail_json( msg='Delete instance got an error: {0}'.format(e))
def main(): argument_spec = ecs_argument_spec() argument_spec.update( dict(state=dict(default="present", choices=["present", "absent"]), db_instance_id=dict(type='str', aliases=['instance_id'], required=True), db_name=dict(type='str', aliases=['name'], required=True), character_set_name=dict(type='str', aliases=['character']), db_description=dict(type='str', aliases=['description']), target_db_instance_id=dict(type='str', aliases=['target_instance_id']), target_db_name=dict(type='str'), backup_id=dict(type='str'), restore_time=dict(type='str'), sync_user_privilege=dict(type='bool', default=False))) modules = AnsibleModule(argument_spec=argument_spec) if HAS_FOOTMARK is False: modules.fail_json(msg="Package 'footmark' required for this module") rds = rds_connect(modules) state = modules.params['state'] db_description = modules.params['db_description'] target_db_instance_id = modules.params['target_db_instance_id'] target_db_name = modules.params['target_db_name'] db_name = modules.params['db_name'] sync_user_privilege = modules.params['sync_user_privilege'] modules.params['sync_user_privilege'] = 'NO' if sync_user_privilege: modules.params['sync_user_privilege'] = 'YES' db = '' try: db = database_exists(modules, rds) except Exception as e: modules.fail_json( msg=str("Unable to describe database, error:{0}".format(e))) if state == 'absent': if not db: modules.exit_json(changed=False, database={}) try: db.delete() modules.exit_json(changed=True, database={}) except Exception as e: modules.fail_json( msg=str("Unable to delete database error: {0}".format(e))) if not db: try: modules.params['client_token'] = "Ansible-Alicloud-%s-%s" % (hash( str(modules.params)), str(time.time())) db = rds.create_database(**modules.params) modules.exit_json(changed=True, database=db.read()) except Exception as e: modules.fail_json( msg=str("Unable to create database error: {0}".format(e))) if db_description: try: res = db.modify_db_description(description=db_description) modules.exit_json(changed=res, database=db.read()) except Exception as e: modules.fail_json(msg=str( "Unable to modify db description error: {0}".format(e))) if target_db_instance_id and target_db_name: try: modules.params['db_names'] = str({db_name: target_db_name}) res = db.copy_database_between_instances(**modules.params) modules.exit_json(changed=res, database=db.read()) except Exception as e: modules.fail_json( msg=str("Unable to copy db instance id error: {0}".format(e)))