Home / AWS

AWSChecklistAdvanced

EC2 IMDSv2 enforcement rollout checklist: find IMDSv1 callers, set account defaults and block regressions

A staged plan to require IMDSv2 across an AWS estate. Measure IMDSv1 use, fix callers, enforce on instances, AMIs and account defaults, then stop new IMDSv1 launches with SCPs.

Deepak Bhardwaj7 min read

Applies toAmazon EC2 instance metadata service (IMDSv1/IMDSv2), EC2 launch templates and AMIs, EC2 account-level metadata defaults, AWS Organizations SCPs, AWS Config, AWS Security Hub

Goal

Every EC2 instance requires session tokens for the instance metadata service (HttpTokens=required), new instances can't launch without it, and nothing breaks on the way there. IMDSv1 is what an SSRF bug uses to steal instance role credentials, which is why auditors and Security Hub control EC2.8 flag it.

Work through the phases in order. Skipping phase 1 is how teams break a payment batch job at 2 a.m.

Phase 1: measure

  • List instances that still allow IMDSv1, per Region:
aws ec2 describe-instances \
  --filters Name=metadata-options.http-tokens,Values=optional \
            Name=instance-state-name,Values=running,stopped \
  --query 'Reservations[].Instances[].[InstanceId,Tags[?Key==`Name`]|[0].Value,MetadataOptions.HttpPutResponseHopLimit]' \
  --output table
  • Find which of those actually make IMDSv1 calls. The AWS/EC2 metric MetadataNoToken counts IMDSv1 requests per instance. A fleet-wide top 20 for the last 14 days with Metrics Insights:
aws cloudwatch get-metric-data \
  --start-time $(date -u -d '14 days ago' +%FT%TZ) --end-time $(date -u +%FT%TZ) \
  --metric-data-queries '[{"Id":"v1","Period":86400,
    "Expression":"SELECT SUM(MetadataNoToken) FROM SCHEMA(\"AWS/EC2\", InstanceId) GROUP BY InstanceId ORDER BY SUM() DESC LIMIT 20"}]' \
  --query 'MetricDataResults[].[Label,sum(Values)]' --output table

Metrics Insights queries only cover recent data (check the current query window in the docs). For a longer history, call get-metric-statistics per instance.

  • Group the results into three buckets:
Bucket Meaning Action
optional, zero MetadataNoToken Allows v1, never uses it Enforce now (phase 3)
optional, non-zero MetadataNoToken Something on the box still calls v1 Fix the caller first (phase 2)
Hop limit 1 and runs containers v2 will fail from bridge-networked containers Raise the hop limit to 2 when you enforce
  • Get Config to track it for you. Turn on the managed rule ec2-imdsv2-check (organisation-wide if you use an aggregator), so the count of non-compliant instances becomes a number you can report every week.

Phase 2: fix the callers

  • Identify the process. The metric tells you which instance, not which program. AWS publishes an open-source IMDS packet analyzer (aws/aws-imds-packet-analyzer on GitHub) that traces IMDSv1 calls on Linux and logs the calling process and its parent. Run it on one instance from each non-zero group for a full business cycle.
  • Usual offenders:
Caller Typical fix
Old AWS SDK or CLI v1 bundled in an app Upgrade to an SDK release that supports IMDSv2 (see the SDK table in the EC2 docs)
Shell scripts using curl http://169.254.169.254/... Get a token first (example below)
Old agents (monitoring, backup, config management) Upgrade the agent; check the vendor's IMDSv2 notes
Custom images built years ago Rebuild from a current base AMI
  • Patch scripts to the token flow:
