Aliyun international distributors: Aliyun API interface call and key configuration method
For students who have just come into contact with cloud computing or back-end development, "calling API interface" is the only way to connect business and cloud resources. Whether you want to write a script to automatically switch on and off, modify security groups in batches, or integrate Aliyun's OSS storage and large model interface into your own system, you cannot do without API.
However, many people have a big head when they see cryptographic terms (such as AccessKey, Secret, HMAC-SHA1, signature algorithm), or accidentally leak the key to GitHub due to improper configuration, resulting in the server being hacked by hackers to mine, resulting in heavy losses.
Today's tutorial uses vernacular to take you through the whole process: from
How to get the key securely
,
How to gracefully configure locally
, then to
Complete the first API call with the simplest code
.
The first stage: the core concept (don't put the door key directly in the mouth)
Before you start, you must understand two core concepts:
AK
and
SK
. They're like yours
Cloud ID and password
.
AccessKey ID (AK for short): equivalent to your "user name". It is public and used to tell Aliyun "who I am".
AccessKey Secret (SK for short): equivalent to your "password". It must never be made public and used to prove that "I really am me".
Each API request of Alibaba Cloud must use SK to encrypt and sign the request content. After receiving the request, ariyun uses the same algorithm to verify it and release it only after it is checked.
🚨Iron Law: Never use AK/SK of the main account!
If you directly use the key of the Alibaba Cloud boss account (main account), this key has the highest control over all the property under your account (deduction of fees, deletion of libraries, and purchase of servers).
Correct approach:
Create a RAM user like a "sweeping monk", assign it only permission to do a specific thing, and then use the AK/SK of this sub-account.
Stage 2: Secure key acquisition (5 minutes)
We will pass Aliyun's
RAM (Access Control)
to create a secure subaccount key.
1. Create a RAM user
Log on to the Alibaba Cloud console, enter RAM in the top search bar, and click Access Control Console.
In the left-side navigation pane, click Identity Management-> Users.
Click the Create User button.
Key parameter configuration: logon name: a meaningful name, such as api-operator-oss (indicates that this account is specifically used to tune the OSS interface). Display name: for example, a dedicated account for the OSS interface. Access: Focus! OpenAPI call access must be checked. There is no need to check "console login" because this account does not need to log in to the web page.
Click OK. At this time, a pop-up will pop up on the screen.
A table containing the AccessKey ID and AccessKey Secret.
Copy and save immediately to a local safe place (such as a password manager)! Note: This Secret will only be displayed this time, once you refresh the page or close the window, you will never see it again. If you lose it, you can only delete it and build another one.
2. Give personnel access (authorization)
The newly created sub-account is a "Bai Ding" and does not have any permission. If you call the interface directly, you will report an error.
User not authorized
.
In the user list just now, find your new user and click Add Permissions on the right.
Select Authorization Scope: entire cloud account.
Select a policy: Enter the service you want to call in the search box. For example, if you want to control the server, search ECS and check AliyunECSFullAccess (administrative permission) or AliyunECSReadOnlyAccess (read-only permission). It is suggested to follow the principle of least authority, give what you need, and don't try to save trouble and give it directly to AdministratorAccess (system administrator).
Click OK to complete the authorization.
Phase 3: Key-local configuration (reject hardcoding!)
After getting AK/SK, ten million
Don't
Write directly in code (this is the legendary "hard coding"). In case the code is transferred to the public warehouse one day, you will wait to pay the cloud bill with full salary.
Industry standard practice is to use
Environment Variables (Environment Variables)
.
1. Linux / macOS configuration method
Open the terminal and edit your environment variable file (e. g.
~/.bashrc
or
~/.zshrc
):
export ALIBABA_CLOUD_ACCESS_KEY_ID = "Your AccessKeyID"
export ALIBABA_CLOUD_ACCESS_KEY_SECRET = "Your AccessKeySecret"
After saving, run
source ~/.bashrc
(or a corresponding file) for the configuration to take effect.
2. Windows configuration method
Right-click "This PC"-> "Properties"-> "Advanced System Settings"-> "Environment Variables".
In "user variables" or "system variables", click "new": variable name: ALIBABA_CLOUD_ACCESS_KEY_ID, variable value: fill in your AK. Create another one: variable name: ALIBABA_CLOUD_ACCESS_KEY_SECRET, variable value: fill in your SK.
Click OK to save all the way. Note: After configuration, you need to restart your integrated development environment (e.g. VS Co
de / PyCharm) or the command line window, otherwise the new variable cannot be read.
The fourth stage: the first API call actual combat (Python example)
Now that the environment is ready, we use the most recommended method-using ariyun's official
V2.0 SDK
To make a call. The following example is to query all ECS instances (DescribeInstances) under your account.
1. Install the SDK core library and corresponding product library
Run in local terminal:
Bash
pip install alibabacloud_tea_openapi
pip install alibabacloud_ecs20140526==4.3.0
2. Write the calling code
Aliyun's V2.0 SDK is very intelligent. It will automatically read the environment variables we just configured.
ALIBABA_CLOUD_ACCESS_KEY_ID
and
ALIBABA_CLOUD_ACCESS_KEY_SECRET
There is no need to write a sensitive word in the code.
import os
import sys
from alibabacloud_ecs20140526.client import Client as Ecs20140526Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_ecs20140526 import models as ecs_20140526_models
class AliyunApiDemo:
@staticmethod
def create_client() -> Ecs20140526Client:
"""
Initialize account client
"""
# SDK automatically obtains ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET from environment variables
config = open_api_
models.Config()
# Select the domain name you want to call, for example, Hangzhou is cn-hangzhou and Shanghai is cn-shanghai
config.endpoint = f"ecs.cn-hangzhou.aliyuncs.com"
return Ecs20140526Client(config)
@staticmethod
def main():
client = AliyunApiDemo.create_client()
# Construct request parameters (query the ECS instances in the current region)
describe_instances_request = (
and (
region_id = "cn-hangzhou"
)
)
try:
# Initiate a call
response = client.describe_instances(describe_instances_request)
# Print the returned JSON result
&nb
sp; print("=== API call is successful, the return result is as follows ===")
print(response.body)
except Exception as error:
# Handle errors gracefully
print(f "=== API call failed ===")
if hasattr(error, "message"):
print(f "Error Message: {error.message}")
if hasattr(error, "code"):
print(f "error code: {error.code}")
if __name__ == "__main__":
AliyunApiDemo.main()
Run this code. If you see the JSON data of your server's instance list, you have successfully opened the API door of Aliyun.
The fifth stage: master advanced immortal tool-OpenAPI Explorer
If you don't want to write code, or don't know how to fill in the parameters of an interface, ariyun provides an absolute "cheating artifact"--
OpenAPI Portal (OpenAPI Explorer)
.
Browser access https://next.api.aliyun.com/.
Enter the function you want to use in the search box on the left, such as "create cloud disk" or "send text messages".
In the middle form, directly use the input box of the visual interface to fill in the parameters.
The key point is: the "SDK Example" tab on the right side of the web page will automatically generate codes in various languages (Python, Java, Go, Node.js all have
).
You can even click "Initiate Call" directly on the web page to see if the result returned by the interface is correct. After debugging, copy the code on the right directly into your project and use it.
Summarize the Tips for Avoiding Pit Mouth
It is not difficult to adjust the interface, but it is difficult to detail and safety. Finally, I'll give you four tips for avoiding the pit:
Minimize permissions: if you can read only, don't read and write, and if you can limit specific products, don't select all.
The code is not densified: if you see access_key followed by strings in the source code, they are all rewritten to read from environment variables.
Regular rotation system: It is recommended to disable the sub-account key of a commercial project in the console every six months and generate a new set to prevent employees from leaving the company or inadvertently leaking it.
Make good use of Explorer: Don't gnaw at official text documents, go to the OpenAPI portal to see the automatically generated Demo code, which can avoid detours.

