How can I prevent containers from accessing Amazon EC2 instance metadata in Amazon ECS?
I want to prevent containers from accessing Amazon Elastic Compute Cloud (Amazon EC2) instance metadata in Amazon Elastic Container Service (Amazon ECS).
"I want to prevent containers from accessing Amazon Elastic Compute Cloud (Amazon EC2) instance metadata in Amazon Elastic Container Service (Amazon ECS).Short descriptionIf you run containers in an Amazon EC2 instance, it's a best practice for security reasons to avoid allowing your applications to assume an instance role.Amazon ECS provides the following networking modes to run a task with external connectivity:The bridge mode. The task uses Docker's built-in virtual network.The awsvpc mode. The task allocates an elastic network interface, and all the containers share the same networking namespace.The host mode. The containers share the host's networking namespace.The following resolution shows you how to prevent containers from accessing the instance metadata using the bridge and awsvpc networking modes.Note: It's not possible to prevent access with the host networking mode, because the Amazon ECS agent runs on the host networking namespace and requires access to it.ResolutionFor tasks using the awsvpc networking mode, add the following parameter to the Amazon ECS configuration file /etc/ecs/ecs.config:ECS_AWSVPC_BLOCK_IMDS=trueFor tasks using the bridge networking mode, use iptables to block the network traffic from the docker0 bridge.You can specify the configuration of iptables in your custom Amazon Machine Image (AMI) or at launch in Amazon EC2 instance user data. See the following example for Amazon Linux 2 AMIs.Note: If you choose Amazon EC2 instance user data, the following configuration must be written before the Docker daemon starts. The cloud-boothook user data format executes earlier in the boot process than most services.#cloud-boothookyum install iptables-services -ycat <<EOF > /etc/sysconfig/iptables *filter:DOCKER-USER - [0:0]-A DOCKER-USER -d 169.254.169.254/32 -j DROPCOMMITEOFsystemctl enable iptables && systemctl start iptablesTo include this configuration with your existing user data, use the MIME multi part archive. See the following example:Content-Type: multipart/mixed; boundary="==BOUNDARY=="MIME-Version: 1.0--==BOUNDARY==Content-Type: text/cloud-boothook; charset="us-ascii"# Set iptables configurationyum install iptables-services -ycat <<EOF > /etc/sysconfig/iptables *filter:DOCKER-USER - [0:0]-A DOCKER-USER -d 169.254.169.254/32 -j DROPCOMMITEOFsystemctl enable iptables && systemctl start iptables--==BOUNDARY==Content-Type: text/x-shellscript; charset="us-ascii"#!/bin/bash# Set any ECS agent configuration optionsecho "ECS_CLUSTER=my-ecs-cluster" >> /etc/ecs/ecs.config--==BOUNDARY==--Follow"