In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/02 Report--
How does OpenAPI code flexibly create and manage ECS? I believe that many inexperienced people are at a loss about this, so this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
Create ECS instances flexibly
Pay attention to the following API when creating an ECS:
Create an ECS instance
Query the list of instances
Start the ECS instance
Assign public network IP address
prerequisite
To launch pay-per-view products, your account balance should not be less than RMB100. for more information, please see the instructions for ECS. You need to make sure your balance is sufficient at Aliyun's expense center.
Create a by-quantity CVM
Required attributes when creating a CVM:
SecurityGroupId: security group ID. The security group implements the configuration of a group of instances through firewall rules to protect the network access requests of the instances. When setting security group access rules, it is recommended to open them as needed instead of opening all access rules by default. You can also create security groups through the ECS console.
InstanceType: instance specification. Refer to the option of selling ECS page, and the input of 1 core 2GB n1.small on the interface is ecs.n1.small.
ImageId: image ID. Refer to the list of images in the ECS console, you can filter system public images or custom images.
For more parameter settings, please see creating an ECS instance.
Create a CVM
As shown in the following code, create a classic network ECS, use the system disk ssd, the disk parameter is cloud_ssd, and select io to optimize the instance optimized.
# create one after pay ecs instance.def create_after_pay_instance (image_id, instance_type, security_group_id): request = CreateInstanceRequest () Request.set_ImageId (image_id) request.set_SecurityGroupId (security_group_id) request.set_InstanceType (instance_type) request.set_IoOptimized ('optimized') request.set_SystemDiskCategory (' cloud_ssd') response = _ send_request (request) instance_id = response.get ('InstanceId') logging.info ("instance% s created task submit successfully.", instance_id) return instance_id
After the creation is successful, the corresponding instance ID will be returned. If it fails, there will also be a corresponding ErrorCode. Due to the large number of parameters, you can make adjustments by referring to the sales page of ECS.
{"InstanceId": "iMurray" * "," RequestId ":" 006C1303-BAC5-48E5-BCDF-7FD5C2E6395D "}
CVM lifecycle
For the status operation of the CVM, please refer to the CVM instance lifecycle.
Only instances in Stopped state can perform Start operations. Only ECS in Running state can perform Stop operations. You can query the status of a CVM by querying the list of instances and passing it to InstanceId for filtering. When you DescribeInstancesRequest, you can query the status of this resource by passing in a String in the format of a JSON array. It is recommended that you use DescribeInstances instead of DescribeInstanceAttribute to query the status of a single instance, because the former returns more properties and content than the latter.
The following code checks the status of the instance and returns the details of the instance only if the status of the instance matches the input parameters.
# output the instance owned in current region.def get_instance_detail_by_id (instance_id, status='Stopped'): logging.info ("Check instance% s status is% s", instance_id Status) request = DescribeInstancesRequest () request.set_InstanceIds (json.dumps ([instance_id])) response = _ send_request (request) instance_detail = None if response is not None: instance_list = response.get ('Instances'). Get (' Instance') for item in instance_list: if item.get ('Status') = status: instance_detail = item break Return instance_detail
Start the CVM
The default state of ECS after successful creation is Stopped. If you want to start the ECS instance in the Running state, you only need to send the startup instruction.
Def start_instance (instance_id): request = StartInstanceRequest () request.set_InstanceId (instance_id) _ send_request (request)
Stop the CVM
You only need to input instanceId to stop the CVM.
Def stop_instance (instance_id): request = StopInstanceRequest () request.set_InstanceId (instance_id) _ send_request (request)
Start "Auto start CVM" when you create it
Starting and stopping the server is an asynchronous operation, which can be performed when the script is created and the status of the CVM is detected at the same time.
To get the instance ID after creating the resource, first determine whether the instance is in the state of Stopped. If it is in the state of Stopped, issue the instruction of the Start server, and then wait for the status of the server to become Running.
Def check_instance_running (instance_id): detail = get_instance_detail_by_id (instance_id=instance_id, status=INSTANCE_RUNNING) index = 0 while detail is None and index < 60: detail = get_instance_detail_by_id (instance_id=instance_id); time.sleep (10) if detail and detail.get ('Status') = =' Stopped': logging.info ("instance% s is stopped now.") Start_instance (instance_id=instance_id) logging.info ("start instance% s job submit.") Detail = get_instance_detail_by_id (instance_id=instance_id, status=INSTANCE_RUNNING) while detail is None and index < 60: detail = get_instance_detail_by_id (instance_id=instance_id, status=INSTANCE_RUNNING); time.sleep (10) logging.info ("instance% s is running now.", instance_id) return instance_id
Assign public network IP
If you specify the public network bandwidth in the process of creating a CVM, you need to call API to allocate the public network IP if you need access to the public network. For more information, please see: assign a public network IP address.
Resource creation with annual or monthly plan
In addition to creating CVMs with postpaid service, your API also supports the creation of prepaid servers. The process of creating an annual or monthly plan is different from that of the official website, which uses the automatic deduction mode, which means that you need to make sure that the account has sufficient balance or credit line before creating the server, and the fee will be deducted directly when you create it.
Compared with pay-by-usage ECS, you only need to specify the payment type and duration, which is 1 month.
Request.set_Period (1) request.set_InstanceChargeType ('PrePaid')
The overall code for creating a prepaid instance is as follows:
# create one prepay ecs instance.def create_prepay_instance (image_id, instance_type, security_group_id): request = CreateInstanceRequest () Request.set_ImageId (image_id) request.set_SecurityGroupId (security_group_id) request.set_InstanceType (instance_type) request.set_IoOptimized ('optimized') request.set_SystemDiskCategory (' cloud_ssd') request.set_Period (1) request.set_InstanceChargeType ('PrePaid') response = _ send_request (request) instance_id = response.get (' InstanceId') logging.info ("instance% s created task submit successfully." Instance_id) return instance_id
Complete code
The complete code is as follows, which you can set according to your own resource parameters.
# coding=utf-8# if the python sdk is not install using 'sudo pip install aliyun-python-sdk-ecs'# if the python sdk is install using' sudo pip install-- upgrade aliyun-python-sdk-ecs'# make sure the sdk version is 2.1.2, you can use command 'pip show aliyun-python-sdk-ecs' to checkimport jsonimport loggingimport timefrom aliyunsdkcore import clientfrom aliyunsdkecs.request.v20140526.CreateInstanceRequest import CreateInstanceRequestfrom aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequestfrom aliyunsdkecs.request.v20140526.StartInstanceRequest import StartInstanceRequest# configuration the log output formatter, if you want to save the output to file # append ", filename='ecs_invoke.log'" after datefmt.logging.basicConfig (level=logging.INFO, format='% (asctime) s% (filename) s [line:% (lineno) d]% (levelname) s% (message) slots, datefmt='%a,% d% b% Y% HRV% MRV% S') clt = client.AcsClient ('Your Access Key Id',' Your Access Key Secrect' 'cn-beijing') IMAGE_ID =' ubuntu1404_64_40G_cloudinit_20160727.raw'INSTANCE_TYPE = 'ecs.s2.large' # 2c4g generation 1SECURITY_GROUP_ID =' sg-****'INSTANCE_RUNNING = 'Running'def create_instance_action (): instance_id = create_after_pay_instance (image_id=IMAGE_ID, instance_type=INSTANCE_TYPE) Security_group_id=SECURITY_GROUP_ID) check_instance_running (instance_id=instance_id) def create_prepay_instance_action (): instance_id= create_prepay_instance (image_id=IMAGE_ID, instance_type=INSTANCE_TYPE) Security_group_id=SECURITY_GROUP_ID) check_instance_running (instance_id=instance_id) # create one after pay ecs instance.def create_after_pay_instance (image_id, instance_type, security_group_id): request = CreateInstanceRequest () Request.set_ImageId (image_id) request.set_SecurityGroupId (security_group_id) request.set_InstanceType (instance_type) request.set_IoOptimized ('optimized') request.set_SystemDiskCategory (' cloud_ssd') response = _ send_request (request) instance_id = response.get ('InstanceId') logging.info ("instance% s created task submit successfully.", instance_id) return instance_id # create one prepay ecs instance.def create_prepay_instance (image_id, instance_type, security_group_id): request = CreateInstanceRequest () Request.set_ImageId (image_id) request.set_SecurityGroupId (security_group_id) request.set_InstanceType (instance_type) request.set_IoOptimized ('optimized') request.set_SystemDiskCategory (' cloud_ssd') request.set_Period (1) request.set_InstanceChargeType ('PrePaid') response = _ send_request (request) instance_id = response.get (' InstanceId') logging.info ("instance% s created task submit successfully." Instance_id) return instance_id Def check_instance_running (instance_id): detail = get_instance_detail_by_id (instance_id=instance_id, status=INSTANCE_RUNNING) index = 0 while detail is None and index < 60: detail = get_instance_detail_by_id (instance_id=instance_id); time.sleep (10) if detail and detail.get ('Status') = =' Stopped': logging.info ("instance% s is stopped now.") Start_instance (instance_id=instance_id) logging.info ("start instance% s job submit.") Detail = get_instance_detail_by_id (instance_id=instance_id, status=INSTANCE_RUNNING) while detail is None and index < 60: detail = get_instance_detail_by_id (instance_id=instance_id, status=INSTANCE_RUNNING); time.sleep (10) logging.info ("instance% s is running now.", instance_id) return instance_id Def start_instance (instance_id): request = StartInstanceRequest () request.set_InstanceId (instance_id) _ send_request (request) # output the instance owned in current region.def get_instance_detail_by_id (instance_id, status='Stopped'): logging.info ("Check instance% s status is% s", instance_id Status) request = DescribeInstancesRequest () request.set_InstanceIds (json.dumps ([instance_id])) response = _ send_request (request) instance_detail = None if response is not None: instance_list = response.get ('Instances'). Get (' Instance') for item in instance_list: if item.get ('Status') = status: instance_detail = item break Return instance_detail # send open api requestdef _ send_request (request): request.set_accept_format ('json') try: response_str = clt.do_action (request) logging.info (response_str) response_detail = json.loads (response_str) return response_detail except Exception as e: logging.error (e) if _ _ name__ = =' _ main__': logging.info ("Create ECS by OpenApi!") Create_instance_action () # create_prepay_instance_action () after reading the above, have you learned how OpenAPI code flexibly creates and manages ECS? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.