TOKEN=$(curl -sS -X PUT "http://169.254.169.254/latest/api/token" \
  -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
curl -sS -H "X-aws-ec2-metadata-token: $TOKEN" \
  http://169.254.169.254/latest/meta-data/instance-id

PowerShell equivalent:

$token = Invoke-RestMethod -Method PUT -Uri 'http://169.254.169.254/latest/api/token' `
  -Headers @{'X-aws-ec2-metadata-token-ttl-seconds' = '21600'}
Invoke-RestMethod -Uri 'http://169.254.169.254/latest/meta-data/instance-id' `
  -Headers @{'X-aws-ec2-metadata-token' = $token}
  • Re-check MetadataNoToken after each fix. Move on only when it has been zero for a full cycle: daily jobs, weekly reports, month-end runs.

Phase 3: enforce on existing instances

  • Enforce in batches, lowest-risk environment first. The change takes effect immediately, with no reboot:
aws ec2 modify-instance-metadata-options \
  --instance-id i-0123456789abcdef0 \
  --http-tokens required \
  --http-put-response-hop-limit 2 \
  --http-endpoint enabled
  • Watch MetadataNoTokenRejected on enforced instances. Once v1 is disabled, IMDSv1 calls are counted in this metric instead of MetadataNoToken. Alarm on any non-zero value during the rollout. It points straight at a caller you missed.
  • Know the rollback. If something breaks, put the instance back and go back to phase 2 for that workload:
aws ec2 modify-instance-metadata-options --instance-id i-0123456789abcdef0 --http-tokens optional

Warning

Don't set --http-endpoint disabled as part of this work. That switches off IMDS entirely: instance profile credentials, SSM Agent registration, cloud-init/EC2Launch and the CloudWatch agent all depend on it.

Phase 4: make new launches v2 by default

  • Launch templates – add a new version and make it the default, then refresh Auto Scaling groups:
aws ec2 create-launch-template-version \
  --launch-template-id lt-0123456789abcdef0 --source-version '$Latest' \
  --launch-template-data '{"MetadataOptions":{"HttpTokens":"required","HttpPutResponseHopLimit":2,"HttpEndpoint":"enabled"}}'
aws ec2 modify-launch-template --launch-template-id lt-0123456789abcdef0 --default-version <new-version>
  • AMIs – mark golden images so instances launched from them require IMDSv2:
aws ec2 modify-image-attribute --image-id ami-0123456789abcdef0 --imds-support v2.0

Caution

ImdsSupport=v2.0 on an AMI is permanent. To undo it you have to register a new AMI from the snapshots. Set it only on images whose software you have tested with IMDSv2, and use register-image --imds-support v2.0 in your image pipeline for new builds.

  • Account defaults – set the per-Region default for launches that don't specify metadata options. Repeat for every Region you use:
for r in $(aws ec2 describe-regions --query 'Regions[].RegionName' --output text); do
  aws ec2 modify-instance-metadata-defaults --region "$r" \
    --http-tokens required --http-put-response-hop-limit 2
done
aws ec2 get-instance-metadata-defaults --region eu-west-1

An explicit value in a launch request or launch template still wins over the account default. That's why phase 5 matters. Check the EC2 docs for the full precedence order between launch parameters, AMI settings, account defaults and declarative policies.

  • Infrastructure as code – set metadata_options { http_tokens = "required" } in Terraform aws_instance and aws_launch_template, and MetadataOptions.HttpTokens: required in CloudFormation. Add a policy-as-code check (Checkov, cfn-guard or similar) so pull requests can't remove it.

Phase 5: block regressions

  • SCP: deny launches that allow IMDSv1 and deny unapproved changes to metadata options. Attach to a test OU first:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "RequireImdsV2OnLaunch",
      "Effect": "Deny",
      "Action": "ec2:RunInstances",
      "Resource": "arn:aws:ec2:*:*:instance/*",
      "Condition": { "StringNotEquals": { "ec2:MetadataHttpTokens": "required" } }
    },
    {
      "Sid": "OnlyPlatformChangesImdsOptions",
      "Effect": "Deny",
      "Action": "ec2:ModifyInstanceMetadataOptions",
      "Resource": "*",
      "Condition": {
        "ArnNotLike": { "aws:PrincipalArn": "arn:aws:iam::*:role/platform-break-glass" }
      }
    }
  ]
}
  • Optional: reject credentials fetched over IMDSv1. The ec2:RoleDelivery condition key carries the IMDS version that delivered instance role credentials. Denying "NumericLessThan": {"ec2:RoleDelivery": "2.0"} across all actions makes stolen v1 credentials useless even on an instance you missed.
  • Declarative policies. If you use AWS Organizations declarative policies for EC2, you can enforce IMDS defaults at the organisation level, and they override account settings. Check the current attribute names in the Organizations docs before you write one.
  • Report. Track ec2-imdsv2-check compliance and Security Hub EC2.8 findings until both reach zero, then alert on any new non-compliant resource.

Done when

  • describe-instances with metadata-options.http-tokens=optional returns nothing in every account and Region.
  • MetadataNoTokenRejected has been zero across the fleet for a full business cycle.
  • Account defaults, launch templates, golden AMIs and IaC modules all specify required.
  • An SCP stops anyone launching an instance with IMDSv1, and you have tested that the break-glass role still works.

Tip

If containers lose their credentials after enforcement, check the hop limit first. Bridge-networked containers need HttpPutResponseHopLimit of 2 or more.