Distribuire, osservare e aggiornare
Task 1: Comporre lo stack
Sezione intitolata “Task 1: Comporre lo stack”Il generatore ha fornito blocchi di costruzione, non una distribuzione. Il tuo stack decide dove risiedono gli artefatti, quale ruolo può leggerli e quale flotta riceve il componente. Sostituisci packages/infra/src/stacks/application-stack.ts:
import { GreengrassArtifactBucket, GreengrassDeployment, Pulse,} from '@greengrass-tutorial/common-constructs';import { CfnParameter, Stack, type StackProps } from 'aws-cdk-lib';import { Role } from 'aws-cdk-lib/aws-iam';import type { Construct } from 'constructs';
export class ApplicationStack extends Stack { constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props);
// Both values are written to .greengrass-tutorial.env by the setup script // and passed with --parameters on every deploy. const tokenExchangeRoleArn = new CfnParameter( this, 'TokenExchangeRoleArn', { type: 'String', description: 'ARN of the core device token exchange role', }, ); const thingGroupArn = new CfnParameter(this, 'ThingGroupArn', { type: 'String', description: 'ARN of the thing group that holds the core device', });
// The retained artifact repository, and the read grant the core device // needs to fetch this component's artifacts from it. const artifacts = new GreengrassArtifactBucket(this, 'Artifacts'); const tokenExchangeRole = Role.fromRoleArn( this, 'TokenExchangeRole', tokenExchangeRoleArn.valueAsString, ); artifacts.grantReadTo(tokenExchangeRole, 'com.example.Pulse/*');
// Publishes the artifact built by pulse-artifact, then deploys it to the // existing thing group. addComponent carries the resolved NEXT_PATCH // version and orders the deployment after the component version. const pulse = new Pulse(this, 'Pulse', { bucket: artifacts }); const fleet = new GreengrassDeployment(this, 'Fleet', { targetArn: thingGroupArn.valueAsString, }); fleet.addComponent(pulse); }}import { Stack, StackProps } from 'aws-cdk-lib';import { Construct } from 'constructs';import { GreengrassArtifactBucket, GreengrassDeployment, Pulse,} from '@greengrass-tutorial/common-constructs';import { CfnParameter, Stack, type StackProps } from 'aws-cdk-lib';import { Role } from 'aws-cdk-lib/aws-iam';import type { Construct } from 'constructs';
export class ApplicationStack extends Stack { constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props);
// The code that defines your stack goes here // Both values are written to .greengrass-tutorial.env by the setup script // and passed with --parameters on every deploy. const tokenExchangeRoleArn = new CfnParameter( this, 'TokenExchangeRoleArn', { type: 'String', description: 'ARN of the core device token exchange role', }, ); const thingGroupArn = new CfnParameter(this, 'ThingGroupArn', { type: 'String', description: 'ARN of the thing group that holds the core device', });
// The retained artifact repository, and the read grant the core device // needs to fetch this component's artifacts from it. const artifacts = new GreengrassArtifactBucket(this, 'Artifacts'); const tokenExchangeRole = Role.fromRoleArn( this, 'TokenExchangeRole', tokenExchangeRoleArn.valueAsString, ); artifacts.grantReadTo(tokenExchangeRole, 'com.example.Pulse/*');
// Publishes the artifact built by pulse-artifact, then deploys it to the // existing thing group. addComponent carries the resolved NEXT_PATCH // version and orders the deployment after the component version. const pulse = new Pulse(this, 'Pulse', { bucket: artifacts }); const fleet = new GreengrassDeployment(this, 'Fleet', { targetArn: thingGroupArn.valueAsString, }); fleet.addComponent(pulse); }}Cosa fa ciascuna parte:
GreengrassArtifactBucketcrea il repository degli artefatti conservato, versionato e solo TLS.grantReadToconcede al ruolo di scambio tokens3:GetObjectsucom.example.Pulse/*, che copre ogni chiave di artefatto che il resolver scrive per questo componente.PulseestendeGreengrassComponentVersion. Legge la ricetta epulse.zipchepulse-artifactha costruito, carica l’archivio sotto una chiave con hash del contenuto e pubblica la versione del componente. La sua proprietàbucketprende il costruttoGreengrassArtifactBucketstesso.GreengrassDeploymentcontargetArndistribuisce al gruppo di cose creato dallo script di configurazione.addComponent(pulse)inserisce la versione risolta nella mappa dei componenti della distribuzione e aggiunge una dipendenza CloudFormation sulla risorsa della versione del componente, in modo che il job IoT non possa raggiungere il dispositivo prima che la versione esista.- I due valori
CfnParameterprovengono da.greengrass-tutorial.env. Passarli come parametri mantiene lo stack libero da letterali specifici dell’account e consente alla suite e2e di sintetizzare lo stesso file.
Task 2: Bootstrap e distribuzione
Sezione intitolata “Task 2: Bootstrap e distribuzione”Carica i valori registrati, sincronizza i riferimenti del progetto e i manifest delle dipendenze, installa le dipendenze aggiornate del workspace ed esegui il bootstrap di CDK nell’account e nella regione se non l’hai già fatto prima:
source .greengrass-tutorial.envpnpm nx syncyarn nx syncnpx nx syncbunx nx syncpnpm installyarnnpm installbun installAWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" pnpm nx run @greengrass-tutorial/infra:bootstrapAWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" yarn nx run @greengrass-tutorial/infra:bootstrapAWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" npx nx run @greengrass-tutorial/infra:bootstrapAWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" bunx nx run @greengrass-tutorial/infra:bootstrapDistribuisci lo stack. packages/infra/src/main.ts posiziona lo stack nello stage greengrass-tutorial-infra-sandbox, e il target deploy esegue cdk deploy senza uno stage proprio, quindi il comando nomina quello stage e passa gli ARN del ruolo e del gruppo di cose come parametri CloudFormation:
AWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" pnpm nx run @greengrass-tutorial/infra:deploy -- "greengrass-tutorial-infra-sandbox/**" --parameters TokenExchangeRoleArn="$TUTORIAL_TOKEN_EXCHANGE_ROLE_ARN" --parameters ThingGroupArn="$TUTORIAL_THING_GROUP_ARN"AWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" yarn nx run @greengrass-tutorial/infra:deploy -- "greengrass-tutorial-infra-sandbox/**" --parameters TokenExchangeRoleArn="$TUTORIAL_TOKEN_EXCHANGE_ROLE_ARN" --parameters ThingGroupArn="$TUTORIAL_THING_GROUP_ARN"AWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" npx nx run @greengrass-tutorial/infra:deploy -- "greengrass-tutorial-infra-sandbox/**" --parameters TokenExchangeRoleArn="$TUTORIAL_TOKEN_EXCHANGE_ROLE_ARN" --parameters ThingGroupArn="$TUTORIAL_THING_GROUP_ARN"AWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" bunx nx run @greengrass-tutorial/infra:deploy -- "greengrass-tutorial-infra-sandbox/**" --parameters TokenExchangeRoleArn="$TUTORIAL_TOKEN_EXCHANGE_ROLE_ARN" --parameters ThingGroupArn="$TUTORIAL_THING_GROUP_ARN"deploy dipende da ^assemble, e il progetto dei costrutti condivisi dipende dall’assemble del progetto di telemetria, che esegue pulse-artifact. Ogni distribuzione pubblica quindi l’artefatto che corrisponde al tuo sorgente attuale. Il target esegue cdk deploy senza modalità express, quindi accetta una revisione di distribuzione successiva che sostituisce la risorsa di distribuzione. Leggi revisioni di distribuzione prima di usare deploy-sandbox per Greengrass.
Alla prima distribuzione il resolver di versione non trova alcuna versione pubblicata di com.example.Pulse e pubblica 1.0.0. La distribuzione raggiunge quindi il gruppo di cose, e il dispositivo core scarica l’artefatto con il ruolo di scambio token e avvia il componente. Attendi da uno a due minuti dopo il completamento dello stack.
Task 3: Osservare l’heartbeat
Sezione intitolata “Task 3: Osservare l’heartbeat”Apri la console AWS IoT in $TUTORIAL_AWS_REGION, scegli MQTT test client e sottoscrivi al topic:
tutorial/greengrass/heartbeatOgni 30 secondi arriva un messaggio:
{"sequence": 3, "greeting": "hello from pulse"}L’AWS CLI non può sottoscrivere ai topic MQTT. Se preferisci il tuo client MQTT, collegalo all’endpoint dati dell’account con il proprio certificato e policy, che questo tutorial non crea:
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" iot describe-endpoint \ --endpoint-type iot:Data-ATS --query endpointAddress --output textTask 4: Controllare il dispositivo
Sezione intitolata “Task 4: Controllare il dispositivo”Una distribuzione riuscita dimostra che il dispositivo ha applicato il documento di distribuzione. Non dimostra che il componente sia in esecuzione. Controlla lo stato del ciclo di vita del componente installato:
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" greengrassv2 list-installed-components \ --core-device-thing-name "$TUTORIAL_THING_NAME" \ --query 'installedComponents[?componentName==`com.example.Pulse`].[componentVersion,lifecycleState]' \ --output textAspettati 1.0.0 e RUNNING. Quindi leggi il log del componente stesso sull’istanza con il pattern Systems Manager del modulo 2:
cat > /tmp/greengrass-tutorial-command.json <<'EOF'{ "commands": ["#!/bin/bash", "tail -n 20 /greengrass/v2/logs/com.example.Pulse.log"] }EOF
TUTORIAL_COMMAND_ID=$(aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" ssm send-command \ --instance-ids "$TUTORIAL_INSTANCE_ID" --document-name AWS-RunShellScript \ --parameters file:///tmp/greengrass-tutorial-command.json \ --query Command.CommandId --output text)sleep 5aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" ssm get-command-invocation \ --command-id "$TUTORIAL_COMMAND_ID" --instance-id "$TUTORIAL_INSTANCE_ID" \ --query StandardOutputContent --output textIl log mostra la connessione IPC e una riga per heartbeat:
INFO:awsiot.eventstreamrpc:<Connection ...> /greengrass/v2/ipc.socket:0> connectedINFO:com.example.Pulse:Published heartbeat 0 to tutorial/greengrass/heartbeatINFO:com.example.Pulse:Published heartbeat 1 to tutorial/greengrass/heartbeatSe la distribuzione riporta SUCCEEDED ma il componente è BROKEN, o get-core-device riporta UNHEALTHY, segui i passaggi di risoluzione dei problemi del componente.
Task 5: Aggiornare il componente
Sezione intitolata “Task 5: Aggiornare il componente”Modifica il saluto in 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 the updated 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 GreengrassCoreIPCClientV2
logging.basicConfig(level=logging.INFO)logger = logging.getLogger("com.example.Pulse")
TOPIC = "tutorial/greengrass/heartbeat"PUBLISH_INTERVAL_SECONDS = 30GREETING = "hello from pulse"GREETING = "hello from the updated 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()Distribuisci di nuovo con lo stesso comando:
AWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" pnpm nx run @greengrass-tutorial/infra:deploy -- "greengrass-tutorial-infra-sandbox/**" --parameters TokenExchangeRoleArn="$TUTORIAL_TOKEN_EXCHANGE_ROLE_ARN" --parameters ThingGroupArn="$TUTORIAL_THING_GROUP_ARN"AWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" yarn nx run @greengrass-tutorial/infra:deploy -- "greengrass-tutorial-infra-sandbox/**" --parameters TokenExchangeRoleArn="$TUTORIAL_TOKEN_EXCHANGE_ROLE_ARN" --parameters ThingGroupArn="$TUTORIAL_THING_GROUP_ARN"AWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" npx nx run @greengrass-tutorial/infra:deploy -- "greengrass-tutorial-infra-sandbox/**" --parameters TokenExchangeRoleArn="$TUTORIAL_TOKEN_EXCHANGE_ROLE_ARN" --parameters ThingGroupArn="$TUTORIAL_THING_GROUP_ARN"AWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" bunx nx run @greengrass-tutorial/infra:deploy -- "greengrass-tutorial-infra-sandbox/**" --parameters TokenExchangeRoleArn="$TUTORIAL_TOKEN_EXCHANGE_ROLE_ARN" --parameters ThingGroupArn="$TUTORIAL_THING_GROUP_ARN"Nx vede il sorgente modificato e ricostruisce pulse-artifact. L’hash del contenuto dell’archivio cambia, quindi il resolver alloca 1.0.1, l’artefatto viene caricato sotto una nuova chiave, viene pubblicata una nuova versione del componente e una nuova revisione di distribuzione punta il gruppo di cose ad essa. La ricetta dice ancora NEXT_PATCH; nulla nel workspace registra il numero.
Verifica sia la versione installata che il payload:
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" greengrassv2 list-installed-components \ --core-device-thing-name "$TUTORIAL_THING_NAME" \ --query 'installedComponents[?componentName==`com.example.Pulse`].[componentVersion,lifecycleState]' \ --output textAspettati 1.0.1 e RUNNING. Nel client di test MQTT il saluto cambia in hello from the updated pulse, e la sequenza riparte da 0 perché il processo del componente è stato riavviato.
Continua con Rimuovere e pulire.