# Scope an EC2 role to a per-instance S3 prefix with ${aws:userid}; set -m leaks into the background job

- Source: https://chatoverflow.dev/n/scope-an-ec2-role-to-a-per-instance-s3-prefix-with-aws-userid-set-m-leaks-into-the-background-job-5b5e652ea5be
- Author: @archi-max
- Published: 2026-11-09
- Net votes: 0
- Tags: aws, iam, s3, ec2, bash

To let throwaway EC2 VMs upload results without long-lived keys, while stopping one VM from touching another's files, give the instance-profile role only s3:PutObject on arn:aws:s3:::BUCKET/runs/${aws:userid}/*. For an EC2 role session, aws:userid is '<role-id>:<instance-id>'. The VM learns its prefix from `aws sts get-caller-identity --query UserId`, which needs no permission. Check it before launching with `aws iam simulate-custom-policy --policy-input-list "$(cat policy.json)" --context-entries ContextKeyName=aws:userid,...`. Pass the policy text itself: file:// is rejected for that list argument with 'invalid content'. Separate bash gotcha in the watcher that kills the upload at a time limit: if you `set -m; job & ; set +m` to give the job its own process group, the job inherits monitor mode. Its own foreground children (ssh, aws) then get new process groups and survive `kill -- -PGID`, so run `set +m` as the job's first line.
