Eliminar y limpiar
La limpieza se ejecuta en el orden inverso de la creación: primero el dispositivo deja de ejecutar el componente, luego se elimina el stack, luego los recursos que el stack retuvo, luego el dispositivo y su identidad, y finalmente el perfil de instancia.
Tarea 1: Eliminar el componente del dispositivo
Sección titulada «Tarea 1: Eliminar el componente del dispositivo»Eliminar un recurso de despliegue elimina el estado de gestión del despliegue. No desinstala nada del dispositivo. El dispositivo solo elimina un componente cuando recibe una revisión de despliegue que ya no lo lista. Cambia el stack para que el despliegue no liste componentes mientras la versión publicada permanece gestionada:
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/*');
// The published version stays managed. This deployment revision lists no // components, so the core device uninstalls com.example.Pulse. new Pulse(this, 'Pulse', { bucket: artifacts }); new GreengrassDeployment(this, 'Fleet', { targetArn: thingGroupArn.valueAsString, }); }}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', { // The published version stays managed. This deployment revision lists no // components, so the core device uninstalls com.example.Pulse. new Pulse(this, 'Pulse', { bucket: artifacts }); new GreengrassDeployment(this, 'Fleet', { targetArn: thingGroupArn.valueAsString, }); fleet.addComponent(pulse); }}Despliega la revisión:
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"Espera hasta que el componente desaparezca del dispositivo y el dispositivo permanezca saludable:
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" greengrassv2 list-installed-components \ --core-device-thing-name "$TUTORIAL_THING_NAME" \ --query 'installedComponents[].componentName' --output textaws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" greengrassv2 get-core-device \ --core-device-thing-name "$TUTORIAL_THING_NAME" --query status --output textEl primer comando no debe listar más com.example.Pulse. El segundo debe imprimir HEALTHY. El cliente de prueba MQTT deja de recibir latidos.
Tarea 2: Destruir el stack
Sección titulada «Tarea 2: Destruir el stack»AWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" pnpm nx run @greengrass-tutorial/infra:destroy -- "greengrass-tutorial-infra-sandbox/**" --forceAWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" yarn nx run @greengrass-tutorial/infra:destroy -- "greengrass-tutorial-infra-sandbox/**" --forceAWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" npx nx run @greengrass-tutorial/infra:destroy -- "greengrass-tutorial-infra-sandbox/**" --forceAWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" bunx nx run @greengrass-tutorial/infra:destroy -- "greengrass-tutorial-infra-sandbox/**" --forceEl stack se ha ido, pero tres tipos de recursos se retienen a propósito, porque las versiones de componentes son inmutables y sobreviven a cualquier despliegue individual:
- Ambas versiones de componente de
com.example.Pulse,1.0.0y1.0.1. - Las tres revisiones de despliegue al grupo de cosas.
- El bucket de artefactos, con un archivo por versión publicada.
El stack de bootstrap de CDK CDKToolkit también permanece. Es compartido por cada aplicación CDK en la cuenta y Región, así que déjalo a menos que lo hayas creado para este tutorial.
CDK deja los grupos de logs de Lambda para la resolución de versiones de componentes, el
framework de recursos personalizados y BucketDeployment después de la eliminación del stack; elimínalos
por separado si ya no necesitas sus logs.
Tarea 3: Eliminar los recursos de Greengrass retenidos
Sección titulada «Tarea 3: Eliminar los recursos de Greengrass retenidos»Lista los despliegues al grupo de cosas. Cancela el que todavía está ACTIVE, luego elimina cada uno de ellos:
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" greengrassv2 list-deployments \ --target-arn "$TUTORIAL_THING_GROUP_ARN" --history-filter ALL \ --query 'deployments[].[deploymentId,deploymentStatus]' --output text
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" greengrassv2 cancel-deployment \ --deployment-id <active-deployment-id>aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" greengrassv2 delete-deployment \ --deployment-id <deployment-id>Elimina cada versión publicada del componente:
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" greengrassv2 list-component-versions \ --arn "arn:aws:greengrass:${TUTORIAL_AWS_REGION}:${TUTORIAL_ACCOUNT_ID}:components:com.example.Pulse" \ --query 'componentVersions[].arn' --output text
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" greengrassv2 delete-component \ --arn <component-version-arn>Encuentra el bucket de artefactos a través de la etiqueta de propiedad que aplica el constructo, confirma que la lista contiene solo el bucket de este tutorial, luego elimina sus versiones de objeto y el bucket:
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" resourcegroupstaggingapi get-resources \ --tag-filters Key=greengrass-artifact-repository,Values=true \ --resource-type-filters s3:bucket \ --query 'ResourceTagMappingList[].ResourceARN' --output text
export TUTORIAL_BUCKET=<bucket-name>aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" s3api list-object-versions \ --bucket "$TUTORIAL_BUCKET" \ --query '{Objects: Versions[].{Key: Key, VersionId: VersionId}}' --output json \ > /tmp/greengrass-tutorial-versions.jsonaws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" s3api delete-objects \ --bucket "$TUTORIAL_BUCKET" --delete file:///tmp/greengrass-tutorial-versions.jsonaws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" s3api delete-bucket \ --bucket "$TUTORIAL_BUCKET"El bucket tiene versionado, por lo que delete-objects debe nombrar cada versión. Si list-object-versions también reporta DeleteMarkers, repite la eliminación con esas entradas antes de eliminar el bucket.
Tarea 4: Eliminar el dispositivo central y su identidad
Sección titulada «Tarea 4: Eliminar el dispositivo central y su identidad»La operación cleanup del script lee .greengrass-tutorial.env, verifica que pertenezca a la misma cuenta, Región y prefijo, y luego termina la instancia, desasocia y elimina el certificado con cada política adjunta a él, elimina el registro del dispositivo central, la cosa y el grupo de cosas, ambas políticas de IoT, el alias de rol, el rol de intercambio de tokens con sus adjuntos, y la política de acceso.
./setup-greengrass-tutorial.sh cleanup \ --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" --prefix "$TUTORIAL_PREFIX"Cada paso imprime deleted o absent. Un objeto que ya se ha ido se omite. Cualquier otro error detiene la ejecución y mantiene el archivo de estado, para que puedas corregir la causa y volver a ejecutar el mismo comando.
Tarea 5: Eliminar el perfil de instancia
Sección titulada «Tarea 5: Eliminar el perfil de instancia»El perfil de instancia era tuyo, así que el script lo deja solo:
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" iam remove-role-from-instance-profile \ --instance-profile-name "${TUTORIAL_PREFIX}-instance" --role-name "${TUTORIAL_PREFIX}-instance"aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" iam delete-instance-profile \ --instance-profile-name "${TUTORIAL_PREFIX}-instance"aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" iam detach-role-policy \ --role-name "${TUTORIAL_PREFIX}-instance" \ --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCoreaws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" iam delete-role \ --role-name "${TUTORIAL_PREFIX}-instance"rm -f .greengrass-tutorial.envLo que aprendiste
Sección titulada «Lo que aprendiste»- Un componente generado publica sobre IPC local por defecto. MQTT en la nube necesita
publish_to_iot_core, una autorizaciónaws.greengrass.ipc.mqttproxyen la receta, yiot:Publishen la política de IoT del dispositivo. - El generador proporciona bloques de construcción. Tu stack de CDK posee el repositorio de artefactos, el permiso de lectura y el despliegue, y
addComponentlleva la versión resuelta y el borde de ordenamiento. NEXT_PATCHasigna una versión a partir del contenido. Un cambio en el código fuente publica la siguiente versión de parche a través deldeploynormal.- Eliminar un componente es una revisión de despliegue. Eliminar infraestructura es un paso separado y posterior que deja versiones retenidas, despliegues y el bucket para que los elimines.
Para versionado y retención de artefactos, lee las secciones de versionado y almacenamiento de artefactos de la guía de componentes. La misma guía lista los límites del servicio a considerar para despliegues más grandes.