Implantar, observar e atualizar
Tarefa 1: Compor a pilha
Seção intitulada “Tarefa 1: Compor a pilha”O gerador forneceu blocos de construção, não uma implantação. Sua pilha decide onde os artefatos residem, qual função pode lê-los e qual frota recebe o componente. Substitua 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); }}O que cada parte faz:
GreengrassArtifactBucketcria o repositório de artefatos retido, versionado e somente TLS.grantReadToconcede à função de troca de tokens3:GetObjectemcom.example.Pulse/*, que cobre todas as chaves de artefato que o resolvedor escreve para este componente.PulseestendeGreengrassComponentVersion. Ele lê a receita epulse.zipquepulse-artifactconstruiu, faz upload do arquivo sob uma chave com hash de conteúdo e publica a versão do componente. Sua propriedadebucketrecebe o próprio construtoGreengrassArtifactBucket.GreengrassDeploymentcomtargetArnimplanta no grupo de coisas que o script de configuração criou.addComponent(pulse)coloca a versão resolvida no mapa de componentes da implantação e adiciona uma dependência CloudFormation no recurso de versão do componente, para que o trabalho IoT não possa alcançar o dispositivo antes que a versão exista.- Os dois valores
CfnParametervêm de.greengrass-tutorial.env. Passá-los como parâmetros mantém a pilha livre de literais específicos da conta e permite que o conjunto e2e sintetize o mesmo arquivo.
Tarefa 2: Inicializar e implantar
Seção intitulada “Tarefa 2: Inicializar e implantar”Carregue os valores gravados, sincronize as referências do projeto e os manifestos de dependência, instale as dependências atualizadas do workspace e inicialize o CDK na conta e Região se você ainda não o fez:
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:bootstrapImplante a pilha. packages/infra/src/main.ts coloca a pilha no estágio greengrass-tutorial-infra-sandbox, e o destino deploy executa cdk deploy sem um estágio próprio, então o comando nomeia esse estágio e passa os ARNs da função e do grupo de coisas como parâmetros 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, e o projeto de construtos compartilhados depende do assemble do projeto de telemetria, que executa pulse-artifact. Cada implantação, portanto, publica o artefato que corresponde ao seu código-fonte atual. O destino executa cdk deploy sem modo expresso, então aceita uma revisão de implantação posterior que substitui o recurso de implantação. Leia revisões de implantação antes de usar deploy-sandbox para Greengrass.
Na primeira implantação, o resolvedor de versão não encontra nenhuma versão publicada de com.example.Pulse e publica 1.0.0. A implantação então alcança o grupo de coisas, e o dispositivo principal baixa o artefato com a função de troca de token e inicia o componente. Aguarde de um a dois minutos após a conclusão da pilha.
Tarefa 3: Observar o heartbeat
Seção intitulada “Tarefa 3: Observar o heartbeat”Abra o console AWS IoT em $TUTORIAL_AWS_REGION, escolha MQTT test client e assine o tópico:
tutorial/greengrass/heartbeatA cada 30 segundos uma mensagem chega:
{"sequence": 3, "greeting": "hello from pulse"}A AWS CLI não pode assinar tópicos MQTT. Se você preferir seu próprio cliente MQTT, conecte-o ao endpoint de dados da conta com seu próprio certificado e política, que este tutorial não cria:
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" iot describe-endpoint \ --endpoint-type iot:Data-ATS --query endpointAddress --output textTarefa 4: Verificar o dispositivo
Seção intitulada “Tarefa 4: Verificar o dispositivo”Uma implantação bem-sucedida prova que o dispositivo aplicou o documento de implantação. Não prova que o componente está em execução. Verifique o estado do ciclo de vida do 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 textEspere 1.0.0 e RUNNING. Em seguida, leia o próprio log do componente na instância com o padrão Systems Manager do 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 textO log mostra a conexão IPC e uma linha por 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 a implantação relatar SUCCEEDED mas o componente estiver BROKEN, ou get-core-device relatar UNHEALTHY, siga as etapas de solução de problemas do componente.
Tarefa 5: Atualizar o componente
Seção intitulada “Tarefa 5: Atualizar o componente”Altere a saudação em 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()Implante novamente com o mesmo 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 vê o código-fonte alterado e reconstrói pulse-artifact. O hash de conteúdo do arquivo muda, então o resolvedor aloca 1.0.1, o artefato é carregado sob uma nova chave, uma nova versão do componente é publicada e uma nova revisão de implantação aponta o grupo de coisas para ela. A receita ainda diz NEXT_PATCH; nada no workspace registra o número.
Verifique tanto a versão instalada quanto o 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 textEspere 1.0.1 e RUNNING. No cliente de teste MQTT, a saudação muda para hello from the updated pulse, e a sequência reinicia de 0 porque o processo do componente foi reiniciado.
Continue com Remover e limpar.