컴포넌트 생성
작업 1: 워크스페이스 생성
섹션 제목: “작업 1: 워크스페이스 생성”워크스페이스를 보관할 디렉터리에서 다음을 실행합니다:
워크스페이스 생성@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=cdk이 단계의 옵션2
필수
그런 다음 해당 디렉터리로 이동합니다:
cd greengrass-tutorial워크스페이스 이름은 npm 스코프 @greengrass-tutorial과 Python 네임스페이스 greengrass_tutorial을 설정합니다. 생성된 프로젝트 이름은 이러한 접두사를 포함하며, nx run은 전체 이름이 필요하므로 이 튜토리얼의 나머지 부분에서는 greengrass_tutorial.telemetry와 @greengrass-tutorial/infra를 사용합니다.
작업 2: 프로젝트 생성
섹션 제목: “작업 2: 프로젝트 생성”컴포넌트를 호스팅할 Python 프로젝트를 생성합니다:
이 제너레이터 실행@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- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - py#project - 필수 매개변수 입력
- name: telemetry
- 클릭
Generate
이 단계의 옵션1
필수
이렇게 하면 packages/telemetry에 greengrass_tutorial.telemetry 프로젝트가 생성됩니다.
여기에 Greengrass 컴포넌트를 추가합니다:
이 제너레이터 실행@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- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - greengrass#component - 필수 매개변수 입력
- project: telemetry
- name: pulse
- language: python
- componentName: com.example.Pulse
- componentVersion: NEXT_PATCH
- platform: linux-amd64
- ipc: true
- infra: component-version
- iac: cdk
- 클릭
Generate
이 단계의 옵션9
필수
필수
각 값은 튜토리얼의 후반부에서 중요합니다:
platform: linux-amd64는 모듈 2에서 프로비저닝하는 x86_64 인스턴스와 일치합니다. 기본값은linux-arm64이며, 한 아키텍처용으로 빌드된 레시피는 다른 아키텍처에서 실행되지 않습니다.componentVersion: NEXT_PATCH는 배포 시점에 버전을 할당합니다. 첫 번째 배포는1.0.0을 게시하고, 모듈 3은 레시피를 편집하지 않고 소스 변경으로부터1.0.1을 게시합니다.ipc: true는 이 튜토리얼이 Greengrass IPC를 통해 게시하도록 컴포넌트를 변경하기 때문에 명시적입니다.infra: component-version과iac: cdk는 재사용 가능한 Greengrass 코어 구성을packages/common/constructs에 추가하고 이 컴포넌트의 아티팩트를 게시하는Pulse앱 구성을 추가합니다.
배포를 보관할 CDK 애플리케이션을 생성합니다:
이 제너레이터 실행@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- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - ts#infra - 필수 매개변수 입력
- name: infra
- 클릭
Generate
이 단계의 옵션1
필수
이 튜토리얼에서 다루는 파일들:
디렉터리packages
디렉터리telemetry
디렉터리greengrass
디렉터리pulse
- main.py 컴포넌트 진입점
- recipe.yaml 컴포넌트 레시피
디렉터리tests
디렉터리greengrass
- test_pulse.py 컴포넌트의 단위 테스트
- project.json
pulse-vendor,pulse-artifact,pulse-deploy-local및pulse-logs타겟
디렉터리common
디렉터리constructs
디렉터리src
- core/greengrass 아티팩트 버킷, 컴포넌트 버전, 배포 및 버전 리졸버 구성
- app/greengrass/pulse.ts
Pulse구성
디렉터리infra
디렉터리src
디렉터리stacks
- application-stack.ts 모듈 3에서 배포를 구성하는 곳
작업 3: 로컬 pub/sub 대신 AWS IoT Core에 게시
섹션 제목: “작업 3: 로컬 pub/sub 대신 AWS IoT Core에 게시”생성된 main.py는 publish_to_topic으로 하트비트를 게시하며, 이는 로컬 Greengrass pub/sub 서비스를 통해 동일한 코어 디바이스의 다른 컴포넌트에 도달합니다. 디바이스를 벗어나지 않습니다. AWS IoT Core에서 하트비트를 보려면 컴포넌트가 IPC 클라이언트의 publish_to_iot_core를 사용해야 하며, 레시피와 디바이스의 IoT 정책 모두 이를 허용해야 합니다.
생성된 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는 토픽 이름, "1"의 QoS(최소 한 번), 그리고 바이트 페이로드를 받습니다. 토픽 tutorial/greengrass/heartbeat는 레시피, 모듈 2에서 생성하는 디바이스 IoT 정책, 그리고 모듈 3의 MQTT 테스트 클라이언트 구독에서 다시 나타납니다.
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.pyAWS IoT Core MQTT용 IPC 서비스는 aws.greengrass.ipc.mqttproxy이며, 게시는 aws.greengrass#PublishToIoTCore 작업입니다. 리소스는 정확한 토픽입니다. 이 권한 부여는 디바이스의 nucleus에 의해 시행됩니다. 디바이스 인증서에 연결된 IoT 정책은 AWS IoT Core에 의해 시행되며, 동일한 토픽에 대한 iot:Publish가 필요합니다. 모듈 2에서 해당 정책을 생성합니다.
호스트 프로젝트의 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}작업 4: 아티팩트 빌드
섹션 제목: “작업 4: 아티팩트 빌드”테스트를 실행하고 컴포넌트 아티팩트를 빌드합니다:
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는 x86_64-manylinux_2_28용 Python 종속성을 벤더링하고, pulse.zip을 패키징하며, 해결된 레시피를 작성합니다:
디렉터리dist/packages/telemetry/greengrass/pulse/greengrass-build
디렉터리recipes
- com.example.Pulse-NEXT_PATCH.yaml mqttproxy 권한 부여가 포함된 레시피
디렉터리artifacts
디렉터리com.example.Pulse
디렉터리NEXT_PATCH
- pulse.zip
코어 디바이스 프로비저닝으로 계속 진행합니다.