Skip to content

Create the component

From the directory that will hold the workspace, run:

Create your workspace@aws/nx-workspace

pnpm create @aws/nx-workspace greengrass-tutorial --iac=cdk
Options for this step2

Required

Then change into it:

Terminal window
cd greengrass-tutorial

The workspace name sets the npm scope @greengrass-tutorial and the Python namespace greengrass_tutorial. Generated project names carry those prefixes, and nx run needs the full name, so the rest of this tutorial uses greengrass_tutorial.telemetry and @greengrass-tutorial/infra.

Create the Python project that hosts the component:

Run this generator@aws/nx-plugin:py#project

pnpm nx g @aws/nx-plugin:py#project --name=telemetry --no-interactive
Options for this step1

Required

This creates the project greengrass_tutorial.telemetry at packages/telemetry.

Add the Greengrass component to it:

Run this generator@aws/nx-plugin:greengrass#component

pnpm nx g @aws/nx-plugin:greengrass#component --project=telemetry --name=pulse --platform=linux-amd64 --infra=component-version --iac=cdk --language=python --componentName=com.example.Pulse --componentVersion=NEXT_PATCH --ipc=true --no-interactive
Options for this step9

Required

Required

Each value matters later in the tutorial:

  • platform: linux-amd64 matches the x86_64 instance you provision in module 2. The default is linux-arm64, and a recipe built for one architecture does not run on the other.
  • componentVersion: NEXT_PATCH allocates the version at deploy time. The first deployment publishes 1.0.0; module 3 publishes 1.0.1 from a source change without editing the recipe.
  • ipc: true is explicit because this tutorial changes the component to publish through Greengrass IPC.
  • infra: component-version with iac: cdk adds the reusable Greengrass core constructs to packages/common/constructs and a Pulse app construct that publishes this component’s artifact.

Create the CDK application that will hold the deployment:

Run this generator@aws/nx-plugin:ts#infra

pnpm nx g @aws/nx-plugin:ts#infra --name=infra --no-interactive
Options for this step1

Required

The files this tutorial touches:

  • Directorypackages
    • Directorytelemetry
      • Directorygreengrass
        • Directorypulse
          • main.py the component entrypoint
          • recipe.yaml the component recipe
      • Directorytests
        • Directorygreengrass
          • test_pulse.py the component’s unit test
      • project.json pulse-vendor, pulse-artifact, pulse-deploy-local and pulse-logs targets
    • Directorycommon
      • Directoryconstructs
        • Directorysrc
          • core/greengrass artifact bucket, component version, deployment and version resolver constructs
          • app/greengrass/pulse.ts the Pulse construct
    • Directoryinfra
      • Directorysrc
        • Directorystacks
          • application-stack.ts where module 3 composes the deployment

Task 3: Publish to AWS IoT Core instead of local pub/sub

Section titled “Task 3: Publish to AWS IoT Core instead of local pub/sub”

The generated main.py publishes a heartbeat with publish_to_topic, which reaches other components on the same core device through the local Greengrass pub/sub service. It never leaves the device. To see the heartbeat in AWS IoT Core, the component must use publish_to_iot_core from the IPC client, and both the recipe and the device’s IoT policy must allow it.

Replace the generated packages/telemetry/greengrass/pulse/main.py:

import json
import logging
import time
from awsiot.greengrasscoreipc.clientv2 import GreengrassCoreIPCClientV2
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("com.example.Pulse")
TOPIC = "tutorial/greengrass/heartbeat"
PUBLISH_INTERVAL_SECONDS = 30
GREETING = "hello from pulse"
def publish_heartbeat(client: GreengrassCoreIPCClientV2, sequence: int) -> None:
payload = json.dumps({"sequence": sequence, "greeting": GREETING}).encode("utf-8")
client.publish_to_iot_core(topic_name=TOPIC, qos="1", payload=payload)
logger.info("Published heartbeat %s to %s", sequence, TOPIC)
def main() -> None:
client = GreengrassCoreIPCClientV2()
sequence = 0
while True:
publish_heartbeat(client, sequence)
sequence += 1
time.sleep(PUBLISH_INTERVAL_SECONDS)
if __name__ == "__main__":
main()

publish_to_iot_core takes the topic name, a QoS of "1" (at least once), and a byte payload. The topic tutorial/greengrass/heartbeat appears again in the recipe, in the device IoT policy that module 2 creates, and in the MQTT test client subscription in module 3.

Replace the access-control block in packages/telemetry/greengrass/pulse/recipe.yaml:

RecipeFormatVersion: '2020-01-25'
ComponentName: com.example.Pulse
ComponentVersion: NEXT_PATCH
ComponentDescription: com.example.Pulse Greengrass component using Python 3.14, generated by greengrass#component.
ComponentPublisher: greengrass-tutorial
ComponentConfiguration:
DefaultConfiguration:
accessControl:
aws.greengrass.ipc.mqttproxy:
com.example.Pulse:mqttproxy:1:
policyDescription: Allow publishing tutorial heartbeats to AWS IoT Core.
operations:
- aws.greengrass#PublishToIoTCore
resources:
- tutorial/greengrass/heartbeat
Manifests:
- Platform:
os: linux
architecture: amd64
Artifacts:
# Placeholders are substituted at publish time. The basename must stay
# pulse.zip, which is what the Run script below unarchives to.
- Uri: s3://BUCKET_NAME/COMPONENT_NAME/COMPONENT_VERSION/pulse.zip
Unarchive: ZIP
Lifecycle:
Run: python3.14 {artifacts:decompressedPath}/pulse/main.py

The IPC service for AWS IoT Core MQTT is aws.greengrass.ipc.mqttproxy, and publishing is the operation aws.greengrass#PublishToIoTCore. The resource is the exact topic. This authorization is enforced by the nucleus on the device. The IoT policy attached to the device certificate is enforced by AWS IoT Core, and it needs iot:Publish on the same topic. Module 2 creates that policy.

Update the generated test, because the host project’s build runs it and the shared constructs build depends on the host build:

import importlib.util
import json
from pathlib import Path
# main.py lives beside recipe.yaml under greengrass/<component>/, outside this
# project's importable package, so it is loaded directly by file path.
PROJECT_ROOT = Path(__file__).resolve().parents[2]
MAIN_PATH = PROJECT_ROOT / "greengrass" / "pulse" / "main.py"
def _load_main():
spec = importlib.util.spec_from_file_location("pulse_main", MAIN_PATH)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def test_publish_heartbeat_publishes_to_iot_core():
module = _load_main()
calls = []
class FakeClient:
def publish_to_iot_core(self, **kwargs):
calls.append(kwargs)
module.publish_heartbeat(FakeClient(), 1)
assert len(calls) == 1
assert calls[0]["topic_name"] == "tutorial/greengrass/heartbeat"
assert calls[0]["qos"] == "1"
assert json.loads(calls[0]["payload"]) == {"sequence": 1, "greeting": module.GREETING}

Run the test and build the component artifact:

Terminal window
pnpm nx run greengrass_tutorial.telemetry:test
pnpm nx run greengrass_tutorial.telemetry:pulse-artifact

pulse-artifact vendors the Python dependencies for x86_64-manylinux_2_28, packages pulse.zip, and writes the resolved recipe:

  • Directorydist/packages/telemetry/greengrass/pulse/greengrass-build
    • Directoryrecipes
      • com.example.Pulse-NEXT_PATCH.yaml the recipe with the mqttproxy authorization
    • Directoryartifacts
      • Directorycom.example.Pulse
        • DirectoryNEXT_PATCH
          • pulse.zip

Continue with Provision the core device.