

文件AWS開發套件範例 GitHub 儲存庫中有更多可用的 [AWSSDK 範例](https://github.com/awsdocs/aws-doc-sdk-examples)。

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# `CreateComponentVersion` 搭配 AWSSDK 或 CLI 使用
<a name="greengrassv2_example_greengrassv2_CreateComponentVersion_section"></a>

下列程式碼範例示範如何使用 `CreateComponentVersion`。

動作範例是大型程式的程式碼摘錄，必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作：
+  [了解AWS IoT Greengrass V2基本概念](greengrassv2_example_greengrassv2_Scenario_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**範例 1：從配方建立元件版本**  
下列 `create-component-version` 範例會從配方檔案建立 Hello World 元件的版本。  

```
aws greengrassv2 create-component-version \
    --inline-recipe {{fileb://com.example.HelloWorld-1.0.0.json}}
```
`com.example.HelloWorld-1.0.0.json` 的內容：  

```
{
    "RecipeFormatVersion": "2020-01-25",
    "ComponentName": "com.example.HelloWorld",
    "ComponentVersion": "1.0.0",
    "ComponentDescription": "My first AWS IoT Greengrass component.",
    "ComponentPublisher": "Amazon",
    "ComponentConfiguration": {
        "DefaultConfiguration": {
            "Message": "world"
        }
    },
    "Manifests": [
        {
            "Platform": {
                "os": "linux"
            },
            "Lifecycle": {
                "Run": "echo 'Hello {configuration:/Message}'"
            }
        }
    ]
}
```
輸出：  

```
{
    "arn": "arn:aws:greengrass:us-west-2:123456789012:components:com.example.HelloWorld:versions:1.0.0",
    "componentName": "com.example.HelloWorld",
    "componentVersion": "1.0.0",
    "creationTimestamp": "2021-01-07T16:24:33.650000-08:00",
    "status": {
        "componentState": "REQUESTED",
        "message": "NONE",
        "errors": {}
    }
}
```
如需詳細資訊，請參閱《*AWS IoT Greengrass V2 開發人員指南*》中的[建立自訂元件](https://docs.aws.amazon.com/greengrass/v2/developerguide/create-components.html)和[上傳要部署的元件](https://docs.aws.amazon.com/greengrass/v2/developerguide/upload-components.html)。  
**範例 2：從 AWSLambda 函數建立元件版本**  
下列`create-component-version`範例會從 AWSLambda 函數建立 Hello World 元件的版本。  

```
aws greengrassv2 create-component-version \
    --cli-input-json {{file://lambda-function-component.json}}
```
`lambda-function-component.json` 的內容：  

```
{
    "lambdaFunction": {
        "lambdaArn": "arn:aws:lambda:us-west-2:123456789012:function:HelloWorldPythonLambda:1",
        "componentName": "com.example.HelloWorld",
        "componentVersion": "1.0.0",
        "componentLambdaParameters": {
            "eventSources": [
                {
                    "topic": "hello/world/+",
                    "type": "IOT_CORE"
                }
            ]
        }
    }
}
```
輸出：  

```
{
    "arn": "arn:aws:greengrass:us-west-2:123456789012:components:com.example.HelloWorld:versions:1.0.0",
    "componentName": "com.example.HelloWorld",
    "componentVersion": "1.0.0",
    "creationTimestamp": "2021-01-07T17:05:27.347000-08:00",
    "status": {
        "componentState": "REQUESTED",
        "message": "NONE",
        "errors": {}
    }
}
```
如需詳細資訊，請參閱 *AWSIoT Greengrass V2 開發人員指南*中的[執行 AWSLambda 函數](https://docs.aws.amazon.com/greengrass/v2/developerguide/run-lambda-functions.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [CreateComponentVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/create-component-version.html)。

------
#### [ Python ]

**適用於 Python 的 SDK (Boto3)**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/greengrassv2#code-examples)中設定和執行。

```
    def create_component_version(
        self, recipe: dict[str, Any], tags: Optional[dict[str, str]] = None
    ) -> dict[str, Any]:
        """
        Creates a component version from an inline JSON recipe.

        :param recipe: A dictionary representing the component recipe.
        :param tags: Optional tags to associate with the component.
        :return: A dictionary containing the component version details.
        """
        try:
            recipe_bytes = json.dumps(recipe).encode("utf-8")
            params = dict()
            params["inlineRecipe"] = recipe_bytes
            if tags is not None:
                params["tags"] = tags
            response = self.client.create_component_version(**params)
            logger.info(
                "Created component %s version %s.",
                response.get("componentName"),
                response.get("componentVersion"),
            )
            return response
        except ClientError as err:
            if err.response["Error"]["Code"] == "ConflictException":
                logger.error(
                    "A component version with the same name and version already exists. "
                    "Use a different version number or delete the existing version first. %s",
                    err.response["Error"]["Message"],
                )
            raise
```
+  如需 API 詳細資訊，請參閱《適用於 *AWSPython (Boto3) 的 SDK API 參考*》中的 [CreateComponentVersion](https://docs.aws.amazon.com/goto/boto3/greengrassv2-2020-11-30/CreateComponentVersion)。

------