ALIYUN::FC::Function is used to create a function. Functions must be associated with services. All functions of a service share the same attributes as the service, such as service 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
  }
}

Properties

Property Type Required Editable Description Constraint
Initializer String No Yes The handler of the initializer function. The format of the value varies based on the programming language that you use.
InitializationTimeout Integer No Yes The timeout period for the execution of the initializer function. Valid values: 1 to 300.

Unit: seconds.

Default value: 3.

When the timeout period ends, Function Compute terminates the execution of the initializer function.
Code Map No Yes The code package in ZIP format. For more information, see Code properties.
InstanceType String No Yes The type of the function instance. Valid values:
  • e1: elastic instance
  • c1: performance instance
Description String No Yes The description of the function. None.
ServiceName String Yes No The name of the service. The name must be 1 to 128 characters in length.
MemorySize Integer No Yes The memory size of the function. Valid values:
  • Valid values for an elastic instance: multiples of 64 that are from 128 to 3072
  • Valid values for a performance instance: 4096, 8192, 16384, and 32768

Unit: MB.

InstanceConcurrency Integer No Yes The maximum number of requests that can be concurrently processed by a function instance. Valid values: 1 to 100.
Note This property is not supported for function instances that are run in Python.
EnvironmentVariables Map No Yes The environment variables that you specify for the function. None.
Handler String Yes Yes The handler of the function. For example, if you set the Handler property to index.handler when you create a Python function, the file name is index.py and the function name is handler. The format of the value varies based on the programming language that you use.
Timeout Integer No Yes The timeout period for the execution of the function. Valid values: 1 to 600.

Default value: 3.

Unit: seconds.

When the timeout period ends, Function Compute terminates the execution of the function.

Runtime String Yes Yes The runtime environment of the function. Valid values: nodejs6, nodejs8, nodejs10, nodejs12, python2.7, python3, java8, custom, and custom-container.
FunctionName String Yes No The name of the function. The name must be 1 to 128 characters in length, and can contain letters, underscores (_), digits, and hyphens (-). The name must start with a letter or underscore (_).
CustomContainerConfig Map No Yes The configurations of the custom container runtime when you set the Runtime property to custom-container. After you configure the custom container runtime, you can use a custom container image to invoke functions. For more information, see CustomContainerConfig properties.
CAPort Integer No Yes The port on which the custom HTTP server listens. Default value: 9000.
Note This property takes effect when you set the Runtime property to custom or custom-container.
AsyncConfiguration Map No Yes The configurations of the asynchronous invocation. For more information, see AsyncConfiguration 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 name of the Object Storage Service (OSS) bucket in which the code package in ZIP format is stored. None.
OssObjectName String No Yes The name of the code package that is used as an object in ZIP format. None.
ZipFile String No Yes The Base64-encoded code package in ZIP format. None.
SourceCode String No Yes The source code of the function. The source code can be up to 4,096 characters in length. Node.js, PHP, and Python are supported.

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

When you specify the ZipFile, SourceCode, OssBucketName, and OssObjectName properties at the same time, the properties are in descending order of priority.

CustomContainerConfig syntax

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

CustomContainerConfig properties

Property Type Required Editable Description Constraint
Command String No Yes The command that you run to start the container. Example: ["/code/myserver"].
Args String No Yes The startup parameters of the container. Example: ["-arg1", "value1"].
Image String Yes Yes The endpoint of the container image. Example: registry-vpc.cn-hangzhou.aliyuncs.com/fc-demo/helloworld:v1beta1.
AccelerationType String No Yes Specifies whether to enable image pull acceleration. Default value: None. Valid values:
  • Default: enables image pull acceleration.
  • None: disables image pull acceleration.
InstanceId String No Yes The ID of the Container Registry Enterprise Edition instance. If you use a Container Registry Enterprise Edition instance, you must specify the instance ID. The default resolved IP address of the instance must be the IP address of the virtual private cloud (VPC) in which the instance is deployed.
Note You cannot use Alibaba Cloud DNS PrivateZone to resolve domain names.

AsyncConfiguration syntax

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

AsyncConfiguration properties

Property Type Required Editable Description Constraint
Destination Map No No The destination for the asynchronous invocation. For more information, see Destination properties.
MaxAsyncRetryAttempts Integer No Yes The maximum number of retries for the asynchronous invocation. None.
MaxAsyncEventAgeInSeconds Integer No Yes The maximum validity period of a message. None.
StatefulInvocation Boolean No Yes Specifies whether to enable a stateful asynchronous invocation. Default value: false. Valid values:
  • true: enables a stateful asynchronous invocation.
  • false: disables a stateful asynchronous invocation.

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 that Function Compute invokes when the function is executed. None
OnFailure String No Yes The destination that Function Compute invokes when the function fails to be executed due to a system error or a function error. None

Return values

Fn::GetAtt

  • FunctionId: the unique ID that is generated by the system for each function.
  • ServiceName: the name of the service.
  • ARN: the Alibaba Cloud Resource Name (ARN) of the function.
  • FunctionName: the name of the function.
  • ServiceId: the ID of the service.

Examples

  • YAMLformat

    ROSTemplateFormatVersion: '2015-09-01'
    Parameters:
      ServiceName:
        Type: String
        Default: mytest
      FunctionName:
        Type: String
        Default: mytest
      Timeout:
        Type: Number
        Default: 60
      X:
        Type: Number
        Default: 1
      'Y':
        Type: Number
        Default: 2
    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: python2.7
          Code:
            SourceCode: |
              import time
              import json
              import urllib2
              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())
                  }
                  req = urllib2.Request(event['ResponseURL'], data=json.dumps(result), headers=headers)
                  resp = urllib2.urlopen(req)
                  resp_content = resp.read()
                  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:
      SimpleTestOutputs:
        Value:
          Fn::GetAtt:
            - SimpleTest
            - Outputs
    
  • JSON format

    {
      "ROSTemplateFormatVersion": "2015-09-01",
      "Parameters": {
        "ServiceName": {
          "Type": "String",
          "Default": "mytest"
        },
        "FunctionName": {
          "Type": "String",
          "Default": "mytest"
        },
        "Timeout": {
          "Type": "Number",
          "Default": 60
        },
        "X": {
          "Type": "Number",
          "Default": 1
        },
        "Y": {
          "Type": "Number",
          "Default": 2
        }
      },
      "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": "python2.7",
            "Code": {
              "SourceCode": "import time\nimport json\nimport urllib2\nimport logging\n\n\ndef handler(event, context):\n    logger = logging.getLogger()\n\n    event = json.loads(event)\n    logger.info('receive request: %s', event)\n\n    res_props = event['ResourceProperties']\n\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\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    req = urllib2.Request(event['ResponseURL'], data=json.dumps(result), headers=headers)\n    resp = urllib2.urlopen(req)\n    resp_content = resp.read()\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": {
        "SimpleTestOutputs": {
          "Value": {
            "Fn::GetAtt": [
              "SimpleTest",
              "Outputs"
            ]
          }
        }
      }
    }
To view more examples, visit FunctionInvoker.json and FunctionInvoker.yml. In the examples, the following resource types are used:
  • ALIYUN::FC::Service
  • ALIYUN::FC::Function
  • ALIYUN::FC::FunctionInvoker
  • ALIYUN::FC::Trigger
  • ALIYUN::FC::Version
  • ALIYUN::FC::Alias
  • ALIYUN::FC::ProvisionConfig