Tutorial: Getting started with Amazon IoT Greengrass V2 - Amazon IoT Greengrass
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Tutorial: Getting started with Amazon IoT Greengrass V2

You can complete this getting started tutorial to learn about the basic features of Amazon IoT Greengrass V2. In this tutorial, you do the following:

  1. Install and configure the Amazon IoT Greengrass Core software on a Linux device, such as a Raspberry Pi, or a Windows device. This device is a Greengrass core device.

  2. Develop a Hello World component on your Greengrass core device. Components are software modules that run on Greengrass core devices.

  3. Upload that component to Amazon IoT Greengrass V2 in the Amazon Web Services Cloud.

  4. Deploy that component from the Amazon Web Services Cloud to your Greengrass core device.

Note

This tutorial describes how to set up a development environment and explore the features of Amazon IoT Greengrass. For more information about how to set up and configure production devices, see the following:

You can expect to spend 20 to 30 minutes on this tutorial.

Prerequisites

To complete this getting started tutorial, you need the following:

  • An Amazon Web Services account. If you don't have one, see Step 1: Set up an Amazon account.

  • The use of an Amazon Web Services Region that supports Amazon IoT Greengrass V2. For the list of supported Regions, see Amazon IoT Greengrass V2 endpoints and quotas in the Amazon General Reference.

  • An Amazon Identity and Access Management (IAM) user with administrator permissions.

  • A Windows, macOS, or Unix-like development computer with an internet connection.

  • A device to set up as a Greengrass core device, such as a Raspberry Pi with Raspberry Pi OS (previously called Raspbian), or a Windows 10 device. You must have administrator permissions on this device, or the ability to acquire administrator privileges, such as through sudo. This device must have an internet connection.

    You can also choose to use a different device that meets the requirements to install and run the Amazon IoT Greengrass Core software. For more information, see Supported platforms and requirements.

    If your development computer meets these requirements, you can set it up as your Greengrass core device in this tutorial.

  • Python 3.5 or later installed for all users on the device and added to the PATH environment variable. On Windows, you must also have the Python Launcher for Windows installed for all users.

    Important

    In Windows, Python doesn't install for all users by default. When you install Python, you must customize the installation to configure it for the Amazon IoT Greengrass Core software to run Python scripts. For example, if you use the graphical Python installer, do the following:

    1. Select Install launcher for all users (recommended).

    2. Choose Customize installation.

    3. Choose Next.

    4. Select Install for all users.

    5. Select Add Python to environment variables.

    6. Choose Install.

    For more information, see Using Python on Windows in the Python 3 documentation.

  • Amazon Command Line Interface (Amazon CLI) installed and configured with credentials on your development computer and on your device. Make sure you use the same Amazon Web Services Region to configure the Amazon CLI on your development computer and on your device. To use Amazon IoT Greengrass V2 with the Amazon CLI, you must have one of the following versions or later:

    • Minimum Amazon CLI V1 version: v1.18.197

    • Minimum Amazon CLI V2 version: v2.1.11

    Tip

    You can run the following command to check the version of the Amazon CLI that you have.

    aws --version

    For more information, see Installing, updating, and uninstalling the Amazon CLI and Configuring the Amazon CLI in the Amazon Command Line Interface User Guide.

    Note

    If you use a 32-bit ARM device, such as a Raspberry Pi with a 32-bit operating system, install Amazon CLI V1. Amazon CLI V2 isn't available for 32-bit ARM devices. For more information, see Installing, updating, and uninstalling the Amazon CLI version 1.

Step 1: Set up an Amazon account

Sign up for an Amazon Web Services account

If you do not have an Amazon Web Services account, use the following procedure to create one.

To sign up for Amazon Web Services
  1. Open http://www.amazonaws.cn/ and choose Sign Up.

  2. Follow the on-screen instructions.

Amazon sends you a confirmation email after the sign-up process is complete. At any time, you can view your current account activity and manage your account by going to http://www.amazonaws.cn/ and choosing My Account.

Secure IAM users

After you sign up for an Amazon Web Services account, safeguard your administrative user by turning on multi-factor authentication (MFA). For instructions, see Enable a virtual MFA device for an IAM user (console) in the IAM User Guide.

To give other users access to your Amazon Web Services account resources, create IAM users. To secure your IAM users, turn on MFA and only give the IAM users the permissions needed to perform their tasks.

For more information about creating and securing IAM users, see the following topics in the IAM User Guide:

Step 2: Set up your environment

Follow the steps in this section to set up a Linux or Windows device to use as your Amazon IoT Greengrass core device.

These steps assume that you use a Raspberry Pi with Raspberry Pi OS. If you use a different device or operating system, consult the relevant documentation for your device.

To set up a Raspberry Pi for Amazon IoT Greengrass V2
  1. Enable SSH on your Raspberry Pi to remotely connect to it. For more information, see SSH (Secure shell) in the Raspberry Pi Documentation.

  2. Find the IP address of your Raspberry Pi to connect to it with SSH. To do so, you can run the following command on your Raspberry Pi.

    hostname -I
  3. Connect to your Raspberry Pi with SSH.

    On your development computer, run the following command. Replace username with the name of the user to sign in, and replace pi-ip-address with the IP address that you found in the previous step.

    ssh username@pi-ip-address

    The default Raspberry Pi user name and password are pi and raspberry, respectively.

    Important

    If your development computer uses an earlier version of Windows, you might not have the ssh command, or you might have ssh but can't connect to your Raspberry Pi. To connect to your Raspberry Pi, you can install and configure PuTTY, which is a no-cost, open source SSH client. Consult the PuTTY documentation to connect to your Raspberry Pi.

  4. Install the Java runtime, which Amazon IoT Greengrass Core software requires to run. On your Raspberry Pi, use the following commands to install Java 11.

    sudo apt install default-jdk

    When the installation completes, run the following command to verify that Java runs on your Raspberry Pi.

    java -version

    The command prints the version of Java that runs on the device. The output might look similar to the following example.

    openjdk version "11.0.9.1" 2020-11-04 OpenJDK Runtime Environment (build 11.0.9.1+1-post-Debian-1deb10u2) OpenJDK 64-Bit Server VM (build 11.0.9.1+1-post-Debian-1deb10u2, mixed mode)
