### Install SDK from source Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/README.md Manual installation steps for building the SDK from the GitHub repository. ```bash git clone git://github.com/aliyun/alibabacloud-python-sdk-v2.git cd alibabacloud-python-sdk-v2 python setup.py install ``` -------------------------------- ### Install Alibaba Cloud Python SDK 2.0 Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Commands to install the SDK via PyPI or from the source repository. ```bash # Install from PyPI pip install alibaba-cloud-python-sdk-v2 # Install from source git clone git://github.com/aliyun/alibabacloud-python-sdk-v2.git cd alibabacloud-python-sdk-v2 python setup.py install ``` -------------------------------- ### Install SDK via pip Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/README.md Standard installation method using the Python package manager. ```bash pip install alibaba-cloud-python-sdk-v2 ``` -------------------------------- ### Manage ECS instance lifecycle Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/README.md Demonstrates creating, starting, and stopping an ECS instance. ```python from alibabacloud.services.ecs import ECSInstanceResource # Assume you already have a ECS resource name 'ecs' instance = ecs.create_instance( ImageId="coreos_1745_7_0_64_30G_alibase_20180705.vhd", InstanceType="ecs.n2.small", ) print(instance.instance_id) instance.start() instance.wait_until(ECSInstanceResource.STATUS_RUNNING) instance.stop() instance.wait_until(ECSInstanceResource.STATUS_STOPPED) ``` -------------------------------- ### Configure Credentials via INI File Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Examples of defining credentials in the ~/.alibabacloud/credentials.ini file for different authentication types. ```ini [default] type = access_key access_key_id = YOUR_ACCESS_KEY_ID access_key_secret = YOUR_ACCESS_KEY_SECRET ``` ```ini [default] type = ram_role_arn access_key_id = YOUR_ACCESS_KEY_ID access_key_secret = YOUR_ACCESS_KEY_SECRET role_arn = acs:ram::123456789:role/your-role role_session_name = your-session-name ``` ```ini [default] type = ecs_ram_role role_name = your-ecs-role-name ``` -------------------------------- ### Get and Operate ECS Instance Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/README.md Retrieve an ECS instance by its ID and perform actions like starting or stopping it. Requires specifying the resource type and resource ID. ```python import alibabacloud instance = alibabacloud.get_resource('ecs.instance', resource_id='Your Instance ID') instance.start() instance.stop() ``` -------------------------------- ### Get VPC Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific VPC resource by its ID and region. The 'vpc.vpc' resource type is used for VPC management. ```python vpc_resource = alibabacloud.get_resource('vpc.vpc', 'vpc-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get ECS Instance Full Status with Events Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieves the full status and system events for specified ECS instances. Ensure the ECS client is initialized. ```python for status in ecs.instance_full_statuses.filter(list_of_instance_id=['i-bp1234567890abcdef']): print(f"Instance health status: {status.health_status}") for event in status.system_events: print(f" Event: {event.event_id} - {event.get_event_type()})") ``` -------------------------------- ### Get ECS Disk Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific ECS disk by its ID and region. Use the 'ecs.disk' resource type for disk operations. ```python disk = alibabacloud.get_resource('ecs.disk', 'd-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get ECS Image Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific ECS image by its ID and region. The 'ecs.image' resource type is used for image management. ```python image = alibabacloud.get_resource('ecs.image', 'm-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get RAM Policy Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific RAM policy by its ID and region. The 'ram.policy' resource type is used for RAM policy management. ```python policy = alibabacloud.get_resource('ram.policy', 'policy-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get RAM Role Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific RAM role by its ID and region. Use the 'ram.role' resource type for RAM role management. ```python role = alibabacloud.get_resource('ram.role', 'role-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get ECS Instance Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific ECS instance by its ID and region. Ensure the 'ecs.instance' resource type and the correct instance ID are provided. ```python instance = alibabacloud.get_resource('ecs.instance', 'i-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get RAM Group Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific RAM group by its ID and region. Use the 'ram.group' resource type for RAM group management. ```python group = alibabacloud.get_resource('ram.group', 'group-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get RDS Account Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific RDS account by its ID and region. Use the 'rds.account' resource type for RDS account management. ```python account = alibabacloud.get_resource('rds.account', 'account-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get RDS Backup Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific RDS backup by its ID and region. The 'rds.backup' resource type is used for RDS backup management. ```python backup = alibabacloud.get_resource('rds.backup', 'backup-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get ECS Snapshot Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific ECS snapshot by its ID and region. The 'ecs.snapshot' resource type is used for snapshot operations. ```python snapshot = alibabacloud.get_resource('ecs.snapshot', 's-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get VPC VSwitch Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific VPC vSwitch by its ID and region. Use the 'vpc.vswitch' resource type for vSwitch management within VPC. ```python vswitch_resource = alibabacloud.get_resource('vpc.vswitch', 'vsw-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get RAM User Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific RAM user by its ID and region. The 'ram.user' resource type is used for RAM user management. ```python user = alibabacloud.get_resource('ram.user', 'user-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get CDN Domain Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific CDN domain by its ID and region. The 'cdn.cdn_domain' resource type is used for CDN domain management. ```python cdn_domain = alibabacloud.get_resource('cdn.cdn_domain', 'domain-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get ECS VSwitch Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific ECS vSwitch by its ID and region. Use the 'ecs.vswitch' resource type for vSwitch management within ECS. ```python vswitch = alibabacloud.get_resource('ecs.vswitch', 'vsw-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get ECS Client with Explicit Region and Endpoint Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/docs/source/higher/04_client.rst Use the get_client interface to explicitly pass region_id and endpoint for the ECS client. These parameters take precedence over other configuration methods. ```python from alibabacloud import get_client ecs_client = get_client('ecs', access_key_id=access_key_id, access_key_secret=access_key_secret, region_id='cn-hangzhou', endpoint='ecs-cn-hangzhou.aliyuncs.com') response = ecs_client.describe_tags(page_size=100) ret = response.get('Tags') print(ret) ``` -------------------------------- ### Get SLB Server Certificate Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific SLB server certificate by its ID and region. Use the 'slb.server_certificate' resource type for SLB server certificate management. ```python server_certificate = alibabacloud.get_resource('slb.server_certificate', 'cert-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get ECS Client with ClientConfig Object Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/docs/source/higher/04_client.rst Pass an explicit ClientConfig object to the get_client interface to configure region_id and endpoint. This method also allows for detailed client configuration. ```python from alibabacloud import get_client, ClientConfig client_config = ClientConfig(region_id='cn-hangzhou', endpoint='ecs-cn-hangzhou.aliyuncs.com') ecs_client = get_client('ecs', access_key_id=access_key_id, access_key_secret=access_key_secret, config=client_config) response = ecs_client.describe_tags(page_size=100) ret = response.get('Tags') print(ret) ``` -------------------------------- ### Get ECS VPC Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific ECS VPC by its ID and region. The 'ecs.vpc' resource type is used for VPC management within ECS. ```python vpc = alibabacloud.get_resource('ecs.vpc', 'vpc-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get Specific SLB Load Balancer Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieves details for a specific Server Load Balancer instance using its ID. The client must be initialized for SLB and the specific load balancer resource. ```python lb = alibabacloud.get_resource( 'slb.load_balancer', resource_id='lb-bp1234567890abcdef', region_id='cn-hangzhou', access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET' ) lb.refresh() print(f"Load Balancer: {lb.load_balancer_name}") print(f"Network Type: {lb.network_type}") ``` -------------------------------- ### Get ECS Key Pair Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific ECS key pair by its ID and region. Use the 'ecs.key_pair' resource type for key pair management. ```python key_pair = alibabacloud.get_resource('ecs.key_pair', 'kp-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get RDS DB Instance Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific RDS DB instance by its ID and region. The 'rds.db_instance' resource type is used for RDS database instance management. ```python db_instance = alibabacloud.get_resource('rds.db_instance', 'rm-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get SLB Load Balancer Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific SLB load balancer by its ID and region. Use the 'slb.load_balancer' resource type for SLB load balancer management. ```python load_balancer = alibabacloud.get_resource('slb.load_balancer', 'lb-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Iterate and Operate ECS Instances using Collections Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/README.md Utilize collections to iterate through all ECS instances in a specified region, printing their details and performing actions like start, stop, or delete. You can also limit the number of instances processed. ```python import alibabacloud ecs = alibabacloud.get_resource('ecs', region_id="Your Region ID") # Iterate all instances for instance in ecs.instances.all(): print(instance.instance_id) print(instance.instance_type) print(instance.status) instance.start() instance.stop() instance.delete() # Limit instance number to 200: for instance in ecs.instances.limit(200): pass ``` -------------------------------- ### Get Specific VPC EIP Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieves details for a specific Elastic IP address using its allocation ID. The client must be initialized for VPC and the specific EIP resource. ```python eip = alibabacloud.get_resource( 'vpc.eip_address', resource_id='eip-bp1234567890abcdef', region_id='cn-hangzhou', access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET' ) eip.refresh() print(f"EIP: {eip.ip_address}") print(f"Instance ID: {eip.instance_id}") ``` -------------------------------- ### Get ECS Security Group Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific ECS security group by its ID and region. Use the 'ecs.security_group' resource type for security group management. ```python security_group = alibabacloud.get_resource('ecs.security_group', 'sg-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get SLB VServer Group Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific SLB vserver group by its ID and region. The 'slb.vserver_group' resource type is used for SLB vserver group management. ```python vserver_group = alibabacloud.get_resource('slb.vserver_group', 'rsp-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get VPC VPN Gateway Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific VPC VPN gateway by its ID and region. Use the 'vpc.vpn_gateway' resource type for VPN gateway management within VPC. ```python vpn_gateway = alibabacloud.get_resource('vpc.vpn_gateway', 'vpn-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get ECS NAT Gateway Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific ECS NAT gateway by its ID and region. Use the 'ecs.nat_gateway' resource type for NAT gateway management within ECS. ```python nat_gateway = alibabacloud.get_resource('ecs.nat_gateway', 'ngw-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get VPC EIP Address Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific VPC Elastic IP (EIP) address by its ID and region. The 'vpc.eip_address' resource type is used for EIP management within VPC. ```python eip_address = alibabacloud.get_resource('vpc.eip_address', 'eip-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Get ECS EIP Address Resource Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieve a specific ECS Elastic IP (EIP) address by its ID and region. The 'ecs.eip_address' resource type is used for EIP management within ECS. ```python eip = alibabacloud.get_resource('ecs.eip_address', 'eip-xxx', region_id='cn-hangzhou') ``` -------------------------------- ### Initialize multiple service resources Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/README.md Obtain service-level resource interfaces for various Alibaba Cloud services. ```python import alibabacloud ecs = alibabacloud.get_resource('ecs') rds = alibabacloud.get_resource('rds') slb = alibabacloud.get_resource('slb') vpc = alibabacloud.get_resource('vpc') cdn = alibabacloud.get_resource('cdn') ram = alibabacloud.get_resource('ram') ``` -------------------------------- ### Initialize ClientConfig for Credentials Providers Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Sets up a basic ClientConfig object, primarily specifying the region, which is often required when initializing various credential providers. ```python import alibabacloud from alibabacloud.credentials import AccessKeyCredentials, SecurityCredentials from alibabacloud.credentials.provider import ( StaticCredentialsProvider, RamRoleCredentialsProvider, InstanceProfileCredentialsProvider, EnvCredentialsProvider, ProfileCredentialsProvider ) from alibabacloud.client import ClientConfig config = ClientConfig(region_id='cn-hangzhou') ``` -------------------------------- ### Obtain Low-Level API Clients with alibabacloud.get_client() Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieving a client for direct API calls with full parameter control. ```python import alibabacloud # Get ECS client ecs_client = alibabacloud.get_client( 'ecs', region_id='cn-hangzhou', access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET' ) # Make direct API calls response = ecs_client.describe_instances( page_number=1, page_size=10 ) print(response) # Specify API version explicitly ecs_client = alibabacloud.get_client( 'ecs', api_version='2014-05-26', region_id='cn-hangzhou' ) ``` -------------------------------- ### Configure Credentials via Environment Variables Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Setting authentication credentials using shell environment variables. ```bash export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret ``` -------------------------------- ### Launch Multiple ECS Instances Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Use the run_instances method to provision multiple instances with specific configurations and tags. ```python import alibabacloud ecs = alibabacloud.get_resource( 'ecs', region_id='cn-hangzhou', access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET' ) # Run multiple instances at once instances = ecs.run_instances( ImageId='centos_7_9_x64_20G_alibase_20210623.vhd', InstanceType='ecs.g6.large', SecurityGroupId='sg-bp1234567890abcdef', VSwitchId='vsw-bp1234567890abcdef', Amount=3, InstanceName='batch-instance', list_of_tag=[ {'Key': 'BatchId', 'Value': 'batch-001'} ], list_of_data_disk=[ {'Size': 100, 'Category': 'cloud_essd'}, {'Size': 200, 'Category': 'cloud_essd'} ] ) # Process created instances for instance in instances: print(f"Created instance: {instance.instance_id}") instance.wait_until_running() ``` -------------------------------- ### Configure Profile File Credentials Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Load credentials from a profile file (e.g., ~/.aliyun/credentials) using ProfileCredentialsProvider. Specify the profile name if not using 'default'. ```python profile_provider = ProfileCredentialsProvider(config, profile_name='default') ``` -------------------------------- ### Import Alibaba Cloud SDK Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Import the Alibaba Cloud SDK library to access its functionalities. ```python import alibabacloud ``` -------------------------------- ### List All RAM Policies Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieves and prints the names and types of all RAM policies in your account. Requires an initialized RAM client. ```python for policy in ram.policies.all(): print(f"Policy: {policy.policy_name}") print(f"Type: {policy.policy_type}") ``` -------------------------------- ### Configure Static Access Key Credentials Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Use static access key credentials for direct authentication. Ensure your access key ID and secret are kept secure. ```python credentials = AccessKeyCredentials( access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET' ) provider = StaticCredentialsProvider(credentials) ecs = alibabacloud.get_resource( 'ecs', config=config, credentials_provider=provider ) ``` -------------------------------- ### Configure AccessKey Credentials Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/docs/source/advance/credentials/03_file.rst Use this configuration for standard AccessKey authentication. It is recommended to use a sub-account for security. ```ini [default] type = access_key access_key_id = YOUR_ACCESS_KEY_ID access_key_secret = YOUR_ACCESS_KEY_SECRET ``` -------------------------------- ### List All SLB Load Balancers Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieves and prints details for all Server Load Balancer instances in a specified region. Requires an initialized SLB client. ```python import alibabacloud slb = alibabacloud.get_resource( 'slb', region_id='cn-hangzhou', access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET' ) for lb in slb.load_balancers.all(): print(f"Load Balancer ID: {lb.load_balancer_id}") print(f"Name: {lb.load_balancer_name}") print(f"Status: {lb.load_balancer_status}") print(f"Address: {lb.address}") ``` -------------------------------- ### List All RAM Roles Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieves and prints the names and ARNs of all RAM roles in your account. Requires an initialized RAM client. ```python for role in ram.roles.all(): print(f"Role: {role.role_name}") print(f"ARN: {role.arn}") ``` -------------------------------- ### Configure Environment Variable Credentials Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt The EnvCredentialsProvider automatically loads credentials from environment variables (e.g., ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET). ```python env_provider = EnvCredentialsProvider() ``` -------------------------------- ### Enable File Logging Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Configure file logging to save SDK logs to a specified file. You can set the log level, file path, maximum file size, and backup count. ```python # Enable file logging ecs = alibabacloud.get_resource( 'ecs', region_id='cn-hangzhou', access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET', enable_file_logger=True, file_logger_path='alibabacloud.log', file_log_level=logging.INFO, file_max_bytes=10485760, # 10MB file_backup_count=5 ) ``` -------------------------------- ### Manage ECS Instance Lifecycle Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Creating and controlling ECS instances, including waiting for status changes. ```python import alibabacloud from alibabacloud.services.ecs import ECSInstanceResource # Initialize ECS resource ecs = alibabacloud.get_resource( 'ecs', region_id='cn-hangzhou', access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET' ) # Create a new ECS instance instance = ecs.create_instance( ImageId='centos_7_9_x64_20G_alibase_20210623.vhd', InstanceType='ecs.g6.large', SecurityGroupId='sg-bp1234567890abcdef', VSwitchId='vsw-bp1234567890abcdef', InstanceName='my-instance', list_of_tag=[ {'Key': 'Environment', 'Value': 'Production'}, {'Key': 'Project', 'Value': 'WebApp'} ] ) print(f"Created instance: {instance.instance_id}") # Start the instance and wait until running instance.start() instance.wait_until(ECSInstanceResource.STATUS_RUNNING) print("Instance is now running") # Stop the instance and wait until stopped instance.stop() instance.wait_until(ECSInstanceResource.STATUS_STOPPED) print("Instance is now stopped") # Use convenience methods instance.wait_until_running() instance.wait_until_stopped() ``` -------------------------------- ### Configure Alibaba Cloud Client with ClientConfig Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Creates a custom client configuration object to set retry, timeout, proxy, and HTTPS settings. This config can then be used when initializing clients. ```python import alibabacloud from alibabacloud.client import ClientConfig config = ClientConfig( region_id='cn-hangzhou', enable_retry=True, max_retry_times=5, enable_https=True, http_port=80, https_port=443, connection_timeout=10, # seconds read_timeout=30, # seconds http_proxy='http://proxy.example.com:8080', https_proxy='https://proxy.example.com:8080', user_agent='MyApp/1.0' ) ecs = alibabacloud.get_resource( 'ecs', config=config, access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET' ) client = alibabacloud.get_client( 'ecs', config=config, access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET' ) ``` -------------------------------- ### Obtain Resource Interfaces with alibabacloud.get_resource() Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Methods for retrieving service-level or entity-level resource interfaces to interact with Alibaba Cloud services. ```python import alibabacloud # Get service-level resource with credentials from file ecs = alibabacloud.get_resource('ecs', region_id='cn-hangzhou') # Get service-level resource with explicit credentials ecs = alibabacloud.get_resource( 'ecs', region_id='cn-hangzhou', access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET' ) # Get other service resources rds = alibabacloud.get_resource('rds', region_id='cn-hangzhou') slb = alibabacloud.get_resource('slb', region_id='cn-hangzhou') vpc = alibabacloud.get_resource('vpc', region_id='cn-hangzhou') cdn = alibabacloud.get_resource('cdn', region_id='cn-hangzhou') ram = alibabacloud.get_resource('ram', region_id='cn-hangzhou') # Get entity-level resource for specific instance instance = alibabacloud.get_resource( 'ecs.instance', resource_id='i-bp1234567890abcdef', region_id='cn-hangzhou' ) # Control the instance directly instance.start() instance.stop() instance.reboot() ``` -------------------------------- ### Create Simulated ECS System Events Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Creates simulated system events for testing purposes, such as maintenance reboots. Requires an initialized ECS client. ```python events = ecs.create_simulated_system_events( list_of_instance_id=['i-bp1234567890abcdef'], EventType='SystemMaintenance.Reboot', NotBefore='2024-01-01T00:00:00Z' ) for event in events: print(f"Created simulated event: {event.event_id}") ``` -------------------------------- ### Enable Console Logging Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Enable console logging to display SDK logs in the console. Set the log level to DEBUG for detailed output. ```python import logging import alibabacloud # Enable console logging ecs = alibabacloud.get_resource( 'ecs', region_id='cn-hangzhou', access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET', enable_stream_logger=True, stream_log_level=logging.DEBUG ) ``` -------------------------------- ### Initialize ECS resource Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/README.md Methods for initializing the ECS resource client using either file-based or direct credentials. ```python import alibabacloud ecs = alibabacloud.get_resource('ecs', region_id="Your Region ID") ``` ```python import alibabacloud ecs = alibabacloud.get_resource( 'ecs', region_id="Your Region ID", access_key_id="Your Access Key ID", access_key_secret="Your Access Key Secret") ``` -------------------------------- ### Enable Both Console and File Logging Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Simultaneously enable both console and file logging for comprehensive monitoring. Configure distinct log levels for each. ```python # Enable both console and file logging ecs = alibabacloud.get_resource( 'ecs', region_id='cn-hangzhou', access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET', enable_stream_logger=True, stream_log_level=logging.DEBUG, enable_file_logger=True, file_logger_path='alibabacloud.log', file_log_level=logging.INFO ) ``` -------------------------------- ### List All RAM Groups Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieves and prints the names of all RAM user groups in your account. Requires an initialized RAM client. ```python for group in ram.groups.all(): print(f"Group: {group.group_name}") ``` -------------------------------- ### Handle SDK Exceptions Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Implement try-except blocks to catch and handle various Alibaba Cloud SDK exceptions, such as ClientException and ServerException, for robust error management. ```python import alibabacloud from alibabacloud.exceptions import ( ClientException, ServerException, ServiceNameInvalidException, ApiVersionInvalidException, NoCredentialsException, NoRegionException, InvalidRegionIDException, NoSuchEndpointException ) try: ecs = alibabacloud.get_resource( 'ecs', region_id='cn-hangzhou', access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET' ) instance = ecs.create_instance( ImageId='centos_7_9_x64_20G_alibase_20210623.vhd', InstanceType='ecs.g6.large', SecurityGroupId='sg-bp1234567890abcdef', VSwitchId='vsw-bp1234567890abcdef' ) except ServiceNameInvalidException as e: print(f"Invalid service name: {e.error_message}") except ApiVersionInvalidException as e: print(f"Invalid API version: {e.error_message}") except NoCredentialsException as e: print(f"Credentials not found: {e.error_message}") except NoRegionException as e: print(f"Region not specified: {e.error_message}") except InvalidRegionIDException as e: print(f"Invalid region ID: {e.error_message}") except NoSuchEndpointException as e: print(f"No endpoint available: {e.error_message}") except ServerException as e: print(f"Server error: {e.error_code} - {e.error_message}") print(f"Request ID: {e.request_id}") print(f"HTTP Status: {e.http_status}") except ClientException as e: print(f"Client error: {e.error_message}") ``` -------------------------------- ### Configure RAM Role Credentials (AssumeRole) Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Employ RAM (Resource Access Management) roles for assuming temporary credentials. This allows granting specific permissions to applications without exposing long-term access keys. ```python role_provider = RamRoleCredentialsProvider( client_config=config, access_key_credentials=credentials, role_arn='acs:ram::123456789:role/your-role', role_session_name='session-name' ) ecs = alibabacloud.get_resource( 'ecs', config=config, credentials_provider=role_provider ) ``` -------------------------------- ### List All RAM Users Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieves and prints the names and IDs of all RAM users in your account. Requires an initialized RAM client. ```python import alibabacloud ram = alibabacloud.get_resource( 'ram', region_id='cn-hangzhou', access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET' ) for user in ram.users.all(): print(f"User: {user.user_name}") print(f"User ID: {user.user_id}") ``` -------------------------------- ### Configure RAM Role ARN Credentials Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/docs/source/advance/credentials/03_file.rst Use this configuration for RAM sub-account role-based authentication. ```ini [default] type = ram_role_arn access_key_id = YOUR_ACCESS_KEY_ID access_key_secret = YOUR_ACCESS_KEY_SECRET role_arn = YOUR_ROLE_ARN role_session_name = YOUR_ROLE_SESSION_NAME ``` -------------------------------- ### Filter VPC EIP Addresses by Status Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Lists Elastic IP addresses that are currently in an 'Available' state. Requires an initialized VPC client. ```python for eip in vpc.eip_addresses.filter(Status='Available'): print(f"Available EIP: {eip.ip_address}") ``` -------------------------------- ### Configure BearerToken Credentials Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/docs/source/advance/credentials/03_file.rst Use this configuration specifically for the Cloud Call Center (CCC) product. Exercise caution as support is limited. ```ini [default] type = bearer_token bearer_token = YOUR BEAR TOKEN ``` -------------------------------- ### Filter SLB Load Balancers by Status Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Lists Server Load Balancer instances that are currently in an 'active' state. Requires an initialized SLB client. ```python for lb in slb.load_balancers.filter(LoadBalancerStatus='active'): print(f"Active LB: {lb.load_balancer_id}") ``` -------------------------------- ### List All VPC EIP Addresses Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Retrieves and prints details for all Elastic IP addresses within a specified VPC region. Requires an initialized VPC client. ```python import alibabacloud vpc = alibabacloud.get_resource( 'vpc', region_id='cn-hangzhou', access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET' ) for eip in vpc.eip_addresses.all(): print(f"EIP ID: {eip.allocation_id}") print(f"IP Address: {eip.ip_address}") print(f"Status: {eip.status}") print(f"Bandwidth: {eip.bandwidth} Mbps") ``` -------------------------------- ### Configure ECS Instance Profile Credentials Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt For applications running on ECS instances with an assigned RAM role, use InstanceProfileCredentialsProvider to automatically fetch temporary credentials. ```python instance_provider = InstanceProfileCredentialsProvider(role_name='ecs-role-name') ecs = alibabacloud.get_resource( 'ecs', config=config, credentials_provider=instance_provider ) ``` -------------------------------- ### List available RAM collections Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/README.md Access these collections through the ram object to manage RAM resources. ```text ram.groups ram.policies ram.roles ram.users ``` -------------------------------- ### Filter and paginate ECS instances Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/README.md Filter instances by status and apply pagination limits. ```python # Assume you already have a ECS resource name 'ecs' for instance in ecs.instances.filter(Status='Running').page_size(100).limit(200): print(instance.instance_id) print(instance.instance_type) print(instance.status) ``` -------------------------------- ### List available VPC collections Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/README.md Access these collections through the vpc object to manage VPC resources. ```text vpc.access_points vpc.bandwidth_packages vpc.bgp_groups vpc.bgp_peers vpc.eip_addresses vpc.flow_logs vpc.global_acceleration_instances vpc.ha_vips vpc.ipv6_translators vpc.ipv6_translator_acl_lists vpc.ipv6_translator_entries vpc.ipv6_addresses vpc.ipv6_egress_only_rules vpc.network_acls vpc.physical_connections vpc.regions vpc.route_tables vpc.router_interfaces vpc.ssl_vpn_client_certs vpc.ssl_vpn_servers vpc.vrouters vpc.vswitches vpc.virtual_border_routers vpc.vpcs vpc.vpn_connections vpc.vpn_pbr_route_entries vpc.zones ``` -------------------------------- ### Configure STS Token Credentials Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/docs/source/advance/credentials/03_file.rst Use this configuration for temporary security token service authentication. ```ini [default] type = sts_token type = ram_role_arn access_key_id = YOUR_ACCESS_KEY_ID access_key_secret = YOUR_ACCESS_KEY_SECRET user_name = YOUR_USER_NAME role_arn = YOUR_ROLE_ARN role_session_name = YOUR_ROLE_SESSION_NAME ``` -------------------------------- ### Configure Custom Log Format Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Customize the log message format for console logging using a format string. This allows for tailored log output. ```python # Custom log format ecs = alibabacloud.get_resource( 'ecs', region_id='cn-hangzhou', access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET', enable_stream_logger=True, stream_format_string='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) ``` -------------------------------- ### Configure ECS RAM Role Credentials Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/docs/source/advance/credentials/03_file.rst Use this configuration when running on an ECS instance with an assigned RAM role. No explicit AccessKey is required. ```ini [default] type = ecs_ram_role role_name = YOUR_ROLE_NAME ``` -------------------------------- ### Iterate and Filter ECS Resource Collections Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Manage resource collections using filtering, pagination, and chaining methods. ```python import alibabacloud ecs = alibabacloud.get_resource( 'ecs', region_id='cn-hangzhou', access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET' ) # Iterate all instances for instance in ecs.instances.all(): print(f"ID: {instance.instance_id}") print(f"Type: {instance.instance_type}") print(f"Status: {instance.status}") # Filter instances by status for instance in ecs.instances.filter(Status='Running'): print(f"Running instance: {instance.instance_id}") # Filter with multiple conditions for instance in ecs.instances.filter( Status='Running', InstanceType='ecs.g6.large', list_of_tag=[{'Key': 'Environment', 'Value': 'Production'}] ): print(f"Production instance: {instance.instance_id}") # Limit results for instance in ecs.instances.limit(10): print(f"Instance: {instance.instance_id}") # Control page size for API calls for instance in ecs.instances.page_size(100).limit(200): print(f"Instance: {instance.instance_id}") # Chain methods together for instance in ecs.instances.filter(Status='Stopped').page_size(50).limit(100): instance.start() print(f"Starting instance: {instance.instance_id}") # Iterate by pages for page in ecs.instances.filter(Status='Running').pages(): print(f"Page contains {len(page)} instances") for instance in page: print(f" - {instance.instance_id}") ``` -------------------------------- ### Configure STS Token Credentials Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Utilize STS (Security Token Service) tokens for temporary credentials. This is recommended for enhanced security. ```python sts_credentials = SecurityCredentials( access_key_id='STS_ACCESS_KEY_ID', access_key_secret='STS_ACCESS_KEY_SECRET', security_token='STS_SECURITY_TOKEN' ) sts_provider = StaticCredentialsProvider(sts_credentials) ecs = alibabacloud.get_resource( 'ecs', config=config, credentials_provider=sts_provider ) ``` -------------------------------- ### List available SLB collections Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/README.md Access these collections through the slb object to manage SLB resources. ```text slb.access_control_lists slb.ca_certificates slb.domain_extensions slb.load_balancers slb.master_slave_server_groups slb.master_slave_vserver_groups slb.regions slb.rules slb.server_certificates slb.vserver_groups slb.zones ``` -------------------------------- ### List available CDN collections Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/README.md Access these collections through the cdn object to manage CDN resources. ```text cdn.fc_triggers ``` -------------------------------- ### List available ECS collections Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/README.md Access these collections through the ecs object to manage various ECS resources. ```text ecs.access_points ecs.auto_provisioning_groups ecs.bandwidth_packages ecs.clusters ecs.commands ecs.dedicated_hosts ecs.deployment_sets ecs.disks ecs.eip_addresses ecs.fleets ecs.ha_vips ecs.hpc_clusters ecs.images ecs.instances ecs.instance_types ecs.key_pairs ecs.launch_templates ecs.network_interfaces ecs.network_interface_permissions ecs.physical_connections ecs.regions ecs.reserved_instances ecs.route_tables ecs.router_interfaces ecs.security_groups ecs.snapshots ecs.snapshot_links ecs.storage_sets ecs.system_events ecs.tasks ecs.vrouters ecs.vswitches ecs.virtual_border_routers ecs.vpcs ecs.zones ``` -------------------------------- ### List available RDS collections Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/README.md Access these collections through the rds object to manage RDS resources. ```text rds.db_instances rds.migrate_tasks rds.parameters rds.regions rds.slow_logs rds.tasks rds.accounts rds.backups rds.dbs ``` -------------------------------- ### Retrieve ECS instance attributes Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/README.md Iterate through all instances to access their properties. ```python # Assume you already have a ECS resource name 'ecs' for instance in ecs.instances.all(): print(instance.instance_id) print(instance.instance_type) print(instance.status) ``` -------------------------------- ### Query ECS System Events Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Monitor and filter system events using specific event types and cycle statuses. ```python import alibabacloud from alibabacloud.services.ecs import ECSSystemEventResource ecs = alibabacloud.get_resource( 'ecs', region_id='cn-hangzhou', access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET' ) # Query system events for event in ecs.system_events.all(): print(f"Event ID: {event.event_id}") print(f"Event Type: {event.get_event_type()}") print(f"Event Status: {event.get_event_cycle_status()}") # Filter events by type for event in ecs.system_events.filter( list_of_event_type=[ECSSystemEventResource.EventType.SYSTEM_MAINTENANCE_REBOOT] ): print(f"Maintenance event: {event.event_id}") # Filter events by status for event in ecs.system_events.filter( list_of_event_cycle_status=[ECSSystemEventResource.EventCycleStatus.SCHEDULED] ): print(f"Scheduled event: {event.event_id}") ``` -------------------------------- ### Manage ECS Disks Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Perform disk operations including iteration, filtering, and individual resource management. ```python import alibabacloud ecs = alibabacloud.get_resource( 'ecs', region_id='cn-hangzhou', access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET' ) # Iterate all disks for disk in ecs.disks.all(): print(f"Disk ID: {disk.disk_id}") print(f"Size: {disk.size} GB") print(f"Status: {disk.status}") print(f"Category: {disk.category}") # Filter disks by category for disk in ecs.disks.filter(Category='cloud_essd'): print(f"ESSD Disk: {disk.disk_id}") # Get a specific disk resource disk = alibabacloud.get_resource( 'ecs.disk', resource_id='d-bp1234567890abcdef', region_id='cn-hangzhou', access_key_id='YOUR_ACCESS_KEY_ID', access_key_secret='YOUR_ACCESS_KEY_SECRET' ) # Refresh disk data disk.refresh() print(f"Disk size: {disk.size} GB") print(f"Attached to: {disk.instance_id}") ``` -------------------------------- ### Filter ECS instances by status Source: https://github.com/aliyun/alibabacloud-python-sdk-v2/blob/master/README.md Use the filter method on an ECS collection to retrieve resources matching specific criteria. ```python for instance in ecs.instances.filter(Status="Stopped"): pass ``` -------------------------------- ### Modify and Delete ECS Instance Attributes Source: https://context7.com/aliyun/alibabacloud-python-sdk-v2/llms.txt Perform lifecycle operations on an existing instance object. ```python # Modify instance attributes instance.modify_attributes( InstanceName='my-updated-instance', Description='Updated description' ) # Refresh instance data from API instance.refresh() print(f"Instance status: {instance.status}") print(f"Instance type: {instance.instance_type}") # Delete the instance instance.delete(Force=True) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.