Create the component
Task 1: Create the workspace
Section titled “Task 1: Create the workspace”From the directory that will hold the workspace, run:
Create your workspace@aws/nx-workspace
pnpm create @aws/nx-workspace greengrass-tutorial --iac=cdk yarn create @aws/nx-workspace greengrass-tutorial --iac=cdk npm create @aws/nx-workspace -- greengrass-tutorial --iac=cdk bun create @aws/nx-workspace greengrass-tutorial --iac=cdkOptions for this step2
Required
Then change into it:
cd greengrass-tutorialThe 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.
Task 2: Generate the projects
Section titled “Task 2: Generate the projects”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 yarn nx g @aws/nx-plugin:py#project --name=telemetry --no-interactive npx nx g @aws/nx-plugin:py#project --name=telemetry --no-interactive bunx nx g @aws/nx-plugin:py#project --name=telemetry --no-interactive- Install the Nx Console VSCode Plugin if you haven't already
- Open the Nx Console in VSCode
- Click
Generate (UI)in the "Common Nx Commands" section - Search for
@aws/nx-plugin - py#project - Fill in the required parameters
- name: telemetry
- Click
Generate
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 yarn 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 npx 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 bunx 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- Install the Nx Console VSCode Plugin if you haven't already
- Open the Nx Console in VSCode
- Click
Generate (UI)in the "Common Nx Commands" section - Search for
@aws/nx-plugin - greengrass#component - Fill in the required parameters
- project: telemetry
- name: pulse
- language: python
- componentName: com.example.Pulse
- componentVersion: NEXT_PATCH
- platform: linux-amd64
- ipc: true
- infra: component-version
- iac: cdk
- Click
Generate
Options for this step9
Required
Required
Each value matters later in the tutorial:
platform: linux-amd64matches the x86_64 instance you provision in module 2. The default islinux-arm64, and a recipe built for one architecture does not run on the other.componentVersion: NEXT_PATCHallocates the version at deploy time. The first deployment publishes1.0.0; module 3 publishes1.0.1from a source change without editing the recipe.ipc: trueis explicit because this tutorial changes the component to publish through Greengrass IPC.infra: component-versionwithiac: cdkadds the reusable Greengrass core constructs topackages/common/constructsand aPulseapp 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 yarn nx g @aws/nx-plugin:ts#infra --name=infra --no-interactive npx nx g @aws/nx-plugin:ts#infra --name=infra --no-interactive bunx nx g @aws/nx-plugin:ts#infra --name=infra --no-interactive- Install the Nx Console VSCode Plugin if you haven't already
- Open the Nx Console in VSCode
- Click
Generate (UI)in the "Common Nx Commands" section - Search for
@aws/nx-plugin - ts#infra - Fill in the required parameters
- name: infra
- Click
Generate
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-localandpulse-logstargets
Directorycommon
Directoryconstructs
Directorysrc
- core/greengrass artifact bucket, component version, deployment and version resolver constructs
- app/greengrass/pulse.ts the
Pulseconstruct
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 jsonimport loggingimport 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 = 30GREETING = "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()import jsonimport loggingimport time
from awsiot.greengrasscoreipc.clientv2 import GreengrassCoreIPCClientV2from awsiot.greengrasscoreipc.model import JsonMessage, PublishMessage
logging.basicConfig(level=logging.INFO)logger = logging.getLogger("com.example.Pulse")
TOPIC = "com.example.Pulse/heartbeat"TOPIC = "tutorial/greengrass/heartbeat"PUBLISH_INTERVAL_SECONDS = 30GREETING = "hello from pulse"
def publish_heartbeat(client: GreengrassCoreIPCClientV2, sequence: int) -> None: client.publish_to_topic( topic=TOPIC, publish_message=PublishMessage(json_message=JsonMessage(message={"sequence": sequence})), ) 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.PulseComponentVersion: NEXT_PATCHComponentDescription: com.example.Pulse Greengrass component using Python 3.14, generated by greengrass#component.ComponentPublisher: greengrass-tutorialComponentConfiguration: 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/heartbeatManifests: - 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.pyRecipeFormatVersion: '2020-01-25'ComponentName: com.example.PulseComponentVersion: NEXT_PATCHComponentDescription: com.example.Pulse Greengrass component using Python 3.14, generated by greengrass#component.ComponentPublisher: greengrass-tutorialComponentConfiguration: DefaultConfiguration: accessControl: aws.greengrass.ipc.pubsub: com.example.Pulse:pubsub:1: policyDescription: Allow publishing heartbeat messages to this component's own topic. aws.greengrass.ipc.mqttproxy: com.example.Pulse:mqttproxy:1: policyDescription: Allow publishing tutorial heartbeats to AWS IoT Core. operations: - aws.greengrass#PublishToTopic - aws.greengrass#PublishToIoTCore resources: - com.example.Pulse/heartbeat - tutorial/greengrass/heartbeatManifests: - 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.pyThe 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.utilimport jsonfrom 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}import importlib.utilimport jsonfrom 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_own_topic():def test_publish_heartbeat_publishes_to_iot_core(): module = _load_main() calls = []
class FakeClient: def publish_to_topic(self, **kwargs): def publish_to_iot_core(self, **kwargs): calls.append(kwargs)
module.publish_heartbeat(FakeClient(), 1)
assert len(calls) == 1 assert calls[0]["topic"] == module.TOPIC assert module.TOPIC == "com.example.Pulse/heartbeat" assert calls[0]["topic_name"] == "tutorial/greengrass/heartbeat" assert calls[0]["qos"] == "1" assert json.loads(calls[0]["payload"]) == {"sequence": 1, "greeting": module.GREETING}Task 4: Build the artifact
Section titled “Task 4: Build the artifact”Run the test and build the component artifact:
pnpm nx run greengrass_tutorial.telemetry:testpnpm nx run greengrass_tutorial.telemetry:pulse-artifactyarn nx run greengrass_tutorial.telemetry:testyarn nx run greengrass_tutorial.telemetry:pulse-artifactnpx nx run greengrass_tutorial.telemetry:testnpx nx run greengrass_tutorial.telemetry:pulse-artifactbunx nx run greengrass_tutorial.telemetry:testbunx nx run greengrass_tutorial.telemetry:pulse-artifactpulse-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.