ALIYUN::FC::Function

更新时间:
复制 MD 格式

ALIYUN::FC::Function creates a function in Function Compute. Functions belong to a service and share service-level attributes such as authorization and log configurations.

Syntax

{
  "Type": "ALIYUN::FC::Function",
  "Properties": {
    "Code": Map,
    "FunctionName": String,
    "ServiceName": String,
    "InstanceType": String,
    "MemorySize": Integer,
    "InstanceConcurrency": Integer,
    "EnvironmentVariables": Map,
    "Initializer": String,
    "Handler": String,
    "Timeout": Integer,
    "InitializationTimeout": Integer,
    "CustomContainerConfig": Map,
    "AsyncConfiguration": Map,
    "CAPort": Integer,
    "Runtime": String,
    "Description": String,
    "Cpu": Number,
    "CustomRuntimeConfig": Map,
    "GpuMemorySize": Integer,
    "InstanceSoftConcurrency": Integer,
    "DiskSize": Integer,
    "InstanceLifecycleConfig": Map,
    "CustomDNS": Map,
    "CustomHealthCheckConfig": Map
  }
}

Properties

Property

Type

Required

Editable

Description

Constraint

Initializer

String

No

Yes

The initializer handler.

Format varies by programming language.

InitializationTimeout

Integer

No

Yes

The initializer execution timeout.

Valid values: 1 to 300.

Unit: seconds.

Default value: 3.

Function Compute terminates the initializer when the timeout is reached.

Code

Map

No

Yes

The ZIP package of the function code.

For more information, see Code properties.

InstanceType

String

No

Yes

The function instance type.

Valid values:

  • e1: elastic instance

  • c1: performance instance

  • fc.gpu.tesla.1: GPU-accelerated instance with Tesla series GPUs

  • fc.gpu.ampere.1: GPU-accelerated instance with Ampere series GPUs

  • fc.gpu.ada.1: GPU-accelerated instance with Ada series GPUs

  • g1: GPU-accelerated instance with Tesla series GPUs

Default value: e1.

Description

String

No

Yes

The description of the function.

None.

ServiceName

String

Yes

No

The Function Compute service name.

1 to 128 characters.

MemorySize

Integer

No

Yes

The function memory size.

Valid values:

  • Valid values when InstanceType is set to e1: multiples of 64 that range from 128 to 3072.

  • Valid values when InstanceType is set to c1: 4096, 8192, 16384, and 32768.

  • Valid values when InstanceType is set to fc.gpu.tesla.1: multiples of 64 that range from 128 to X. X is calculated by using the following formula: X = GPU memory (GB) × 2048.

  • Valid value when InstanceType is set to fc.gpu.ada.1: 65536. 65536 MB is equivalent to 64 GB.

Unit: MB.

For more information, see Instance types and usage modes.

InstanceConcurrency

Integer

No

Yes

The instance concurrency value.

Valid values: 1 to 100.

EnvironmentVariables

Map

No

Yes

Environment variables for the function.

None.

Handler

String

Yes

Yes

The function handler.

Example: setting Handler to index.handler for a Python function means the file is index.py and the handler function is handler. Format varies by programming language.

Timeout

Integer

No

Yes

The function execution timeout.

Valid values: 1 to 600.

Default value: 3.

Unit: seconds.

Function Compute terminates execution when the timeout is reached.

Runtime

String

Yes

Yes

The function runtime.

Valid values: nodejs6, nodejs8, nodejs10, nodejs12, python3, java8, custom, and custom-container. For more information, see Runtimes supported by Function Compute.

FunctionName

String

Yes

No

The function name.

1 to 128 characters. Supports letters, digits, underscores (_), and hyphens (-). Must start with a letter or underscore (_).

CustomContainerConfig

Map

No

Yes

Custom Container runtime configuration. Applies when Runtime is set to custom-container, allowing function invocation with a custom container image.

For more information, see CustomContainerConfig properties.

CAPort

Integer

No

Yes

The custom HTTP server listening port.

Default value: 9000.

Note

Applies when Runtime is set to custom or custom-container.

AsyncConfiguration

Map

No

Yes

The async invocation configuration.

For more information, see AsyncConfiguration properties.

Cpu

Number

No

Yes

The function vCPU count.

None.

CustomRuntimeConfig

Map

No

Yes

The custom runtime configuration.

None.

GpuMemorySize

