

# Develop AWS IoT Greengrass components
<a name="develop-greengrass-components"></a>

You can develop and test components on your Greengrass core device. As a result, you can create and iterate your AWS IoT Greengrass software without interacting with the AWS Cloud. When you finish a version of your component, you can upload it to AWS IoT Greengrass in the cloud, so you and your team can deploy the component to other devices in your fleet. For more information about how to deploy components, see [Deploy AWS IoT Greengrass components to devices](manage-deployments.md).

Every component is composed of a *recipe* and *artifacts*.
+ <a name="component-recipe-definition"></a>**Recipes**

  Every component contains a recipe file, which defines its metadata. The recipe also specifies the component's configuration parameters, component dependencies, lifecycle, and platform compatibility. The component lifecycle defines the commands that install, run, and shut down the component. For more information, see [AWS IoT Greengrass component recipe reference](component-recipe-reference.md).

  You can define recipes in [JSON](https://en.wikipedia.org/wiki/JSON) or [YAML](https://en.wikipedia.org/wiki/YAML) format.
+ <a name="component-artifacts-definition"></a>**Artifacts**

  Components can have any number of artifacts, which are component binaries. Artifacts can include scripts, compiled code, static resources, and any other files that a component consumes. Components can also consume artifacts from component dependencies.

AWS IoT Greengrass provides pre-built components that you can use in your applications and deploy to your devices. For example, you can use the stream manager component to upload data to various AWS services, or you can use the CloudWatch metrics component to publish custom metrics to Amazon CloudWatch. For more information, see [AWS-provided components](public-components.md).

AWS IoT Greengrass curates an index of Greengrass components, called the Greengrass Software Catalog. This catalog tracks Greengrass components that are developed by the Greengrass community. From this catalog, you can download, modify, and deploy components to create your Greengrass applications. For more information, see [Community components](greengrass-software-catalog.md).

The AWS IoT Greengrass Core software runs components as the system user and group, such as `ggc_user` and `ggc_group`, that you configure on the core device. This means that components have the permissions of that system user. If you use a system user without a home directory, then components can't use run commands or code that use a home directory. This means that you can't use the `pip install some-library --user` command to install Python packages for example. If you followed the [getting started tutorial](getting-started.md) to set up your core device, then your system user doesn't have a home directory. For more information about how to configure the user and group that run components, see [Configure the user that runs components](configure-greengrass-core-v2.md#configure-component-user).

**Note**  <a name="semver-note"></a>
<a name="semver-para"></a>AWS IoT Greengrass uses semantic versions for components. Semantic versions follow a *major*.*minor*.*patch* number system. For example, version `1.0.0` represents the first major release for a component. For more information, see the [semantic version specification](https://semver.org/).

**Topics**
+ [

## Component lifecycle
](#component-lifecycle)
+ [

## Component types
](#component-types)
+ [

# Create AWS IoT Greengrass components
](create-components.md)
+ [

# Test AWS IoT Greengrass components with local deployments
](test-components.md)
+ [

# Publish components to deploy to your core devices
](publish-components.md)
+ [

# Interact with AWS services
](interact-with-aws-services.md)
+ [

# Run a Docker container
](run-docker-container.md)
+ [

# AWS IoT Greengrass component recipe reference
](component-recipe-reference.md)
+ [

# Component environment variable reference
](component-environment-variables.md)

## Component lifecycle
<a name="component-lifecycle"></a>

The *component lifecycle* defines the stages that the AWS IoT Greengrass Core software uses to install and run components. Each stage defines a script and other information that specifies how the component behaves. For example, when you install a component, the AWS IoT Greengrass Core software runs the `install` lifecycle script for that component. Components on core devices have the following lifecycle states:
+ `NEW` – The component's recipe and artifacts are loaded on the core device, but the component isn't installed. After a component enters this state, it runs its [install script](component-recipe-reference.md#install-lifecycle-definition).
+ `INSTALLED` – The component is installed on the core device. The component enters this state after it runs its [install script](component-recipe-reference.md#install-lifecycle-definition).
+ `STARTING` – The component is starting on the core device. The component enters this state when it runs its [startup script](component-recipe-reference.md#startup-lifecycle-definition). If the startup succeeds, the component enters the `RUNNING` state.
+ `RUNNING` – The component is running on the core device. The component enters this state when it runs its [run script](component-recipe-reference.md#run-lifecycle-definition) or when it has active background processes from its startup script.
+ `FINISHED` – The component ran successfully and completed its run.
+ `STOPPING` – The component is stopping. The component enters this state when it runs its [shutdown script](component-recipe-reference.md#shutdown-lifecycle-definition).
+ `ERRORED` – The component encountered an error. When the component enters this state, it runs its [recover script](component-recipe-reference.md#recover-lifecycle-definition). Then, the component restarts to try returning to normal use. If the component enters the `ERRORED` state three times without a successful run, the component becomes `BROKEN`.
+ `BROKEN` – The component encountered errors multiple times and can't recover. You must deploy the component again to fix it.
+ `UNINSTALLING` – The component is running its [uninstall script](component-recipe-reference.md#uninstall-lifecycle-definition) before permanent removal. The component enters this state when a deployment removes the component from the device. This state does not apply during component version upgrades.
+ `UNINSTALLED` – The component completed its uninstall lifecycle step and is removed from the device.

## Component types
<a name="component-types"></a>

The *component type* specifies how the AWS IoT Greengrass Core software runs the component. Components can have the following types:
+ **Nucleus** (`aws.greengrass.nucleus`)

  The Greengrass nucleus is the component that provides the minimum functionality of the AWS IoT Greengrass Core software. For more information, see [Greengrass nucleus](greengrass-nucleus-component.md).
+ **Plugin** (`aws.greengrass.plugin`)

  The Greengrass nucleus runs a plugin component in the same Java Virtual Machine (JVM) as the nucleus. The nucleus restarts when you change the version of a plugin component on a core device. To install and run plugin components, you must configure the Greengrass nucleus to run as a system service. For more information, see [Configure the Greengrass nucleus as a system service](configure-greengrass-core-v2.md#configure-system-service).

  Several components that are provided by AWS are plugin components, which enables them to interface directly with the Greengrass nucleus. Plugin components use the same log file as the Greengrass nucleus. For more information, see [Monitor AWS IoT Greengrass logs](monitor-logs.md).
+ **Generic** (`aws.greengrass.generic`)

  The Greengrass nucleus runs a generic component's lifecycle scripts, if the component defines a lifecycle.

  This type is the default type for custom components.
+ **Lambda** (`aws.greengrass.lambda`)

  The Greengrass nucleus runs a Lambda function component using the [Lambda launcher component](lambda-launcher-component.md).

  When you create a component from a Lambda function, the component has this type. For more information, see [Run AWS Lambda functions](run-lambda-functions.md).

**Note**  <a name="recipe-component-type-recommendation"></a>
We don't recommend that you specify the component type in a recipe. AWS IoT Greengrass sets the type for you when you create a component.

# Create AWS IoT Greengrass components
<a name="create-components"></a>

You can develop custom AWS IoT Greengrass components on a local development computer or a Greengrass core device. AWS IoT Greengrass provides the [AWS IoT Greengrass Development Kit Command-Line Interface (GDK CLI)](greengrass-development-kit-cli.md) to help you create, build, and publish components from predefined component templates and [community components](greengrass-software-catalog.md). You can also run built-in shell commands to create, build, and publish components. Choose from the following options to create custom Greengrass components:
+ **Use the Greengrass Development Kit CLI**

  Use the GDK CLI to develop components on a local development computer. The GDK CLI builds and packages component source code into a recipe and artifacts that you can publish as a private component to the AWS IoT Greengrass service. You can configure the GDK CLI to automatically update the component's version and artifact URIs when you publish the component, so you don't need to update the recipe each time. To develop a component using the GDK CLI, you can start from a template or a community component from the [Greengrass Software Catalog](greengrass-software-catalog.md). For more information, see [AWS IoT Greengrass Development Kit Command-Line Interface](greengrass-development-kit-cli.md).
+ **Run built-in shell commands**

  You can run built-in shell commands to develop components on a local development computer or on a Greengrass core device. You use shell commands to copy or build component source code into artifacts. Each time you create a new version of a component, you must create or update the recipe with the new component version. When you publish the component to the AWS IoT Greengrass service, you must update the URI to each component artifact in the recipe.

**Topics**
+ [

## Create a component (GDK CLI)
](#create-component-gdk-cli)
+ [

## Create a component (shell commands)
](#create-component-shell-commands)

## Create a component (GDK CLI)
<a name="create-component-gdk-cli"></a>

Follow instructions in this section to create and build a component using the GDK CLI.

**To develop a Greengrass component (GDK CLI)**

1. If you haven't already, install the GDK CLI on your development computer. For more information, see [Install or update the AWS IoT Greengrass Development Kit Command-Line Interface](install-greengrass-development-kit-cli.md).

1. Change to the folder where you want to create component folders.

------
#### [ Linux or Unix ]

   ```
   mkdir ~/greengrassv2
   cd ~/greengrassv2
   ```

------
#### [ Windows Command Prompt (CMD) ]

   ```
   mkdir %USERPROFILE%\greengrassv2
   cd %USERPROFILE%\greengrassv2
   ```

------
#### [ PowerShell ]

   ```
   mkdir ~/greengrassv2
   cd ~/greengrassv2
   ```

------

1. Choose a component template or community component to download. The GDK CLI downloads the template or community component, so you can start from a functional example. Use the [component list](greengrass-development-kit-cli-component.md#greengrass-development-kit-cli-component-list) command to retrieve the list of available templates or community components.
   + To list component templates, run the following command. Each line in the response includes a template's name and programming language.

     ```
     gdk component list --template
     ```
   + To list community components, run the following command.

     ```
     gdk component list --repository
     ```

1. Create and change to a component folder where the GDK CLI downloads the template or community component. Replace *HelloWorld* with the name of the component, or another name that helps you identify this component folder.

------
#### [ Linux or Unix ]

   ```
   mkdir HelloWorld
   cd HelloWorld
   ```

------
#### [ Windows Command Prompt (CMD) ]

   ```
   mkdir HelloWorld
   cd HelloWorld
   ```

------
#### [ PowerShell ]

   ```
   mkdir HelloWorld
   cd HelloWorld
   ```

------

1. Download the template or community component to the current folder. Use the [component init](greengrass-development-kit-cli-component.md#greengrass-development-kit-cli-component-init) command.
   + To create a component folder from a template, run the following command. Replace *HelloWorld* with the name of the template, and replace *python* with the name of the programming language.

     ```
     gdk component init --template HelloWorld --language python
     ```
   + To create a component folder from a community component, run the following command. Replace *ComponentName* with the name of the community component.

     ```
     gdk component init --repository ComponentName
     ```
**Note**  
<a name="gdk-cli-component-init-empty-folder-requirement"></a>If you use GDK CLI v1.0.0, you must run this command in an empty folder. The GDK CLI downloads the template or community component to the current folder.  
<a name="gdk-cli-component-init-empty-folder-requirement-gdk-cli-v1.1.0"></a>If you use GDK CLI v1.1.0 or later, you can specify the `--name` argument to specify the folder where the GDK CLI downloads the template or community component. If you use this argument, specify a folder that doesn't exist. The GDK CLI creates the folder for you. If you don't specify this argument, the GDK CLI uses the current folder, which must be empty.

1. The GDK CLI reads from the [GDK CLI configuration file](gdk-cli-configuration-file.md), named `gdk-config.json`, to build and publish components. This configuration file exists in the root of the component folder. The previous step creates this file for you. In this step, you update `gdk-config.json` with information about your component. Do the following:

   1. Open `gdk-config.json` in a text editor.

   1. (Optional) Change the name of the component. The component name is the key in the `component` object.

   1. Change the author of the component.

   1. (Optional) Change the version of the component. Specify one of the following:<a name="gdk-cli-configuration-file-component-version-options"></a>
      + `NEXT_PATCH` – When you choose this option, the GDK CLI sets the version when you publish the component. The GDK CLI queries the AWS IoT Greengrass service to identify the latest published version of the component. Then, it sets the version to the next patch version after that version. If you haven't published the component before, the GDK CLI uses version `1.0.0`.

        If you choose this option, you can't use the [Greengrass CLI](greengrass-cli-component.md) to locally deploy and test the component to your local development computer that runs the AWS IoT Greengrass Core software. To enable local deployments, you must specify a semantic version instead.
      + A semantic version, such as **1.0.0**. Semantic versions use a *major*.*minor*.*patch* numbering system. For more information, see the [semantic version specification](https://semver.org/).

        If you develop components on a Greengrass core device where you want to deploy and test the component, choose this option. You must build the component with a specific version to create local deployments with the [Greengrass CLI](greengrass-cli-component.md).

   1. (Optional) Change the build configuration for the component. The build configuration defines how the GDK CLI builds the component's source into artifacts. Choose from the following options for `build_system`:<a name="gdk-cli-configuration-file-component-build-system-options"></a>
      + `zip` – Packages the component's folder into a ZIP file to define as the component's only artifact. Choose this option for the following types of components:
        + Components that use interpreted programming languages, such as Python or JavaScript.
        + Components that package files other than code, such as machine learning models or other resources.

        The GDK CLI zips the component's folder into a zip file with the same name as the component folder. For example, if the component folder's name is `HelloWorld`, the GDK CLI creates a zip file named `HelloWorld.zip`.
**Note**  
If you use GDK CLI version 1.0.0 on a Windows device, the component folder and zip file names must contain only lowercase letters.

        When the GDK CLI zips the component's folder into a zip file, it skips the following files:
        + The `gdk-config.json` file
        + The recipe file (`recipe.json` or `recipe.yaml`)
        + Build folders, such as `greengrass-build`
      + `maven` – Runs the `mvn clean package` command to build the component's source into artifacts. Choose this option for components that use [Maven](https://maven.apache.org/), such as Java components.

        On Windows devices, this feature is available for GDK CLI v1.1.0 and later.
      + `gradle` – Runs the `gradle build` command to build the component's source into artifacts. Choose this option for components that use [Gradle](https://gradle.org/). This feature is available for GDK CLI v1.1.0 and later.

        The `gradle` build system supports Kotlin DSL as the build file. This feature is available for GDK CLI v1.2.0 and later.
      + `gradlew` – Runs the `gradlew` command to build the component's source into artifacts. Choose this option for components that use the [Gradle Wrapper ](https://docs.gradle.org/current/userguide/gradle_wrapper.html).

        This feature is available for GDK CLI v1.2.0 and later.
      + `custom` – Runs a custom command to build the component's source into a recipe and artifacts. Specify the custom command in the `custom_build_command` parameter.

   1. If you specify `custom` for `build_system`, add the `custom_build_command` to the `build` object. In `custom_build_command`, specify a single string or list of strings, where each string is a word in the command. For example, to run a custom build command for a C\$1\$1 component, you might specify **["cmake", "--build", "build", "--config", "Release"]**.

   1. <a name="gdk-cli-s3-bucket-name-formation"></a>If you use GDK CLI v1.1.0 or later, you can specify the `--bucket` argument to specify the S3 bucket where the GDK CLI uploads the component's artifacts. <a name="gdk-cli-s3-bucket-name-formation-format"></a>If you don't specify this argument, the GDK CLI uploads to the S3 bucket whose name is `bucket-region-accountId`, where *bucket* and *region* are the values that you specify in `gdk-config.json`, and *accountId* is your AWS account ID. The GDK CLI creates the bucket if it doesn't exist.

      Change the publish configuration for the component. Do the following:

      1. Specify the name of the S3 bucket to use to host component artifacts.

      1. Specify the AWS Region where the GDK CLI publishes the component.

   When you're done with this step, the `gdk-config.json` file might look similar to the following example.

   ```
   {
     "component": {
       "com.example.PythonHelloWorld": {
         "author": "Amazon",
         "version": "NEXT_PATCH",
         "build": {
           "build_system" : "zip"
         },
         "publish": {
           "bucket": "greengrass-component-artifacts",
           "region": "us-west-2"
         }
       }
     },
     "gdk_version": "1.0.0"
   }
   ```

1. Update the component recipe file, named `recipe.yaml` or `recipe.json`. Do the following:

   1. If you downloaded a template or community component that uses the `zip` build system, check that the zip artifact name matches the name of the component folder. The GDK CLI zips the component folder into a zip file with the same name as the component folder. The recipe contains the zip artifact name in the list of component artifacts and in lifecycle scripts that use files in the zip artifact. Update the `Artifacts` and `Lifecycle` definitions such that the zip file name matches the name of the component folder. The following partial recipe examples highlight the zip file name in the `Artifacts` and `Lifecycle` definitions.

------
#### [ JSON ]

      ```
      {
        ...
        "Manifests": [
          {
            "Platform": {
              "os": "all"
            },
            "Artifacts": [
              {
                "URI": "s3://{COMPONENT_NAME}/{COMPONENT_VERSION}/HelloWorld.zip",
                "Unarchive": "ZIP"
              }
            ],
            "Lifecycle": {
              "Run": "python3 -u {artifacts:decompressedPath}/HelloWorld/main.py {configuration:/Message}"
            }
          }
        ]
      }
      ```

------
#### [ YAML ]

      ```
      ---
      ...
      Manifests:
        - Platform:
            os: all
          Artifacts:
            - URI: "s3://BUCKET_NAME/COMPONENT_NAME/COMPONENT_VERSION/HelloWorld.zip"
              Unarchive: ZIP
          Lifecycle:
            Run: "python3 -u {artifacts:decompressedPath}/HelloWorld/main.py {configuration:/Message}"
      ```

------

   1. (Optional) Update the component description, default configuration, artifacts, lifecycle scripts, and platform support. For more information, see [AWS IoT Greengrass component recipe reference](component-recipe-reference.md).

   When you're done with this step, the recipe file might look similar to the following examples.

------
#### [ JSON ]

   ```
   {
     "RecipeFormatVersion": "2020-01-25",
     "ComponentName": "{COMPONENT_NAME}",
     "ComponentVersion": "{COMPONENT_VERSION}",
     "ComponentDescription": "This is a simple Hello World component written in Python.",
     "ComponentPublisher": "{COMPONENT_AUTHOR}",
     "ComponentConfiguration": {
       "DefaultConfiguration": {
         "Message": "World"
       }
     },
     "Manifests": [
       {
         "Platform": {
           "os": "all"
         },
         "Artifacts": [
           {
             "URI": "s3://{COMPONENT_NAME}/{COMPONENT_VERSION}/HelloWorld.zip",
             "Unarchive": "ZIP"
           }
         ],
         "Lifecycle": {
           "Run": "python3 -u {artifacts:decompressedPath}/HelloWorld/main.py {configuration:/Message}"
         }
       }
     ]
   }
   ```

------
#### [ YAML ]

   ```
   ---
   RecipeFormatVersion: "2020-01-25"
   ComponentName: "{COMPONENT_NAME}"
   ComponentVersion: "{COMPONENT_VERSION}"
   ComponentDescription: "This is a simple Hello World component written in Python."
   ComponentPublisher: "{COMPONENT_AUTHOR}"
   ComponentConfiguration:
     DefaultConfiguration:
       Message: "World"
   Manifests:
     - Platform:
         os: all
       Artifacts:
         - URI: "s3://BUCKET_NAME/COMPONENT_NAME/COMPONENT_VERSION/HelloWorld.zip"
           Unarchive: ZIP
       Lifecycle:
         Run: "python3 -u {artifacts:decompressedPath}/HelloWorld/main.py {configuration:/Message}"
   ```

------

1. Develop and build the Greengrass component. The [component build](greengrass-development-kit-cli-component.md#greengrass-development-kit-cli-component-build) command produces a recipe and artifacts in the `greengrass-build` folder in the component folder. Run the following command.

   ```
   gdk component build
   ```

When you're ready to test your component, use the GDK CLI to publish it to the AWS IoT Greengrass service. Then, you can deploy the component to Greengrass core devices. For more information, see [Publish components to deploy to your core devices](publish-components.md).

## Create a component (shell commands)
<a name="create-component-shell-commands"></a>

Follow instructions in this section to create recipe and artifact folders that contain source code and artifacts for multiple components.

**To develop a Greengrass component (shell commands)**

1. <a name="create-component-recipes-artifacts-folder-step"></a>Create a folder for your components with subfolders for recipes and artifacts. Run the following commands on your Greengrass core device to create these folders and change to the component folder. Replace *\$1/greengrassv2* or *%USERPROFILE%\$1greengrassv2* with the path to the folder to use for local development.

------
#### [ Linux or Unix ]

   ```
   mkdir -p ~/greengrassv2/{recipes,artifacts}
   cd ~/greengrassv2
   ```

------
#### [ Windows Command Prompt (CMD) ]

   ```
   mkdir %USERPROFILE%\greengrassv2\\recipes, %USERPROFILE%\greengrassv2\\artifacts
   cd %USERPROFILE%\greengrassv2
   ```

------
#### [ PowerShell ]

   ```
   mkdir ~/greengrassv2/recipes, ~/greengrassv2/artifacts
   cd ~/greengrassv2
   ```

------

1. <a name="create-component-recipe-file-step"></a>Use a text editor to create a recipe file that defines your component's metadata, parameters, dependencies, lifecycle, and platform capability. Include the component version in the recipe file name so that you can identify which recipe reflects which component version. You can choose YAML or JSON format for your recipe.

   <a name="nano-command-intro"></a>For example, on a Linux-based system, you can run the following command to use GNU nano to create the file.

------
#### [ JSON ]

   ```
   nano recipes/com.example.HelloWorld-1.0.0.json
   ```

------
#### [ YAML ]

   ```
   nano recipes/com.example.HelloWorld-1.0.0.yaml
   ```

------
**Note**  
<a name="semver-para"></a>AWS IoT Greengrass uses semantic versions for components. Semantic versions follow a *major*.*minor*.*patch* number system. For example, version `1.0.0` represents the first major release for a component. For more information, see the [semantic version specification](https://semver.org/).

1. Define the recipe for your component. For more information, see [AWS IoT Greengrass component recipe reference](component-recipe-reference.md).

   Your recipe might look similar to the following Hello World example recipe.

------
#### [ 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": "python3 -u {artifacts:path}/hello_world.py {configuration:/Message}"
         }
       },
       {
         "Platform": {
           "os": "windows"
         },
         "Lifecycle": {
           "run": "py -3 -u {artifacts:path}/hello_world.py {configuration:/Message}"
         }
       }
     ]
   }
   ```

------
#### [ YAML ]

   ```
   ---
   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: |
           python3 -u {artifacts:path}/hello_world.py "{configuration:/Message}"
     - Platform:
         os: windows
       Lifecycle:
         run: |
           py -3 -u {artifacts:path}/hello_world.py "{configuration:/Message}"
   ```

------

   This recipe runs a Hello World Python script, which might look similar to the following example script.

   ```
   import sys
   
   message = "Hello, %s!" % sys.argv[1]
   
   # Print the message to stdout, which Greengrass saves in a log file.
   print(message)
   ```

1. Create a folder for the component version to develop. We recommend that you use a separate folder for each component version's artifacts so that you can identify which artifacts are for each component version. Run the following command.

------
#### [ Linux or Unix ]

   ```
   mkdir -p artifacts/com.example.HelloWorld/1.0.0
   ```

------
#### [ Windows Command Prompt (CMD) ]

   ```
   mkdir artifacts/com.example.HelloWorld/1.0.0
   ```

------
#### [ PowerShell ]

   ```
   mkdir artifacts/com.example.HelloWorld/1.0.0
   ```

------
**Important**  <a name="local-artifact-folder-name-requirements"></a>
You must use the following format for the artifact folder path. Include the component name and version that you specify in the recipe.  

   ```
   artifacts/componentName/componentVersion/
   ```

1. Create the artifacts for your component in the folder that you created in the previous step. Artifacts can include software, images, and any other binaries that your component uses.

   When your component is ready, [test your component](test-components.md).

# Test AWS IoT Greengrass components with local deployments
<a name="test-components"></a>

If you develop a Greengrass component on a core device, you can create a local deployment to install and test it. Follow the steps in this section to create a local deployment.

If you develop the component on a different computer, such as a local development computer, you can't create a local deployment. Instead, publish the component to the AWS IoT Greengrass service so that you can deploy it to Greengrass core devices to test it. For more information, see [Publish components to deploy to your core devices](publish-components.md) and [Deploy AWS IoT Greengrass components to devices](manage-deployments.md).

**To test a component on an Greengrass core device**

1. The core device logs events such as component updates. You can view this log file to discover and troubleshoot errors with your component, such as an invalid recipe. This log file also displays messages that your component prints to standard out (stdout). We recommend that you open an additional terminal session on your core device to observe new log messages in real time. Open a new terminal session, such as through SSH, and run the following command to view the logs. Replace `/greengrass/v2` with the path to the AWS IoT Greengrass root folder.

------
#### [ Linux or Unix ]

   ```
   sudo tail -f /greengrass/v2/logs/greengrass.log
   ```

------
#### [ PowerShell ]

   ```
   gc C:\greengrass\v2\logs\greengrass.log -Tail 10 -Wait
   ```

------

   You can also view the log file for your component.

------
#### [ Linux or Unix ]

   ```
   sudo tail -f /greengrass/v2/logs/com.example.HelloWorld.log
   ```

------
#### [ PowerShell ]

   ```
   gc C:\greengrass\v2\logs\com.example.HelloWorld.log -Tail 10 -Wait
   ```

------

1. In your original terminal session, run the following command to update the core device with your component. Replace `/greengrass/v2` with the path to the AWS IoT Greengrass root folder, and replace *\$1/greengrassv2* with the path to your local development folder.

------
#### [ Linux or Unix ]

   ```
   sudo /greengrass/v2/bin/greengrass-cli deployment create \
     --recipeDir ~/greengrassv2/recipes \
     --artifactDir ~/greengrassv2/artifacts \
     --merge "com.example.HelloWorld=1.0.0"
   ```

------
#### [ Windows Command Prompt (CMD) ]

   ```
   C:\greengrass\v2\bin\greengrass-cli deployment create ^
     --recipeDir %USERPROFILE%\greengrassv2\recipes ^
     --artifactDir %USERPROFILE%\greengrassv2\artifacts ^
     --merge "com.example.HelloWorld=1.0.0"
   ```

------
#### [ PowerShell ]

   ```
   C:\greengrass\v2\bin\greengrass-cli deployment create `
     --recipeDir ~/greengrassv2/recipes `
     --artifactDir ~/greengrassv2/artifacts `
     --merge "com.example.HelloWorld=1.0.0"
   ```

------
**Note**  
You can also use the `greengrass-cli deployment create` command to set the value of your component's configuration parameters. For more information, see [create](gg-cli-deployment.md#deployment-create).

1. Use the `greengrass-cli deployment status` command to monitor the progress of your component's deployment. 

------
#### [ Unix or Linux ]

   ```
   sudo /greengrass/v2/bin/greengrass-cli deployment status \
     -i deployment-id
   ```

------
#### [ Windows Command Prompt (CMD) ]

   ```
   C:\greengrass\v2\bin\greengrass-cli deployment status ^
     -i deployment-id
   ```

------
#### [ PowerShell ]

   ```
   C:\greengrass\v2\bin\greengrass-cli deployment status `
     -i deployment-id
   ```

------

1. Test your component as it runs on the Greengrass core device. When you finish this version of your component, you can upload it to the AWS IoT Greengrass service. Then, you can deploy the component to other core devices. For more information, see [Publish components to deploy to your core devices](publish-components.md).

# Publish components to deploy to your core devices
<a name="publish-components"></a>

After you build or complete a version of a component, you can publish it to the AWS IoT Greengrass service. Then, you can deploy it to Greengrass core devices.

If you use the [Greengrass Development Kit CLI (GDK CLI)](greengrass-development-kit-cli.md) to [develop and build a component](create-components.md), you can [use the GDK CLI](#publish-component-gdk-cli) to publish the component to the AWS Cloud. Otherwise, [use built-in shell commands and the AWS CLI](#publish-component-shell-commands) to publish the component.

You can also use AWS CloudFormation to create components and other AWS resources from templates. For more information, see [What is AWS CloudFormation?](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) and [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-greengrassv2-componentversion.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-greengrassv2-componentversion.html) in the *AWS CloudFormation User Guide*.

**Topics**
+ [

## Publish a component (GDK CLI)
](#publish-component-gdk-cli)
+ [

## Publish a component (shell commands)
](#publish-component-shell-commands)

## Publish a component (GDK CLI)
<a name="publish-component-gdk-cli"></a>

Follow instructions in this section to publish a component using the GDK CLI. The GDK CLI uploads build artifacts to an S3 bucket, updates the artifact URIs in the recipe, and creates the component from the recipe. You specify the S3 bucket and Region to use in the [GDK CLI configuration file](gdk-cli-configuration-file.md).

<a name="gdk-cli-s3-bucket-name-formation"></a>If you use GDK CLI v1.1.0 or later, you can specify the `--bucket` argument to specify the S3 bucket where the GDK CLI uploads the component's artifacts. <a name="gdk-cli-s3-bucket-name-formation-format"></a>If you don't specify this argument, the GDK CLI uploads to the S3 bucket whose name is `bucket-region-accountId`, where *bucket* and *region* are the values that you specify in `gdk-config.json`, and *accountId* is your AWS account ID. The GDK CLI creates the bucket if it doesn't exist.

**Important**  <a name="publish-component-s3-bucket-token-exchange-role-permissions"></a>
Core device roles don't allow access to S3 buckets by default. If this is your first time using this S3 bucket, you must add permissions to the role to allow core devices to retrieve component artifacts from this S3 bucket. For more information, see [Allow access to S3 buckets for component artifacts](device-service-role.md#device-service-role-access-s3-bucket).

**To publish a Greengrass component (GDK CLI)**

1. Open the component folder in a command prompt or terminal.

1. If you haven't already, build the Greengrass component. The [component build](greengrass-development-kit-cli-component.md#greengrass-development-kit-cli-component-build) command produces a recipe and artifacts in the `greengrass-build` folder in the component folder. Run the following command.

   ```
   gdk component build
   ```

1. Publish the component to the AWS Cloud. The [component publish](greengrass-development-kit-cli-component.md#greengrass-development-kit-cli-component-publish) command uploads the component's artifacts to Amazon S3 and updates the component's recipe with each artifact's URI. Then, it creates the component in the AWS IoT Greengrass service.
**Note**  <a name="publish-component-s3-bucket-artifact-digest-warning"></a>
AWS IoT Greengrass computes the digest of each artifact when you create the component. This means that you can't modify the artifact files in your S3 bucket after you create a component. If you do, deployments that include this component will fail, because the file digest doesn't match. If you modify an artifact file, you must create a new version of the component.

   If you specify `NEXT_PATCH` for the component version in the GDK CLI configuration file, the GDK CLI uses the next patch version that doesn't already exist in the AWS IoT Greengrass service.

   Run the following command.

   ```
   gdk component publish
   ```

   The output tells you the version of the component that the GDK CLI created.

   After you publish the component, you can deploy the component to core devices. For more information, see [Deploy AWS IoT Greengrass components to devices](manage-deployments.md).

## Publish a component (shell commands)
<a name="publish-component-shell-commands"></a>

Use the following procedure to publish a component using shell commands and the AWS Command Line Interface (AWS CLI). When you publish a component, you do the following:

1. Publish component artifacts to an S3 bucket.

1. Add each artifact's Amazon S3 URI to the component recipe.

1. Create a component version in AWS IoT Greengrass from the component recipe.

**Note**  <a name="component-version-uniqueness-note"></a>
<a name="component-version-uniqueness-para"></a>Each component version that you upload must be unique. Make sure that you upload the correct component version, because you can't edit it after you upload it.

You can follow these steps to publish a component from your development computer or your Greengrass core device.

**To publish a component (shell commands)**

1. If the component uses a version that exists in the AWS IoT Greengrass service, then you must change the version of the component. Open the recipe in a text editor, increment the version, and save the file. Choose a new version that reflects the changes that you made to the component.
**Note**  <a name="semver-note"></a>
<a name="semver-para"></a>AWS IoT Greengrass uses semantic versions for components. Semantic versions follow a *major*.*minor*.*patch* number system. For example, version `1.0.0` represents the first major release for a component. For more information, see the [semantic version specification](https://semver.org/).

1. If your component has artifacts, do the following:

   1. Publish the component's artifacts to an S3 bucket in your AWS account.
**Tip**  <a name="artifact-path-tip"></a>
We recommend that you include the component name and version in the path to the artifact in the S3 bucket. This naming scheme can help you maintain the artifacts that previous versions of the component use, so you can continue to support previous component versions.

      Run the following command to publish an artifact file to an S3 bucket. Replace amzn-s3-demo-bucket with the name of the bucket, and replace *artifacts/com.example.HelloWorld/1.0.0/artifact.py* with the path to the artifact file.

      ```
      aws s3 cp artifacts/com.example.HelloWorld/1.0.0/artifact.py s3://amzn-s3-demo-bucket/artifacts/com.example.HelloWorld/1.0.0/artifact.py
      ```
**Important**  <a name="publish-component-s3-bucket-token-exchange-role-permissions"></a>
Core device roles don't allow access to S3 buckets by default. If this is your first time using this S3 bucket, you must add permissions to the role to allow core devices to retrieve component artifacts from this S3 bucket. For more information, see [Allow access to S3 buckets for component artifacts](device-service-role.md#device-service-role-access-s3-bucket).

   1. Add a list named `Artifacts` to the component recipe if it isn't present. The `Artifacts` list appears in each manifest, which defines the component's requirements on each platform that it supports (or the component's default requirements for all platforms).

   1. Add each artifact to the list of artifacts, or update the URI of existing artifacts. The Amazon S3 URI is composed of the bucket name and the path to the artifact object in the bucket. Your artifacts' Amazon S3 URIs should look similar to the following example.

      ```
      s3://amzn-s3-demo-bucket/artifacts/com.example.HelloWorld/1.0.0/artifact.py
      ```

   After you complete these steps, your recipe should have an `Artifacts` list that looks like the following.

------
#### [ JSON ]

   ```
   {
     ...
     "Manifests": [
       {
         "Lifecycle": {
           ...
         },
         "Artifacts": [
           {
             "URI": "s3://amzn-s3-demo-bucket/artifacts/MyGreengrassComponent/1.0.0/artifact.py",
             "Unarchive": "NONE"
           }
         ]
       }
     ]
   }
   ```

**Note**  
You can add the `"Unarchive": "ZIP"` option for a ZIP artifact to configure the AWS IoT Greengrass Core software to unzip the artifact when the component deploys.

------
#### [ YAML ]

   ```
   ...
   Manifests:
     - Lifecycle:
         ...
       Artifacts:
         - URI: s3://amzn-s3-demo-bucket/artifacts/MyGreengrassComponent/1.0.0/artifact.py
           Unarchive: NONE
   ```

**Note**  
You can use the `Unarchive: ZIP` option to configure the AWS IoT Greengrass Core software to unzip a ZIP artifact when the component deploys. For more information about how to use ZIP artifacts in a component, see the [artifacts:decompressedPath recipe variable](component-recipe-reference.md#component-recipe-artifacts-decompressed-path).

------

   For more information about recipes, see [AWS IoT Greengrass component recipe reference](component-recipe-reference.md).

1. Use the AWS IoT Greengrass console to create a component from the recipe file.

   Run the following command to create the component from a recipe file. This command creates the component and publishes it as a private AWS IoT Greengrass component in your AWS account. Replace *path/to/recipeFile* with the path to the recipe file.

   ```
   aws greengrassv2 create-component-version --inline-recipe fileb://path/to/recipeFile
   ```

   Copy the `arn` from the response to check the state of the component in the next step.
**Note**  <a name="publish-component-s3-bucket-artifact-digest-warning"></a>
AWS IoT Greengrass computes the digest of each artifact when you create the component. This means that you can't modify the artifact files in your S3 bucket after you create a component. If you do, deployments that include this component will fail, because the file digest doesn't match. If you modify an artifact file, you must create a new version of the component.

1. Each component in the AWS IoT Greengrass service has a state. Run the following command to confirm the state of the component version that you publish in this procedure. Replace *com.example.HelloWorld* and *1.0.0* with the component version to query. Replace the `arn` with the ARN from the previous step.

   ```
   aws greengrassv2 describe-component --arn "arn:aws:greengrass:region:account-id:components:com.example.HelloWorld:versions:1.0.0"
   ```

   The operation returns a response that contains the component's metadata. The metadata contains a `status` object that contains the component state and any errors, if applicable.

   When the component state is `DEPLOYABLE`, you can deploy the component to devices. For more information, see [Deploy AWS IoT Greengrass components to devices](manage-deployments.md).

# Interact with AWS services
<a name="interact-with-aws-services"></a>

Greengrass core devices use X.509 certificates to connect to AWS IoT Core using TLS mutual authentication protocols. These certificates let devices interact with AWS IoT without AWS credentials, which typically comprise an access key ID and a secret access key. Other AWS services require AWS credentials instead of X.509 certificates to call API operations at service endpoints. AWS IoT Core has a credentials provider that enables devices to use their X.509 certificate to authenticate AWS requests. The AWS IoT credentials provider authenticates devices using an X.509 certificate and issues AWS credentials in the form a temporary, limited-privilege security token. Devices can use this token to sign and authenticate any AWS request. This eliminates the need to store AWS credentials on Greengrass core devices. For more information, see [Authorizing direct calls to AWS services](https://docs.aws.amazon.com/iot/latest/developerguide/authorizing-direct-aws.html) in the *AWS IoT Core Developer Guide*.

To fetch credentials from AWS IoT, Greengrass, core devices use an AWS IoT role alias that points to an IAM role. This IAM role is called the *token exchange role*. You create the role alias and token exchange role when you install the AWS IoT Greengrass Core software. To specify the role alias that a core device uses, configure the `iotRoleAlias` parameter of the [Greengrass nucleus](greengrass-nucleus-component.md).

The AWS IoT credentials provider assumes the token exchange role on your behalf to provide AWS credentials to core devices. You can attach appropriate IAM policies to this role to allow your core devices access to your AWS resources, such as components artifacts in S3 buckets. For more information about how to configure the token exchange role, see [Authorize core devices to interact with AWS services](device-service-role.md).

Greengrass core devices store AWS credentials in memory, and the credentials expire after an hour by default. If the AWS IoT Greengrass Core software restarts, it must fetch credentials again. You can use the [UpdateRoleAlias](https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateRoleAlias.html) operation to configure the duration that credentials are valid.

AWS IoT Greengrass provides a public component, the token exchange service component, that you can define as a dependency in your custom component to interact with AWS services. The token exchange service provides your component with an environment variable, `AWS_CONTAINER_CREDENTIALS_FULL_URI`, that defines the URI to a local server that provides AWS credentials. When you create an AWS SDK client, the client checks for this environment variable and connects to the local server to retrieve AWS credentials and uses them to sign API requests. This lets you use AWS SDKs and other tools to call AWS services in your components. For more information, see [Token exchange service](token-exchange-service-component.md).

**Important**  <a name="token-exchange-service-aws-sdk-requirement"></a>
Support to acquire AWS credentials in this way was added to the AWS SDKs on July 13th, 2016. Your component must use an AWS SDK version that was created on or after that date. For more information, see [Using a supported AWS SDK](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html#task-iam-roles-minimum-sdk) in the *Amazon Elastic Container Service Developer Guide*.

To acquire AWS credentials in your custom component, define `aws.greengrass.TokenExchangeService` as a dependency in the component recipe. The following example recipe defines a component that installs [boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) and runs a Python script that uses AWS credentials from the token exchange service to list Amazon S3 buckets.

**Note**  
To run this example component, your device must have the `s3:ListAllMyBuckets` permission. For more information, see [Authorize core devices to interact with AWS services](device-service-role.md).

------
#### [ JSON ]

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.ListS3Buckets",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "A component that uses the token exchange service to list S3 buckets.",
  "ComponentPublisher": "Amazon",
  "ComponentDependencies": {
    "aws.greengrass.TokenExchangeService": {
      "VersionRequirement": "^2.0.0",
      "DependencyType": "HARD"
    }
  },
  "Manifests": [
    {
      "Platform": {
        "os": "linux"
      },
      "Lifecycle": {
        "install": "pip3 install --user boto3",
        "Run": "python3 -u {artifacts:path}/list_s3_buckets.py"
      }
    },
    {
      "Platform": {
        "os": "windows"
      },
      "Lifecycle": {
        "install": "pip3 install --user boto3",
        "Run": "py -3 -u {artifacts:path}/list_s3_buckets.py"
      }
    }
  ]
}
```

------
#### [ YAML ]

```
---
RecipeFormatVersion: '2020-01-25'
ComponentName: com.example.ListS3Buckets
ComponentVersion: '1.0.0'
ComponentDescription: A component that uses the token exchange service to list S3 buckets.
ComponentPublisher: Amazon
ComponentDependencies:
  aws.greengrass.TokenExchangeService:
    VersionRequirement: '^2.0.0'
    DependencyType: HARD
Manifests:
  - Platform:
      os: linux
    Lifecycle:
      install:
        pip3 install --user boto3
      Run: |-
        python3 -u {artifacts:path}/list_s3_buckets.py
  - Platform:
      os: windows
    Lifecycle:
      install:
        pip3 install --user boto3
      Run: |-
        py -3 -u {artifacts:path}/list_s3_buckets.py
```

------

This example component runs the following Python script, `list_s3_buckets.py` that lists Amazon S3 buckets.

```
import boto3
import os

try:
    print("Creating boto3 S3 client...")
    s3 = boto3.client('s3')
    print("Successfully created boto3 S3 client")
except Exception as e:
    print("Failed to create boto3 s3 client. Error: " + str(e))
    exit(1)

try:
    print("Listing S3 buckets...")
    response = s3.list_buckets()
    for bucket in response['Buckets']:
        print(f'\t{bucket["Name"]}')
    print("Successfully listed S3 buckets")
except Exception as e:
    print("Failed to list S3 buckets. Error: " + str(e))
    exit(1)
```

# Run a Docker container
<a name="run-docker-container"></a>

You can configure AWS IoT Greengrass components to run a [Docker](https://www.docker.com/) container from images stored in the following locations:
+ Public and private image repositories in Amazon Elastic Container Registry (Amazon ECR)
+ Public Docker Hub repository
+ Public Docker Trusted Registry
+ S3 bucket

In your custom component, include the Docker image URI as an artifact to retrieve the image and run it on the core device. For Amazon ECR and Docker Hub images, you can use the [Docker application manager](docker-application-manager-component.md) component to download the images and manage credentials for private Amazon ECR repositories.

**Topics**
+ [

## Requirements
](#run-docker-container-requirements)
+ [

## Run a Docker container from a public image in Amazon ECR or Docker Hub
](#run-docker-container-public-ecr-dockerhub)
+ [

## Run a Docker container from a private image in Amazon ECR
](#run-docker-container-private-ecr)
+ [

## Run a Docker container from an image in Amazon S3
](#run-docker-container-s3)
+ [

## Use interprocess communication in Docker container components
](#docker-container-ipc)
+ [

## Use AWS credentials in Docker container components (Linux)
](#docker-container-token-exchange-service)
+ [

## Use stream manager in Docker container components (Linux)
](#docker-container-stream-manager)

## Requirements
<a name="run-docker-container-requirements"></a>

To run a Docker container in a component, you need the following:
+ A Greengrass core device. If you don't have one, see [Tutorial: Getting started with AWS IoT Greengrass V2](getting-started.md).
+ <a name="docker-engine-requirement"></a>[Docker Engine](https://docs.docker.com/engine/) 1.9.1 or later installed on the Greengrass core device. Version 20.10 is the latest version that is verified to work with the AWS IoT Greengrass Core software. You must install Docker directly on the core device before you deploy components that run Docker containers.
**Tip**  
You can also configure the core device to install Docker Engine when the component installs. For example, the following install script installs Docker Engine before it loads the Docker image. This install script works on Debian-based Linux distributions, such as Ubuntu. If you configure the component to install Docker Engine with this command, you may need to set `RequiresPrivilege` to `true` in the lifecycle script to run the installation and `docker` commands. For more information, see [AWS IoT Greengrass component recipe reference](component-recipe-reference.md).  

  ```
  apt-get install docker-ce docker-ce-cli containerd.io && docker load -i {artifacts:path}/hello-world.tar
  ```
+ <a name="docker-user-permissions-requirement"></a>The system user that runs a Docker container component must have root or administrator permissions, or you must configure Docker to run it as a non-root or non-admistrator user.
  + On Linux devices, you can add a user to the `docker` group to call `docker` commands without `sudo`.
  + On Windows devices, you can add a user to the `docker-users` group to call `docker` commands without adminstrator privileges.

------
#### [ Linux or Unix ]

  To add `ggc_user`, or the non-root user that you use to run Docker container components, to the `docker` group, run the following command.

  ```
  sudo usermod -aG docker ggc_user
  ```

  For more information, see [Manage Docker as a non-root user](https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user).

------
#### [ Windows Command Prompt (CMD) ]

  To add `ggc_user`, or the user that you use to run Docker container components, to the `docker-users` group, run the following command as an administrator.

  ```
  net localgroup docker-users ggc_user /add
  ```

------
#### [ Windows PowerShell ]

  To add `ggc_user`, or the user that you use to run Docker container components, to the `docker-users` group, run the following command as an administrator.

  ```
  Add-LocalGroupMember -Group docker-users -Member ggc_user
  ```

------
+ Files accessed by the Docker container component [mounted as a volume](https://docs.docker.com/storage/volumes/) in the Docker container.
+ <a name="docker-proxy-requirement"></a>If you [configure the AWS IoT Greengrass Core software to use a network proxy](configure-greengrass-core-v2.md#configure-alpn-network-proxy), you must [configure Docker to use the same proxy server](https://docs.docker.com/network/proxy/).

In addition to these requirements, you must also meet the following requirements if they apply to your environment:
+ To use [Docker Compose](https://docs.docker.com/compose/) to create and start your Docker containers, install Docker Compose on your Greengrass core device, and upload your Docker Compose file to an S3 bucket. You must store your Compose file in an S3 bucket in the same AWS account and AWS Region as the component. For an example that uses the `docker-compose up` command in a custom component, see [Run a Docker container from a public image in Amazon ECR or Docker Hub](#run-docker-container-public-ecr-dockerhub).
+ If you run AWS IoT Greengrass behind a network proxy, configure the Docker daemon to use a [proxy server](https://docs.docker.com/network/proxy/). 
+ If your Docker images are stored in Amazon ECR or Docker Hub, include the [Docker component manager](docker-application-manager-component.md) component as a dependency in your Docker container component. You must start the Docker daemon on the core device before you deploy your component. 

  Also, include the image URIs as component artifacts. Image URIs must be in the format `docker:registry/image[:tag|@digest]` as shown in the following examples:<a name="docker-image-artifact-uri"></a>
  + Private Amazon ECR image: `docker:account-id.dkr.ecr.region.amazonaws.com/repository/image[:tag|@digest]`
  + Public Amazon ECR image: `docker:public.ecr.aws/repository/image[:tag|@digest]`
  + Public Docker Hub image: `docker:name[:tag|@digest]`

  For more information about running Docker containers from images stored in public repositories, see [Run a Docker container from a public image in Amazon ECR or Docker Hub](#run-docker-container-public-ecr-dockerhub).
+ If your Docker images are stored in an Amazon ECR private repository, then you must include the token exchange service component as a dependency in the Docker container component. Also, the [Greengrass device role](device-service-role.md) must allow the `ecr:GetAuthorizationToken`, `ecr:BatchGetImage`, and `ecr:GetDownloadUrlForLayer` actions, as shown in the following example IAM policy. 

------
#### [ JSON ]

****  

  ```
  {
    "Version":"2012-10-17",		 	 	 
    "Statement": [
      {
        "Action": [
          "ecr:GetAuthorizationToken",
          "ecr:BatchGetImage",
          "ecr:GetDownloadUrlForLayer"
        ],
        "Resource": [
          "*"
        ],
        "Effect": "Allow"
      }
    ]
  }
  ```

------

  For information about running Docker containers from images stored in an Amazon ECR private repository, see [Run a Docker container from a private image in Amazon ECR](#run-docker-container-private-ecr).
+ To use Docker images stored in an Amazon ECR private repository, the private repository must be in the same AWS Region as the core device.
+ If your Docker images or Compose files are stored in an S3 bucket, the [Greengrass device role](device-service-role.md) must allow the `s3:GetObject` permission to allow core devices to download the images as component artifacts, as shown in the following example IAM policy. 

------
#### [ JSON ]

****  

  ```
  {
    "Version":"2012-10-17",		 	 	 
    "Statement": [
      {
        "Action": [
          "s3:GetObject"
        ],
        "Resource": [
          "*"
        ],
        "Effect": "Allow"
      }
    ]
  }
  ```

------

  For information about running Docker containers from images stored in Amazon S3, see [Run a Docker container from an image in Amazon S3](#run-docker-container-s3).
+ <a name="docker-greengrass-features-requirements"></a>To use interprocess communication (IPC), AWS credentials, or stream manager in your Docker container component, you must specify additional options when you run the Docker container. For more information, see the following:<a name="docker-greengrass-features-requirements-links"></a>
  + [Use interprocess communication in Docker container components](#docker-container-ipc)
  + [Use AWS credentials in Docker container components (Linux)](#docker-container-token-exchange-service)
  + [Use stream manager in Docker container components (Linux)](#docker-container-stream-manager)

## Run a Docker container from a public image in Amazon ECR or Docker Hub
<a name="run-docker-container-public-ecr-dockerhub"></a>

This section describes how you can create a custom component that uses Docker Compose to run a Docker container from Docker images that are stored Amazon ECR and Docker Hub.

**To run a Docker container using Docker Compose**

1. Create and upload a Docker Compose file to an Amazon S3 bucket. Make sure that the [Greengrass device role](device-service-role.md) allows the `s3:GetObject` permission to enable the device to access the Compose file. The example Compose file shown in the following example includes the Amazon CloudWatch Agent image from Amazon ECR and the MySQL image from Docker Hub.

   ```
   version: "3"
   services:
     cloudwatchagent:
       image: "public.ecr.aws/cloudwatch-agent/cloudwatch-agent:latest"
     mysql:
       image: "mysql:8.0"
   ```

1. [Create a custom component](create-components.md) on your AWS IoT Greengrass core device. The example recipe shown in the following example has the following properties:
   + The Docker application manager component as a dependency. This component enables AWS IoT Greengrass to download images from public Amazon ECR and Docker Hub repositories.
   + A component artifact that specifies a Docker image in a public Amazon ECR repository.
   + A component artifact that specifies a Docker image in a public Docker Hub repository.
   + A component artifact that specifies the Docker Compose file that includes containers for the Docker images that you want to run. 
   + A lifecycle run script that uses [docker-compose up](https://docs.docker.com/compose/reference/up/) to create and start a container from the specified images.

------
#### [ JSON ]

   ```
   {
     "RecipeFormatVersion": "2020-01-25",
     "ComponentName": "com.example.MyDockerComposeComponent",
     "ComponentVersion": "1.0.0",
     "ComponentDescription": "A component that uses Docker Compose to run images from public Amazon ECR and Docker Hub.",
     "ComponentPublisher": "Amazon",
     "ComponentDependencies": {
       "aws.greengrass.DockerApplicationManager": {
         "VersionRequirement": "~2.0.0"
       }
     },
     "Manifests": [
       {
         "Platform": {
           "os": "all"
         },
         "Lifecycle": {
           "Run": "docker-compose -f {artifacts:path}/docker-compose.yaml up"
         },
         "Artifacts": [
           {
             "URI": "docker:public.ecr.aws/cloudwatch-agent/cloudwatch-agent:latest"
           },
           {
             "URI": "docker:mysql:8.0"
           },
           {
             "URI": "s3://amzn-s3-demo-bucket/folder/docker-compose.yaml"
           }
         ]
       }
     ]
   }
   ```

------
#### [ YAML ]

   ```
   ---
   RecipeFormatVersion: '2020-01-25'
   ComponentName: com.example.MyDockerComposeComponent
   ComponentVersion: '1.0.0'
   ComponentDescription: 'A component that uses Docker Compose to run images from public Amazon ECR and Docker Hub.'
   ComponentPublisher: Amazon
   ComponentDependencies:
     aws.greengrass.DockerApplicationManager:
       VersionRequirement: ~2.0.0
   Manifests:
     - Platform:
         os: all
       Lifecycle:
           Run: docker-compose -f {artifacts:path}/docker-compose.yaml up
       Artifacts:
         - URI: "docker:public.ecr.aws/cloudwatch-agent/cloudwatch-agent:latest"
         - URI: "docker:mysql:8.0"
         - URI: "s3://amzn-s3-demo-bucket/folder/docker-compose.yaml"
   ```

------
**Note**  
<a name="docker-greengrass-features-requirements"></a>To use interprocess communication (IPC), AWS credentials, or stream manager in your Docker container component, you must specify additional options when you run the Docker container. For more information, see the following:  
[Use interprocess communication in Docker container components](#docker-container-ipc)
[Use AWS credentials in Docker container components (Linux)](#docker-container-token-exchange-service)
[Use stream manager in Docker container components (Linux)](#docker-container-stream-manager)

1. [Test the component](test-components.md) to verify that it works as expected.
**Important**  
You must install and start the Docker daemon before you deploy the component.

   After you deploy the component locally, you can run the [docker container ls](https://docs.docker.com/engine/reference/commandline/container_ls/) command to verify that your container runs.

   ```
   docker container ls
   ```

1. When the component is ready, upload the component to AWS IoT Greengrass to deploy to other core devices. For more information, see [Publish components to deploy to your core devices](publish-components.md).

## Run a Docker container from a private image in Amazon ECR
<a name="run-docker-container-private-ecr"></a>

This section describes how you can create a custom component that runs a Docker container from a Docker image that is stored in a private repository in Amazon ECR.

**To run a Docker container**

1. [Create a custom component](create-components.md) on your AWS IoT Greengrass core device. Use the following example recipe, which has the following properties:
   + The Docker application manager component as a dependency. This component enables AWS IoT Greengrass to manage credentials to download images from private repositories.
   + The token exchange service component as a dependency. This component enables AWS IoT Greengrass to retrieve AWS credentials to interact with Amazon ECR.
   + A component artifact that specifies a Docker image in a private Amazon ECR repository.
   + A lifecycle run script that uses [docker run](https://docs.docker.com/engine/reference/commandline/run/) to create and start a container from the image.

------
#### [ JSON ]

   ```
   {
     "RecipeFormatVersion": "2020-01-25",
     "ComponentName": "com.example.MyPrivateDockerComponent",
     "ComponentVersion": "1.0.0",
     "ComponentDescription": "A component that runs a Docker container from a private Amazon ECR image.",
     "ComponentPublisher": "Amazon",
     "ComponentDependencies": {
       "aws.greengrass.DockerApplicationManager": {
         "VersionRequirement": "~2.0.0"
       },
       "aws.greengrass.TokenExchangeService": {
         "VersionRequirement": "~2.0.0"
       }
     },
     "Manifests": [
       {
         "Platform": {
           "os": "all"
         },
         "Lifecycle": {
           "Run": "docker run account-id.dkr.ecr.region.amazonaws.com/repository[:tag|@digest]"
         },
         "Artifacts": [
           {
             "URI": "docker:account-id.dkr.ecr.region.amazonaws.com/repository[:tag|@digest]"
           }
         ]
       }
     ]
   }
   ```

------
#### [ YAML ]

   ```
   ---
   RecipeFormatVersion: '2020-01-25'
   ComponentName: com.example.MyPrivateDockerComponent
   ComponentVersion: '1.0.0'
   ComponentDescription: 'A component that runs a Docker container from a private Amazon ECR image.'
   ComponentPublisher: Amazon
   ComponentDependencies:
     aws.greengrass.DockerApplicationManager:
       VersionRequirement: ~2.0.0
     aws.greengrass.TokenExchangeService:
       VersionRequirement: ~2.0.0
   Manifests:
     - Platform:
         os: all
       Lifecycle:
           Run: docker run account-id.dkr.ecr.region.amazonaws.com/repository[:tag|@digest]
       Artifacts:
         - URI: "docker:account-id.dkr.ecr.region.amazonaws.com/repository[:tag|@digest]"
   ```

------
**Note**  
<a name="docker-greengrass-features-requirements"></a>To use interprocess communication (IPC), AWS credentials, or stream manager in your Docker container component, you must specify additional options when you run the Docker container. For more information, see the following:  
[Use interprocess communication in Docker container components](#docker-container-ipc)
[Use AWS credentials in Docker container components (Linux)](#docker-container-token-exchange-service)
[Use stream manager in Docker container components (Linux)](#docker-container-stream-manager)

1. [Test the component](test-components.md) to verify that it works as expected.
**Important**  
You must install and start the Docker daemon before you deploy the component.

   After you deploy the component locally, you can run the [docker container ls](https://docs.docker.com/engine/reference/commandline/container_ls/) command to verify that your container runs.

   ```
   docker container ls
   ```

1. Upload the component to AWS IoT Greengrass to deploy to other core devices. For more information, see [Publish components to deploy to your core devices](publish-components.md).

## Run a Docker container from an image in Amazon S3
<a name="run-docker-container-s3"></a>

This section describes how you can run a Docker container in a component from a Docker image that is stored in Amazon S3.

**To run a Docker container in a component from an image in Amazon S3**

1. Run the [docker save](https://docs.docker.com/engine/reference/commandline/save/) command to create a backup of a Docker container. You provide this backup as a component artifact to run the container on AWS IoT Greengrass. Replace *hello-world* with the name of the image, and replace *hello-world.tar* with the name of the archive file to create.

   ```
   docker save hello-world > artifacts/com.example.MyDockerComponent/1.0.0/hello-world.tar
   ```

1. [Create a custom component](create-components.md) on your AWS IoT Greengrass core device. Use the following example recipe, which has the following properties:
   + A lifecycle install script that uses [docker load](https://docs.docker.com/engine/reference/commandline/load/) to load a Docker image from an archive.
   + A lifecycle run script that uses [docker run](https://docs.docker.com/engine/reference/commandline/run/) to create and start a container from the image. The `--rm` option cleans up the container when it exits.

------
#### [ JSON ]

   ```
   {
     "RecipeFormatVersion": "2020-01-25",
     "ComponentName": "com.example.MyS3DockerComponent",
     "ComponentVersion": "1.0.0",
     "ComponentDescription": "A component that runs a Docker container from an image in an S3 bucket.",
     "ComponentPublisher": "Amazon",
     "Manifests": [
       {
         "Platform": {
           "os": "linux"
         },
         "Lifecycle": {
           "install": {
             "Script": "docker load -i {artifacts:path}/hello-world.tar"
           },
           "Run": {
             "Script": "docker run --rm hello-world"
           }
         }
       }
     ]
   }
   ```

------
#### [ YAML ]

   ```
   ---
   RecipeFormatVersion: '2020-01-25'
   ComponentName: com.example.MyS3DockerComponent
   ComponentVersion: '1.0.0'
   ComponentDescription: 'A component that runs a Docker container from an image in an S3 bucket.'
   ComponentPublisher: Amazon
   Manifests:
     - Platform:
         os: linux
       Lifecycle:
         install:
           Script: docker load -i {artifacts:path}/hello-world.tar
         Run:
           Script: docker run --rm hello-world
   ```

------
**Note**  
<a name="docker-greengrass-features-requirements"></a>To use interprocess communication (IPC), AWS credentials, or stream manager in your Docker container component, you must specify additional options when you run the Docker container. For more information, see the following:  
[Use interprocess communication in Docker container components](#docker-container-ipc)
[Use AWS credentials in Docker container components (Linux)](#docker-container-token-exchange-service)
[Use stream manager in Docker container components (Linux)](#docker-container-stream-manager)

1. [Test the component](test-components.md) to verify that it works as expected.

   After you deploy the component locally, you can run the [docker container ls](https://docs.docker.com/engine/reference/commandline/container_ls/) command to verify that your container runs.

   ```
   docker container ls
   ```

1. When the component is ready, upload the Docker image archive to an S3 bucket, and add its URI to the component recipe. Then, you can upload the component to AWS IoT Greengrass to deploy to other core devices. For more information, see [Publish components to deploy to your core devices](publish-components.md).

   When you're done, the component recipe should look like the following example.

------
#### [ JSON ]

   ```
   {
     "RecipeFormatVersion": "2020-01-25",
     "ComponentName": "com.example.MyS3DockerComponent",
     "ComponentVersion": "1.0.0",
     "ComponentDescription": "A component that runs a Docker container from an image in an S3 bucket.",
     "ComponentPublisher": "Amazon",
     "Manifests": [
       {
         "Platform": {
           "os": "linux"
         },
         "Lifecycle": {
           "install": {
             "Script": "docker load -i {artifacts:path}/hello-world.tar"
           },
           "Run": {
             "Script": "docker run --rm hello-world"
           }
         },
         "Artifacts": [
           {
             "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.MyDockerComponent/1.0.0/hello-world.tar"
           }
         ]
       }
     ]
   }
   ```

------
#### [ YAML ]

   ```
   ---
   RecipeFormatVersion: '2020-01-25'
   ComponentName: com.example.MyS3DockerComponent
   ComponentVersion: '1.0.0'
   ComponentDescription: 'A component that runs a Docker container from an image in an S3 bucket.'
   ComponentPublisher: Amazon
   Manifests:
     - Platform:
         os: linux
       Lifecycle:
         install:
           Script: docker load -i {artifacts:path}/hello-world.tar
         Run:
           Script: docker run --rm hello-world
       Artifacts:
         - URI: s3://amzn-s3-demo-bucket/artifacts/com.example.MyDockerComponent/1.0.0/hello-world.tar
   ```

------

## Use interprocess communication in Docker container components
<a name="docker-container-ipc"></a>

You can use the Greengrass interprocess communication (IPC) library in the AWS IoT Device SDK or the AWS IoT Greengrass Component SDK to communicate with the Greengrass nucleus, other Greengrass components, and AWS IoT Core. For more information, see [Use the AWS IoT Device SDK to communicate with the Greengrass nucleus, other components, and AWS IoT CoreCommunicate with the Greengrass nucleus, other components, and AWS IoT Core](interprocess-communication.md).

To use IPC in a Docker container component, you must run the Docker container with the following parameters:
+ Mount the IPC socket in the container. The Greengrass nucleus provides the IPC socket file path in the `AWS_GG_NUCLEUS_DOMAIN_SOCKET_FILEPATH_FOR_COMPONENT` environment variable.
+ Set the `SVCUID` and `AWS_GG_NUCLEUS_DOMAIN_SOCKET_FILEPATH_FOR_COMPONENT` environment variables to the values that the Greengrass nucleus provides to components. Your component uses these environment variables to authenticate connections to the Greengrass nucleus.

**Example recipe: Publish an MQTT message to AWS IoT Core (Python)**  
The following recipe defines an example Docker container component that publishes an MQTT message to AWS IoT Core. This recipe has the following properties:  
+ An authorization policy (`accessControl`) that allows the component to publish MQTT messages to AWS IoT Core on all topics. For more information, see [Authorize components to perform IPC operations](interprocess-communication.md#ipc-authorization-policies) and [AWS IoT Core MQTT IPC authorization](ipc-iot-core-mqtt.md#ipc-iot-core-mqtt-authorization).
+ A component artifact that specifies a Docker image as a TAR archive in Amazon S3.
+ A lifecycle install script that loads the Docker image from the TAR archive.
+ A lifecycle run script that runs a Docker container from the image. The [Docker run](https://docs.docker.com/engine/reference/run/) command has the following arguments:
  + The `-v` argument mounts the Greengrass IPC socket in the container.
  + The first two `-e` arguments set the required environment variables in the Docker container.
  + The additional `-e` arguments set environment variables used by this example.
  + The `--rm` argument cleans up the container when it exits.

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.python.docker.PublishToIoTCore",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "Uses interprocess communication to publish an MQTT message to IoT Core.",
  "ComponentPublisher": "Amazon",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "topic": "test/topic/java",
      "message": "Hello, World!",
      "qos": "1",
      "accessControl": {
        "aws.greengrass.ipc.mqttproxy": {
          "com.example.python.docker.PublishToIoTCore:pubsub:1": {
            "policyDescription": "Allows access to publish to IoT Core on all topics.",
            "operations": [
              "aws.greengrass#PublishToIoTCore"
            ],
            "resources": [
              "*"
            ]
          }
        }
      }
    }
  },
  "Manifests": [
    {
      "Platform": {
        "os": "all"
      },
      "Lifecycle": {
        "install": "docker load -i {artifacts:path}/publish-to-iot-core.tar",
        "Run": "docker run -v $AWS_GG_NUCLEUS_DOMAIN_SOCKET_FILEPATH_FOR_COMPONENT:$AWS_GG_NUCLEUS_DOMAIN_SOCKET_FILEPATH_FOR_COMPONENT -e SVCUID -e AWS_GG_NUCLEUS_DOMAIN_SOCKET_FILEPATH_FOR_COMPONENT -e MQTT_TOPIC=\"{configuration:/topic}\" -e MQTT_MESSAGE=\"{configuration:/message}\" -e MQTT_QOS=\"{configuration:/qos}\" --rm publish-to-iot-core"
      },
      "Artifacts": [
        {
          "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.python.docker.PublishToIoTCore/1.0.0/publish-to-iot-core.tar"
        }
      ]
    }
  ]
}
```

```
RecipeFormatVersion: '2020-01-25'
ComponentName: com.example.python.docker.PublishToIoTCore
ComponentVersion: 1.0.0
ComponentDescription: Uses interprocess communication to publish an MQTT message to IoT Core.
ComponentPublisher: Amazon
ComponentConfiguration:
  DefaultConfiguration:
    topic: 'test/topic/java'
    message: 'Hello, World!'
    qos: '1'
    accessControl:
      aws.greengrass.ipc.mqttproxy:
        'com.example.python.docker.PublishToIoTCore:pubsub:1':
          policyDescription: Allows access to publish to IoT Core on all topics.
          operations:
            - 'aws.greengrass#PublishToIoTCore'
          resources:
            - '*'
Manifests:
  - Platform:
      os: all
    Lifecycle:
      install: 'docker load -i {artifacts:path}/publish-to-iot-core.tar'
      Run: |
        docker run \
          -v $AWS_GG_NUCLEUS_DOMAIN_SOCKET_FILEPATH_FOR_COMPONENT:$AWS_GG_NUCLEUS_DOMAIN_SOCKET_FILEPATH_FOR_COMPONENT \
          -e SVCUID \
          -e AWS_GG_NUCLEUS_DOMAIN_SOCKET_FILEPATH_FOR_COMPONENT \
          -e MQTT_TOPIC="{configuration:/topic}" \
          -e MQTT_MESSAGE="{configuration:/message}" \
          -e MQTT_QOS="{configuration:/qos}" \
          --rm publish-to-iot-core
    Artifacts:
      - URI: s3://amzn-s3-demo-bucket/artifacts/com.example.python.docker.PublishToIoTCore/1.0.0/publish-to-iot-core.tar
```

## Use AWS credentials in Docker container components (Linux)
<a name="docker-container-token-exchange-service"></a>

You can use the [token exchange service component](token-exchange-service-component.md) to interact with AWS services in Greengrass components. This component provides AWS credentials from the core device's [token exchange role](device-service-role.md) using a local container server. For more information, see [Interact with AWS services](interact-with-aws-services.md).

**Note**  
The example in this section works only on Linux core devices.

To use AWS credentials from the token exchange service in a Docker container component, you must run the Docker container with the following parameters:
+ Provide access to the host network using the `--network=host` argument. This option enables the Docker container to connect to the local token exchange service to retrieve AWS credentials. This argument works on only Docker for Linux.
**Warning**  <a name="docker-network-host-security-warning"></a>
This option gives the container access to all local network interfaces on the host, so this option is less secure than if you run Docker containers without this access to the host network. Consider this when you develop and run Docker container components that use this option. For more information, see [Network: host](https://docs.docker.com/engine/reference/run/#network-host) in the *Docker Documentation*.
+ Set the `AWS_CONTAINER_CREDENTIALS_FULL_URI` and `AWS_CONTAINER_AUTHORIZATION_TOKEN` environment variables to the values that the Greengrass nucleus provides to components. AWS SDKs use these environment variables to retrieve AWS credentials.

**Example recipe: List S3 buckets in a Docker container component (Python)**  
The following recipe defines an example Docker container component that lists the S3 buckets in your AWS account. This recipe has the following properties:  
+ The token exchange service component as a dependency. This dependency enables the component to retrieve AWS credentials to interact with other AWS services.
+ A component artifact that specifies a Docker image as a tar archive in Amazon S3.
+ A lifecycle install script that loads the Docker image from the TAR archive.
+ A lifecycle run script that runs a Docker container from the image. The [Docker run](https://docs.docker.com/engine/reference/run/) command has the following arguments:
  + The `--network=host` argument provides the container access to the host network, so the container can connect to the token exchange service.
  + The `-e` argument sets the required environment variables in the Docker container.
  + The `--rm` argument cleans up the container when it exits.

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.python.docker.ListS3Buckets",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "Uses the token exchange service to lists your S3 buckets.",
  "ComponentPublisher": "Amazon",
  "ComponentDependencies": {
    "aws.greengrass.TokenExchangeService": {
      "VersionRequirement": "^2.0.0",
      "DependencyType": "HARD"
    }
  },
  "Manifests": [
    {
      "Platform": {
        "os": "linux"
      },
      "Lifecycle": {
        "install": "docker load -i {artifacts:path}/list-s3-buckets.tar",
        "Run": "docker run --network=host -e AWS_CONTAINER_AUTHORIZATION_TOKEN -e AWS_CONTAINER_CREDENTIALS_FULL_URI --rm list-s3-buckets"
      },
      "Artifacts": [
        {
          "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.python.docker.ListS3Buckets/1.0.0/list-s3-buckets.tar"
        }
      ]
    }
  ]
}
```

```
RecipeFormatVersion: '2020-01-25'
ComponentName: com.example.python.docker.ListS3Buckets
ComponentVersion: 1.0.0
ComponentDescription: Uses the token exchange service to lists your S3 buckets.
ComponentPublisher: Amazon
ComponentDependencies:
  aws.greengrass.TokenExchangeService:
    VersionRequirement: ^2.0.0
    DependencyType: HARD
Manifests:
  - Platform:
      os: linux
    Lifecycle:
      install: 'docker load -i {artifacts:path}/list-s3-buckets.tar'
      Run: |
        docker run \
          --network=host \
          -e AWS_CONTAINER_AUTHORIZATION_TOKEN \
          -e AWS_CONTAINER_CREDENTIALS_FULL_URI \
          --rm list-s3-buckets
    Artifacts:
      - URI: s3://amzn-s3-demo-bucket/artifacts/com.example.python.docker.ListS3Buckets/1.0.0/list-s3-buckets.tar
```

## Use stream manager in Docker container components (Linux)
<a name="docker-container-stream-manager"></a>

You can use the [stream manager component](stream-manager-component.md) to manage data streams in Greengrass components. This component enables you to process data streams and transfer high-volume IoT data to the AWS Cloud. AWS IoT Greengrass provides a stream manager SDK that you use to interact with the stream manager component. For more information, see [Manage data streams on Greengrass core devices](manage-data-streams.md).

**Note**  
The example in this section works only on Linux core devices.

To use the stream manager SDK in a Docker container component, you must run the Docker container with the following parameters:
+ Provide access to the host network using the `--network=host` argument. This option enables the Docker container to interact with the stream manager component over a local TLS connection. This argument works on only Docker for Linux
**Warning**  <a name="docker-network-host-security-warning"></a>
This option gives the container access to all local network interfaces on the host, so this option is less secure than if you run Docker containers without this access to the host network. Consider this when you develop and run Docker container components that use this option. For more information, see [Network: host](https://docs.docker.com/engine/reference/run/#network-host) in the *Docker Documentation*.
+ If you configure the stream manager component to require authentication, which is the default behavior, set the `AWS_CONTAINER_CREDENTIALS_FULL_URI` environment variable to the value that the Greengrass nucleus provides to components. For more information, see [stream manager configuration](stream-manager-component.md#stream-manager-component-configuration).
+ If you configure the stream manager component to use a non-default port, use [interprocess communication (IPC)](interprocess-communication.md) to get the port from the stream manager component configuration. You must run the Docker container with additional options to use IPC. For more information, see the following:
  + [Connect to stream manager in application code](use-stream-manager-in-custom-components.md#connect-to-stream-manager)
  + [Use interprocess communication in Docker container components](#docker-container-ipc)

**Example recipe: Stream a file to an S3 bucket in a Docker container component (Python)**  
The following recipe defines an example Docker container component that creates a file and streams it to an S3 bucket. This recipe has the following properties:  
+ The stream manager component as a dependency. This dependency enables the component to use the stream manager SDK to interact with the stream manager component.
+ A component artifact that specifies a Docker image as a TAR archive in Amazon S3.
+ A lifecycle install script that loads the Docker image from the TAR archive.
+ A lifecycle run script that runs a Docker container from the image. The [Docker run](https://docs.docker.com/engine/reference/run/) command has the following arguments:
  + The `--network=host` argument provides the container access to the host network, so the container can connect to the stream manager component.
  + The first `-e` argument sets the required `AWS_CONTAINER_AUTHORIZATION_TOKEN` environment variable in the Docker container.
  + The additional `-e` arguments set environment variables used by this example.
  + The `-v` argument mounts the component's [work folder](component-recipe-reference.md#component-recipe-work-path) in the container. This example creates a file in the work folder to upload that file to Amazon S3 using stream manager.
  + The `--rm` argument cleans up the container when it exits.

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.python.docker.StreamFileToS3",
  "ComponentVersion": "1.0.0",
  "ComponentDescription": "Creates a text file and uses stream manager to stream the file to S3.",
  "ComponentPublisher": "Amazon",
  "ComponentDependencies": {
    "aws.greengrass.StreamManager": {
      "VersionRequirement": "^2.0.0",
      "DependencyType": "HARD"
    }
  },
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "bucketName": ""
    }
  },
  "Manifests": [
    {
      "Platform": {
        "os": "linux"
      },
      "Lifecycle": {
        "install": "docker load -i {artifacts:path}/stream-file-to-s3.tar",
        "Run": "docker run --network=host -e AWS_CONTAINER_AUTHORIZATION_TOKEN -e BUCKET_NAME=\"{configuration:/bucketName}\" -e WORK_PATH=\"{work:path}\" -v {work:path}:{work:path} --rm stream-file-to-s3"
      },
      "Artifacts": [
        {
          "URI": "s3://amzn-s3-demo-bucket/artifacts/com.example.python.docker.StreamFileToS3/1.0.0/stream-file-to-s3.tar"
        }
      ]
    }
  ]
}
```

```
RecipeFormatVersion: '2020-01-25'
ComponentName: com.example.python.docker.StreamFileToS3
ComponentVersion: 1.0.0
ComponentDescription: Creates a text file and uses stream manager to stream the file to S3.
ComponentPublisher: Amazon
ComponentDependencies:
  aws.greengrass.StreamManager:
    VersionRequirement: ^2.0.0
    DependencyType: HARD
ComponentConfiguration:
  DefaultConfiguration:
    bucketName: ''
Manifests:
  - Platform:
      os: linux
    Lifecycle:
      install: 'docker load -i {artifacts:path}/stream-file-to-s3.tar'
      Run: |
        docker run \
          --network=host \
          -e AWS_CONTAINER_AUTHORIZATION_TOKEN \
          -e BUCKET_NAME="{configuration:/bucketName}" \
          -e WORK_PATH="{work:path}" \
          -v {work:path}:{work:path} \
          --rm stream-file-to-s3
    Artifacts:
      - URI: s3://amzn-s3-demo-bucket/artifacts/com.example.python.docker.StreamFileToS3/1.0.0/stream-file-to-s3.tar
```

# AWS IoT Greengrass component recipe reference
<a name="component-recipe-reference"></a>

The component recipe is a file that defines a component's details, dependencies, artifacts, and lifecycles. The component *lifecycle* specifies the commands to run to install, run, and shut down the component, for example. The AWS IoT Greengrass core uses the lifecycles that you define in the recipe to install and run components. The AWS IoT Greengrass service uses the recipe to identify the dependencies and artifacts to deploy to your core devices when you deploy the component.

In the recipe, you can define unique dependencies and lifecycles for each platform that a component supports. You can use this capability to deploy a component to devices with multiple platforms that have different requirements. You can also use this to prevent AWS IoT Greengrass from installing a component on devices that don't support it.

Each recipe contains a list of *manifests*. Each manifest specifies a set of platform requirements and the lifecycle and artifacts to use for core devices whose platform meets those requirements. The core device uses the first manifest with platform requirements that the device meets. Specify a manifest without any platform requirements to match any core device.

You can also specify a global lifecycle that isn't in a manifest. In the global lifecycle, you can use *selection keys* that identify sub-sections of the lifecycle. Then, you can specify these selection keys within a manifest to use those sections of the global lifecycle in addition to the manifest's lifecycle. The core device uses the manifest's selection keys only if the manifest doesn't define a lifecycle. You can use the `all` selection in a manifest to match sections of the global lifecycle without selection keys.

After the AWS IoT Greengrass Core software selects a manifest that matches the core device, it does the following to identify the lifecycle steps to use:
+ If the selected manifest defines a lifecycle, the core device uses that lifecycle.
+ If the selected manifest doesn't define a lifecycle, the core device uses the global lifecycle. The core device does the following to identify which sections of the global lifecycle to use:
  + If the manifest defines selection keys, the core device uses the sections of the global lifecycle that contain the manifest's selection keys.
  + If the manifest doesn't define selection keys, the core device uses the sections of the global lifecycle that don't have selection keys. This behavior is equivalent to a manifest that defines the `all` selection.

**Important**  <a name="recipe-core-device-manifest-requirement"></a>
A core device must match least one manifest's platform requirements to install the component. If no manifest matches the core device, then the AWS IoT Greengrass Core software doesn't install the component and the deployment fails.

You can define recipes in [JSON](https://en.wikipedia.org/wiki/JSON) or [YAML](https://en.wikipedia.org/wiki/YAML) format. The recipe examples section includes recipes in each format.

**Topics**
+ [

## Recipe validation
](#recipe-validation)
+ [

## Recipe format
](#recipe-format)
+ [

## Recipe variables
](#recipe-variables)
+ [

## Recipe examples
](#recipe-examples)

## Recipe validation
<a name="recipe-validation"></a>

Greengrass validates a JSON or YAML component recipe when creating a component version. This recipe validation checks your JSON or YAML component recipe for common errors in order to prevent potential deployment issues. The validation checks the recipe for common errors (e.g., missing commas, braces, and fields) and to make sure the recipe is well-formed.

If you receive a recipe validation error message, check your recipe for any missing commas, braces, or fields. Verify that you are not missing any fields by looking at the [recipe format](#recipe-format).

## Recipe format
<a name="recipe-format"></a>

When you define a recipe for a component, you specify the following information in the recipe document. The same structure applies to recipes in YAML and JSON formats.

`RecipeFormatVersion`  
The template version for the recipe. Choose the following option:  
+ `2020-01-25`

`ComponentName`  
The name of the component that this recipe defines. The component name must be unique in your AWS account in each Region.  
**Tips**  
+ Use inverse domain name format to avoid name collision within your company. For example, if your company owns `example.com` and you work on a solar energy project, you can name your Hello World component `com.example.solar.HelloWorld`. This helps avoid component name collisions within your company.
+ Avoid the `aws.greengrass` prefix in your component names. AWS IoT Greengrass uses this prefix for the [public components](public-components.md) that it provides. If you choose the same name as a public component, your component replaces that component. Then, AWS IoT Greengrass provides your component instead of the public component when it deploys components with a dependency on that public component. This feature enables you to override the behavior of public components, but it can also break other components if you don't intend to override a public component.

`ComponentVersion`  
The version of the component. The maximum value for the major, minor, and patch values is 999999.  
<a name="semver-para"></a>AWS IoT Greengrass uses semantic versions for components. Semantic versions follow a *major*.*minor*.*patch* number system. For example, version `1.0.0` represents the first major release for a component. For more information, see the [semantic version specification](https://semver.org/).

`ComponentDescription`  
(Optional) The description of the component.

`ComponentPublisher`  
The publisher or author of the component.

`ComponentConfiguration`  
(Optional) An object that defines the configuration or parameters for the component. You define the default configuration, and then when you deploy the component, you can specify the configuration object to provide to the component. Component configuration supports nested parameters and structures. This object contains the following information:    
`DefaultConfiguration`  
An object that defines the default configuration for the component. You define the structure of this object.  
<a name="configuration-value-type-note"></a>AWS IoT Greengrass uses JSON for configuration values. JSON specifies a number type but doesn't differentiate between integers and floats. As a result, configuration values might convert to floats in AWS IoT Greengrass. To ensure that your component uses the correct data type, we recommend that you define numeric configuration values as strings. Then, have your component parse them as integers or floats. This ensures that your configuration values have the same type in the configuration and on your core device.

`ComponentDependencies`  <a name="recipe-reference-component-dependencies"></a>
(Optional) A dictionary of objects that each define a component dependency for the component. The key for each object identifies the name of the component dependency. AWS IoT Greengrass installs component dependencies when the component installs. AWS IoT Greengrass waits for dependencies to start before it starts the component. Each object contains the following information:    
`VersionRequirement`  
The npm-style semantic version constraint that defines the compatible component versions for this dependency. You can specify a version or a range of versions. For more information, see the [npm semantic version calculator](https://semver.npmjs.com/).  
`DependencyType`  
(Optional) The type of this dependency. Choose from the following options.  
+ `SOFT` – The component doesn't restart if the dependency changes state.
+ `HARD` – The component restarts if the dependency changes state.
Defaults to `HARD`.

`ComponentType`  
(Optional) The type of component.  
We don't recommend that you specify the component type in a recipe. AWS IoT Greengrass sets the type for you when you create a component.
The type can be one the following types:  
+ `aws.greengrass.generic` – The component runs commands or provides artifacts.
+ `aws.greengrass.lambda` – The component runs a Lambda function using the [Lambda launcher component](lambda-launcher-component.md). The `ComponentSource` parameter specifies the ARN of the Lambda function that this component runs.

  We don't recommend that you use this option, because it's set by AWS IoT Greengrass when you create a component from a Lambda function. For more information, see [Run AWS Lambda functions](run-lambda-functions.md).
+ `aws.greengrass.plugin` – The component runs in the same Java Virtual Machine (JVM) as the Greengrass nucleus. If you deploy or restart a plugin component, the Greengrass nucleus restarts.

  Plugin components use the same log file as the Greengrass nucleus. For more information, see [Monitor AWS IoT Greengrass logs](monitor-logs.md).

  We don't recommend that you use this option in component recipes, because it's intended for AWS-provided components written in Java that directly interface with the Greengrass nucleus. For more information about which public components are plugins, see [AWS-provided components](public-components.md).
+ `aws.greengrass.nucleus` – The nucleus component. For more information, see [Greengrass nucleus](greengrass-nucleus-component.md).

  We don't recommend that you use this option in component recipes. It is intended for the Greengrass nucleus component, which provides the minimum functionality of the AWS IoT Greengrass Core software.
Defaults to `aws.greengrass.generic` when you create a component from a recipe, or `aws.greengrass.lambda` when you create a component from a Lambda function.  
For more information, see [Component types](develop-greengrass-components.md#component-types).

`ComponentSource`  
(Optional) The ARN of the Lambda function that a component runs.  
We don't recommend that you specify the component source in a recipe. AWS IoT Greengrass sets this parameter for you when you create a component from a Lambda function. For more information, see [Run AWS Lambda functions](run-lambda-functions.md).

  `Manifests`   
A list of objects that each define the component's lifecycle, parameters, and requirements for a platform. If a core device matches multiple manifests' platform requirements, AWS IoT Greengrass uses the first manifest that the core device matches. To ensure that core devices use the correct manifest, define the manifests with stricter platform requirements first. A manifest that applies to all platforms must be the last manifest in the list.  
A core device must match least one manifest's platform requirements to install the component. If no manifest matches the core device, then the AWS IoT Greengrass Core software doesn't install the component and the deployment fails.
Each object contains the following information:    
`Name`  
(Optional) A friendly name for the platform that this manifest defines.  
If you omit this parameter, AWS IoT Greengrass creates a name from the platform `os` and `architecture`.  
  `Platform`   
(Optional) An object that defines the platform to which this manifest applies. Omit this parameter to define a manifest that applies to all platforms.  
This object specifies key-value pairs about the platform on which a core device runs. When you deploy this component, the AWS IoT Greengrass Core software compares these key-value pairs with the platform attributes on the core device. The AWS IoT Greengrass Core software always defines `os` and `architecture`, and it might define additional attributes. You can specify custom platform attributes for a core device when you deploy the Greengrass nucleus component. For more information, see the [platform overrides parameter](greengrass-nucleus-component.md#greengrass-nucleus-component-configuration-platform-overrides) of the [Greengrass nucleus component](greengrass-nucleus-component.md).  
For each key-value pair, you can specify one of the following values:  
+ An exact value, such as `linux` or `windows`. Exact values must start with a letter or a number.
+ `*`, which matches any value. This also matches when a value isn't present.
+ A Java-style regular expression, such as `/windows|linux/`. The regular expression must start and end with a slash character (`/`). For example, the regular expression `/.+/` matches any non-blank value.
This object contains the following information:    
`runtime`  
The [Greengrass nucleus runtime](https://docs.aws.amazon.com/greengrass/v2/developerguide/how-it-works.html#concept-overview) for the platform that this manifest supports. When defining multiple manifests with platform `runtime`, The supported runtime values in a recipe are `aws_nucleus_lite` and `*` only. To target a classic device, runtime field MUST NOT be specified in the the recipe. Supported Greengrass Nucleus runtimes include the following values:  
+ `*`
+ `aws_nucleus_lite`  
`os`  
(Optional) The name of the operating system for the platform that this manifest supports. Common platforms include the following values:  
+ `linux`
+ `windows`
+ `darwin` (macOS)  
`architecture`  
(Optional) The processor architecture for the platform that this manifest supports. Common architectures include the following values:  
+ `amd64`
+ `arm`
+ `aarch64`
+ `x86`  
`architecture.detail`  
(Optional) The processor architecture detail for the platform that this manifest supports. Common architecture details include the following values:  
+ `arm61`
+ `arm71`
+ `arm81`  
`key`  
(Optional) A platform attribute that you define for this manifest. Replace *Key* with the name of the platform attribute. The AWS IoT Greengrass Core software matches this platform attribute with the key-value pairs that you specify in the Greengrass nucleus component configuration. For more information, see the [platform overrides parameter](greengrass-nucleus-component.md#greengrass-nucleus-component-configuration-platform-overrides) of the [Greengrass nucleus component](greengrass-nucleus-component.md).  
Use inverse domain name format to avoid name collision within your company. For example, if your company owns `example.com` and you work on a radio project, you can name a custom platform attribute `com.example.radio.RadioModule`. This helps avoid platform attribute name collisions within your company.
For example, you might define a platform attribute, `com.example.radio.RadioModule`, to specify a different manifest based on which radio module is available on a core device. Each manifest can include different artifacts that apply to different hardware configurations, so that you deploy the minimal set of software to the core device.  
  `Lifecycle`   
An object or string that defines how to install and run the component on the platform that this manifest defines. You can also define a [global lifecycle](#global-lifecycle-definition) that applies to all platforms. The core device uses the global lifecycle only if the manifest to use doesn't specify a lifecycle.  
You define this lifecycle within a manifest. The lifecycle steps that you specify here apply to only the platform that this manifest defines. You can also define a [global lifecycle](#global-lifecycle-definition) that applies to all platforms.
This object or string contains the following information:    
  `Setenv`   
(Optional) A dictionary of environment variables to provide to all lifecycle scripts. You can override these environment variables with `Setenv` in each lifecycle script.  
  `install`   
(Optional) An object or string that defines the script to run when the component installs. The AWS IoT Greengrass Core software also runs this lifecycle step each time the software launches.  
If the `install` script exits with a success code, the component enters the `INSTALLED` state.  
This object or string contains the following information:    
`Script`  <a name="recipe-lifecycle-script"></a>
The script to run.  
`RequiresPrivilege`  <a name="recipe-lifecycle-requiresprivilege"></a>
(Optional) If you set this option to `true`, the AWS IoT Greengrass Core software runs this lifecycle script as the user that runs the Greengrass nucleus instead of the system user configured for this component. When the nucleus runs as root, this grants root privileges to the script. Defaults to `false`.  
`Skipif`  <a name="recipe-lifecycle-skipif"></a>
(Optional) The check to determine whether or not to run the script. You can define to check if an executable is on the path or if a file exists. If the output is true, then the AWS IoT Greengrass Core software skips the step. Choose one of the following checks:  
+ `onpath runnable` – Check if a runnable is on the system path. For example, use **onpath python3** to skip this lifecycle step if Python 3 is available.
+ `exists file` – Check if a file exists. For example, use **exists /tmp/my-configuration.db** to skip this lifecycle step if `/tmp/my-configuration.db` is present.  
`Timeout`  <a name="recipe-lifecycle-timeout"></a>
(Optional) The maximum amount of time in seconds that the script can run before the AWS IoT Greengrass Core software terminates the process.  
Default: 120 seconds  
`Setenv`  <a name="recipe-lifecycle-environment"></a>
(Optional) The dictionary of environment variables to provide to the script. These environment variables override the variables that you provide in `Lifecycle.Setenv`.  
  `run`   
(Optional) An object or string that defines the script to run when the component starts.  
The component enters the `RUNNING` state when this lifecycle step runs. If the `run` script exits with a success code, the component enters the `STOPPING` state. If a `shutdown` script is specified, it runs; otherwise the component enters the `FINISHED` state.  
Components that depend on this component start when this lifecycle step runs. To run a background process, such as a service that dependent components use, use the `startup` lifecycle step instead.  
When you deploy components with a `run` lifecycle, the core device can report the deployment as complete as soon as this lifecycle script runs. As a result, the deployment can be complete and successful even if the `run` lifecycle script fails soon after running. If you want the deployment status to depend on the result of the component's start script, use the `startup` lifecycle step instead.  
You can define only one `startup` or `run` lifecycle.
This object or string contains the following information:    
`Script`  <a name="recipe-lifecycle-script"></a>
The script to run.  
`RequiresPrivilege`  <a name="recipe-lifecycle-requiresprivilege"></a>
(Optional) If you set this option to `true`, the AWS IoT Greengrass Core software runs this lifecycle script as the user that runs the Greengrass nucleus instead of the system user configured for this component. When the nucleus runs as root, this grants root privileges to the script. Defaults to `false`.  
`Skipif`  <a name="recipe-lifecycle-skipif"></a>
(Optional) The check to determine whether or not to run the script. You can define to check if an executable is on the path or if a file exists. If the output is true, then the AWS IoT Greengrass Core software skips the step. Choose one of the following checks:  
+ `onpath runnable` – Check if a runnable is on the system path. For example, use **onpath python3** to skip this lifecycle step if Python 3 is available.
+ `exists file` – Check if a file exists. For example, use **exists /tmp/my-configuration.db** to skip this lifecycle step if `/tmp/my-configuration.db` is present.  
`Timeout`  <a name="recipe-lifecycle-timeout"></a>
(Optional) The maximum amount of time in seconds that the script can run before the AWS IoT Greengrass Core software terminates the process.  
This lifecycle step doesn't timeout by default. If you omit this timeout, the `run` script runs until it exits.  
`Setenv`  <a name="recipe-lifecycle-environment"></a>
(Optional) The dictionary of environment variables to provide to the script. These environment variables override the variables that you provide in `Lifecycle.Setenv`.  
  `startup`   
(Optional) An object or string that defines the background process to run when the component starts.  
Use `startup` to run a command that must exit successfully or update the component's status to `RUNNING` before dependent components can start. Use the [UpdateState](ipc-component-lifecycle.md#ipc-operation-updatestate) IPC operation to set the component's status to `RUNNING` or `ERRORED` when the component starts a script that doesn't exit. For example, you might define a `startup` step that starts the MySQL process with `/etc/init.d/mysqld start`.  
The component enters the `STARTING` state when this lifecycle step runs. If the `startup` script exits with a success code, the component enters the `RUNNING` state. Then, dependent components can start.  
When you deploy components with a `startup` lifecycle, the core device can report the deployment as complete after this lifecycle script exits or reports its state. In other words, the deployment's status is `IN_PROGRESS` until all components' startup scripts exit or report a state.  
You can define only one `startup` or `run` lifecycle.
This object or string contains the following information:    
`Script`  <a name="recipe-lifecycle-script"></a>
The script to run.  
`RequiresPrivilege`  <a name="recipe-lifecycle-requiresprivilege"></a>
(Optional) If you set this option to `true`, the AWS IoT Greengrass Core software runs this lifecycle script as the user that runs the Greengrass nucleus instead of the system user configured for this component. When the nucleus runs as root, this grants root privileges to the script. Defaults to `false`.  
`Skipif`  <a name="recipe-lifecycle-skipif"></a>
(Optional) The check to determine whether or not to run the script. You can define to check if an executable is on the path or if a file exists. If the output is true, then the AWS IoT Greengrass Core software skips the step. Choose one of the following checks:  
+ `onpath runnable` – Check if a runnable is on the system path. For example, use **onpath python3** to skip this lifecycle step if Python 3 is available.
+ `exists file` – Check if a file exists. For example, use **exists /tmp/my-configuration.db** to skip this lifecycle step if `/tmp/my-configuration.db` is present.  
`Timeout`  <a name="recipe-lifecycle-timeout"></a>
(Optional) The maximum amount of time in seconds that the script can run before the AWS IoT Greengrass Core software terminates the process.  
Default: 120 seconds  
`Setenv`  <a name="recipe-lifecycle-environment"></a>
(Optional) The dictionary of environment variables to provide to the script. These environment variables override the variables that you provide in `Lifecycle.Setenv`.  
  `shutdown`   
(Optional) An object or string that defines the script to run when the component shuts down. Use the shutdown lifecycle to execute code that you want to run when the component is in the `STOPPING` state. The shutdown lifecycle can be used to stop a process started by the `startup` or `run` scripts.  
If you start a background process in `startup`, use the `shutdown` step to stop that process when the component shuts down. For example, you might define a `shutdown` step that stops the MySQL process with `/etc/init.d/mysqld stop`.  
The `shutdown` script runs after the component enters the `STOPPING` state. If the script completes successfully, the component enters the `FINISHED` state.  
This object or string contains the following information:    
`Script`  <a name="recipe-lifecycle-script"></a>
The script to run.  
`RequiresPrivilege`  <a name="recipe-lifecycle-requiresprivilege"></a>
(Optional) If you set this option to `true`, the AWS IoT Greengrass Core software runs this lifecycle script as the user that runs the Greengrass nucleus instead of the system user configured for this component. When the nucleus runs as root, this grants root privileges to the script. Defaults to `false`.  
`Skipif`  <a name="recipe-lifecycle-skipif"></a>
(Optional) The check to determine whether or not to run the script. You can define to check if an executable is on the path or if a file exists. If the output is true, then the AWS IoT Greengrass Core software skips the step. Choose one of the following checks:  
+ `onpath runnable` – Check if a runnable is on the system path. For example, use **onpath python3** to skip this lifecycle step if Python 3 is available.
+ `exists file` – Check if a file exists. For example, use **exists /tmp/my-configuration.db** to skip this lifecycle step if `/tmp/my-configuration.db` is present.  
`Timeout`  
(Optional) The maximum amount of time in seconds that the script can run before the AWS IoT Greengrass Core software terminates the process.  
Default: 15 seconds.  
`Setenv`  <a name="recipe-lifecycle-environment"></a>
(Optional) The dictionary of environment variables to provide to the script. These environment variables override the variables that you provide in `Lifecycle.Setenv`.  
  `uninstall`   
(Optional) An object or string that defines the script to run when the component is permanently removed from the device. The AWS IoT Greengrass Core software runs this step when a deployment removes a component. This step does not run during component version upgrades.  
The component enters the `UNINSTALLING` state when this lifecycle step runs. If the uninstall script fails or times out, the component is still removed. Uninstall failures do not fail the deployment.  
This object or string contains the following information:    
`Script`  <a name="recipe-lifecycle-script"></a>
The script to run.  
`RequiresPrivilege`  <a name="recipe-lifecycle-requiresprivilege"></a>
(Optional) If you set this option to `true`, the AWS IoT Greengrass Core software runs this lifecycle script as the user that runs the Greengrass nucleus instead of the system user configured for this component. When the nucleus runs as root, this grants root privileges to the script. Defaults to `false`.  
`Skipif`  <a name="recipe-lifecycle-skipif"></a>
(Optional) The check to determine whether or not to run the script. You can define to check if an executable is on the path or if a file exists. If the output is true, then the AWS IoT Greengrass Core software skips the step. Choose one of the following checks:  
+ `onpath runnable` – Check if a runnable is on the system path. For example, use **onpath python3** to skip this lifecycle step if Python 3 is available.
+ `exists file` – Check if a file exists. For example, use **exists /tmp/my-configuration.db** to skip this lifecycle step if `/tmp/my-configuration.db` is present.  
`Timeout`  <a name="recipe-lifecycle-timeout"></a>
(Optional) The maximum amount of time in seconds that the script can run before the AWS IoT Greengrass Core software terminates the process.  
Default: 120 seconds  
`Setenv`  <a name="recipe-lifecycle-environment"></a>
(Optional) The dictionary of environment variables to provide to the script. These environment variables override the variables that you provide in `Lifecycle.Setenv`.  
  `recover`   
(Optional) An object or string that defines the script to run when the component encounters an error.  
This step runs when a component enters the `ERRORED` state. If the component becomes `ERRORED` three times without successfully recovering, the component changes to the `BROKEN` state. To fix a `BROKEN` component, you must deploy it again.  
This object or string contains the following information:    
`Script`  <a name="recipe-lifecycle-script"></a>
The script to run.  
`RequiresPrivilege`  <a name="recipe-lifecycle-requiresprivilege"></a>
(Optional) If you set this option to `true`, the AWS IoT Greengrass Core software runs this lifecycle script as the user that runs the Greengrass nucleus instead of the system user configured for this component. When the nucleus runs as root, this grants root privileges to the script. Defaults to `false`.  
`Skipif`  <a name="recipe-lifecycle-skipif"></a>
(Optional) The check to determine whether or not to run the script. You can define to check if an executable is on the path or if a file exists. If the output is true, then the AWS IoT Greengrass Core software skips the step. Choose one of the following checks:  
+ `onpath runnable` – Check if a runnable is on the system path. For example, use **onpath python3** to skip this lifecycle step if Python 3 is available.
+ `exists file` – Check if a file exists. For example, use **exists /tmp/my-configuration.db** to skip this lifecycle step if `/tmp/my-configuration.db` is present.  
`Timeout`  
(Optional) The maximum amount of time in seconds that the script can run before the AWS IoT Greengrass Core software terminates the process.  
Default: 60 seconds.  
`Setenv`  <a name="recipe-lifecycle-environment"></a>
(Optional) The dictionary of environment variables to provide to the script. These environment variables override the variables that you provide in `Lifecycle.Setenv`.  
  `bootstrap`   
(Optional) An object or string that defines a script that requires the AWS IoT Greengrass Core software or core device to restart. This lets you develop a component that performs a restart after it installs operating system updates or runtime updates, for example.  
To install updates or dependencies that don't require the AWS IoT Greengrass Core software or device to restart, use the [install lifecycle](#install-lifecycle-definition).
This lifecycle step runs before the install lifecycle step in the following cases when the AWS IoT Greengrass Core software deploys the component:  
+ The component deploys to the core device for the first time.
+ The component version changes.
+ The bootstrap script changes as the result of a component configuration update.
After the AWS IoT Greengrass Core software completes the bootstrap step for all components that have a bootstrap step in a deployment, the software restarts.  
You must configure the AWS IoT Greengrass Core software as a system service to restart the AWS IoT Greengrass Core software or the core device. If you don't configure the AWS IoT Greengrass Core software as a system service, the software won't restart. For more information, see [Configure the Greengrass nucleus as a system service](configure-greengrass-core-v2.md#configure-system-service).
This object or string contains the following information:    
`BootstrapOnRollback`  
When this feature is enabled, `BootstrapOnRollback` will only run for components that have either completed or attempted to run the bootstrap lifecycle steps as part of a failed target deployment. This feature is available for Greengrass nucleus versions 2.12.0 and later.
(Optional) You can run the bootstrap lifecycle steps as part of a rollback deployment. If you set this option to `true`, the bootstrap lifecycle steps defined within a rollback deployment will run. When a deployment fails, the previous version of the component bootstrap lifecycle will run again during a rollback deployment.  
Defaults to `false`.  
`Script`  
The script to run. The exit code of this script defines the restart instruction. Use the following exit codes:  
+ `0` – Don't restart the AWS IoT Greengrass Core software or the core device. The AWS IoT Greengrass Core software still restarts after all components bootstrap.
+ `100` – Request to restart the AWS IoT Greengrass Core software.
+ `101` – Request to restart the core device.
Exit codes 100 to 199 are reserved for special behavior. Other exit codes represent script errors.  
`RequiresPrivilege`  <a name="recipe-lifecycle-requiresprivilege"></a>
(Optional) If you set this option to `true`, the AWS IoT Greengrass Core software runs this lifecycle script as the user that runs the Greengrass nucleus instead of the system user configured for this component. When the nucleus runs as root, this grants root privileges to the script. Defaults to `false`.  
`Timeout`  <a name="recipe-lifecycle-timeout"></a>
(Optional) The maximum amount of time in seconds that the script can run before the AWS IoT Greengrass Core software terminates the process.  
Default: 120 seconds  
`Setenv`  <a name="recipe-lifecycle-environment"></a>
(Optional) The dictionary of environment variables to provide to the script. These environment variables override the variables that you provide in `Lifecycle.Setenv`.  
  `Selections`   
(Optional) A list of selection keys that specify sections of the [global lifecycle](#global-lifecycle-definition) to run for this manifest. In the global lifecycle, you can define lifecycle steps with selection keys at any level to select sub-sections of the lifecycle. Then, the core device uses those sections that match the selection keys in this manifest. For more information, see the [global lifecycle examples](#global-lifecycle-definition).  
The core device uses the selections from the global lifecycle only if this manifest doesn't define a lifecycle.
You can specify the `all` selection key to run sections of the global lifecycle that don't have selection keys.  
  `Artifacts`   
(Optional) A list of objects that each define a binary artifact for the component on the platform that this manifest defines. For example, you can define code or images as artifacts.  
When the component deploys, the AWS IoT Greengrass Core software downloads the artifact to a folder on the core device. You can also define artifacts as archive files that the software extracts after it downloads them.  
You can use [recipe variables](#recipe-variables) to get the paths to the folders where the artifacts install on the core device.  
+ Normal files – Use the [artifacts:path recipe variable](#component-recipe-artifacts-path) to get the path to the folder that contains the artifacts. For example, specify `{artifacts:path}/my_script.py` in a recipe to get the path to an artifact that has the URI `s3://amzn-s3-demo-bucket/path/to/my_script.py`.
+ Extracted archives – Use the [artifacts:decompressedPath recipe variable](#component-recipe-artifacts-decompressed-path) to get the path to the folder that contains the extracted archive artifacts. The AWS IoT Greengrass Core software extracts each archive to a folder with the same name as the archive. For example, specify `{artifacts:decompressedPath}/my_archive/my_script.py` in a recipe to get the path to `my_script.py` in the archive artifact that has the URI `s3://amzn-s3-demo-bucket/path/to/my_archive.zip`.
When you develop a component with an archive artifact on a local core device, you might not have a URI for that artifact. To test your component with an `Unarchive` option that extracts the artifact, specify a URI where the file name matches the name of your archive artifact file. You can specify the URI where you expect to upload the archive artifact, or you can specify a new placeholder URI. For example, to extract the `my_archive.zip` artifact during a local deployment, you can specify `s3://amzn-s3-demo-bucket/my_archive.zip`.
Each object contains the following information:    
`Uri`  
The URI of an artifact in an S3 bucket. The AWS IoT Greengrass Core software fetches the artifact from this URI when the component installs, unless the artifact already exists on the device. Each artifact must have a unique file name within each manifest.  
`Unarchive`  
(Optional) The type of archive to unpack. Choose from the following options:  
+ `NONE` – The file isn't an archive to unpack. The AWS IoT Greengrass Core software installs the artifact to a folder on the core device. You can use the [artifacts:path recipe variable](#component-recipe-artifacts-path) to get the path to this folder.
+ `ZIP` – The file is a ZIP archive. The AWS IoT Greengrass Core software extracts the archive to a folder with the same name as the archive. You can use the [artifacts:decompressedPath recipe variable](#component-recipe-artifacts-decompressed-path) to get the path to the folder that contains this folder.
Defaults to `NONE`.  
  `Permission`   
(Optional) An object that defines the access permissions to set for this artifact file. You can set the read permission and the execute permission.  
You can't set the write permission, because the AWS IoT Greengrass Core software doesn't allow components to edit artifact files in the artifacts folder. To edit an artifact file in a component, copy it to another location or publish and deploy a new artifact file.
If you define an artifact as an archive to unpack, then the AWS IoT Greengrass Core software sets these access permissions on the files that it unpacks from the archive. The AWS IoT Greengrass Core software sets the folder's access permissions to `ALL` for `Read` and `Execute`. This allows components to view the unpacked files in the folder. To set permissions on individual files from the archive, you can set the permissions in the [install lifecycle script](#install-lifecycle-definition).  
This object contains the following information:    
`Read`  
(Optional) The read permission to set for this artifact file. To allow other components to access this artifact, such as components that depend on this component, specify `ALL`. Choose from the following options:  
+ `NONE` – The file isn't readable.
+ `OWNER` – The file is readable by the system user that you configure to run this component.
+ `ALL` – The file is readable by all users.
Defaults to `OWNER`.  
`Execute`  
(Optional) The run permission to set for this artifact file. The `Execute` permission implies the `Read` permission. For example, if you specify `ALL` for `Execute`, then all users can read and run this artifact file.  
Choose from the following options:  
+ `NONE` – The file isn't runnable.
+ `OWNER` – The file is runnable by the system user that you configure to run the component.
+ `ALL` – The file is runnable by all users.
Defaults to `NONE`.  
`Digest`  
(Read-only) The cryptographic digest hash of the artifact. When you create a component, AWS IoT Greengrass uses a hash algorithm to calculate a hash of the artifact file. Then, when you deploy the component, the Greengrass nucleus calculates the hash of the downloaded artifact and compares the hash with this digest to verify the artifact before installation. If the hash doesn't match the digest, the deployment fails.  
If you set this parameter, AWS IoT Greengrass replaces the value that you set when you create the component.  
`Algorithm`  
(Read-only) The hash algorithm that AWS IoT Greengrass uses to calculate the digest hash of the artifact.  
If you set this parameter, AWS IoT Greengrass replaces the value that you set when you create the component.

  `Lifecycle`   
An object that defines how to install and run the component. The core device uses the global lifecycle only if the [manifest](#manifest-definition) to use doesn't specify a lifecycle.  
You define this lifecycle outside a manifest. You can also define a [manifest lifecycle](#manifest-lifecycle-definition) that applies to the platforms that match that manifest.
In the global lifecycle, you can specify lifecycles that run for certain [selection keys](#manifest-selections-definition) that you specify in each manifest. Selection keys are strings that identify sections of the global lifecycle to run for each manifest.  
The `all` selection key is the default on any section without a selection key. This means that you can specify the `all` selection key in a manifest to run the sections of the global lifecycle without selection keys. You don't need to specify the `all` selection key in the global lifecycle.  
If a manifest doesn't define a lifecycle or selection keys, the core device defaults to use the `all` selection. This means that in this case, the core device uses the sections of the global lifecycle that don't use selection keys.  
This object contains the same information as the [manifest lifecycle](#manifest-lifecycle-definition), but you can specify selection keys at any level to select sub-sections of the lifecycle.  
We recommend that you use only lowercase letters for each selection key to avoid conflicts between selection keys and lifecycle keys. Lifecycle keys start with a capital letter.

**Example global lifecycle with top-level selection keys**  

```
Lifecycle:
  key1:
    install:
      SkipIf: either onpath executable or exists file
      Script: command1
  key2:
    install:
      Script: command2
  all:
    install:
      Script: command3
```

**Example global lifecycle with bottom-level selection keys**  

```
Lifecycle:
  install:
    Script:
      key1: command1
      key2: command2
      all: command3
```

**Example global lifecycle with multiple levels of selection keys**  

```
Lifecycle:
  key1:
    install:
      SkipIf: either onpath executable or exists file
      Script: command1
  key2:
    install:
      Script: command2
  all:
    install:
      Script:
        key3: command3
        key4: command4
        all: command5
```

## Recipe variables
<a name="recipe-variables"></a>

Recipe variables expose information from the current component and nucleus for you to use in your recipes. For example, you can use a recipe variable to pass component configuration parameters to an application that you run in a lifecycle script.

You can use recipe variables in the following sections of component recipes:
+ Lifecycle definitions.
+ Component configuration definitions, if you use [Greengrass nucleus](greengrass-nucleus-component.md) v2.6.0 or later and set the [interpolateComponentConfiguration](greengrass-nucleus-component.md#greengrass-nucleus-component-configuration-interpolate-component-configuration) configuration option to `true`. You can also use recipes variables when you [deploy component configuration updates](update-component-configurations.md#merge-configuration-update-recipe-variables).

Recipe variables use `{recipe_variable}` syntax. The curly braces indicate a recipe variable.

AWS IoT Greengrass supports the following recipe variables:

`component_dependency_name:configuration:json_pointer`  
The value of a configuration parameter for the component that this recipe defines or for a component on which this component depends.  
You can use this variable to provide a parameter to a script that you run in the component lifecycle.  
AWS IoT Greengrass supports this recipe variable only in component lifecycle definitions.
This recipe variable has the following inputs:  
+ <a name="recipe-variable-component-dependency-name"></a>`component_dependency_name` – (Optional) The name of the component dependency to query. Omit this segment to query the component that this recipe defines. You can specify only direct dependencies.
+ `json_pointer` – The JSON pointer to the configuration value to evaluate. JSON pointers start with a forward slash `/`. To identify a value in a nested component configuration, use forward slashes (`/`) to separate the keys for each level in the configuration. You can use a number as a key to specify an index in a list. For more information, see the [JSON pointer specification](https://tools.ietf.org/html/rfc6901).

  AWS IoT Greengrass Core uses JSON pointers for recipes in YAML format.
The JSON pointer can reference the following node types:  
+ A value node. AWS IoT Greengrass Core replaces the recipe variable with the string representation of the value. Null values convert to `null` as a string.
+ An object node. AWS IoT Greengrass Core replaces the recipe variable with the serialized JSON string representation of that object.
+ No node. AWS IoT Greengrass Core doesn't replace the recipe variable.
For example, the `{configuration:/Message}` recipe variable retrieves the value of the `Message` key in the component configuration. The `{com.example.MyComponentDependency:configuration:/server/port}` recipe variable retrieves the value of `port` in the `server` configuration object of a component dependency.

  `component_dependency_name:artifacts:path`   
The root path of the artifacts for the component that this recipe defines or for a component on which this component depends.  
When a component installs, AWS IoT Greengrass copies the component's artifacts to the folder that this variable exposes. You can use this variable to identify the location of a script to run in the component lifecycle, for example.  
<a name="recipe-variable-artifact-folder-permissions"></a>The folder at this path is read-only. To modify artifact files, copy the files to another location, such as the current working directory (`$PWD` or `.`). Then, modify the files there.  
<a name="recipe-variable-component-dependency-artifact-file-permissions"></a>To read or run an artifact from a component dependency, that artifact's `Read` or `Execute` permission must be `ALL`. For more information, see the [artifact permissions](#component-artifact-permission) that you define in the component recipe.  
This recipe variable has the following inputs:  
+ <a name="recipe-variable-component-dependency-name"></a>`component_dependency_name` – (Optional) The name of the component dependency to query. Omit this segment to query the component that this recipe defines. You can specify only direct dependencies.

  `component_dependency_name:artifacts:decompressedPath`   
The root path of the decompressed archive artifacts for the component that this recipe defines or for a component on which this component depends.  
When a component installs, AWS IoT Greengrass unpacks the component's archive artifacts to the folder that this variable exposes. You can use this variable to identify the location of a script to run in the component lifecycle, for example.  
Each artifact unzips to a folder within the decompressed path, where the folder has the same name as the artifact minus its extension. For example, a ZIP artifact named `models.zip` unpacks to the `{artifacts:decompressedPath}/models` folder.  
<a name="recipe-variable-artifact-folder-permissions"></a>The folder at this path is read-only. To modify artifact files, copy the files to another location, such as the current working directory (`$PWD` or `.`). Then, modify the files there.  
<a name="recipe-variable-component-dependency-artifact-file-permissions"></a>To read or run an artifact from a component dependency, that artifact's `Read` or `Execute` permission must be `ALL`. For more information, see the [artifact permissions](#component-artifact-permission) that you define in the component recipe.  
This recipe variable has the following inputs:  
+ <a name="recipe-variable-component-dependency-name"></a>`component_dependency_name` – (Optional) The name of the component dependency to query. Omit this segment to query the component that this recipe defines. You can specify only direct dependencies.

  `component_dependency_name:work:path`   
This feature is available for v2.0.4 and later of the [Greengrass nucleus component](greengrass-nucleus-component.md).  
The work path for the component that this recipe defines or for a component on which this component depends. The value of this recipe variable is equivalent to the output of the `$PWD` environment variable and the [pwd](https://en.wikipedia.org/wiki/Pwd) command when run from the context of the component.  
You can use this recipe variable to share files between a component and a dependency.  
The folder at this path is readable and writable by the component that this recipe defines and by other components that run as the same user and group.  
This recipe variable has the following inputs:  
+ <a name="recipe-variable-component-dependency-name"></a>`component_dependency_name` – (Optional) The name of the component dependency to query. Omit this segment to query the component that this recipe defines. You can specify only direct dependencies.

`kernel:rootPath`  
The AWS IoT Greengrass Core root path.

`iot:thingName`  
This feature is available for v2.3.0 and later of the [Greengrass nucleus component](greengrass-nucleus-component.md).  
The name of the core device's AWS IoT thing.

## Recipe examples
<a name="recipe-examples"></a>

You can reference the following recipe examples to help you create recipes for your components.

AWS IoT Greengrass curates an index of Greengrass components, called the Greengrass Software Catalog. This catalog tracks Greengrass components that are developed by the Greengrass community. From this catalog, you can download, modify, and deploy components to create your Greengrass applications. For more information, see [Community components](greengrass-software-catalog.md).

**Topics**
+ [

### Hello World component recipe
](#recipe-example-hello-world)
+ [

### Python runtime component example
](#recipe-example-python-runtime)
+ [

### Component recipe that specifies several fields
](#recipe-example-all-fields)

### Hello World component recipe
<a name="recipe-example-hello-world"></a>

The following recipe describes a Hello World component that runs a Python script. This component supports all platforms and accepts a `Message` parameter that AWS IoT Greengrass passes as an argument to the Python script. This is the recipe for the Hello World component in the [Getting started tutorial](getting-started.md).

------
#### [ 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": "python3 -u {artifacts:path}/hello_world.py {configuration:/Message}"
      }
    },
    {
      "Platform": {
        "os": "windows"
      },
      "Lifecycle": {
        "run": "py -3 -u {artifacts:path}/hello_world.py {configuration:/Message}"
      }
    }
  ]
}
```

------
#### [ YAML ]

```
---
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: |
        python3 -u {artifacts:path}/hello_world.py "{configuration:/Message}"
  - Platform:
      os: windows
    Lifecycle:
      run: |
        py -3 -u {artifacts:path}/hello_world.py "{configuration:/Message}"
```

------

### Python runtime component example
<a name="recipe-example-python-runtime"></a>

The following recipe describes a component that installs Python. This component supports 64-bit Linux devices.

------
#### [ JSON ]

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.PythonRuntime",
  "ComponentDescription": "Installs Python 3.7",
  "ComponentPublisher": "Amazon",
  "ComponentVersion": "3.7.0",
  "Manifests": [
    {
      "Platform": {
        "os": "linux",
        "architecture": "amd64"
      },
      "Lifecycle": {
        "install": "apt-get update\napt-get install python3.7"
      }
    }
  ]
}
```

------
#### [ YAML ]

```
---
RecipeFormatVersion: '2020-01-25'
ComponentName: com.example.PythonRuntime
ComponentDescription: Installs Python 3.7
ComponentPublisher: Amazon
ComponentVersion: '3.7.0'
Manifests:
  - Platform:
      os: linux
      architecture: amd64
    Lifecycle:
      install: |
        apt-get update
        apt-get install python3.7
```

------

### Component recipe that specifies several fields
<a name="recipe-example-all-fields"></a>

The following component recipe uses several recipe fields.

------
#### [ JSON ]

```
{
  "RecipeFormatVersion": "2020-01-25",
  "ComponentName": "com.example.FooService",
  "ComponentDescription": "Complete recipe for AWS IoT Greengrass components",
  "ComponentPublisher": "Amazon",
  "ComponentVersion": "1.0.0",
  "ComponentConfiguration": {
    "DefaultConfiguration": {
      "TestParam": "TestValue"
    }
  },
  "ComponentDependencies": {
    "BarService": {
      "VersionRequirement": "^1.1.0",
      "DependencyType": "SOFT"
    },
    "BazService": {
      "VersionRequirement": "^2.0.0"
    }
  },
  "Manifests": [
    {
      "Platform": {
        "os": "linux",
        "architecture": "amd64"
      },
      "Lifecycle": {
        "install": {
          "Skipif": "onpath git",
          "Script": "sudo apt-get install git"
        },
        "Setenv": {
          "environment_variable1": "variable_value1",
          "environment_variable2": "variable_value2"
        }
      },
      "Artifacts": [
        {
          "Uri": "s3://amzn-s3-demo-bucket/hello_world.zip",
          "Unarchive": "ZIP"
        },
        {
          "Uri": "s3://amzn-s3-demo-bucket/hello_world_linux.py"
        }
      ]
    },
    {
      "Lifecycle": {
        "install": {
          "Skipif": "onpath git",
          "Script": "sudo apt-get install git",
          "RequiresPrivilege": "true"
        }
      },
      "Artifacts": [
        {
          "Uri": "s3://amzn-s3-demo-bucket/hello_world.py"
        }
      ]
    }
  ]
}
```

------
#### [ YAML ]

```
---
RecipeFormatVersion: '2020-01-25'
ComponentName: com.example.FooService
ComponentDescription: Complete recipe for AWS IoT Greengrass components
ComponentPublisher: Amazon
ComponentVersion: 1.0.0
ComponentConfiguration:
  DefaultConfiguration:
    TestParam: TestValue
ComponentDependencies:
  BarService:
    VersionRequirement: ^1.1.0
    DependencyType: SOFT
  BazService:
    VersionRequirement: ^2.0.0
Manifests:
  - Platform:
      os: linux
      architecture: amd64
    Lifecycle:
      install:
        SkipIf: onpath git
        Script: sudo apt-get install git
      SetEnv:
        environment_variable1: variable_value1
        environment_variable2: variable_value2
    Artifacts:
      - Uri: 's3://amzn-s3-demo-bucket/hello_world.zip'
        Unarchive: ZIP
      - Uri: 's3://amzn-s3-demo-bucket/hello_world_linux.py'
  - Lifecycle:
      install:
        SkipIf: onpath git
        Script: sudo apt-get install git
        RequiresPrivilege: 'true'
    Artifacts:
      - Uri: 's3://amzn-s3-demo-bucket/hello_world.py'
```

------

# Component environment variable reference
<a name="component-environment-variables"></a>

The AWS IoT Greengrass Core software sets environment variables when it runs lifecycle scripts for components. You can get these environment variables in your components to get the thing name, AWS Region, and Greengrass nucleus version. The software also sets environment variables that your component requires to use [the interprocess communication SDK](interprocess-communication.md) and to [interact with AWS services](interact-with-aws-services.md).

You can also set custom environment variables for your component's lifecycle scripts. For more information, see [Setenv](component-recipe-reference.md#lifecycle-setenv-definition).

The AWS IoT Greengrass Core software sets the following environment variables:

`AWS_IOT_THING_NAME`  
The name of the AWS IoT thing that represents this Greengrass core device.

`AWS_REGION`  
The AWS Region where this Greengrass core device operates.  
The AWS SDKs use this environment variable to identify the default Region to use. This variable is equivalent to `AWS_DEFAULT_REGION`.

`AWS_DEFAULT_REGION`  
The AWS Region where this Greengrass core device operates.  
The AWS CLI uses this environment variable to identify the default Region to use. This variable is equivalent to `AWS_REGION`.

`GGC_VERSION`  
The version of the [Greengrass nucleus component](greengrass-nucleus-component.md) that runs on this Greengrass core device.

`GG_ROOT_CA_PATH`  
This feature is available for v2.5.5 and later of the [Greengrass nucleus component](greengrass-nucleus-component.md).  
The path to the root certificate authority (CA) certificate that the Greengrass nucleus uses.

`AWS_GG_NUCLEUS_DOMAIN_SOCKET_FILEPATH_FOR_COMPONENT`  
The path to the IPC socket that components use to communicate with the AWS IoT Greengrass Core software. For more information, see [Use the AWS IoT Device SDK to communicate with the Greengrass nucleus, other components, and AWS IoT CoreCommunicate with the Greengrass nucleus, other components, and AWS IoT Core](interprocess-communication.md).

`SVCUID`  
The secret token that components use to connect to the IPC socket and communicate with the AWS IoT Greengrass Core software. For more information, see [Use the AWS IoT Device SDK to communicate with the Greengrass nucleus, other components, and AWS IoT CoreCommunicate with the Greengrass nucleus, other components, and AWS IoT Core](interprocess-communication.md).

`AWS_CONTAINER_AUTHORIZATION_TOKEN`  
The secret token that components use to retrieve credentials from the [token exchange service component](token-exchange-service-component.md).

`AWS_CONTAINER_CREDENTIALS_FULL_URI`  
The URI that components request to retrieve credentials from the [token exchange service component](token-exchange-service-component.md).