Déployer, observer et mettre à jour
Tâche 1 : Composer la pile
Section intitulée « Tâche 1 : Composer la pile »Le générateur a fourni des blocs de construction, pas un déploiement. Votre pile décide où vivent les artefacts, quel rôle peut les lire et quelle flotte reçoit le composant. Remplacez 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); }}Ce que fait chaque partie :
GreengrassArtifactBucketcrée le référentiel d’artefacts conservé, versionné et TLS uniquement.grantReadTodonne au rôle d’échange de jetonss3:GetObjectsurcom.example.Pulse/*, ce qui couvre chaque clé d’artefact que le résolveur écrit pour ce composant.PulseétendGreengrassComponentVersion. Il lit la recette etpulse.zipquepulse-artifacta construit, télécharge l’archive sous une clé hachée par contenu et publie la version du composant. Sa propriétébucketprend la constructionGreengrassArtifactBucketelle-même.GreengrassDeploymentavectargetArndéploie vers le groupe de choses que le script de configuration a créé.addComponent(pulse)place la version résolue dans la carte des composants du déploiement et ajoute une dépendance CloudFormation sur la ressource de version du composant, de sorte que la tâche IoT ne peut pas atteindre l’appareil avant que la version n’existe.- Les deux valeurs
CfnParameterproviennent de.greengrass-tutorial.env. Les passer en tant que paramètres maintient la pile exempte de littéraux spécifiques au compte et permet à la suite e2e de synthétiser le même fichier.
Tâche 2 : Bootstrap et déploiement
Section intitulée « Tâche 2 : Bootstrap et déploiement »Chargez les valeurs enregistrées, synchronisez les références de projet et les manifestes de dépendances, installez les dépendances de l’espace de travail mises à jour et amorcez CDK dans le compte et la région si vous ne l’avez pas déjà fait :
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:bootstrapDéployez la pile. packages/infra/src/main.ts place la pile dans l’étape greengrass-tutorial-infra-sandbox, et la cible deploy exécute cdk deploy sans étape propre, donc la commande nomme cette étape et passe les ARN du rôle et du groupe de choses en tant que paramètres 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 dépend de ^assemble, et le projet de constructions partagées dépend de l’assemble du projet de télémétrie, qui exécute pulse-artifact. Chaque déploiement publie donc l’artefact qui correspond à votre source actuelle. La cible exécute cdk deploy sans mode express, elle accepte donc une révision de déploiement ultérieure qui remplace la ressource de déploiement. Lisez révisions de déploiement avant d’utiliser deploy-sandbox pour Greengrass.
Lors du premier déploiement, le résolveur de version ne trouve aucune version publiée de com.example.Pulse et publie 1.0.0. Le déploiement atteint ensuite le groupe de choses, et l’appareil principal télécharge l’artefact avec le rôle d’échange de jetons et démarre le composant. Comptez une à deux minutes après la fin de la pile.
Tâche 3 : Observer le heartbeat
Section intitulée « Tâche 3 : Observer le heartbeat »Ouvrez la console AWS IoT dans $TUTORIAL_AWS_REGION, choisissez MQTT test client et abonnez-vous au sujet :
tutorial/greengrass/heartbeatToutes les 30 secondes, un message arrive :
{"sequence": 3, "greeting": "hello from pulse"}L’AWS CLI ne peut pas s’abonner aux sujets MQTT. Si vous préférez votre propre client MQTT, connectez-le au point de terminaison de données du compte avec son propre certificat et sa propre politique, que ce tutoriel ne crée pas :
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" iot describe-endpoint \ --endpoint-type iot:Data-ATS --query endpointAddress --output textTâche 4 : Vérifier l’appareil
Section intitulée « Tâche 4 : Vérifier l’appareil »Un déploiement réussi prouve que l’appareil a appliqué le document de déploiement. Il ne prouve pas que le composant s’exécute. Vérifiez l’état du cycle de vie du composant installé :
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 textAttendez-vous à 1.0.0 et RUNNING. Ensuite, lisez le journal propre du composant sur l’instance avec le modèle Systems Manager du module 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 textLe journal montre la connexion IPC et une ligne par 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/heartbeatSi le déploiement signale SUCCEEDED mais que le composant est BROKEN, ou si get-core-device signale UNHEALTHY, suivez les étapes de dépannage du composant.
Tâche 5 : Mettre à jour le composant
Section intitulée « Tâche 5 : Mettre à jour le composant »Modifiez le message d’accueil dans 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()Déployez à nouveau avec la même commande :
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 voit la source modifiée et reconstruit pulse-artifact. Le hachage du contenu de l’archive change, donc le résolveur alloue 1.0.1, l’artefact est téléchargé sous une nouvelle clé, une nouvelle version du composant est publiée et une nouvelle révision de déploiement pointe le groupe de choses vers celle-ci. La recette dit toujours NEXT_PATCH ; rien dans l’espace de travail n’enregistre le numéro.
Vérifiez à la fois la version installée et la charge utile :
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 textAttendez-vous à 1.0.1 et RUNNING. Dans le client de test MQTT, le message d’accueil devient hello from the updated pulse, et la séquence redémarre à partir de 0 car le processus du composant a été redémarré.
Continuez avec Supprimer et nettoyer.