Integer

No

Yes

The function GPU memory size.

Multiples of 1024. Unit: MB.

InstanceSoftConcurrency

Integer

No

Yes

The soft concurrency threshold for graceful instance scale-up.

When instance concurrency exceeds the soft concurrency value, a scale-up is triggered. Specify an appropriate soft concurrency value to pre-warm instances with long startup times.

The value of InstanceSoftConcurrency must be less than or equal to the value of InstanceConcurrency.

DiskSize

Integer

No

Yes

The function disk size.

Unit: MB.

Valid values: 512 and 10240.

InstanceLifecycleConfig

Map

No

Yes

The instance lifecycle configuration.

For more information, see InstanceLifecycleConfig properties.

CustomDNS

Map

No

Yes

The custom DNS configuration.

For more information, see CustomDNS properties.

CustomHealthCheckConfig

Map

No

Yes

Health check configuration for custom and custom-container runtimes.

For more information, see CustomHealthCheckConfig properties.

Code syntax

"Code": {
  "OssBucketName": String,
  "OssObjectName": String,
  "ZipFile": String,
  "SourceCode": String
}

Code properties

Property

Type

Required

Editable

Description

Constraint

OssBucketName

String

No

Yes

The OSS bucket that stores the function code ZIP package.

None.

OssObjectName

String

No

Yes

The ZIP package object name in OSS.

None.

ZipFile

String

No

Yes

The Base64-encoded content of the ZIP package.

None.

SourceCode

String

No

Yes

The source code of the function.

Up to 4,096 characters. Supports Node.js, PHP, and Python.

ROS writes this value to a UTF-8 encoded file named index.

Priority order (highest to lowest): ZipFile, SourceCode, OssBucketName, OssObjectName.

CustomContainerConfig syntax

"CustomContainerConfig": {
  "Command": String,
  "Args": String,
  "Image": String,
  "AccelerationType": String,
  "InstanceId": String,
  "WebServerMode": Boolean
}

CustomContainerConfig properties

Property

Type

Required

Editable

Description

Constraint

Command

String

No

Yes

The container startup command.

Example: ["/code/myserver"].

Args

String

No

Yes

The container startup parameters.

Example: ["-arg1", "value1"].

Image

String

Yes

Yes

The container image URL.

Example: registry-vpc.cn-hangzhou.aliyuncs.com/fc-demo/helloworld:v1beta1.

AccelerationType

String

No

Yes

Whether to enable image acceleration.

Valid values:

  • Default: enables image acceleration.

  • None (default): disables image acceleration.

InstanceId

String

No

Yes

The Container Registry Enterprise Edition instance ID.

Required when using a Container Registry Enterprise Edition instance. The default resolved IP address must be a VPC IP address where Container Registry resides.

Note

You cannot use Alibaba Cloud DNS PrivateZone to define domain name resolution.

WebServerMode

Boolean

No

Yes

Whether to use web server mode for container images.

Valid values:

  • true (default): runs a web server in the container to listen on ports and process requests.

  • false: does not use web server mode. The container must actively exit after execution with exit code 0.

AsyncConfiguration syntax

"AsyncConfiguration": {
  "Destination": Map
  "MaxAsyncRetryAttempts": Integer,
  "MaxAsyncEventAgeInSeconds": Integer,
  "StatefulInvocation": Boolean
}

AsyncConfiguration properties

Property

Type

Required

Editable

Description

Constraint

Destination

Map

No

No

The async invocation destination.

For more information, see Destination properties.

MaxAsyncRetryAttempts

Integer

No

Yes

The maximum number of retries.

None.

MaxAsyncEventAgeInSeconds

Integer

No

Yes

The maximum message validity period.

None.

StatefulInvocation

Boolean

No

Yes

Whether to enable stateful async invocations.

Valid values:

  • true

  • false (default)

For more information, see Overview.

Destination syntax

"Destination": {
  "OnSuccess": String,
  "OnFailure": String
}

Destination properties

Property

Type

Required

Editable

Description

Constraint

OnSuccess

String

No

Yes

The destination invoked on successful function execution.

None.

OnFailure

String

No

Yes

The destination invoked on function execution failure due to a system error or built-in function error.

None.

InstanceLifecycleConfig syntax

"InstanceLifecycleConfig":{
  "PreFreeze": Map,
  "PreStop": Map
}