To set up a Linux device for Amazon IoT Greengrass V2
  1. Install the Java runtime, which Amazon IoT Greengrass Core software requires to run. We recommend that you use Amazon Corretto 11 or OpenJDK 11. The following commands show you how to install OpenJDK on your device.

    • For Debian-based or Ubuntu-based distributions:

      sudo apt install default-jdk
    • For Red Hat-based distributions:

      sudo yum install java-11-openjdk-devel
    • For Amazon Linux 2:

      sudo amazon-linux-extras install java-openjdk11

    When the installation completes, run the following command to verify that Java runs on your Linux device.

    java -version

    The command prints the version of Java that runs on the device. For example, on a Debian-based distribution, the output might look similar to the following sample.

    openjdk version "11.0.9.1" 2020-11-04
    OpenJDK Runtime Environment (build 11.0.9.1+1-post-Debian-1deb10u2)
    OpenJDK 64-Bit Server VM (build 11.0.9.1+1-post-Debian-1deb10u2, mixed mode)
  2. (Optional) Create the default system user and group that runs components on the device. You can also choose to let the Amazon IoT Greengrass Core software installer create this user and group during installation with the --component-default-user installer argument. For more information, see Installer arguments.

    sudo useradd --system --create-home ggc_user sudo groupadd --system ggc_group
  3. Verify that the user that runs the Amazon IoT Greengrass Core software (typically root), has permission to run sudo with any user and any group.

    1. Run the following command to open the /etc/sudoers file.

      sudo visudo
    2. Verify that the permission for the user looks like the following example.

      root ALL=(ALL:ALL) ALL
  4. (Optional) To run containerized Lambda functions, you must enable cgroups v1, and you must enable and mount the memory and devices cgroups. If you don't plan to run containerized Lambda functions, you can skip this step.

    To enable these cgroups options, boot the device with the following Linux kernel parameters.

    cgroup_enable=memory cgroup_memory=1 systemd.unified_cgroup_hierarchy=0

    For information about viewing and setting kernel parameters for your device, see the documentation for your operating system and boot loader. Follow the instructions to permanently set the kernel parameters.

    Tip: Set kernel parameters on a Raspberry Pi

    If your device is a Raspberry Pi, you can complete the following steps to view and update its Linux kernel parameters:

    1. Open the /boot/cmdline.txt file. This file specifies Linux kernel parameters to apply when the Raspberry Pi boots.

      For example, on a Linux-based system, you can run the following command to use GNU nano to open the file.

      sudo nano /boot/cmdline.txt
    2. Verify that the /boot/cmdline.txt file contains the following kernel parameters. The systemd.unified_cgroup_hierarchy=0 parameter specifies to use cgroups v1 instead of cgroups v2.

      cgroup_enable=memory cgroup_memory=1 systemd.unified_cgroup_hierarchy=0

      If the /boot/cmdline.txt file doesn't contain these parameters, or it contains these parameters with different values, update the file to contain these parameters and values.

    3. If you updated the /boot/cmdline.txt file, reboot the Raspberry Pi to apply the changes.

      sudo reboot
  5. Install all other required dependencies on your device as indicated by the list of requirements in Device requirements.

To set up a Windows device for Amazon IoT Greengrass V2
  1. Install the Java runtime, which Amazon IoT Greengrass Core software requires to run. We recommend that you use Amazon Corretto 11 or OpenJDK 11.

  2. Check whether Java is available on the PATH system variable, and add it if not. The LocalSystem account runs the Amazon IoT Greengrass Core software, so you must add Java to the PATH system variable instead of the PATH user variable for your user. Do the following:

    1. Press the Windows key to open the start menu.

    2. Type environment variables to search for the system options from the start menu.

    3. In the start menu search results, choose Edit the system environment variables to open the System properties window.

    4. Choose Environment variables... to open the Environment Variables window.

    5. Under System variables, select Path, and then choose Edit. In the Edit environment variable window, you can view each path on a separate line.

    6. Check if the path to the Java installation's bin folder is present. The path might look similar to the following example.

      C:\Program Files\Amazon Corretto\jdk11.0.13_8\bin
    7. If the Java installation's bin folder is missing from Path, choose New to add it, and then choose OK.

  3. Open the Windows Command Prompt (cmd.exe) as an administrator.

  4. Create the default user in the LocalSystem account on the Windows device. Replace password with a secure password.

    net user /add ggc_user password
    Tip

    Depending on your Windows configuration, the user's password might be set to expire at a date in the future. To ensure your Greengrass applications continue to operate, track when the password expires, and update it before it expires. You can also set the user's password to never expire.

    • To check when a user and its password expire, run the following command.

      net user ggc_user | findstr /C:expires
    • To set a user's password to never expire, run the following command.

      wmic UserAccount where "Name='ggc_user'" set PasswordExpires=False
  5. Download and install the PsExec utility from Microsoft on the device.

  6. Use the PsExec utility to store the user name and password for the default user in the Credential Manager instance for the LocalSystem account. Replace password with the user's password that you set earlier.

    psexec -s cmd /c cmdkey /generic:ggc_user /user:ggc_user /pass:password

    If the PsExec License Agreement opens, choose Accept to agree to the license and run the command.

    Note

    On Windows devices, the LocalSystem account runs the Greengrass nucleus, and you must use the PsExec utility to store the default user information in the LocalSystem account. Using the Credential Manager application stores this information in the Windows account of the currently logged on user, instead of the LocalSystem account.

Step 3: Install the Amazon IoT Greengrass Core software

