Desplegar, observar y actualizar
Tarea 1: Componer el stack
Sección titulada «Tarea 1: Componer el stack»El generador proporcionó bloques de construcción, no un despliegue. Tu stack decide dónde viven los artefactos, qué rol puede leerlos y qué flota recibe el componente. Reemplaza 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); }}Lo que hace cada parte:
GreengrassArtifactBucketcrea el repositorio de artefactos retenido, versionado y solo TLS.grantReadTootorga al rol de intercambio de tokenss3:GetObjectencom.example.Pulse/*, que cubre cada clave de artefacto que el resolvedor escribe para este componente.PulseextiendeGreengrassComponentVersion. Lee la receta ypulse.zipquepulse-artifactconstruyó, sube el archivo bajo una clave con hash de contenido y publica la versión del componente. Su propiedadbuckettoma el constructoGreengrassArtifactBucketen sí.GreengrassDeploymentcontargetArndespliega al grupo de cosas que el script de configuración creó.addComponent(pulse)coloca la versión resuelta en el mapa de componentes del despliegue y agrega una dependencia de CloudFormation en el recurso de versión del componente, por lo que el trabajo de IoT no puede alcanzar el dispositivo antes de que exista la versión.- Los dos valores
CfnParameterprovienen de.greengrass-tutorial.env. Pasarlos como parámetros mantiene el stack libre de literales específicos de la cuenta y permite que la suite e2e sintetice el mismo archivo.
Tarea 2: Inicializar y desplegar
Sección titulada «Tarea 2: Inicializar y desplegar»Carga los valores registrados, sincroniza las referencias del proyecto y los manifiestos de dependencias, instala las dependencias actualizadas del espacio de trabajo e inicializa CDK en la cuenta y Región si no lo has hecho antes:
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:bootstrapDespliega el stack. packages/infra/src/main.ts coloca el stack en el stage greengrass-tutorial-infra-sandbox, y el objetivo deploy ejecuta cdk deploy sin un stage propio, por lo que el comando nombra ese stage y pasa los ARN del rol y del grupo de cosas como parámetros de 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 depende de ^assemble, y el proyecto de constructos compartidos depende del assemble del proyecto de telemetría, que ejecuta pulse-artifact. Por lo tanto, cada despliegue publica el artefacto que coincide con tu fuente actual. El objetivo ejecuta cdk deploy sin modo express, por lo que acepta una revisión de despliegue posterior que reemplaza el recurso de despliegue. Lee revisiones de despliegue antes de usar deploy-sandbox para Greengrass.
En el primer despliegue, el resolvedor de versiones no encuentra ninguna versión publicada de com.example.Pulse y publica 1.0.0. El despliegue luego alcanza el grupo de cosas, y el dispositivo central descarga el artefacto con el rol de intercambio de tokens e inicia el componente. Permite de uno a dos minutos después de que se complete el stack.
Tarea 3: Observar el latido
Sección titulada «Tarea 3: Observar el latido»Abre la consola de AWS IoT en $TUTORIAL_AWS_REGION, elige MQTT test client y suscríbete al tema:
tutorial/greengrass/heartbeatCada 30 segundos llega un mensaje:
{"sequence": 3, "greeting": "hello from pulse"}La AWS CLI no puede suscribirse a temas MQTT. Si prefieres tu propio cliente MQTT, conéctalo al endpoint de datos de la cuenta con su propio certificado y política, que este tutorial no crea:
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" iot describe-endpoint \ --endpoint-type iot:Data-ATS --query endpointAddress --output textTarea 4: Verificar el dispositivo
Sección titulada «Tarea 4: Verificar el dispositivo»Un despliegue exitoso demuestra que el dispositivo aplicó el documento de despliegue. No demuestra que el componente se ejecute. Verifica el estado del ciclo de vida del componente instalado:
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 textEspera 1.0.0 y RUNNING. Luego lee el registro propio del componente en la instancia con el patrón de Systems Manager del módulo 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 textEl registro muestra la conexión IPC y una línea por latido:
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 el despliegue reporta SUCCEEDED pero el componente está BROKEN, o get-core-device reporta UNHEALTHY, sigue los pasos de solución de problemas del componente.
Tarea 5: Actualizar el componente
Sección titulada «Tarea 5: Actualizar el componente»Cambia el saludo en 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()Despliega nuevamente con el mismo 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 ve la fuente cambiada y reconstruye pulse-artifact. El hash de contenido del archivo cambia, por lo que el resolvedor asigna 1.0.1, el artefacto se sube bajo una nueva clave, se publica una nueva versión del componente y una nueva revisión de despliegue apunta el grupo de cosas a ella. La receta todavía dice NEXT_PATCH; nada en el espacio de trabajo registra el número.
Verifica tanto la versión instalada como la carga útil:
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 textEspera 1.0.1 y RUNNING. En el cliente de prueba MQTT, el saludo cambia a hello from the updated pulse, y la secuencia se reinicia desde 0 porque el proceso del componente fue reiniciado.
Continúa con Eliminar y limpiar.