InstanceLifecycleConfig properties

Property

Type

Required

Editable

Description

Constraint

PreFreeze

Map

No

Yes

The PreFreeze hook configuration.

For more information, see PreFreeze properties.

PreStop

Map

No

Yes

The PreStop hook configuration.

For more information, see PreStop properties.

PreStop syntax

"PreStop":{
  "Handler": String,
  "Timeout": Integer
}

PreStop properties

Property

Type

Required

Editable

Description

Constraint

Handler

String

No

Yes

The handler of the function.

For more information, see Basic information.

Timeout

Integer

No

Yes

The timeout period for the execution.

Unit: seconds.

PreFreeze syntax

"PreFreeze":{
  "Handler": String,
  "Timeout": Integer
}

PreFreeze properties

Property

Type

Required

Editable

Description

Constraint

Handler

String

No

Yes

The handler of the function.

For more information, see Basic information.

Timeout

Integer

No

Yes

The timeout period for the execution.

Unit: seconds.

CustomHealthCheckConfig syntax

"CustomHealthCheckConfig":{
  "SuccessThreshold": Integer,
  "InitialDelaySeconds": Integer,
  "PeriodSeconds": Integer,
  "HttpGetUrl": String,
  "TimeoutSeconds": Integer,
  "FailureThreshold": Integer
}

CustomHealthCheckConfig properties

Property

Type

Required

Editable

Description

Constraint

SuccessThreshold

Integer

No

Yes

Consecutive successful health checks required to declare a container healthy.

Valid values: 1 to 120.

Default value: 1.

InitialDelaySeconds

Integer

No

Yes

The delay before the first health check after container startup.

Valid values: 0 to 120.

Default value: 0.

PeriodSeconds

Integer

No

Yes

The health check interval.

Valid values: 1 to 120.

Default value: 3.

HttpGetUrl

String

No

Yes

The custom health check URL of the container.

The URL can be up to 2,048 characters in length.

TimeoutSeconds

Integer

No

Yes

The timeout period of a health check.

Valid values: 1 to 3.

Default value: 1.

FailureThreshold

Integer

No

Yes

Consecutive failed health checks required to declare a container unhealthy.

Valid values: 1 to 120.

Default value: 3.

CustomRuntimeConfig syntax

"CustomRuntimeConfig":{
  "Args": List,
  "Command": List,
}

CustomRuntimeConfig properties

Property

Type

Required

Editable

Description

Constraint

Args

List

No

Yes

The startup command parameters.

Example:

["-arg1", "value1"]

Command

List

No

Yes

The startup command.

Example:

["/code/myserver"]

CustomDNS syntax

"CustomDNS":{
  "NameServers": List,
  "DnsOptions": List,
  "Searches": List
}

CustomDNS properties

Property

Type

Required

Editable

Description

Constraint

NameServers

List

No

Yes

The DNS server IP addresses.

None.

DnsOptions

List

No

Yes

The configuration items in the resolv.conf file.

None.

Searches

List

No

Yes

The DNS search domains.

None.

DnsOptions syntax

"DnsOptions":{
  "Value": String,
  "Name": String,
}

DnsOptions properties

Property

Type

Required

Editable

Description

Constraint

Value

String

No

Yes

The value of the configuration item.

Example: 2.

Name

String

Yes

Yes

The name of the configuration item.

Example: ndots.

Return values

Fn::GetAtt

  • FunctionId: the system-generated unique function ID.

  • ServiceName: the name of the service in Function Compute.

  • ARN: the Alibaba Cloud Resource Name (ARN) of the function.

  • FunctionName: the name of the function.

  • ServiceId: the Function Compute service ID.

Examples

ROSTemplateFormatVersion: '2015-09-01'
Parameters:
  ServiceName:
    Type: String
    Default: test-service
  FunctionName:
    Type: String
    Default: test-function
  Timeout:
    Type: Number
    Default: 60
  X:
    Type: Number
  Y:
    Type: Number
