﻿# Deploy Armor on AWS ECS

> Deploy encrypted configuration on ECS Fargate, retrieve its private key from Armor at startup, and verify the key-access audit event

[Armor custody](/docs/custody/armor/)

Deploy a Docker service on AWS ECS Fargate with encrypted .env.production in its image and its private key in Armor. AWS Secrets Manager holds an Armor automation token. ECS injects that token when a task starts, and Dotenvx uses it to retrieve the key before starting the app.

This guide uses **Armored Keys**. It builds a small HTTP service so you can verify startup without exposing configuration values.

## What runs where

| Component | What it holds and does |
| --- | --- |
| Git and Amazon ECR | App code, encrypted .env.production, and its public key. |
| CI runner | AWS deployment permissions. Builds and publishes the image without retrieving the production private key or Armor token. |
| Armor | Production private key, access settings, and key-access audit records. |
| AWS Secrets Manager | The production team's Armor automation token. |
| ECS task execution role | Lets ECS pull the image, write container logs, and inject the token from Secrets Manager. |
| Running container | Uses the injected token to retrieve the Armored key, decrypt configuration, and start the app. |

The ECS execution role authorizes AWS operations. Armor authenticates the workload using its **automation token**. Create a dedicated Armor production team and treat its token as a credential for that team. The token identifies a credential in audit logs; it does not attest a particular ECS task or image.

Automation tokens require [Business](/pricing/). The operator checking audit events also needs permission to read the team's logs.

## Prerequisites

Use an AWS staging account or environment for the walkthrough. You need:

- AWS CLI v2, Docker with Buildx, and jq.
- AWS credentials configured for your account and deployment region. In CI, use an AWS identity authorized to push to ECR, register task definitions, update the ECS service, and pass its execution role.
- A VPC with two public subnets, internet-gateway routes, and a security group allowing outbound HTTPS and inbound TCP port 3000 from your workstation's IP address. The example assigns each task a public IP for a direct startup check.
- An Armor account with a production team and an automation token.

For a production service, use your load balancer and private-subnet network design. Tasks need a route to Armor over HTTPS. ECR, Secrets Manager, and CloudWatch Logs also need to be reachable through your AWS network configuration.

AWS describes these requirements in its [Fargate networking guide](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/fargate-task-networking.html) and [Secrets Manager integration guide](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/secrets-envvar-secrets-manager.html).

## Prepare the production key

On your workstation, install Dotenvx, add Armor, and sign in:

```console
$ curl -sfS https://dotenvx.sh | sh
$ dotenvx install --add armor
$ dotenvx armor login
```

Create .env.production with this demonstration startup value:

```dotenv
DEPLOYMENT_CHECK="armor-production-ready"
```

Encrypt it, choosing **Classic (.env.keys)** when prompted, then move its private key into your production team. Replace YOUR_PRODUCTION_TEAM with the team's slug:

```console
$ dotenvx encrypt -f .env.production
$ dotenvx armor up -f .env.production --team YOUR_PRODUCTION_TEAM
```

Armor up removes the local key after a successful upload. Earlier copies of that key remain usable. Keep remaining .env.keys files out of Git and the image.

If Guard is enabled for this key, a new task may wait for human approval. Choose an access policy suitable for your service's unattended starts and include approval time in the service's health-check and deployment timing.

## Build an image that decrypts at startup

Create server.cjs:

```javascript
const http = require('node:http')

if (process.env.DEPLOYMENT_CHECK !== 'armor-production-ready') {
  throw new Error('Production configuration was not loaded')
}

http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' })
  res.end('ok\n')
}).listen(3000, '0.0.0.0', () => {
  console.log('Production configuration loaded; listening on port 3000')
})
```

Create start.sh:

```shell
#!/bin/sh
set -eu
: "${DOTENVX_TOKEN:?ECS must inject the Armor automation token}"
export DOTENVX_CONFIG=/tmp/dotenvx
mkdir -p "$DOTENVX_CONFIG"
exec dotenvx run --strict -f .env.production \
  --token "$DOTENVX_TOKEN" -- node server.cjs
```

