目次
AWS IoT Greengrass V2 完全ガイド v2.0
初心者から実務者向けの包括的解説
AWS IoT Greengrass V2 は、エッジデバイス上で AWS クラウド機能をローカルで実行するためのオープンソースランタイムおよびサービスです。Lambda 関数・Docker コンテナ・カスタムコンポーネント・機械学習モデルをエッジデバイス(Raspberry Pi・産業用 PC・EC2 等)にデプロイでき、クラウド接続なしでのローカル推論・リアルタイム制御・データフィルタリングを実現します。コンポーネントベースのアーキテクチャで、エッジアプリケーションの管理・更新・スケーリングが容易です。
目次
- 概要
- Greengrass V2 が解決する課題
- 主な特徴
- アーキテクチャ
- コアコンポーネント
- 主要ユースケース
- インストール・セットアップ
- コンポーネント開発と配置
- ML 推論エッジコンポーネント
- ローカル pub/sub と IPC
- ストリームマネージャー
- 設定・操作の具体例
- 類似サービス比較表
- ベストプラクティス
- トラブルシューティング
- 2025-2026 年の最新動向
- 学習リソース・参考文献
- 実装例・チェックリスト
- まとめ
概要
AWS IoT Greengrass V2 とは
AWS IoT Greengrass V2 は、エッジデバイスでの分散コンピューティングを実現するマネージドランタイムサービスです。クラウド品質のセキュリティ・管理性を保ちながら、以下を提供します:
- エッジコンピューティング: デバイスのローカル処理で低レイテンシ・自律性を実現
- コンポーネントモデル: 独立した、バージョン管理可能なソフトウェアユニット
- IoT Core 統合: クラウドとの安全な双方向通信
- ML 推論: SageMaker モデルのエッジでのローカル実行
- OTA 更新: フリート全体への一括コンポーネント更新
- ローカル リソースアクセス: GPIO・カメラ・シリアルポート等
V1 からの主な改善
- 完全モジュール化: コンポーネントベースで個別のライフサイクル管理
- Docker サポート: コンテナアプリケーションのネイティブ対応
- 言語柔軟性: Java・Python・Node.js・Go・Rust等対応
- セキュリティ強化: TPM 2.0・ハードウェアセキュリティ対応
- 管理機能向上: リモートコンポーネント更新・ロールバック機能
Greengrass V2 が解決する課題
| 課題 | 従来の方法 | Greengrass V2 での解決 |
|---|---|---|
| 低レイテンシ要求 | すべてクラウド処理。往復で数百 ms の遅延 | ローカル処理で 10~50 ms 実現。リアルタイム制御対応 |
| インターネット不安定環境 | 接続断時は機能停止 | オフラインで自律稼働。再接続時に同期 |
| 帯域コスト削減 | センサーデータをそのまま送信。高帯域・高コスト | エッジフィルタリング・圧縮で帯域 90% 削減可能 |
| ML 推論の遅延 | API コール往復で 100 ms~1 秒 | エッジで 10~50 ms 推論。リアルタイム AI 判定 |
| エッジアプリ管理 | SSH でスクリプト実行。バージョン管理困難 | コンポーネント OTA で安全な段階的更新 |
| 複数言語対応 | C/C++ のみ対応。開発効率低い | Python・Java・Node.js 等で開発・実行 |
| セキュア通信 | 証明書管理が複雑 | Greengrass Agent が自動ローテーション |
| ハードウェア多様性 | 特定プラットフォームへの依存 | Raspberry Pi~産業用 PC まで対応 |
主な特徴
✅ エッジランタイムの完全マネージメント
- オープンソース設計で自由度が高い
- AWS IoT Core との自動統合
- クラウド側管理コンソールでリモート管理
✅ コンポーネントベースアーキテクチャ
- 独立した機能ユニット(Lambda・Docker・Native)
- 依存関係の明示的な定義
- ローリング更新・キャナリアデプロイ対応
✅ 機械学習推論対応
- SageMaker Neo でコンパイルしたモデルをエッジで実行
- TensorFlow Lite・PyTorch・ONNX 等のフレームワーク対応
- DLR(Deep Learning Runtime)での高速実行
✅ ローカル IPC(Inter-Process Communication)
- コンポーネント間の安全な通信
- 標準化された Unix ソケット
- JSON ペイロード対応
✅ ストリームマネージャー
- クラウド接続時のデータ自動エクスポート
- オンメモリ・ファイルベースのバッファリング
- S3・Kinesis・IoT Core への自動転送
✅ 完全監査ログ
- CloudWatch Logs 統合
- デバイス側ログの集約・検索
- トラブルシューティング情報の充実
アーキテクチャ
全体構成図
graph TB
subgraph EdgeDevice["エッジデバイス(Greengrass Core)"]
Nucleus["Greengrass Nucleus<br/>コアランタイム"]
subgraph Components["コンポーネント層"]
LambdaComp["Lambda Component<br/>AWS Lambda コンテナ"]
DockerComp["Docker Component<br/>コンテナアプリ"]
MLComp["ML Inference<br/>SageMaker Neo モデル"]
CustomComp["Custom Component<br/>Python/Java/Node.js"]
end
subgraph LocalServices["ローカルサービス"]
IPC["IPC Server<br/>コンポーネント間通信"]
SM["Stream Manager<br/>データバッファリング"]
LRA["Local Resource<br/>GPIO/Camera/Serial"]
DS["Device Shadow<br/>状態同期"]
end
subgraph Security["セキュリティ"]
TokenEx["Token Exchange Service<br/>AWS 認証情報"]
Logger["Logger<br/>監査ログ"]
end
end
subgraph Cloud["AWS クラウド"]
IoTCore["IoT Core<br/>メッセージ配信"]
SageMaker["SageMaker<br/>ML モデル管理"]
CloudWatch["CloudWatch<br/>ログ・メトリクス"]
Kinesis["Kinesis<br/>ストリーム処理"]
S3["S3<br/>データ保存"]
end
Nucleus --> Components
Nucleus --> LocalServices
Nucleus --> Security
Components --> IPC
Components --> SM
Components --> LRA
SM --> IoTCore
SM --> S3
SM --> Kinesis
TokenEx --> Cloud
Logger --> CloudWatch
IoTCore <--> Cloud
デプロイメントフロー
sequenceDiagram
participant Dev as Developer
participant GitHub as GitHub/S3
participant Console as Greengrass Console
participant Device as Edge Device
participant Cloud as AWS Cloud
Dev->>GitHub: Push component recipe + artifacts
Dev->>Console: Create Deployment
Console->>Console: Specify target device/group
Console->>Cloud: Register deployment
Cloud->>Device: Pull deployment config
Device->>GitHub: Download component artifacts
Device->>Device: Install dependencies
Device->>Device: Start component
Device->>Cloud: Report status
Cloud->>Console: Show deployment success
コアコンポーネント
1. Greengrass Nucleus
エッジデバイスで動作する中核ランタイム。すべてのコンポーネントのライフサイクル管理、通信、認証を担当。
Nucleus 機能:
├── Component Lifecycle Manager:起動・停止・再起動
├── IPC Server:コンポーネント間通信
├── Configuration Manager:リモート設定更新
├── Device Shadow Sync:クラウドとの状態同期
└── Logging & Diagnostics:ログ集約・監視
2. Lambda Component
AWS Lambda 関数をエッジで実行。クラウドの Lambda と同じ関数コードを利用。
# Lambda コンポーネント例
def lambda_handler(event, context):
# エッジデバイスで実行
return {
'statusCode': 200,
'body': 'Hello from Edge'
}
3. Docker Component
Docker イメージとしてコンテナアプリをデプロイ。既存アプリの再利用が容易。
4. Custom Component
Python・Java・Node.js 等で実装したカスタムコンポーネント。完全にカスタマイズ可能。
5. ML Inference Component
SageMaker Neo コンパイルモデル、TensorFlow Lite、PyTorch 等での推論実行。
# ML コンポーネント例(image classification)
import awsiot.greengrasscoreipc
from dlr import DLRModel
model = DLRModel('./model', device_type='cpu')
prediction = model.predict(input_data)
6. Token Exchange Service
AWS 認証情報(STS トークン)を自動更新・配布。デバイス側で IAM ロール活用を可能化。
7. Device Shadow Manager
デバイスシャドウの同期。desired/reported 状態の自動更新。
8. Stream Manager
ローカルデータのバッファリング・キューイング・クラウド自動送信。
主要ユースケース
1. リアルタイム産業用 AI 検査
工場カメラからのフレームをエッジで推論。数 ms の遅延で欠陥を検出・即座に生産ラインを停止。
構成:
- Edge Device: Greengrass Core
- Components: OpenCV + SageMaker Neo (defect detection model)
- Output: S3 への異常フレーム保存
2. オフライン対応のスマートホーム
インターネット断絶時もローカルで照明・温度制御を継続。再接続時に同期。
実装:
- Component: Home Automation Lambda
- Local Storage: Device Shadow(desired 状態を保持)
- Sync: 再接続時に IoT Core と同期
3. 予知保全(Predictive Maintenance)
機械の振動・温度データをエッジで分析。異常パターンをローカルで検知。
フロー:
- Stream Manager でセンサー時系列を S3 に蓄積
- SageMaker で ML モデル学習(週 1 回)
- 新モデルをコンポーネント更新で配布
- エッジで推論・異常検知
4. 自律ロボット
LiDAR 等のセンサーデータをローカルで処理。経路計画・障害物回避を遅延なく実行。
5. 遠隔医療機器モニタリング
医療機器のデータをエッジで前処理。プライバシー保護しながらクラウドに送信。
6. スマートメーター・UtilityIoT
分散センサーネットワークの管理。ローカルでフィルタリング・集約して帯域を削減。
7. 車両・ドローン制御
GPS・IMU データのローカル処理で自律運転ロジックを実行。遅延 < 50 ms。
8. エッジサイドログ集約
複数デバイスのログを Stream Manager でキューイング。ネットワーク復帰時に CloudWatch Logs へ送信。
9. 多ウイルス・マルウェア検出
エッジで動作する AV エンジンでローカルスキャン。署名データベース定期更新。
10. IoT Gateway
複数のセンサーネットワーク(Zigbee・BLE 等)を Greengrass で統合。MQTT に変換してクラウドへ。
インストール・セットアップ
前提条件
- Linux OS(Ubuntu・Amazon Linux・Raspberry Pi OS等)
- Java Runtime Environment(JRE)8.0 以上
- ネットワーク接続(初期セットアップ時)
- AWS IAM 認証情報
Greengrass Core のインストール
# 1. 最新 Greengrass Nucleus をダウンロード
cd ~
wget https://d2s8p88vqu9w66.cloudfront.net/releases/greengrass-nucleus-latest.zip
unzip greengrass-nucleus-latest.zip -d GreengrassInstaller
# 2. インストール(自動プロビジョニング)
sudo -E java -Droot="/greengrass/v2" \
-Dlog.store=FILE \
-jar ./GreengrassInstaller/lib/Greengrass.jar \
--aws-region ap-northeast-1 \
--thing-name my-greengrass-core \
--thing-group-name factory-edge-devices \
--component-default-user ggc_user:ggc_group \
--provision true \
--setup-system-service true \
--deploy-dev-tools true
# 3. Greengrass Agent を Linux サービスとして起動
sudo systemctl start greengrass.service
sudo systemctl status greengrass.service
# 4. ログを確認
sudo cat /greengrass/v2/logs/greengrass.log
手動プロビジョニング
# 1. IoT Core で Thing と証明書を作成
aws iot create-thing --thing-name my-greengrass-core
# 2. 証明書をダウンロード(PEM フォーマット)
aws iot create-keys-and-certificate --set-as-active \
--certificate-pem-outfile device-cert.pem \
--private-key-outfile private.pem.key
# 3. ポリシーをアタッチ
aws iot attach-policy --policy-name GreengrassPolicy --target <cert-arn>
# 4. /greengrass/v2/certs/ に証明書をコピー
sudo mkdir -p /greengrass/v2/certs
sudo cp device-cert.pem /greengrass/v2/certs/
sudo cp private.pem.key /greengrass/v2/certs/
sudo cp AmazonRootCA1.pem /greengrass/v2/certs/
# 5. 設定ファイルを作成
cat > config.yaml << 'EOF'
---
coreThing:
thingArn: "arn:aws:iot:ap-northeast-1:123456789012:thing/my-greengrass-core"
thingName: "my-greengrass-core"
certificateArn: "arn:aws:iot:ap-northeast-1:123456789012:cert/abc123xyz"
privateKeyPath: "/greengrass/v2/certs/private.pem.key"
certificatePath: "/greengrass/v2/certs/device-cert.pem"
rootCaPath: "/greengrass/v2/certs/AmazonRootCA1.pem"
...
EOF
# 6. Nucleus インストール
sudo java -Droot="/greengrass/v2" \
-jar ./GreengrassInstaller/lib/Greengrass.jar \
--config-file config.yaml \
--setup-system-service true
コンポーネント開発と配置
コンポーネント Recipe の作成
Recipe は YAML または JSON で、コンポーネントのメタデータ・依存関係・ビルド・実行スクリプトを定義。
RecipeFormatVersion: '2020-01-25'
ComponentName: com.example.SensorReader
ComponentVersion: '1.0.0'
ComponentDescription: 'Sensor data collector component'
ComponentPublisher: 'My Company'
ComponentConfiguration:
DefaultConfiguration:
interval: 30
topic: 'factory/sensors'
Manifests:
- Platform:
os: linux
architecture: x86_64
Lifecycle:
Install:
Script: |
pip3 install -r {artifacts:path}/requirements.txt
Run:
Script: |
export PYTHONPATH={artifacts:path}
python3 {artifacts:path}/sensor_reader.py
Shutdown:
Timeout: 30
Artifacts:
- URI: s3://my-greengrass-artifacts/sensor-reader-v1.zip
Unarchive: ZIP
Dependencies:
- ComponentName: aws.greengrass.Nucleus
VersionRequirement: '>=2.0.0'
コンポーネント実装例
# sensor_reader.py
import json
import time
import awsiot.greengrasscoreipc
import awsiot.greengrasscoreipc.client as client
from awsiot.greengrasscoreipc.model import (
PublishToIoTCoreRequest,
QOS,
)
def main():
ipc_client = awsiot.greengrasscoreipc.connect()
while True:
# センサーデータ取得(ダミー)
temperature = 20.5 + (time.time() % 10)
humidity = 60.0
payload = json.dumps({
'temperature': temperature,
'humidity': humidity,
'timestamp': int(time.time())
})
# IoT Core に Publish
request = PublishToIoTCoreRequest(
topic_name='factory/sensors',
payload=payload.encode(),
qos=QOS.AT_LEAST_ONCE
)
try:
response = ipc_client.new_publish_to_iot_core().activate(request).result(timeout=5.0)
print(f"Published: {payload}")
except Exception as e:
print(f"Failed to publish: {e}")
time.sleep(30)
if __name__ == '__main__':
main()
コンポーネントのデプロイ
# 1. コンポーネントを S3 にアップロード
aws s3 cp sensor-reader-v1.zip s3://my-greengrass-artifacts/
# 2. コンポーネントバージョンを作成(レシピ登録)
aws greengrassv2 create-component-version \
--inline-recipe fileb://com.example.SensorReader-1.0.0.yaml \
--region ap-northeast-1
# 3. デプロイメントを作成
aws greengrassv2 create-deployment \
--target-arn arn:aws:iot:ap-northeast-1:123456789012:thing/my-greengrass-core \
--components '{
"com.example.SensorReader": {
"componentVersion": "1.0.0",
"configurationUpdate": {
"merge": "{\"interval\": 10}"
}
}
}' \
--region ap-northeast-1
# 4. デプロイメント状態確認
aws greengrassv2 describe-deployment \
--deployment-id xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
ML 推論エッジコンポーネント
SageMaker Neo モデルのエクスポート
# SageMaker で学習モデルをコンパイル
import sagemaker
sess = sagemaker.Session()
role = sagemaker.get_execution_role()
# 学習済みモデル(例:TensorFlow)をコンパイル
from sagemaker.tensorflow.estimator import TensorFlow
estimator = TensorFlow.attach('model-xxx')
# Neo でエッジ最適化版にコンパイル
predictor = estimator.deploy(
initial_instance_count=1,
instance_type='ml.m5.large',
framework_version='2.0'
)
# Neo コンパイルジョブ
neo_compile_response = sess.sagemaker_client.create_compilation_job(
CompilationJobName='defect-detection-edge-compile',
RoleArn=role,
InputConfig={
'S3Uri': 's3://my-models/defect-model.tar.gz',
'DataInputConfig': '{"data":[1,3,224,224]}'
},
OutputConfig={
'S3OutputLocation': 's3://my-models/compiled/',
'TargetDevice': 'deepsense_iotbot_docker' # エッジデバイス
}
)
ML コンポーネント Recipe
RecipeFormatVersion: '2020-01-25'
ComponentName: com.example.DefectDetection
ComponentVersion: '1.0.0'
ComponentDescription: 'ML defect detection using SageMaker Edge'
ComponentConfiguration:
DefaultConfiguration:
imageInputTopic: 'factory/camera/frames'
alertOutputTopic: 'factory/alerts'
confidenceThreshold: 0.8
Manifests:
- Platform:
os: linux
architecture: x86_64
Lifecycle:
Install:
Script: |
pip3 install opencv-python dlr
Run:
Script: |
python3 {artifacts:path}/inference.py
Artifacts:
- URI: s3://my-greengrass-artifacts/defect-model.tar.gz
Unarchive: TAR_GZ
Destination: /tmp/model
Dependencies:
- ComponentName: aws.greengrass.Nucleus
VersionRequirement: '>=2.0.0'
- ComponentName: aws.greengrass.DockerApplicationManager
VersionRequirement: '>=0.1.0'
推論実装例
# inference.py
import cv2
import json
import time
from dlr import DLRModel
import awsiot.greengrasscoreipc
import awsiot.greengrasscoreipc.client as client
from awsiot.greengrasscoreipc.model import (
PublishToIoTCoreRequest,
SubscribeToIoTCoreRequest,
QOS,
)
class DefectDetector:
def __init__(self):
self.model = DLRModel('/tmp/model', device_type='cpu')
self.ipc_client = awsiot.greengrasscoreipc.connect()
self.confidence_threshold = 0.8
def infer_frame(self, frame):
# 前処理
resized = cv2.resize(frame, (224, 224))
normalized = resized.astype('float32') / 255.0
# 推論(< 50ms on CPU)
prediction = self.model.predict(normalized)
# 結果解析
defect_confidence = prediction[1]
return {
'defect_detected': defect_confidence > self.confidence_threshold,
'confidence': float(defect_confidence)
}
def subscribe_and_process(self):
def on_message(message):
try:
payload = json.loads(message.payload)
frame_data = bytes.fromhex(payload['frame'])
frame = cv2.imdecode(frame_data, cv2.IMREAD_COLOR)
result = self.infer_frame(frame)
if result['defect_detected']:
alert = {
'deviceId': 'camera-01',
'defect': True,
'confidence': result['confidence'],
'timestamp': int(time.time())
}
request = PublishToIoTCoreRequest(
topic_name='factory/alerts',
payload=json.dumps(alert).encode(),
qos=QOS.AT_LEAST_ONCE
)
self.ipc_client.new_publish_to_iot_core().activate(request)
except Exception as e:
print(f"Error: {e}")
# Subscribe
request = SubscribeToIoTCoreRequest(
topic_name='factory/camera/frames',
qos=QOS.AT_LEAST_ONCE
)
self.ipc_client.new_subscribe_to_iot_core(on_message).activate(request)
if __name__ == '__main__':
detector = DefectDetector()
detector.subscribe_and_process()
ローカル pub/sub と IPC
IPC メッセージング
コンポーネント間で低レイテンシ通信を実現する Unix ソケットベースの通信。
# Publisher コンポーネント
import awsiot.greengrasscoreipc.client as client
from awsiot.greengrasscoreipc.model import (
PublishMessage,
QOS,
)
ipc_client = awsiot.greengrasscoreipc.connect()
request = client.PublishToTopicRequest(
topic='local/sensor/temperature',
publish_message=PublishMessage(
binary_message=b'{"temp": 25.5}',
json_message='{"temp": 25.5}'
)
)
ipc_client.new_publish_to_topic().activate(request).result()
# Subscriber コンポーネント
from awsiot.greengrasscoreipc.model import SubscribeToTopicRequest
def on_message(message):
print(f"Received: {message.binary_message}")
request = SubscribeToTopicRequest(topic='local/sensor/temperature')
ipc_client.new_subscribe_to_topic(on_message).activate(request)
ストリームマネージャー
ローカルデータストレージと自動エクスポート
from stream_manager import (
StreamManagerClient,
MessageStreamDefinition,
StrategyOnFull,
Persistence,
ExportDefinition,
S3ExportTaskDefinition,
StatusLevel
)
from datetime import datetime
client = StreamManagerClient()
# ストリーム定義
stream = MessageStreamDefinition(
name='SensorDataStream',
strategy_on_full=StrategyOnFull.OverwriteOldestData,
persistence=Persistence.File,
max_size=256 * 1024 * 1024, # 256 MB
flush_on_write=False,
export_definition=ExportDefinition(
s3_task_executor=[
S3ExportTaskDefinition(
identifier='SensorDataExporter',
bucket_name='my-iot-data-bucket',
key_name_delimiter='/',
batch_size=10,
batch_interval_millis=5000,
priority=1,
start_sequence_number=0
)
]
)
)
# ストリーム作成
try:
client.create_message_stream(stream)
print('Stream created')
except Exception as e:
print(f'Stream already exists: {e}')
# データを追加(バッファリング)
import json
import time
for i in range(100):
message = json.dumps({
'sensor_id': 'temp-01',
'temperature': 20.0 + (i % 10),
'timestamp': int(time.time())
})
try:
client.append_message(
stream_name='SensorDataStream',
payload=message.encode()
)
except Exception as e:
print(f'Failed to append: {e}')
time.sleep(1)
設定・操作の具体例
CLI: コンポーネント管理
# コンポーネント一覧表示
aws greengrassv2 list-components --region ap-northeast-1
# 特定コンポーネント情報取得
aws greengrassv2 get-component-version-artifact \
--arn "arn:aws:greengrass:ap-northeast-1:123456789012:components:com.example.SensorReader:versions:1.0.0"
# デプロイメント一覧
aws greengrassv2 list-deployments --target-arn "arn:aws:iot:ap-northeast-1:123456789012:thing/my-greengrass-core"
# デプロイメント詳細
aws greengrassv2 describe-deployment --deployment-id "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
# デプロイメントキャンセル
aws greengrassv2 cancel-deployment --deployment-id "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
SDK: Deployment via Python
import boto3
import json
client = boto3.client('greengrassv2', region_name='ap-northeast-1')
# デプロイメント作成
response = client.create_deployment(
targetArn='arn:aws:iot:ap-northeast-1:123456789012:thinggroup/factory-devices',
components={
'com.example.SensorReader': {
'componentVersion': '1.0.0',
'configurationUpdate': {
'merge': json.dumps({
'interval': 10,
'topic': 'factory/sensors/realtime'
})
}
},
'com.example.DefectDetection': {
'componentVersion': '1.0.0',
'configurationUpdate': {
'merge': json.dumps({
'confidenceThreshold': 0.85
})
}
}
},
deploymentType='STANDARD',
iotJobConfiguration={
'jobExecutionsRolloutConfig': {
'exponentialRate': {
'baseRatePerMinute': 10,
'incrementFactor': 1.5
}
}
}
)
print(f"Deployment ID: {response['deploymentId']}")
CloudFormation での IaC 定義
AWSTemplateFormatVersion: '2010-09-09'
Description: Greengrass V2 Core Setup
Resources:
GreengrassThing:
Type: AWS::IoT::Thing
Properties:
ThingName: my-greengrass-core
GreengrassPolicy:
Type: AWS::IoT::Policy
Properties:
PolicyName: GreengrassCorePolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- iot:Connect
- iot:Publish
- iot:Subscribe
- iot:Receive
Resource:
- !Sub 'arn:aws:iot:${AWS::Region}:${AWS::AccountId}:client/${iot:Connection.Thing.ThingName}'
- Effect: Allow
Action:
- iot:GetThingShadow
- iot:UpdateThingShadow
Resource:
- !Sub 'arn:aws:iot:${AWS::Region}:${AWS::AccountId}:thing/${iot:Connection.Thing.ThingName}'
- Effect: Allow
Action:
- s3:GetObject
- s3:PutObject
Resource:
- !Sub 'arn:aws:s3:::my-greengrass-artifacts/*'
GreengrassComponentRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: greengrassv2.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/CloudWatchLogsFullAccess
Policies:
- PolicyName: GreengrassComponentPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- s3:GetObject
Resource:
- !Sub 'arn:aws:s3:::my-greengrass-artifacts/*'
- Effect: Allow
Action:
- iot:PublishMessage
Resource:
- !Sub 'arn:aws:iot:${AWS::Region}:${AWS::AccountId}:topicfilter/*'
類似サービス比較表
| 特性 | Greengrass V2 | Azure IoT Edge | KubeEdge | EdgeX Foundry |
|---|---|---|---|---|
| 管理方式 | フルマネージド | 親オープン | オープンソース | オープンソース |
| ランタイム | Java-based Nucleus | Docker/Container | Kubernetes | Go-based microservices |
| 言語対応 | Python/Java/Node.js/.NET/Go | C#/Node.js/Python/Java | Go/Python | Go/C/Java |
| ML サポート | ✅ SageMaker Neo | ✅ Azure ML | △ KServe | △ |
| コンポーネント | ✅ モジュール化 | ✅ モジュール | △ microservices | ✅ services |
| IPC/Messaging | ✅ Local pub/sub | ✅ MQTT | ✅ EdgeMesh | ✅ Message Bus |
| コスト | 無料(Greengrass コア) | Azure 従量課金 | 無料 | 無料 |
| AWS 統合 | ✅ ネイティブ | × | × | × |
| セキュリティ | ✅ 自動証明書更新 | △ Manual | △ Manual | × |
| スケーラビリティ | ✅ 大規模フリート | ✅ 中規模 | ✅ Kubernetes | △ |
ベストプラクティス
✅ 推奨事項
| 項目 | 実装方法 |
|---|---|
| コンポーネント粒度 | 単一責任の原則。1 コンポーネント = 1 機能 |
| バージョン管理 | セマンティックバージョニング(MAJOR.MINOR.PATCH) |
| ロールアウト | 段階的(Exponential rate)で小さい グループから開始 |
| ローカルリソース | 専用ディレクトリで管理。root 権限を避ける |
| ログレベル | 本番環境では DEBUG を回避。INFO・WARN 推奨 |
| タイムアウト | Lambda/Docker のタイムアウトを明示的に設定 |
| Stream Manager | バッファサイズとエクスポート間隔を調整 |
| 秘密管理 | AWS Secrets Manager + Token Exchange Service 利用 |
| リソース監視 | CloudWatch メトリクス(CPU・メモリ・ディスク) |
| 自動更新 | Greengrass Nucleus の自動更新を有効化 |
❌ アンチパターン
| 反パターン | 問題 | 対策 |
|---|---|---|
| モノリシック設計 | 1 コンポーネントに複数責務。更新困難 | コンポーネント分割 |
| コンテナのサイズ過大 | イメージ > 1GB でデプロイが遅延 | マルチステージビルド |
| ハードコード設定 | デバイス間で異なる値が必要でも固定値 | 環境変数・configuration merge |
| ローカルストレージ無視 | ネットワーク断時にデータ喪失 | Stream Manager 活用 |
| エラーハンドリング欠如 | 例外で即座にクラッシュ | try-except と retry ロジック |
| ログを無効化 | トラブルシューティング困難 | CloudWatch Logs 有効化 |
トラブルシューティング
よくある問題と解決方法
| 問題 | 原因 | 解決方法 |
|---|---|---|
| Nucleus 起動失敗 | Java 未インストール・権限不足 | java -version 確認・sudo で実行 |
| コンポーネント起動しない | 依存関係の不足・スクリプトエラー | /greengrass/v2/logs/ でエラーログ確認 |
| IPC 通信失敗 | Unix ソケット権限・アドレス間違い | IPC server が起動していることを確認 |
| ML 推論が遅い | モデルサイズ大きい・CPU 不足 | Neo で最適化・GPU 利用検討 |
| Stream Manager バッファ満杯 | エクスポート遅延・フラッシュ失敗 | S3 権限確認・バッチサイズ調整 |
| デプロイメント失敗 | IAM ロール権限不足 | デプロイ IAM ロールのポリシー確認 |
| Shadow 同期されない | Device Shadow 機能無効 | FEATURE_FLAGS_CONFIG で有効化 |
| **メモリ不足(OOM) | コンポーネント メモリリーク | メモリプロファイリング・限度設定 |
ログ確認方法
# Greengrass Nucleus ログ
sudo cat /greengrass/v2/logs/greengrass.log
# コンポーネント個別ログ
sudo cat /greengrass/v2/logs/com.example.SensorReader.log
# CloudWatch Logs(デバイスから)
aws logs tail /aws/greengrass/core/my-greengrass-core --follow
# 過去 1 時間のエラー
aws logs filter-log-events \
--log-group-name "/aws/greengrass/core/my-greengrass-core" \
--filter-pattern "ERROR"
2025-2026 年の最新動向
新機能・改善
-
TPM 2.0 ハードウェアセキュリティ対応(v2.16.0)
- セキュアエレメントでの秘密鍵保管
- ハードウェアベースの暗号化
-
ML コンポーネントレシピ属性拡張
- より詳細な推論パラメータ制御
- フレームワーク統合の簡素化
-
Greengrass for IoT Core for LoRaWAN 統合
- LoRaWAN ゲートウェイでのエッジ処理
- ローカル network server 機能
-
DLMG(Deployment and Lifecycle Management)の強化
- キャナリアデプロイメント自動ロールバック
- A/B テストの標準化
-
AI/ML ワークロード最適化
- Inferentia2・Trainium チップ対応
- モデルキャッシング機構
-
コスト最適化
- Greengrass コア/コンポーネントの無料ティア拡大
- 計算コスト削減オプション
採用トレンド
- Industrial 5.0: エッジ AI + 人間協働ロボット
- Generative AI at Edge: 小規模言語モデルのローカル推論
- Zero Trust Security: エッジでのセキュリティポリシー強制
- OT/IT 統合: IT システムと産業制御の融合
学習リソース・参考文献
AWS 公式ドキュメント
- AWS IoT Greengrass V2 Developer Guide
- Getting Started with Greengrass V2
- Component Recipe Reference
- Machine Learning Components
- Interprocess Communication (IPC)
- Stream Manager
- Deployment Configuration
- Migrate from V1
AWS ブログ・チュートリアル
- AWS IoT Greengrass Official Blog
- Greengrass V2 in Production - Managing Edge ML Deployments
- Perform Machine Learning Inference on Edge Devices
オープンソース・サンプルコード
- AWS IoT Greengrass Component Examples
- Greengrass ML Deployment Sample
- ML Edge Getting Started
- Greengrass on Raspberry Pi
- Edge Impulse Greengrass Integration
実装例・チェックリスト
Greengrass V2 デプロイメント前チェックリスト
セットアップ準備
□ Linux OS(Ubuntu/Amazon Linux)にアクセス可能
□ Java 8.0 以上インストール済み
□ AWS IAM 認証情報(Access Key・Secret Key)取得済み
□ AWS IoT Core エンドポイント確認済み
AWS IoT Core 準備
□ Thing 作成(または自動プロビジョニング)
□ 証明書生成・ダウンロード
□ ポリシーアタッチ(Greengrass Principal ポリシー)
□ CloudWatch Logs IAM ロール設定
Greengrass Nucleus インストール
□ Nucleus ZIP ダウンロード
□ インストールディレクトリ指定(/greengrass/v2 推奨)
□ Linux サービス登録(systemctl)
□ ログ確認(/greengrass/v2/logs/greengrass.log)
コンポーネント開発準備
□ Recipe.yaml 作成(RecipeFormatVersion: 2020-01-25)
□ コンポーネント実装(Python/Java/Node.js)
□ 依存関係明示(aws.greengrass.Nucleus等)
□ アーティファクト S3 にアップロード
デプロイメント実施
□ コンポーネントバージョン登録
□ デプロイメント作成(target: Thing/ThingGroup)
□ ロールアウト設定(Exponential rate)
□ 進捗監視( console または describe-deployment API)
運用・監視
□ CloudWatch Logs 有効化
□ メトリクス設定(CPU・メモリ・ディスク)
□ アラーム設定(エラー率・デプロイ失敗)
□ ローテーション計画(コンポーネント更新スケジュール)
まとめ
AWS IoT Greengrass V2 は、エッジデバイスでの分散コンピューティングを実現するオープンソースランタイムです。
核心的な価値
- 低レイテンシ: ローカル処理で数 ms の遠延を実現。リアルタイム制御が可能
- オフライン自律性: ネットワーク断でも動作。再接続時に同期
- ML 推論: SageMaker Neo モデルをエッジで実行。API 往復遅延ゼロ
- コンポーネント管理: OTA で大規模フリートへの安全な更新を実装
- 多言語対応: Python・Java・Node.js 等で開発。開発効率向上
- セキュア通信: 自動証明書更新・Token Exchange で IAM 統合
適用判断
Greengrass V2 を選ぶべき場合:
- < 50 ms のレイテンシが必須
- オフライン環境での自律稼働が必要
- 機械学習推論をエッジで実行したい
- 数百~数万台のエッジデバイス一元管理が必要
他の選択肢を検討すべき場合:
- クラウド処理だけで足りる場合(IoT Core のみ)
- Kubernetes ベースの統一プラットフォーム重視(KubeEdge)
- Azure スタック統合(Azure IoT Edge)
次のステップ
- 小規模 PoC: Raspberry Pi で Greengrass Core セットアップ
- コンポーネント開発: Python でセンサーリーダーを実装
- ML 統合: SageMaker で学習・Neo でコンパイル・エッジで推論
- AWS Greengrass コンソール でハンズオン開始
最終更新:2026-04-27
バージョン:v2.0