Resources:
  Service:
    Type: ALIYUN::FC::Service
    Properties:
      ServiceName:
        Ref: ServiceName
  Function:
    Type: ALIYUN::FC::Function
    Properties:
      ServiceName:
        Fn::GetAtt: [Service, ServiceName]
      FunctionName: 
        Ref: FunctionName
      Handler: index.handler
      Runtime: python3.10
      Code:
        SourceCode: |
          import time
          import json
          import requests
          import logging
          def handler(event, context):
              logger = logging.getLogger()
              event = json.loads(event)
              logger.info('receive request: %s', event)
              res_props = event['ResourceProperties']
              result = dict(
                  RequestId=event['RequestId'],
                  LogicalResourceId=event['LogicalResourceId'],
                  StackId=event['StackId'],
                  Status='SUCCESS',
                  PhysicalResourceId='dummy'
              )
              if event['RequestType'] != 'Delete':
                  result['Data'] = dict(Z=res_props['X'] + res_props['Y'])
              headers = {
                  'Content-type': 'application/json',
                  'Accept': 'application/json',
                  'Date': time.strftime('%a, %d %b %Y %X GMT', time.gmtime())
              }
            
              resp = requests.post(event['ResponseURL'], json=result, headers=headers)
              resp_content = resp.json()
              logger.info('response: %s', resp_content)

  SimpleTest:
    Type: Custom::Add
    Properties:
      ServiceToken:
        Fn::GetAtt: [Function, ARN]
      Parameters:
        X:
          Ref: X
        Y:
          Ref: Y
      Timeout:
        Ref: Timeout
Outputs:
  Result:
    Value:
      Fn::GetAtt: [SimpleTest, Z]
{
  "ROSTemplateFormatVersion": "2015-09-01",
  "Parameters": {
    "ServiceName": {
      "Type": "String",
      "Default": "test-service"
    },
    "FunctionName": {
      "Type": "String",
      "Default": "test-function"
    },
    "Timeout": {
      "Type": "Number",
      "Default": 60
    },
    "X": {
      "Type": "Number"
    },
    "Y": {
      "Type": "Number"
    }
  },
  "Resources": {
    "Service": {
      "Type": "ALIYUN::FC::Service",
      "Properties": {
        "ServiceName": {
          "Ref": "ServiceName"
        }
      }
    },
    "Function": {
      "Type": "ALIYUN::FC::Function",
      "Properties": {
        "ServiceName": {
          "Fn::GetAtt": [
            "Service",
            "ServiceName"
          ]
        },
        "FunctionName": {
          "Ref": "FunctionName"
        },
        "Handler": "index.handler",
        "Runtime": "python3.10",
        "Code": {
          "SourceCode": "import time\nimport json\nimport requests\nimport logging\ndef handler(event, context):\n    logger = logging.getLogger()\n    event = json.loads(event)\n    logger.info('receive request: %s', event)\n    res_props = event['ResourceProperties']\n    result = dict(\n        RequestId=event['RequestId'],\n        LogicalResourceId=event['LogicalResourceId'],\n        StackId=event['StackId'],\n        Status='SUCCESS',\n        PhysicalResourceId='dummy'\n    )\n    if event['RequestType'] != 'Delete':\n        result['Data'] = dict(Z=res_props['X'] + res_props['Y'])\n    headers = {\n        'Content-type': 'application/json',\n        'Accept': 'application/json',\n        'Date': time.strftime('%a, %d %b %Y %X GMT', time.gmtime())\n    }\n  \n    resp = requests.post(event['ResponseURL'], json=result, headers=headers)\n    resp_content = resp.json()\n    logger.info('response: %s', resp_content)\n"
        }
      }
    },
    "SimpleTest": {
      "Type": "Custom::Add",
      "Properties": {
        "ServiceToken": {
          "Fn::GetAtt": [
            "Function",
            "ARN"
          ]
        },
        "Parameters": {
          "X": {
            "Ref": "X"
          },
          "Y": {
            "Ref": "Y"
          }
        },
        "Timeout": {
          "Ref": "Timeout"
        }
      }
    }
  },
  "Outputs": {
    "Result": {
      "Value": {
        "Fn::GetAtt": [
          "SimpleTest",
          "Z"
        ]
      }
    }
  }
}

For more examples, visit function-invoker.yml. In the examples, the following resource types are used:

  • ALIYUN::FC::Service: creates a service in Function Compute.

  • ALIYUN::FC::Function: creates a function.

  • ALIYUN::FC::FunctionInvoker: invokes a function.

  • ALIYUN::FC::Trigger: triggers a function.

  • ALIYUN::FC::Version: releases a service version.

  • ALIYUN::FC::Alias: creates an alias.

  • ALIYUN::FC::ProvisionConfig: creates a provisioned instance.