Obtain and use temporary credentials using FC function roles
This topic describes how to obtain and use a Security Token Service (STS) token for an application that is deployed on Function Compute. This method helps you avoid hard coding an AccessKey pair in your application, which reduces the risk of credential exposure.
Overview
Function Compute obtains a Security Token Service (STS) token by calling the AssumeRole operation based on the role configured for a function. The STS token is then passed to your function through the Credentials or credentials parameter in the context. This temporary token grants access to all resources based on the configured permissions. You can use this token in your function code to access other Alibaba Cloud services.
Advantages
This solution significantly improves the security, flexibility, and convenience of your cloud applications. It also reduces maintenance costs and operational complexity.
Improve security
By associating an FC function with a RAM role, you can use an STS token to access cloud resources. This helps you avoid hard coding an AccessKey pair in your code and reduces the risk of AccessKey pair leaks. Using temporary credentials, such as an STS token, effectively mitigates the security risks associated with permanent credentials.
Fine-grained permission management
You can assign RAM roles with specific authorization policies to different FC functions. This ensures that each function can access only the resources it needs, which helps you achieve least privilege.
Enhance flexibility
An application deployed on an FC function can use an official Alibaba Cloud software development kit (SDK) to set the function role authentication method and obtain an STS token. This method lets you dynamically obtain and use temporary credentials as needed without pre-configuring fixed access credentials. You do not need to manage credentials directly on the FC function. To adjust permissions, you can simply modify the authorization policy of the RAM role. This simplifies the maintenance of access permissions for the FC function.
Reduce maintenance costs
Using an STS token eliminates the need to frequently update AccessKey pairs in your code. This reduces maintenance costs and operational complexity. This solution provides Java and Python code samples to help you quickly refactor your applications and reduce development and deployment complexity.
Customer scenarios
AK-free architecture for applications deployed in FC functions
Scenario description
An application deployed on Function Compute needs to access other cloud resources. The traditional method is to hard code the AccessKey pair of a RAM user into the function. If the AccessKey pair is written in a configuration file, it can be easily leaked and is difficult to maintain. A function RAM role associates an FC function with a RAM role. This allows the function to use an STS token to access cloud resources and mitigates the security risks associated with permanent credentials.
Applicable customers
- High security requirements: You need to ensure that your AccessKey pair is not exposed to prevent security vulnerabilities.
- Dynamic access management: You need to dynamically manage and temporarily grant permissions for instances to access other resources. This avoids the risks associated with long-term credentials.
- Simplified O&M: You want to simplify credential management during O&M and reduce the complexity of manual maintenance.
Solution architecture
This solution uses an FC function role to obtain and use temporary credentials. The architecture and process allow for dynamic management and temporary granting of access permissions. This avoids the risks of long-term AccessKey pair exposure and improves system security and flexibility. An administrator configures the role and permissions only once. The function can then dynamically obtain and use temporary credentials at runtime, which simplifies O&M.
An administrator creates a RAM role that is trusted by Function Compute and grants the required permissions to the role. The role permissions include the permissions to access the required cloud resources (Step 1 in the figure). The administrator attaches the created role to the corresponding FC function to associate the function with the role (Step 2 in the figure). The customer application obtains an STS token from the function context (Step 3 in the figure). During this process, Function Compute uses the identity of the cloud service to call the AssumeRole operation and obtain an STS token from the RAM/STS service (Step i in the figure). The customer application uses the obtained STS token to call the API of the destination cloud resource service (Step 4 in the figure). The resource service API processes the request and returns the result to the client application, which then completes the business logic. 
Product costs and terms
Product costs
| Product Name |
Description |
Cost |
| RAM |
Resource Access Management (RAM) is an Alibaba Cloud service that lets you manage user identities and control access to your resources. You can use RAM to create and manage RAM users, roles, and permissions for employees, systems, or applications to control their access to your resources. |
Free. For more information, see Pricing. |
| Function Compute |
Function Compute is a fully managed, event-driven compute service. With Function Compute, you can run code without provisioning or managing servers and other infrastructure. Function Compute prepares computing resources for you and runs your code in a reliable and elastic manner. It also provides features such as log query, performance monitoring, and alerts. |
Billed. For more information, see Product Billing. |
| Cloud Config |
Cloud Config is a resource auditing service that provides capabilities such as resource configuration history tracking and configuration compliance auditing. It helps you easily achieve automated oversight of your infrastructure and ensure continuous compliance when managing many resources. |
Free. For more information, see Product Billing. |
| ActionTrail |
ActionTrail is an Alibaba Cloud service that lets you query and deliver operation records of your Alibaba Cloud resources. You can use it for scenarios such as security analytics, resource change tracking, and compliance auditing. |
Free. For more information, see Product Billing. |
| Resource Directory |
Resource Directory is an Alibaba Cloud service that provides multi-level account and resource relationship management for enterprise customers. |
Free. For more information, see Product Billing. |
Glossary
| Name |
Description |
| Management account |
When an enterprise has multiple Alibaba Cloud accounts, this term refers to the administrator account that has permissions to manage the resources of other accounts. It is used to manage multiple accounts, centrally configure identity and permissions for multiple accounts, view bills for all Alibaba Cloud accounts, and centrally configure audit rules that are applied to each member account. |
| RAM administrator |
A RAM administrator has permissions to manage the RAM resources within an account. A RAM administrator can be an Alibaba Cloud account or a RAM user under the Alibaba Cloud account that has the AliyunRAMFullAccess permission. We strongly recommend that you use a RAM user as the RAM administrator. |
| AccessKey |
An AccessKey pair is a permanent access credential that Alibaba Cloud provides to users. It consists of an AccessKey ID and an AccessKey secret. Requests carry the AccessKey ID and a signature generated by encrypting the request content with the AccessKey secret. This is used for identity verification and request legality checks. |
| RAM role |
A RAM role is a virtual user to which a set of access policies can be granted. Unlike a RAM user, a RAM role does not have permanent identity credentials, such as a logon password or an AccessKey pair. A RAM role must be assumed by a trusted entity. After the role is assumed, the trusted entity obtains the temporary identity credential of the RAM role, which is a Security Token Service (STS) token. The trusted entity can then use the STS token to access authorized resources as the RAM role. |
| Function RAM role |
An FC function obtains the permissions of a function RAM role. It can then use a temporary Security Token Service (STS) token to access the APIs of specified Alibaba Cloud services and operate on specified cloud resources. This provides higher security. |
Security
Function Compute service-linked role
In some scenarios, Function Compute needs to access other Alibaba Cloud services to perform certain functions. For this purpose, Function Compute creates a service-linked role named AliyunServiceRoleForFC. Function Compute 3.0 supports attaching the AliyunServiceRoleForFC role to FaaS functions. This lets you grant functions permissions to access other Alibaba Cloud services within the scope of least privilege.
For more information about service-linked roles, see Service-linked Role.
Function Compute security
Function Compute is a fully managed, event-driven compute service. With Function Compute, you can run code without provisioning or managing servers and other infrastructure. Function Compute prepares computing resources for you and runs your code in a reliable and elastic manner. It also provides features such as log query, performance monitoring, and alerts. At the data plane, Function Compute uses Transport Layer Security (TLS) 1.2 or later to encrypt invocation requests and responses during communication with users. Internal communication uses a proprietary protocol to prevent information leakage and tampering. At the control plane, you can use Alibaba Cloud Resource Access Management (RAM) for access control. For more information about Function Compute security, see Security Compliance.
Notes
Temporary key validity
Function Compute obtains an STS token by calling the AssumeRole operation based on the role configured for a function. The STS token is valid for 36 hours and its validity period cannot be changed. The maximum running time of a function is 24 hours. Therefore, the temporary token does not expire while the function is running.
Function Compute version limit for continuous compliance auditing
The Cloud Config rule Function Compute service is configured with a service role supports auditing only for Function Compute 2.0 service instances.
Alibaba Cloud services that support STS
For a list of Alibaba Cloud services that support STS, see Services that work with STS.
Implementation steps
Preparations
To audit whether a function role is attached to a function, ensure that you have activated Cloud Config. For more information, see Activate Cloud Config.
Implementation time
After you complete the preparations, the implementation of this solution is expected to take 30 minutes.
Procedure
Continuous compliance auditing (Optional)
You can use Cloud Config to continuously audit the service role configurations of your Function Compute services and promptly identify services that are not configured with a service role.
Note: The Cloud Config rule "Function Compute service is configured with a service role" supports auditing only for Function Compute 2.0 service instances.
Create an account group (Optional)
If you are in a multi-account environment and want to centrally manage compliance for multiple member accounts, you can use a management account to add all or some member accounts from your resource directory to the same account group. The account group serves as a management unit for cross-account compliance management. If you are in a single-account environment, you can skip this step.
- Log on to the management account and go to the Resource Management console. In the navigation pane on the left, choose Resource Directory > Trusted Services. Select Cloud Config and click Manage.
- In the Delegated Administrator Account section, click Add to delegate the log archive account as the administrator for the Cloud Config service.
- Log on to the log archive account and go to the Cloud Config console. In the navigation pane on the left, choose Account Group. Click Create Account Group to centrally manage compliance for the member accounts in your resource directory.
- When you create the account group, you can set Account Group Type to Global. The members of a global account group are automatically synchronized with your resource directory. The global account group automatically detects new members in the resource directory and adds them to the group. This ensures that the scope of compliance management is always consistent with the resource directory. Note that you can create only one global account group. In this example, a global account group named ResourceDirectory is created.
Create a rule
- Go to the Cloud Config console. If you are using the account group from the previous steps for multi-account compliance management, switch to the required account group in the navigation pane on the left.
- In the navigation pane on the left, choose Compliance Auditing > Rules and click Create Rule. Select the rule named Function Compute service is configured with a service role. Click Next.
- On the Set Basic Properties page, you can set the risk level, trigger mechanism, and trigger frequency for the rule.
- Click Next. You can also set the scope of the rule. For example, you can configure the rule to apply only to resources within certain resource groups or resources with specific tags. This allows for more fine-grained management of the compliance scope.
- After the rule is created, you can view all non-compliant resources under the current account group on the rule details page. This is a list of Function Compute services that are not configured with a service role. By default, this rule runs a check every 24 hours. You can configure the trigger frequency when you create or modify the rule.
- Finally, you can deliver the non-compliant resource data to other Alibaba Cloud products, such as Simple Log Service or Object Storage Service. This helps you further archive, process, and audit the data. For more information about data delivery, see Deliver data from Cloud Config.
Create and attach a function role
Function Compute 3.0
- Log on to the Function Compute console. In the navigation pane on the left, click Functions.
- In the top menu bar, select a region. On the Functions page, find the target function and click Configure in the Actions column.
- On the function details page, click the Configuration tab. In the navigation pane on the left, choose Permissions. Click Edit. In the Edit Permissions panel, click Create Role to go to the RAM console. Follow the on-screen instructions to create a role and grant the required permissions to it.
You can also use an existing role. If the permissions are insufficient, click Edit Policy to add permissions as needed. For more information, see Grant permissions to a RAM role.
- In the RAM console, on the Roles page, click Create Role.
- On the Select Type tab, select Alibaba Cloud Service as the trusted entity type and click Next.
- On the Configure Role tab, select Normal Service Role. Set the role name (for example, fc-test-role). Set Select Trusted Service to Function Compute and click Finish.
- On the Creation Finished tab, click Grant Permission to Role. Find the target role and click Add Permissions in the Actions column.
- On the Grant Permission page, select the Authorization Scope. The Authorized Principal defaults to the selected target role. Select the required system or custom policy and add it to the selected list on the right. Then, click OK. For more information, see Policies and examples.
- Entire Alibaba Cloud Account: The permission takes effect within the current Alibaba Cloud account.
- Specified Resource Group: The permission takes effect within the specified resource group. For this to take effect, the Alibaba Cloud service must support resource groups. For more information, see Alibaba Cloud services that support resource groups.
- Attach the role fc-test-role created in the previous step to the target function, and then click the Deploy button at the bottom.
Function Compute 2.0
- Log on to the Function Compute console. In the navigation pane on the left, click Services and Functions.
- In the top menu bar, select a region. On the Services and Functions page, find the target service and click Configure in the Actions column.
- On the Edit Service page, in the Role Configuration panel, click Create Role to go to the RAM console. Follow the on-screen instructions to create a role and grant the required permissions to it.
You can also use an existing role. If the permissions are insufficient, click Edit Policy to add permissions as needed. For more information, see Grant permissions to a RAM role.
- In the RAM console, on the Roles page, click Create Role.
- On the Select Type tab, select Alibaba Cloud Service as the trusted entity type and click Next.
- On the Configure Role tab, select Normal Service Role. Set the role name (for example, fc-test-role). Set Select Trusted Service to Function Compute and click Finish.
- On the Creation Finished tab, click Grant Permission to Role. Find the target role and click Add Permissions in the Actions column.
- On the Grant Permission page, select the Authorization Scope. The Authorized Principal defaults to the selected target role. Select the required system or custom policy and add it to the selected list on the right. Then, click OK. For more information, see Policies and examples.
- Entire Alibaba Cloud Account: The permission takes effect within the current Alibaba Cloud account.
- Specified Resource Group: The permission takes effect within the specified resource group. For this to take effect, the Alibaba Cloud service must support resource groups. For more information, see Alibaba Cloud services that support resource groups.
- Attach the `fc-test-role` role created in the previous step to the target function and click the Save button at the bottom.
Obtain and use a temporary credential based on the function role
You can use the temporary credential to perform operations permitted by the fc-test-role function role. In the following steps, you can call GetCallerIdentity to view the identity information of the current caller.
Write and deploy the code
In the function list, click the target function. Then, click the Code tab. In the code editor on the Code tab, write or upload your code, and then click Deploy Code.
You can use an Alibaba Cloud SDK to obtain a temporary credential from the context based on the function role and use that credential to call an Alibaba Cloud OpenAPI.
Node.js
The following is the code for the Node.js standard runtime:
'use strict';
const RPCClient = require('@alicloud/pop-core').RPCClient;
const httpModule = require('http');
const keepAliveAgent = new httpModule.Agent({
keepAlive: false,
});
const requestOption = {
method: 'POST',
formatParams: false,
timeout: 10000,
agent: keepAliveAgent,
};
exports.handler = (event, context, callback) => {
main(context)
.then((res) => {
callback(null, JSON.stringify(res));
})
.catch((err) => callback(err));
};
async function main(context) {
const { credentials, logger } = context;
// Obtain the AK, SK, and Security Token from the context to initialize the OpenAPI client.
const client = new RPCClient({
accessKeyId: credentials.accessKeyId,
accessKeySecret: credentials.accessKeySecret,
securityToken: credentials.securityToken,
endpoint: 'https://sts.cn-hangzhou.aliyuncs.com',
apiVersion: '2015-04-01'
});
const result = await client.request('GetCallerIdentity', {
pageSize: 1
}, requestOption);
return result;
}
Python
The following is the code for the Python standard runtime:
from aliyunsdksts.request.v20150401.GetCallerIdentityRequest import GetCallerIdentityRequest
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.auth.credentials import StsTokenCredential
def handler(event, context):
# Obtain credential information from the context.
creds = context.credentials
# Create a credential object.
credentials = StsTokenCredential(creds.access_key_id, creds.access_key_secret, creds.security_token)
# Initialize the client and set information such as the region.
client = AcsClient(region_id='cn-hangzhou', credential=credentials)
# Create a request object.
request = GetCallerIdentityRequest()
# Set parameters. For example, you can set filter conditions. This example shows only the most basic call.
request.set_accept_format('json')
# Send the request and obtain the response.
response = client.do_action_with_exception(request)
# Print the response.
return(str(response, encoding='utf-8'))
Java
The following is the Java code and its Maven dependencies:
<dependency>
<groupid>com.aliyun.fc.runtime</groupid>
<artifactid>fc-java-core</artifactid>
<version>1.4.1</version>
</dependency>
<dependency>
<groupid>com.aliyun.fc.runtime</groupid>
<artifactid>fc-java-event</artifactid>
<version>1.2.0</version>
</dependency>
<!--We recommend that you use the latest version of Credentials.-->
<!--For a list of all released versions, see https://github.com/aliyun/credentials-java/blob/master/ChangeLog.txt-->
<dependency>
<groupid>com.aliyun</groupid>
<artifactid>credentials-java</artifactid>
<version>LATEST</version>
</dependency>
<dependency>
<groupid>com.aliyun</groupid>
<artifactid>sts20150401</artifactid>
<version>1.1.4</version>
</dependency>
<dependency>
<groupid>com.alibaba.fastjson2</groupid>
<artifactid>fastjson2</artifactid>
<version>2.0.51</version>
</dependency>
import java.io.InputStream;
import java.io.OutputStream;
import com.alibaba.fastjson2.JSON;
import com.aliyun.credentials.utils.AuthConstant;
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.Credentials;
import com.aliyun.fc.runtime.StreamRequestHandler;
import com.aliyun.sts20150401.Client;
import com.aliyun.sts20150401.models.GetCallerIdentityResponse;
import com.aliyun.teaopenapi.models.Config;
public class App implements StreamRequestHandler {
@Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) {
// Obtain credential information from the context.
Credentials creds = context.getExecutionCredentials();
try {
Config config = new Config().setRegionId("cn-hangzhou").setCredential(createCredential(creds));
// View the identity of the current caller.
Client stsClient = new Client(config);
GetCallerIdentityResponse getCallerIdentityResponse = stsClient.getCallerIdentity();
outputStream.write(JSON.toJSONString(getCallerIdentityResponse).getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
private static com.aliyun.credentials.Client createCredential(Credentials creds) {
com.aliyun.credentials.models.Config config = new com.aliyun.credentials.models.Config();
config.type = AuthConstant.STS;
config.accessKeyId = creds.getAccessKeyId();
config.accessKeySecret = creds.getAccessKeySecret();
config.securityToken = creds.getSecurityToken();
return new com.aliyun.credentials.Client(config);
}
}
Note:
- The credentials must be obtained from the context.
- The temporary token is valid for 36 hours and its validity period cannot be changed. The maximum running time of a function is 24 hours. Therefore, the temporary token does not expire while the function is running.
For more runtime examples in other languages, see the help document.
View the result
Click Test Function and click Details to view the result.
OSS SDK
You can also use the OSS SDK to obtain and manage access credentials and complete API calls.
Note: You need to grant the AliyunOSSFullAccess permission to the function role configured for this function.
Python
The following is the code for the Python standard runtime:
import json
import oss2
def handler(event, context):
endpoint = 'http://oss-cn-hangzhou.aliyuncs.com'
bucket = 'web****'
object = 'myObj'
message = 'test-message'
# Obtain the temporary credential from the context.
creds = context.credentials
# Convert it to an OSS SDK credential.
auth = oss2.StsAuth(creds.access_key_id, creds.access_key_secret, creds.security_token)
# Call the OpenAPI.
bucket = oss2.Bucket(auth, endpoint, bucket)
bucket.put_object(object, message)
return 'success'
In the example above, replace bucket with the name of a bucket that you have created in the same region as the function.
Java
The Alibaba Cloud OSS SDK and related FC dependencies are as follows:
<dependencies>
<dependency>
<groupid>com.aliyun.oss</groupid>
<artifactid>aliyun-sdk-oss</artifactid>
<version>3.17.4</version>
</dependency>
<dependency>
<groupid>com.aliyun.fc.runtime</groupid>
<artifactid>fc-java-core</artifactid>
<version>1.4.1</version>
</dependency>
<dependency>
<groupid>com.aliyun.fc.runtime</groupid>
<artifactid>fc-java-event</artifactid>
<version>1.2.0</version>
</dependency>
<dependency>
<groupid>com.alibaba.fastjson2</groupid>
<artifactid>fastjson2</artifactid>
<version>2.0.51</version>
</dependency>
</dependencies>
The Java code is as follows:
package org.example.oss_sdk;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import com.alibaba.fastjson2.JSON;
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.StreamRequestHandler;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.auth.Credentials;
import com.aliyun.oss.common.auth.DefaultCredentials;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.Bucket;
public class App implements StreamRequestHandler {
@Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
// Obtain credential information from the context.
com.aliyun.fc.runtime.Credentials creds = context.getExecutionCredentials();
// Convert it to OSS Credentials.
Credentials ossCreds = new DefaultCredentials(creds.getAccessKeyId(), creds.getAccessKeySecret(), creds.getSecurityToken());
CredentialsProvider credentialsProvider = new DefaultCredentialProvider(ossCreds);
// The endpoint corresponding to the region where the bucket is located. China (Hangzhou) is used as an example.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// The region information corresponding to the endpoint, such as cn-hangzhou.
String region = "cn-hangzhou";
// We recommend that you use the more secure V4 signature algorithm. When initializing, you need to add the region information corresponding to the endpoint and declare SignVersion.V4.
// OSS Java SDK 3.17.4 and later versions support V4 signatures.
ClientBuilderConfiguration configuration = new ClientBuilderConfiguration();
configuration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(configuration)
.region(region)
.build();
// Call the OpenAPI.
List<bucket> buckets = ossClient.listBuckets();
outputStream.write(JSON.toJSONString(buckets).getBytes());
}
}</bucket>
SLS SDK
You can also use the SLS SDK to obtain and manage access credentials and complete API calls.
Note: You need to grant the AliyunLogReadOnlyAccess permission to the function role configured for this function.
Python
The following is the code for the Python standard runtime:
from aliyun.log import LogClient
def handler(event, context):
endpoint = 'cn-hangzhou.log.aliyuncs.com'
# Obtain the temporary credential from the context.
creds = context.credentials
# Initialize LogClient.
client = LogClient(endpoint, creds.access_key_id, creds.access_key_secret, creds.security_token)
# Call the ListProject interface.
response = client.list_project()
return response.get_projects()
Java
The Alibaba Cloud SLS SDK and related FC dependencies are as follows:
<dependencies>
<dependency>
<groupid>com.aliyun.fc.runtime</groupid>
<artifactid>fc-java-core</artifactid>
<version>1.4.1</version>
</dependency>
<dependency>
<groupid>com.aliyun.fc.runtime</groupid>
<artifactid>fc-java-event</artifactid>
<version>1.2.0</version>
</dependency>
<dependency>
<groupid>com.aliyun.openservices</groupid>
<artifactid>aliyun-log</artifactid>
<version>0.6.107</version>
</dependency>
<dependency>
<groupid>com.alibaba.fastjson2</groupid>
<artifactid>fastjson2</artifactid>
<version>2.0.51</version>
</dependency>
</dependencies>
The Java code is as follows:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import com.alibaba.fastjson2.JSON;
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.StreamRequestHandler;
import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.ClientBuilder;
import com.aliyun.openservices.log.common.Project;
import com.aliyun.openservices.log.common.auth.Credentials;
import com.aliyun.openservices.log.common.auth.CredentialsProvider;
import com.aliyun.openservices.log.common.auth.DefaultCredentials;
import com.aliyun.openservices.log.common.auth.StaticCredentialsProvider;
import com.aliyun.openservices.log.exception.LogException;
public class App implements StreamRequestHandler {
@Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
// Obtain credentials from the context.
com.aliyun.fc.runtime.Credentials creds = context.getExecutionCredentials();
// Convert to SLS Credentials.
Credentials slsCreds = new DefaultCredentials(creds.getAccessKeyId(), creds.getAccessKeySecret(), creds.getSecurityToken());
CredentialsProvider credentialsProvider = new StaticCredentialsProvider(slsCreds);
// The SLS endpoint. This example uses the endpoint in Hangzhou.
String endpoint = "https://cn-hangzhou.log.aliyuncs.com";
Client slsClient = new ClientBuilder(endpoint, credentialsProvider).build();
// Call the OpenAPI.
try {
List<Project> projects = slsClient.ListProject().getProjects();
outputStream.write(JSON.toJSONString(projects).getBytes());
} catch (LogException e) {
throw new RuntimeException(e);
}
}
}</project>
Code samples
Code description
This solution provides FC code samples in Java and Python that use the Alibaba Cloud SDK, OSS SDK, and SLS SDK to obtain temporary credentials from the context. This helps you quickly refactor your applications.
Code repository
For more information about the code, see the code repository.
Audit operations of the function role (Optional)
To audit the operations performed by an FC function role, you can use your log audit account to go to the ActionTrail console. In Events > Event Query, find the operation events for the instance role and click to view the event details.
In the audited event, stsTokenPrincipalName is in the following format: ${FunctionRoleName}/FunctionCompute.
If audit log delivery is enabled for your account, you can run the following SQL statement in Events > Advanced Search to quickly find all operations performed by the instance using the instance role identity:
requestParameters.stsTokenPrincipalName:${FunctionRoleName}/FunctionCompute
Troubleshooting
Why does the function fail to execute?
If the runtime is Java and the error message Cannot find the class example.App in your zip file and please make sure it is in the right path 'example/App' appears, check that the Request Handler in Configuration > Runtime is in the [package].[class]::[method] format. For example, if the current value is example.HelloFC::handleRequest, the handleRequest function in the HelloFC class of the example package is executed when the function is triggered.
For more information about common issues when using FC, see FC Service Support.