Follow the steps in this section to set up your Raspberry Pi as a Amazon IoT Greengrass core device that you can use for local development. In this section, you download and run an installer that does the following to configure the Amazon IoT Greengrass Core software for your device:

  • Installs the Greengrass nucleus component. The nucleus is a mandatory component and is the minimum requirement to run the Amazon IoT Greengrass Core software on a device. For more information, see Greengrass nucleus component.

  • Registers your device as an Amazon IoT thing and downloads a digital certificate that allows your device to connect to Amazon. For more information, see Device authentication and authorization for Amazon IoT Greengrass.

  • Adds the device's Amazon IoT thing to a thing group, which is a group or fleet of Amazon IoT things. Thing groups enable you to manage fleets of Greengrass core devices. When you deploy software components to your devices, you can choose to deploy to individual devices or to groups of devices. For more information, see Managing devices with Amazon IoT in the Amazon IoT Core Developer Guide.

  • Creates the IAM role that allows your Greengrass core device to interact with Amazon services. By default, this role allows your device to interact with Amazon IoT and send logs to Amazon CloudWatch Logs. For more information, see Authorize core devices to interact with Amazon services.

  • Installs the Amazon IoT Greengrass command line interface (greengrass-cli), which you can use to test custom components that you develop on the core device. For more information, see Greengrass Command Line Interface.

  1. Sign in to the Amazon IoT Greengrass console.

  2. Under Get started with Greengrass, choose Set up one core device.

  3. Under Step 1: Register a Greengrass core device, for Core device name, enter the name of the Amazon IoT thing for your Greengrass core device. If the thing doesn't exist, the installer creates it.

  4. Under Step 2: Add to a thing group to apply a continuous deployment, for Thing group, choose the Amazon IoT thing group to which you want to add your core device.

    • If you select Enter a new group name, then in Thing group name, enter the name of the new group to create. The installer creates the new group for you.

    • If you select Select an existing group, then in Thing group name, choose the existing group that you want to use.

    • If you select No group, then the installer doesn't add the core device to a thing group.

  5. Under Step 3: Install the Greengrass Core software, complete the following steps.

    1. Choose your core device's operating system: Linux or Windows.

    2. Provide your Amazon credentials to the device so that the installer can provision the Amazon IoT and IAM resources for your core device. To increase security, we recommend that you get temporary credentials for an IAM role that allows only the minimum permissions necessary to provision. For more information, see Minimal IAM policy for installer to provision resources.

      Note

      The installer doesn't save or store your credentials.

      On your device, do one of the following to retrieve credentials and make them available to the Amazon IoT Greengrass Core software installer:

      • Use long-term credentials from an IAM user:

        1. Provide the access key ID and secret access key for your IAM user. For more information about how to retrieve long-term credentials, see Managing access keys for IAM users in the IAM User Guide.

        2. Run the following commands to provide the credentials to the Amazon IoT Greengrass Core software.

          Linux or Unix
          export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
          Windows Command Prompt (CMD)
          set AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE set AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
          PowerShell
          $env:AWS_ACCESS_KEY_ID="AKIAIOSFODNN7EXAMPLE" $env:AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
      • (Recommended) Use temporary security credentials from an IAM role:

        1. Provide the access key ID, secret access key, and session token from an IAM role that you assume. For more information about how to retrieve these credentials, see Requesting temporary security credentials in the IAM User Guide.

        2. Run the following commands to provide the credentials to the Amazon IoT Greengrass Core software.

          Linux or Unix
          export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY export AWS_SESSION_TOKEN=AQoDYXdzEJr1K...o5OytwEXAMPLE=
          Windows Command Prompt (CMD)
          set AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE set AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY set AWS_SESSION_TOKEN=AQoDYXdzEJr1K...o5OytwEXAMPLE=
          PowerShell
          $env:AWS_ACCESS_KEY_ID="AKIAIOSFODNN7EXAMPLE" $env:AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" $env:AWS_SESSION_TOKEN="AQoDYXdzEJr1K...o5OytwEXAMPLE="
    3. Under Run the installer, complete the following steps.

      1. Under Download the installer, choose Copy and run the copied command on your core device. This command downloads the latest version of the Amazon IoT Greengrass Core software and unzips it on your device.

      2. Under Run the installer, choose Copy, and run the copied command on your core device. This command uses the Amazon IoT thing and thing group names that you specified earlier to run the Amazon IoT Greengrass Core software installer and set up Amazon resources for your core device.

        This command also does the following:

        • Set up the Amazon IoT Greengrass Core software as a system service that runs at boot. On Linux devices, this requires the Systemd init system.

          Important

          On Windows core devices, you must set up the Amazon IoT Greengrass Core software as a system service.

        • Deploy the Amazon IoT Greengrass CLI component, which is a command-line tool that enables you to develop custom Greengrass components on the core device.

        • Specify to use the ggc_user system user to run software components on the core device. On Linux devices, this command also specifies to use the ggc_group system group, and the installer creates the system user and group for you.

        When you run this command, you should see the following messages to indicate that the installer succeeded.

        Successfully configured Nucleus with provisioned resource details! Configured Nucleus to deploy aws.greengrass.Cli component Successfully set up Nucleus as a system service
        Note

        If you have a Linux device and it doesn't have systemd, the installer won't set up the software as a system service, and you won't see the success message for setting up the nucleus as a system service.