The app starts only after configuration loads successfully. The token expands into a command argument, so keep shell tracing disabled and restrict access to the container's process information.

Create Dockerfile:

```dockerfile
FROM node:22-bookworm-slim

RUN apt-get update \
  && apt-get install -y --no-install-recommends curl ca-certificates \
  && rm -rf /var/lib/apt/lists/* \
  && curl -sfS https://dotenvx.sh | sh \
  && dotenvx install --add armor

WORKDIR /app
COPY server.cjs start.sh .env.production ./
RUN chmod 755 /app/start.sh
EXPOSE 3000
ENTRYPOINT ["/app/start.sh"]
```

For reproducible production images, pin your base image digest and Dotenvx version or use your approved installer artifact.

Add the following to .gitignore and .dockerignore:

```gitignore
.env.keys*
**/.env.keys*
```

Also exclude .git and node_modules from .dockerignore. If your existing rules exclude .env.production, add !.env.production after them. Keep plaintext configuration, tokens, and developer login files outside the build context.

```console
$ git add -f .env.production
$ git add server.cjs start.sh Dockerfile .gitignore .dockerignore
$ git commit -m "add encrypted ECS configuration"
```

## Configure AWS credentials for the task

In **AWS Secrets Manager**, create an **Other type of secret** in the deployment region. Use **Plaintext** to store only the Armor automation token, without a JSON wrapper or trailing newline. Name it armor/production/token and select the default Secrets Manager encryption key for this walkthrough. Record its full ARN, including its generated suffix.

Create an IAM role named armorEcsExecutionRole with this trust policy in ecs-trust.json:

```json
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Service": "ecs-tasks.amazonaws.com" },
    "Action": "sts:AssumeRole"
  }]
}
```

```console
$ aws iam create-role --role-name armorEcsExecutionRole --assume-role-policy-document file://ecs-trust.json
$ aws iam attach-role-policy --role-name armorEcsExecutionRole --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
```

Create ecs-secret-policy.json. Replace SECRET_ARN with the full ARN you recorded:

```json
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": "secretsmanager:GetSecretValue",
    "Resource": "SECRET_ARN"
  }]
}
```

```console
$ aws iam put-role-policy --role-name armorEcsExecutionRole --policy-name ReadArmorToken --policy-document file://ecs-secret-policy.json
```

If you use a customer-managed KMS key, add the required kms:Decrypt permission for that key and allow the execution role in its key policy. See AWS's [task execution role permissions](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_execution_IAM_role.html).

The sample app does not call AWS APIs, so it needs no application task role. ECS uses the execution role to inject the secret. Keep your CI deployment identity separate from the execution role and give it iam:PassRole permission for that role.

## Publish the image

Replace the example region and account ID. Keep the same values for subsequent commands:

```shell
export AWS_REGION=us-east-1
export AWS_ACCOUNT_ID=123456789012
export ECS_IMAGE_TAG=armor-demo-1
export ECS_IMAGE_REPOSITORY="$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/armor-demo"
```

Bootstrap the repository, cluster, and log group once:

```console
$ aws ecr create-repository --repository-name armor-demo --image-tag-mutability IMMUTABLE
$ aws ecs create-cluster --cluster-name armor-demo
$ aws logs create-log-group --log-group-name /ecs/armor-demo
$ aws logs put-retention-policy --log-group-name /ecs/armor-demo --retention-in-days 30
```

From the checked-out project, publish a Linux x86_64 image. These are also the image-publishing commands for your CI runner:

```console
$ aws ecr get-login-password | docker login --username AWS --password-stdin "$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com"
$ docker buildx build --platform linux/amd64 --provenance=false --tag "$ECS_IMAGE_REPOSITORY:$ECS_IMAGE_TAG" --push .
```

Use a new tag for each build. The repository rejects overwriting an existing tag. CI needs AWS deployment credentials; it does not need the Armor automation token or the production private key.

## Register and deploy the task

Create task-definition.json. Replace ACCOUNT_ID, REGION, IMAGE_TAG, and SECRET_ARN with your deployment values. The image tag is the immutable tag pushed above.