To install and configure the Amazon IoT Greengrass Core software
  1. On your Greengrass core device, run the following command to switch to the home directory.

    Linux or Unix
    cd ~
    Windows Command Prompt (CMD)
    cd %USERPROFILE%
    PowerShell
    cd ~
  2. On your core device, download the Amazon IoT Greengrass Core software to a file named greengrass-nucleus-latest.zip.

    Linux or Unix
    curl -s https://d2s8p88vqu9w66.cloudfront.net/releases/greengrass-nucleus-latest.zip > greengrass-nucleus-latest.zip
    Windows Command Prompt (CMD)
    curl -s https://d2s8p88vqu9w66.cloudfront.net/releases/greengrass-nucleus-latest.zip > greengrass-nucleus-latest.zip
    PowerShell
    iwr -Uri https://d2s8p88vqu9w66.cloudfront.net/releases/greengrass-nucleus-latest.zip -OutFile greengrass-nucleus-latest.zip

    By downloading this software, you agree to the Greengrass Core Software License Agreement.

  3. Unzip the Amazon IoT Greengrass Core software to a folder on your device. Replace GreengrassInstaller with the folder that you want to use.

    Linux or Unix
    unzip greengrass-nucleus-latest.zip -d GreengrassInstaller && rm greengrass-nucleus-latest.zip
    Windows Command Prompt (CMD)
    mkdir GreengrassInstaller && tar -xf greengrass-nucleus-latest.zip -C GreengrassInstaller && del greengrass-nucleus-latest.zip
    PowerShell
    Expand-Archive -Path greengrass-nucleus-latest.zip -DestinationPath .\GreengrassInstaller rm greengrass-nucleus-latest.zip
  4. Run the following command to launch the Amazon IoT Greengrass Core software installer. This command does the following:

    • Create the Amazon resources that the core device requires to operate.

    • Set up the Amazon IoT Greengrass Core software as a system service that runs at boot. On Linux devices, this requires the Systemd init system.

      Important

      On Windows core devices, you must set up the Amazon IoT Greengrass Core software as a system service.

    • Deploy the Amazon IoT Greengrass CLI component, which is a command-line tool that enables you to develop custom Greengrass components on the core device.

    • Specify to use the ggc_user system user to run software components on the core device. On Linux devices, this command also specifies to use the ggc_group system group, and the installer creates the system user and group for you.

    Replace argument values in your command as follows.

    1. /greengrass/v2 or C:\greengrass\v2: The path to the root folder to use to install the Amazon IoT Greengrass Core software.

    2. GreengrassInstaller. The path to the folder where you unpacked the Amazon IoT Greengrass Core software installer.

    3. region. The Amazon Web Services Region in which to find or create resources.

    4. MyGreengrassCore. The name of the Amazon IoT thing for your Greengrass core device. If the thing doesn't exist, the installer creates it. The installer downloads the certificates to authenticate as the Amazon IoT thing. For more information, see Device authentication and authorization for Amazon IoT Greengrass.

      Note

      The thing name can't contain colon (:) characters.

    5. MyGreengrassCoreGroup. The name of Amazon IoT thing group for your Greengrass core device. If the thing group doesn't exist, the installer creates it and adds the thing to it. If the thing group exists and has an active deployment, the core device downloads and runs the software that the deployment specifies.

      Note

      The thing group name can't contain colon (:) characters.

    6. GreengrassV2IoTThingPolicy. The name of the Amazon IoT policy that allows the Greengrass core devices to communicate with Amazon IoT and Amazon IoT Greengrass. If the Amazon IoT policy doesn't exist, the installer creates a permissive Amazon IoT policy with this name. You can restrict this policy's permissions for you use case. For more information, see Minimal Amazon IoT policy for Amazon IoT Greengrass V2 core devices.

    7. GreengrassV2TokenExchangeRole. The name of the IAM role that allows the Greengrass core device to get temporary Amazon credentials. If the role doesn't exist, the installer creates it and creates and attaches a policy named GreengrassV2TokenExchangeRoleAccess. For more information, see Authorize core devices to interact with Amazon services.

    8. GreengrassCoreTokenExchangeRoleAlias. The alias to the IAM role that allows the Greengrass core device to get temporary credentials later. If the role alias doesn't exist, the installer creates it and points it to the IAM role that you specify. For more information, see Authorize core devices to interact with Amazon services.

    Linux or Unix
    sudo -E java -Droot="/greengrass/v2" -Dlog.store=FILE \ -jar ./GreengrassInstaller/lib/Greengrass.jar \ --aws-region region \ --thing-name MyGreengrassCore \ --thing-group-name MyGreengrassCoreGroup \ --thing-policy-name GreengrassV2IoTThingPolicy \ --tes-role-name GreengrassV2TokenExchangeRole \ --tes-role-alias-name GreengrassCoreTokenExchangeRoleAlias \ --component-default-user ggc_user:ggc_group \ --provision true \ --setup-system-service true \ --deploy-dev-tools true
    Windows Command Prompt (CMD)
    java -Droot="C:\greengrass\v2" "-Dlog.store=FILE" ^ -jar ./GreengrassInstaller/lib/Greengrass.jar ^ --aws-region region ^ --thing-name MyGreengrassCore ^ --thing-group-name MyGreengrassCoreGroup ^ --thing-policy-name GreengrassV2IoTThingPolicy ^ --tes-role-name GreengrassV2TokenExchangeRole ^ --tes-role-alias-name GreengrassCoreTokenExchangeRoleAlias ^ --component-default-user ggc_user ^ --provision true ^ --setup-system-service true ^ --deploy-dev-tools true
    PowerShell
    java -Droot="C:\greengrass\v2" "-Dlog.store=FILE" ` -jar ./GreengrassInstaller/lib/Greengrass.jar ` --aws-region region ` --thing-name MyGreengrassCore ` --thing-group-name MyGreengrassCoreGroup ` --thing-policy-name GreengrassV2IoTThingPolicy ` --tes-role-name GreengrassV2TokenExchangeRole ` --tes-role-alias-name GreengrassCoreTokenExchangeRoleAlias ` --component-default-user ggc_user ` --provision true ` --setup-system-service true ` --deploy-dev-tools true
    Note

    If you are running Amazon IoT Greengrass on a device with limited memory, you can control the amount of memory that Amazon IoT Greengrass Core software uses. To control memory allocation, you can set JVM heap size options in the jvmOptions configuration parameter in your nucleus component. For more information, see Control memory allocation with JVM options.

    When you run this command, you should see the following messages to indicate that the installer succeeded.

    Successfully configured Nucleus with provisioned resource details! Configured Nucleus to deploy aws.greengrass.Cli component Successfully set up Nucleus as a system service
    Note

    If you have a Linux device and it doesn't have systemd, the installer won't set up the software as a system service, and you won't see the success message for setting up the nucleus as a system service.

(Optional) Run the Greengrass software (Linux)

If you installed the software as a system service, the installer runs the software for you. Otherwise, you must run the software. To see if the installer set up the software as a system service, look for the following line in the installer output.

Successfully set up Nucleus as a system service

If you don't see this message, do the following to run the software:

  1. Run the following command to run the software.

    sudo /greengrass/v2/alts/current/distro/bin/loader

    The software prints the following message if it launches successfully.

    Launched Nucleus successfully.
  2. You must leave the current command shell open to keep the Amazon IoT Greengrass Core software running. If you use SSH to connect to the core device, run the following command on your development computer to open a second SSH session that you can use to run additional commands on the core device. Replace username with the name of the user to sign in, and replace pi-ip-address with the IP address of the device.

    ssh username@pi-ip-address

For more information about how to interact with the Greengrass system service, see Configure the Greengrass nucleus as a system service.

Verify the Greengrass CLI installation on the device

The Greengrass CLI can take up to a minute to deploy. Run the following command to check the status of the deployment. Replace MyGreengrassCore with the name of your core device.

aws greengrassv2 list-effective-deployments --core-device-thing-name MyGreengrassCore

The coreDeviceExecutionStatus indicates the status of the deployment to the core device. When the status is SUCCEEDED, run the following command to verify that the Greengrass CLI is installed and runs. Replace /greengrass/v2 with the path to the root folder.

Linux or Unix
/greengrass/v2/bin/greengrass-cli help
Windows Command Prompt (CMD)
C:\greengrass\v2\bin\greengrass-cli help
PowerShell
C:\greengrass\v2\bin\greengrass-cli help

The command outputs help information for the Greengrass CLI. If the greengrass-cli isn't found, the deployment might have failed to install the Greengrass CLI. For more information, see Troubleshooting Amazon IoT Greengrass V2.

You can also run the following command to manually deploy the Amazon IoT Greengrass CLI to your device.

  • Replace region with the Amazon Web Services Region that you use. Make sure that you use the same Amazon Web Services Region that you used to configure the Amazon CLI on your device.

  • Replace account-id with your Amazon Web Services account ID.

  • Replace MyGreengrassCore with the name of your core device.

Linux, macOS, or Unix
aws greengrassv2 create-deployment \ --target-arn "arn:aws-cn:iot:region:account-id:thing/MyGreengrassCore" \ --components '{ "aws.greengrass.Cli": { "componentVersion": "2.9.4" } }'
Windows Command Prompt (CMD)
aws greengrassv2 create-deployment ^ --target-arn "arn:aws-cn:iot:region:account-id:thing/MyGreengrassCore" ^ --components "{\"aws.greengrass.Cli\":{\"componentVersion\":\"2.9.4\"}}"
PowerShell
aws greengrassv2 create-deployment ` --target-arn "arn:aws-cn:iot:region:account-id:thing/MyGreengrassCore" ` --components '{\"aws.greengrass.Cli\":{\"componentVersion\":\"2.9.4\"}}'
Tip

You can add /greengrass/v2/bin (Linux) or C:\greengrass\v2\bin (Windows) to your PATH environment variable to run greengrass-cli without its absolute path.

The Amazon IoT Greengrass Core software and local development tools run on your device. Next, you can develop a Hello World Amazon IoT Greengrass component on your device.

Step 4: Develop and test a component on your device

A component is a software module that runs on Amazon IoT Greengrass core devices. Components enable you to create and manage complex applications as discrete building blocks that you can reuse from one Greengrass core device to another. Every component is composed of a recipe and artifacts.

  • 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 Amazon IoT Greengrass component recipe reference.

    You can define recipes in JSON or YAML format.

  • 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.

With Amazon IoT Greengrass, you can use the Greengrass CLI to develop and test components locally on a Greengrass core device without interaction with the Amazon Cloud. When you complete your local component, you can use the component recipe and artifacts to create that component in the Amazon IoT Greengrass service in the Amazon Cloud, and then deploy it to all of your Greengrass core devices. For more information about components, see Develop Amazon IoT Greengrass components.

In this section, you learn how to create and run a basic Hello World component locally on your core device.

To develop a Hello World component on your device
  1. 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 ~/greengrassv2 or %USERPROFILE%\greengrassv2 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
  2. 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.

    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

    Amazon 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.

  3. Paste the following recipe into the file.

    JSON
    { "RecipeFormatVersion": "2020-01-25", "ComponentName": "com.example.HelloWorld", "ComponentVersion": "1.0.0", "ComponentDescription": "My first Amazon 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 Amazon 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's ComponentConfiguration section defines a parameter, Message, that defaults to world. The Manifests section defines a manifest, which is a set of lifecycle instructions and artifacts for a platform. You can define multiple manifests to specify different install instructions for various platforms, for example. In the manifest, the Lifecycle section instructs the Greengrass core device to run the Hello World script with the Message parameter value as an argument.

  4. Run the following command to create a folder for the component artifacts.

    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

    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/
  5. Use a text editor to create a Python script artifact file for your Hello World component.

    For example, on a Linux-based system, you can run the following command to use GNU nano to create the file.

    nano artifacts/com.example.HelloWorld/1.0.0/hello_world.py

    Copy and paste the following Python script into the file.

    import sys message = "Hello, %s!" % sys.argv[1] # Print the message to stdout, which Greengrass saves in a log file. print(message)
  6. Use the local Amazon IoT Greengrass CLI to manage components on your Greengrass core device.

    Run the following command to deploy the component to the Amazon IoT Greengrass core. Replace /greengrass/v2 or C:\greengrass\v2 with your Amazon IoT Greengrass V2 root folder, and replace ~/greengrassv2 or %USERPROFILE%\greengrassv2 with your component 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"

    This command adds the component that uses the recipe in recipes and the Python script in artifacts. The --merge option adds or updates the component and version that you specify.

  7. The Amazon IoT Greengrass Core software saves stdout from component process to log files in the logs folder. Run the following command to verify that the Hello World component runs and prints messages.

    Linux or Unix
    sudo tail -f /greengrass/v2/logs/com.example.HelloWorld.log
    Windows Command Prompt (CMD)
    type C:\greengrass\v2\logs\com.example.HelloWorld.log

    The type command writes the file's contents to the terminal. Run this command multiple times to observe changes in the file.

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

    You should see messages similar to the following example.

    Hello, world!
    Note

    If the file doesn't exist, the local deployment may not be complete yet. If the file doesn't exist within 15 seconds, the deployment likely failed. This can occur if your recipe isn't valid, for example. Run the following command to view the Amazon IoT Greengrass core log file. This file includes logs from the Greengrass core device's deployment service.

    Linux or Unix
    sudo tail -f /greengrass/v2/logs/greengrass.log
    Windows Command Prompt (CMD)
    type C:\greengrass\v2\logs\greengrass.log

    The type command writes the file's contents to the terminal. Run this command multiple times to observe changes in the file.

    PowerShell
    gc C:\greengrass\v2\logs\greengrass.log -Tail 10 -Wait
  8. Modify the local component to iterate and test your code. Open hello_world.py in a text editor, and add the following code at line 4 to edit the message that the Amazon IoT Greengrass core logs.

    message += " Greetings from your first Greengrass component."

    The hello_world.py script should now have the following contents.

    import sys message = "Hello, %s!" % sys.argv[1] message += " Greetings from your first Greengrass component." # Print the message to stdout, which Greengrass saves in a log file. print(message)
  9. Run the following command to update the component with your changes.

    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"

    This command updates the com.example.HelloWorld component with the latest Hello World artifact.

  10. Run the following command to restart the component. When you restart a component, the core device uses the latest changes.

    Linux or Unix
    sudo /greengrass/v2/bin/greengrass-cli component restart \ --names "com.example.HelloWorld"
    Windows Command Prompt (CMD)
    C:\greengrass\v2\bin\greengrass-cli component restart ^ --names "com.example.HelloWorld"
    PowerShell
    C:\greengrass\v2\bin\greengrass-cli component restart ` --names "com.example.HelloWorld"
  11. Check the log again to verify that the Hello World component prints the new message.

    Linux or Unix
    sudo tail -f /greengrass/v2/logs/com.example.HelloWorld.log
    Windows Command Prompt (CMD)
    type C:\greengrass\v2\logs\com.example.HelloWorld.log

    The type command writes the file's contents to the terminal. Run this command multiple times to observe changes in the file.

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

    You should see messages similar to the following example.

    Hello, world! Greetings from your first Greengrass component.
  12. You can update the component's configuration parameters to test different configurations. When you deploy a component, you can specify a configuration update, which defines how to modify the component's configuration on the core device. You can specify which configuration values to reset to default values and the new configuration values to merge onto the core device. For more information, see Update component configurations.

    Do the following:

    1. Use a text editor to create a file called hello-world-config-update.json to contain the configuration update

      For example, on a Linux-based system, you can run the following command to use GNU nano to create the file.

      nano hello-world-config-update.json
    2. Copy and paste the following JSON object into the file. This JSON object defines a configuration update that merges the value friend to the Message parameter to update its value. This configuration update doesn't specify any values to reset. You don't need to reset the Message parameter because the merge update replaces the existing value.

      { "com.example.HelloWorld": { "MERGE": { "Message": "friend" } } }
    3. Run the following command to deploy the configuration update to the Hello World component.

      Linux or Unix
      sudo /greengrass/v2/bin/greengrass-cli deployment create \ --merge "com.example.HelloWorld=1.0.0" \ --update-config hello-world-config-update.json
      Windows Command Prompt (CMD)
      C:\greengrass\v2\bin\greengrass-cli deployment create ^ --merge "com.example.HelloWorld=1.0.0" ^ --update-config hello-world-config-update.json
      PowerShell
      C:\greengrass\v2\bin\greengrass-cli deployment create ` --merge "com.example.HelloWorld=1.0.0" ` --update-config hello-world-config-update.json
    4. Check the log again to verify that the Hello World component outputs the new message.

      Linux or Unix
      sudo tail -f /greengrass/v2/logs/com.example.HelloWorld.log
      Windows Command Prompt (CMD)
      type C:\greengrass\v2\logs\com.example.HelloWorld.log

      The type command writes the file's contents to the terminal. Run this command multiple times to observe changes in the file.

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

      You should see messages similar to the following example.

      Hello, friend! Greetings from your first Greengrass component.
  13. After you finish testing your component, remove it from your core device. Run the following command.

    Linux or Unix
    sudo /greengrass/v2/bin/greengrass-cli deployment create --remove="com.example.HelloWorld"
    Windows Command Prompt (CMD)
    C:\greengrass\v2\bin\greengrass-cli deployment create --remove="com.example.HelloWorld"
    PowerShell
    C:\greengrass\v2\bin\greengrass-cli deployment create --remove="com.example.HelloWorld"
    Important

    This step is required for you to deploy the component back to the core device after you upload it to Amazon IoT Greengrass. Otherwise, the deployment fails with a version compatibility error because the local deployment specifies a different version of the component.

    Run the following command and verify that the com.example.HelloWorld component doesn't appear in the list of components on your device.

    Linux or Unix
    sudo /greengrass/v2/bin/greengrass-cli component list
    Windows Command Prompt (CMD)
    C:\greengrass\v2\bin\greengrass-cli component list
    PowerShell
    C:\greengrass\v2\bin\greengrass-cli component list