```json
{
  "family": "armor-demo",
  "networkMode": "awsvpc",
  "requiresCompatibilities": ["FARGATE"],
  "cpu": "256",
  "memory": "512",
  "runtimePlatform": {
    "cpuArchitecture": "X86_64",
    "operatingSystemFamily": "LINUX"
  },
  "executionRoleArn": "arn:aws:iam::ACCOUNT_ID:role/armorEcsExecutionRole",
  "containerDefinitions": [{
    "name": "app",
    "image": "ACCOUNT_ID.dkr.ecr.REGION.amazonaws.com/armor-demo:IMAGE_TAG",
    "essential": true,
    "portMappings": [{ "containerPort": 3000, "protocol": "tcp" }],
    "secrets": [{ "name": "DOTENVX_TOKEN", "valueFrom": "SECRET_ARN" }],
    "healthCheck": {
      "command": ["CMD-SHELL", "node -e \"fetch('http://127.0.0.1:3000').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))\""],
      "interval": 30,
      "timeout": 5,
      "retries": 3,
      "startPeriod": 120
    },
    "logConfiguration": {
      "logDriver": "awslogs",
      "options": {
        "awslogs-group": "/ecs/armor-demo",
        "awslogs-region": "REGION",
        "awslogs-stream-prefix": "ecs"
      }
    }
  }]
}
```

Leave DEPLOYMENT_CHECK and DOTENV_PRIVATE_KEY_PRODUCTION out of the task definition and AWS secret store for this path. The startup assertion should succeed using the encrypted file and its Armored key.

Register the task definition and capture its revision ARN:

```shell
export ECS_TASK_DEFINITION=$(aws ecs register-task-definition \
  --cli-input-json file://task-definition.json \
  --query 'taskDefinition.taskDefinitionArn' --output text)
```

Replace the subnet and security-group IDs with your VPC resources:

```shell
export ECS_SUBNET_A=subnet_REPLACE_A
export ECS_SUBNET_B=subnet_REPLACE_B
export ECS_SECURITY_GROUP=sg_REPLACE
```

Create a one-task Fargate service. The deployment circuit breaker rolls back failed updates when a previously successful deployment exists:

```console
$ aws ecs create-service --cluster armor-demo --service-name armor-demo --task-definition "$ECS_TASK_DEFINITION" --desired-count 1 --launch-type FARGATE --platform-version 1.4.0 --deployment-configuration 'minimumHealthyPercent=100,maximumPercent=200,deploymentCircuitBreaker={enable=true,rollback=true}' --network-configuration "awsvpcConfiguration={subnets=[$ECS_SUBNET_A,$ECS_SUBNET_B],securityGroups=[$ECS_SECURITY_GROUP],assignPublicIp=ENABLED}"
$ aws ecs wait services-stable --cluster armor-demo --services armor-demo
```

{: copy="aws ecs create-service --cluster armor-demo --service-name armor-demo --task-definition "$ECS_TASK_DEFINITION" --desired-count 1 --launch-type FARGATE --platform-version 1.4.0 --deployment-configuration 'minimumHealthyPercent=100,maximumPercent=200,deploymentCircuitBreaker={enable=true,rollback=true}' --network-configuration "awsvpcConfiguration={subnets=[$ECS_SUBNET_A,$ECS_SUBNET_B],securityGroups=[$ECS_SECURITY_GROUP],assignPublicIp=ENABLED}" aws ecs wait services-stable --cluster armor-demo --services armor-demo"}

For later releases, push a new image tag, update task-definition.json, register a new revision, and deploy it:

```console
$ aws ecs update-service --cluster armor-demo --service armor-demo --task-definition "$ECS_TASK_DEFINITION"
$ aws ecs wait services-stable --cluster armor-demo --services armor-demo
```

## Verify startup and the audit event

Inspect the service's recent events and the container log:

```console
$ aws ecs describe-services --cluster armor-demo --services armor-demo --query 'services[0].{running:runningCount,desired:desiredCount,deployments:deployments,events:events[:5]}'
$ aws logs tail /ecs/armor-demo --since 10m
```

{: copy="aws ecs describe-services --cluster armor-demo --services armor-demo --query 'services[0].{running:runningCount,desired:desiredCount,deployments:deployments,events:events[:5]}' aws logs tail /ecs/armor-demo --since 10m"}

Confirm the active deployment uses the revision you registered and that its rollout completed. The app should print Production configuration loaded; listening on port 3000. The startup assertion verifies the sample value without logging it.

Get the running task's network interface and public IP:

```shell
ECS_TASK_ARN=$(aws ecs list-tasks --cluster armor-demo --service-name armor-demo --desired-status RUNNING --query 'taskArns[0]' --output text)
ECS_ENI=$(aws ecs describe-tasks --cluster armor-demo --tasks "$ECS_TASK_ARN" --query 'tasks[0].attachments[0].details[?name==`networkInterfaceId`].value | [0]' --output text)
ECS_PUBLIC_IP=$(aws ec2 describe-network-interfaces --network-interface-ids "$ECS_ENI" --query 'NetworkInterfaces[0].Association.PublicIp' --output text)
curl --fail "http://$ECS_PUBLIC_IP:3000"
```

From a workstation permitted by the task's security group, the response should be ok. If startup fails, inspect stopped tasks and service events for image-pull, secret-injection, or application errors.

Record the deployment time in UTC and the production public key in .env.production. On your workstation, set DOTENVX_ARMOR_TOKEN to an operator token with log-read access. Query the team's key-access events, replacing the team slug and public key:

```console
$ curl --fail --get 'https://armor.dotenvx.com/api/logs' --header "Authorization: Bearer $DOTENVX_ARMOR_TOKEN" --data-urlencode 'team=YOUR_PRODUCTION_TEAM' --data-urlencode 'events=keypair/access' --data-urlencode 'keypair=YOUR_PRODUCTION_PUBLIC_KEY' --data-urlencode 'per=100'
```

Find an entry with name keypair/access, outcome success, metadata.endpoint /api/armor/keyring, the matching metadata.public_key, and the automation token's metadata.access_token_short prefix. Its occurred_at or created_at should match the deployment window. Audit writes are asynchronous; retry if the event has not appeared yet.

An automation token has no human username. Match the key, credential prefix, and time. If multiple tasks share the token, those fields alone do not identify which task accessed the key. See the [Armor API](/docs/api/#logs) for query options.

## Restarts, outages, and token rotation

Every new Dotenvx process in this setup retrieves its key from Armor. With no alternative key source, an unreachable Armor service or rejected token causes --strict to exit before Node starts. ECS then treats the task as failed and attempts to replace it. Guard approval delays must fit your startup and health-check timing.

An existing process keeps its loaded environment. Revoking the token does not erase values already loaded into a running app. A restart, deployment, or scale-out requires a new authorized retrieval.

Test a blocked connection to Armor in staging: confirm that an already-running task continues serving and a replacement cannot become healthy. Restore connectivity and verify a fresh startup and key-access event. A request that never reaches Armor cannot produce an Armor-side event.

ECS injects Secrets Manager values when the container starts. Updating the stored token does not change running containers. When rotating, store the new token, force a new deployment, confirm startup and audit events, then revoke the old token. See AWS's [secret injection behavior](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/secrets-envvar-secrets-manager.html).

```console
$ aws ecs update-service --cluster armor-demo --service armor-demo --force-new-deployment
```

That's it! Your ECS service starts from encrypted configuration, with Armor controlling access to its private key and recording the key-access request.

## Deployment verification

This guide adapts the documented Armored-key workflow to an ECS Fargate task using AWS secret injection, an execution role, and CloudWatch Logs. Live AWS deployment and the current installer/add-on behavior inside this image remain unverified. AWS documentation requests were blocked from this authoring environment.

Before adopting the setup, run the walkthrough in staging and confirm successful secret injection, startup, audit delivery, Guard timing, blocked-Armor restarts, and token rotation. Check the linked AWS references for your region, network design, and IAM policies.