Your Hello World component is complete, and you can now upload it to the Amazon IoT Greengrass cloud service. Then, you can deploy the component to Greengrass core devices.

Step 5: Create your component in the Amazon IoT Greengrass service

When you finish developing a component on your core device, you can upload it to the Amazon IoT Greengrass service in the Amazon Web Services Cloud. You can also directly create the component in the Amazon IoT Greengrass console. Amazon IoT Greengrass provides a component management service that hosts your components so that you can deploy them to individual devices or fleets of devices. To upload a component to the Amazon IoT Greengrass service, you complete the following steps:

  • Upload component artifacts to an S3 bucket.

  • Add each artifact's Amazon Simple Storage Service (Amazon S3) URI to the component recipe.

  • Create a component in Amazon IoT Greengrass from the component recipe.

In this section, you complete these steps on your Greengrass core device to upload your Hello World component to the Amazon IoT Greengrass service.

  1. Use an S3 bucket in your Amazon account to host Amazon IoT Greengrass component artifacts. When you deploy the component to a core device, the device downloads the component's artifacts from the bucket.

    You can use an existing S3 bucket, or you can create a new bucket.

    1. In the Amazon S3 console, under Buckets, choose Create bucket.

    2. For Bucket name, enter a unique bucket name. For example, you can use greengrass-component-artifacts-region-123456789012. Replace 123456789012 with your Amazon account ID and region with the Amazon Web Services Region that you use for this tutorial.

    3. For Amazon region, select the Amazon Region that you use for this tutorial.

    4. Choose Create bucket.

    5. Under Buckets, choose the bucket that you created, upload the hello_world.py script to the artifacts/com.example.HelloWorld/1.0.0 folder in the bucket. For information about uploading objects to S3 buckets, see Uploading objects in the Amazon Simple Storage Service User Guide.

    6. Copy the S3 URI of the hello_world.py object in the S3 bucket. This URI should look similar to the following example. Replace DOC-EXAMPLE-BUCKET with the name of the S3 bucket.

      s3://DOC-EXAMPLE-BUCKET/artifacts/com.example.HelloWorld/1.0.0/hello_world.py
  2. Allow the core device to access component artifacts in the S3 bucket.

    Each core device has a core device IAM role that allows it to interact with Amazon IoT and send logs to the Amazon Cloud. This device role doesn't allow access to S3 buckets by default, so you must create and attach a policy that allows the core device to retrieve component artifacts from the S3 bucket.

    If your device's role already allows access to the S3 bucket, you can skip this step. Otherwise, create an IAM policy that allows access and attach it to the role, as follows:

    1. In the IAM console navigation menu, choose Policies, and then choose Create policy.

    2. On the JSON tab, replace the placeholder content with the following policy. Replace DOC-EXAMPLE-BUCKET with the name of the S3 bucket that contains component artifacts for the core device to download.

      { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws-cn:s3:::DOC-EXAMPLE-BUCKET/*" } ] }
    3. Choose Next: Tags, and then choose Next: Review.

    4. For Name, enter MyGreengrassV2ComponentArtifactPolicy.

    5. Choose Create policy.

    6. In the IAM console navigation menu, choose Role, and then choose the name of the role for the core device. You specified this role name when you installed the Amazon IoT Greengrass Core software. If you did not specify a name, the default is GreengrassV2TokenExchangeRole.

    7. Under Permissions, choose Add permissions, then choose Attach policies.

    8. On the Add permissions page, select the check box next to the MyGreengrassV2ComponentArtifactPolicy policy that you created, and then choose Attach policies.

  3. Use the component recipe to create a component in the Amazon IoT Greengrass console.

    1. In the Amazon IoT Greengrass console navigation menu, choose Components, and then choose Create component.

    2. Under Component information, choose Enter recipe as JSON. The placeholder recipe should look similar to the following example.

      { "RecipeFormatVersion": "2020-01-25", "ComponentName": "com.example.HelloWorld", "ComponentVersion": "1.0.0", "ComponentDescription": "My first Amazon IoT Greengrass component.", "ComponentPublisher": "Amazon", "ComponentConfiguration": { "DefaultConfiguration": { "Message": "world" } }, "Manifests": [ { "Platform": { "os": "linux" }, "Lifecycle": { "Run": "python3 -u {artifacts:path}/hello_world.py \"{configuration:/Message}\"" }, "Artifacts": [ { "URI": "s3://DOC-EXAMPLE-BUCKET/artifacts/com.example.HelloWorld/1.0.0/hello_world.py" } ] }, { "Platform": { "os": "windows" }, "Lifecycle": { "Run": "py -3 -u {artifacts:path}/hello_world.py \"{configuration:/Message}\"" }, "Artifacts": [ { "URI": "s3://DOC-EXAMPLE-BUCKET/artifacts/com.example.HelloWorld/1.0.0/hello_world.py" } ] } ] }
    3. Replace the placeholder URI in each Artifacts section with S3 URI of your hello_world.py object.

    4. Choose Create component.

    5. On the com.example.HelloWorld component page, verify that the Status of the component is Deployable.

To upload your Hello World component
  1. Use an S3 bucket in your Amazon Web Services account to host Amazon IoT Greengrass component artifacts. When you deploy the component to a core device, the device downloads the component's artifacts from the bucket.

    You can use an existing S3 bucket, or run the following command to create a bucket. This command creates a bucket with your Amazon Web Services account ID and Amazon Web Services Region to form a unique bucket name. Replace 123456789012 with your Amazon Web Services account ID and region with the Amazon Web Services Region that you use for this tutorial.

    aws s3 mb s3://greengrass-component-artifacts-123456789012-region

    The command outputs the following information if the request succeeds.

    make_bucket: greengrass-component-artifacts-123456789012-region
  2. Allow the core device to access component artifacts in the S3 bucket.

    Each core device has a core device IAM role that allows it to interact with Amazon IoT and send logs to the Amazon Web Services Cloud. This device role doesn't allow access to S3 buckets by default, so you must create and attach a policy that allows the core device to retrieve component artifacts from the S3 bucket.

    If the core device's role already allows access to the S3 bucket, you can skip this step. Otherwise, create an IAM policy that allows access and attach it to the role, as follows:

    1. Create a file called component-artifact-policy.json and copy the following JSON into the file. This policy allows access to all files in an S3 bucket. Replace DOC-EXAMPLE-BUCKET with the name of the S3 bucket.

      { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::DOC-EXAMPLE-BUCKET/*" } ] }
    2. Run the following command to create the policy from the policy document in component-artifact-policy.json.

      Linux or Unix
      aws iam create-policy \ --policy-name MyGreengrassV2ComponentArtifactPolicy \ --policy-document file://component-artifact-policy.json
      Windows Command Prompt (CMD)
      aws iam create-policy ^ --policy-name MyGreengrassV2ComponentArtifactPolicy ^ --policy-document file://component-artifact-policy.json
      PowerShell
      aws iam create-policy ` --policy-name MyGreengrassV2ComponentArtifactPolicy ` --policy-document file://component-artifact-policy.json

      Copy the policy Amazon Resource Name (ARN) from the policy metadata in the output. You use this ARN to attach this policy to the core device role in the next step.

    3. Run the following command to attach the policy to the core device role. Replace GreengrassV2TokenExchangeRole with the name of the role for the core device. You specified this role name when you installed the Amazon IoT Greengrass Core software. Replace the policy ARN with the ARN from the previous step.

      Linux or Unix
      aws iam attach-role-policy \ --role-name GreengrassV2TokenExchangeRole \ --policy-arn arn:aws-cn:iam::123456789012:policy/MyGreengrassV2ComponentArtifactPolicy
      Windows Command Prompt (CMD)
      aws iam attach-role-policy ^ --role-name GreengrassV2TokenExchangeRole ^ --policy-arn arn:aws-cn:iam::123456789012:policy/MyGreengrassV2ComponentArtifactPolicy
      PowerShell
      aws iam attach-role-policy ` --role-name GreengrassV2TokenExchangeRole ` --policy-arn arn:aws-cn:iam::123456789012:policy/MyGreengrassV2ComponentArtifactPolicy

      If the command has no output, it succeeded. The core device can now access artifacts that you upload to this S3 bucket.

  3. Upload the Hello World Python script artifact to the S3 bucket.

    Run the following command to upload the script to the same path in the bucket where the script exists on your Amazon IoT Greengrass core. Replace DOC-EXAMPLE-BUCKET with the name of the S3 bucket.

    Linux or Unix
    aws s3 cp \ artifacts/com.example.HelloWorld/1.0.0/hello_world.py \ s3://DOC-EXAMPLE-BUCKET/artifacts/com.example.HelloWorld/1.0.0/hello_world.py
    Windows Command Prompt (CMD)
    aws s3 cp ^ artifacts/com.example.HelloWorld/1.0.0/hello_world.py ^ s3://DOC-EXAMPLE-BUCKET/artifacts/com.example.HelloWorld/1.0.0/hello_world.py
    PowerShell
    aws s3 cp ` artifacts/com.example.HelloWorld/1.0.0/hello_world.py ` s3://DOC-EXAMPLE-BUCKET/artifacts/com.example.HelloWorld/1.0.0/hello_world.py

    The command outputs a line that starts with upload: if the request succeeds.

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

    The Amazon S3 URI is composed of the bucket name and the path to the artifact object in the bucket. Your script artifact's Amazon S3 URI is the URI that you upload the artifact to in the previous step. This URI should look similar to the following example. Replace DOC-EXAMPLE-BUCKET with the name of the S3 bucket.

    s3://DOC-EXAMPLE-BUCKET/artifacts/com.example.HelloWorld/1.0.0/hello_world.py

    To add the artifact to the recipe, add a list of Artifacts that contains a structure with the Amazon S3 URI.

    JSON
    "Artifacts": [ { "URI": "s3://DOC-EXAMPLE-BUCKET/artifacts/com.example.HelloWorld/1.0.0/hello_world.py" } ]

    Open the recipe file in a text editor.

    For example, on a Linux-based system, you can run the following command to use GNU nano to create the file.

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

    Add the artifact to the recipe. Your recipe file should look similar to the following example.

    { "RecipeFormatVersion": "2020-01-25", "ComponentName": "com.example.HelloWorld", "ComponentVersion": "1.0.0", "ComponentDescription": "My first Amazon IoT Greengrass component.", "ComponentPublisher": "Amazon", "ComponentConfiguration": { "DefaultConfiguration": { "Message": "world" } }, "Manifests": [ { "Platform": { "os": "linux" }, "Lifecycle": { "Run": "python3 -u {artifacts:path}/hello_world.py \"{configuration:/Message}\"" }, "Artifacts": [ { "URI": "s3://DOC-EXAMPLE-BUCKET/artifacts/com.example.HelloWorld/1.0.0/hello_world.py" } ] }, { "Platform": { "os": "windows" }, "Lifecycle": { "Run": "py -3 -u {artifacts:path}/hello_world.py \"{configuration:/Message}\"" }, "Artifacts": [ { "URI": "s3://DOC-EXAMPLE-BUCKET/artifacts/com.example.HelloWorld/1.0.0/hello_world.py" } ] } ] }
    YAML
    Artifacts: - URI: s3://DOC-EXAMPLE-BUCKET/artifacts/com.example.HelloWorld/1.0.0/hello_world.py

    Open the recipe file in a text editor.

    For example, on a Linux-based system, you can run the following command to use GNU nano to create the file.

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

    Add the artifact to the recipe. Your recipe file should look similar to the following example.

    --- RecipeFormatVersion: '2020-01-25' ComponentName: com.example.HelloWorld ComponentVersion: '1.0.0' ComponentDescription: My first Amazon IoT Greengrass component. ComponentPublisher: Amazon ComponentConfiguration: DefaultConfiguration: Message: world Manifests: - Platform: os: linux Lifecycle: Run: | python3 -u {artifacts:path}/hello_world.py "{configuration:/Message}" Artifacts: - URI: s3://DOC-EXAMPLE-BUCKET/artifacts/com.example.HelloWorld/1.0.0/hello_world.py - Platform: os: windows Lifecycle: Run: | py -3 -u {artifacts:path}/hello_world.py "{configuration:/Message}" Artifacts: - URI: s3://DOC-EXAMPLE-BUCKET/artifacts/com.example.HelloWorld/1.0.0/hello_world.py
  5. Create a component resource in Amazon IoT Greengrass from the recipe. Run the following command to create the component from the recipe, which you provide as a binary file.

    JSON
    aws greengrassv2 create-component-version --inline-recipe fileb://recipes/com.example.HelloWorld-1.0.0.json
    YAML
    aws greengrassv2 create-component-version --inline-recipe fileb://recipes/com.example.HelloWorld-1.0.0.yaml

    The response looks similar to the following example if the request succeeds.

    { "arn": "arn:aws-cn:greengrass:region:123456789012:components:com.example.HelloWorld:versions:1.0.0", "componentName": "com.example.HelloWorld", "componentVersion": "1.0.0", "creationTimestamp": "Mon Nov 30 09:04:05 UTC 2020", "status": { "componentState": "REQUESTED", "message": "NONE", "errors": {} } }

    Copy the arn from the output to check the state of the component in the next step.

    Note

    You can also see your Hello World component in the Amazon IoT Greengrass console on the Components page.

  6. Verify that the component creates and is ready to be deployed. When you create a component, its state is REQUESTED. Then, Amazon IoT Greengrass validates that the component is deployable. You can run the following command to query the component status and verify that your component is deployable. Replace the arn with the ARN from the previous step.

    aws greengrassv2 describe-component --arn "arn:aws-cn:greengrass:region:123456789012:components:com.example.HelloWorld:versions:1.0.0"

    If the component validates, the response indicates that the component state is DEPLOYABLE.

    { "arn": "arn:aws-cn:greengrass:region:123456789012:components:com.example.HelloWorld:versions:1.0.0", "componentName": "com.example.HelloWorld", "componentVersion": "1.0.0", "creationTimestamp": "2020-11-30T18:04:05.823Z", "publisher": "Amazon", "description": "My first Greengrass component.", "status": { "componentState": "DEPLOYABLE", "message": "NONE", "errors": {} }, "platforms": [ { "os": "linux", "architecture": "all" } ] }

Your Hello World component is now available in Amazon IoT Greengrass. You can deploy it back to this Greengrass core device or to other core devices.

Step 6: Deploy your component

With Amazon IoT Greengrass, you can deploy components to individual devices or groups of devices. When you deploy a component, Amazon IoT Greengrass installs and runs that component's software on each target device. You specify which components to deploy and the configuration update to deploy for each component. You can also control how the deployment rolls out to the devices that the deployment targets. For more information, see Deploy Amazon IoT Greengrass components to devices.

In this section, you deploy your Hello World component back to your Greengrass core device.

  1. In the Amazon IoT Greengrass console navigation menu, choose Components.

  2. On the Components page, on the My components tab, choose com.example.HelloWorld.

  3. On the com.example.HelloWorld page, choose Deploy.

  4. From Add to deployment, choose Create new deployment, then choose Next.

  5. On the Specify target page, do the following:

    1. In the Name box, enter Deployment for MyGreengrassCore.

    2. For Deployment target, choose Core device, and the name of the Amazon IoT thing for your core device. The default value in this tutorial is MyGreengrassCore.

    3. Choose Next.

  6. On the Select components page, under My components, verify that the com.example.HelloWorld component is selected, and choose Next.

  7. On the Configure components page, choose com.example.HelloWorld, and do the following:

    1. Choose Configure component.

    2. Under Configuration update, in Configuration to merge, enter the following configuration.

      { "Message": "universe" }

      This configuration update sets the Hello World Message parameter to universe for the device in this deployment.

    3. Choose Confirm.

    4. Choose Next.

  8. On the Configure advanced settings page, keep the default configuration settings, and choose Next.

  9. On the Review page, choose Deploy.

  10. Verify that the deployment completes successfully. The deployment can take several minutes to complete. Check the Hello World log to verify the change. Run the following command on your Greengrass core device.

    Linux or Unix
    sudo tail -f /greengrass/v2/logs/com.example.HelloWorld.log
    Windows Command Prompt (CMD)
    type C:\greengrass\v2\logs\com.example.HelloWorld.log
    PowerShell
    gc C:\greengrass\v2\logs\com.example.HelloWorld.log -Tail 10 -Wait

    You should see messages similar to the following example.

    Hello, universe! Greetings from your first Greengrass component.
    Note

    If the log messages don't change, the deployment failed or didn't reach the core device. This can occur if your core device isn't connected to the internet or doesn't have permissions to retrieve artifacts from your S3 bucket. Run the following command on your core device to view the Amazon IoT Greengrass Core software log file. This file includes logs from the Greengrass core device's deployment service.

    Linux or Unix
    sudo tail -f /greengrass/v2/logs/greengrass.log
    Windows Command Prompt (CMD)
    type C:\greengrass\v2\logs\greengrass.log

    The type command writes the file's contents to the terminal. Run this command multiple times to observe changes in the file.

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

    For more information, see Troubleshooting Amazon IoT Greengrass V2.

To deploy your Hello World component
  1. On your development computer, create a file called hello-world-deployment.json and copy the following JSON into the file. This file defines the components and configurations to deploy.

    { "components": { "com.example.HelloWorld": { "componentVersion": "1.0.0", "configurationUpdate": { "merge": "{\"Message\":\"universe\"}" } } } }

    This configuration file specifies to deploy version 1.0.0 of the Hello World component that you developed and published in the previous procedure. The configurationUpdate specifies to merge the component configuration in a JSON-encoded string. This configuration update sets the Hello World Message parameter to universe for the device in this deployment.

  2. Run the following command to deploy the component to your Greengrass core device. You can deploy to things, which are individual devices, or thing groups, which are groups of devices. Replace MyGreengrassCore with the name of the Amazon IoT thing for your core device.

    Linux or Unix
    aws greengrassv2 create-deployment \ --target-arn "arn:aws-cn:iot:region:account-id:thing/MyGreengrassCore" \ --cli-input-json file://hello-world-deployment.json
    Windows Command Prompt (CMD)
    aws greengrassv2 create-deployment ^ --target-arn "arn:aws-cn:iot:region:account-id:thing/MyGreengrassCore" ^ --cli-input-json file://hello-world-deployment.json
    PowerShell
    aws greengrassv2 create-deployment ` --target-arn "arn:aws-cn:iot:region:account-id:thing/MyGreengrassCore" ` --cli-input-json file://hello-world-deployment.json

    The command outputs a response similar to the following example.

    { "deploymentId": "deb69c37-314a-4369-a6a1-3dff9fce73a9", "iotJobId": "b5d92151-6348-4941-8603-bdbfb3e02b75", "iotJobArn": "arn:aws-cn:iot:region:account-id:job/b5d92151-6348-4941-8603-bdbfb3e02b75" }
  3. Verify that the deployment completes successfully. The deployment can take several minutes to complete. Check the Hello World log to verify the change. Run the following command on your Greengrass core device.

    Linux or Unix
    sudo tail -f /greengrass/v2/logs/com.example.HelloWorld.log
    Windows Command Prompt (CMD)
    type C:\greengrass\v2\logs\com.example.HelloWorld.log
    PowerShell
    gc C:\greengrass\v2\logs\com.example.HelloWorld.log -Tail 10 -Wait

    You should see messages similar to the following example.

    Hello, universe! Greetings from your first Greengrass component.
    Note

    If the log messages don't change, the deployment failed or didn't reach the core device. This can occur if your core device isn't connected to the internet or doesn't have permissions to retrieve artifacts from your S3 bucket. Run the following command on your core device to view the Amazon IoT Greengrass Core software log file. This file includes logs from the Greengrass core device's deployment service.

    Linux or Unix
    sudo tail -f /greengrass/v2/logs/greengrass.log
    Windows Command Prompt (CMD)
    type C:\greengrass\v2\logs\greengrass.log

    The type command writes the file's contents to the terminal. Run this command multiple times to observe changes in the file.

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

    For more information, see Troubleshooting Amazon IoT Greengrass V2.

Next steps

You've completed this tutorial. The Amazon IoT Greengrass Core software and your Hello World component run on your device. Also, your Hello World component is available in the Amazon IoT Greengrass cloud service to deploy to other devices. For more information about the topics that this tutorial explores, see the following: