Closed3

ECS on Fargate : ECS exec 有効化

munno000munno000

Let's dive into how task roles work with ecs-exec on AWS Fargate, focusing on the security implications and best practices:

ECS on Fargate and Task Roles

  • Fargate's Simplicity: Fargate manages the underlying infrastructure for you, so you don't need to provision and manage EC2 instances. This also means you don't have the usual access to the host operating system that you might with EC2-based ECS.
  • Task Roles: The Key to Security: Task roles act as a secure bridge between your Fargate tasks and AWS resources. They allow you to grant specific permissions for your task to perform actions within the AWS environment, but without exposing your full AWS account credentials.

Using Task Roles with ecs-exec

  1. Create an IAM Role (Task Role): Start by creating an IAM role specifically for your Fargate task. This role will define the permissions your task needs to interact with AWS resources via ecs-exec.

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Principal": {
            "Service": "ecs-tasks.amazonaws.com" 
          },
          "Action": "sts:AssumeRole" 
        },
        {
          "Effect": "Allow",
          "Action": [
            "ec2:DescribeInstances", 
            "ec2:DescribeVolumes",
            "ec2:DescribeVolumeAttachments"
          ],
          "Resource": "*"
        },
        {
          "Effect": "Allow",
          "Action": [
            "ecs:DescribeTasks",
            "ecs:DescribeContainerInstances",
            "ecs:ExecuteCommand" 
          ],
          "Resource": "*"
        }
      ]
    }
    
    • ecs-tasks.amazonaws.com: This ensures that only ECS tasks running on Fargate can assume the role.
    • ec2:Describe* Actions: These are needed to gather information about the underlying Fargate infrastructure (which is provisioned as EC2 instances) so ecs-exec can function correctly.
    • ecs:ExecuteCommand: This is crucial for running commands within your Fargate container using ecs-exec.
  2. Attach the Role to Your Task Definition: In your ECS task definition, include the ARN of the task role you just created:

    {
      "family": "my-fargate-task",
      "taskRoleArn": "arn:aws:iam::<YOUR_ACCOUNT_ID>:role/ecs-exec-fargate-role",
      "containerDefinitions": [
        {
          "name": "my-app",
          "image": "my-app-image",
          "portMappings": [
            {
              "containerPort": 8080,
              "hostPort": 80 
            }
          ],
          "logConfiguration": {
            "logDriver": "awslogs",
            "options": {
              "awslogs-group": "/ecs/my-fargate-task",
              "awslogs-region": "us-east-1" 
            }
          }
        }
      ]
    }
    
  3. Deploy Your Task: Deploy your Fargate task as usual. It will now run with the permissions defined by the task role.

  4. Use ecs-exec: Use ecs-exec to connect to your container and run commands as you would with a standard ECS task.

    aws ecs execute-command --cluster <your-cluster-name> --task <your-task-id> --command 'bash' \
      --interactive --container 'my-app' --region us-east-1 --profile <your-aws-profile> 
    

Important Security Considerations

  • Least Privilege: The golden rule! Only grant the task role the absolute minimum permissions it needs to function. Avoid broad "*"-based permissions if possible.
  • Permissions Auditing: Regularly review the permissions granted to your task role. As your applications and requirements evolve, these permissions may need adjustments.
  • Logging: Enable logging for your ecs-exec sessions and any changes made to the container.
  • Alternative Solutions: For more complex operations, explore other options like:
    • Configuration Management Tools: Ansible, Puppet, or Chef can manage configuration changes within your containers, eliminating the need for direct ecs-exec interaction.
    • Environment Variables: Store configuration values in environment variables that can be easily updated without using ecs-exec.

Best Practices

  • Use a Separate IAM Role for ecs-exec: Consider creating a dedicated task role specifically for interacting with containers via ecs-exec. This helps isolate permissions and improves security.
  • Avoid Using root User: If possible, run your containers with a non-root user to further restrict potential damage.
  • Regularly Update Task Roles: Keep your task roles up to date with the latest security best practices and avoid using outdated or overly permissive permissions.

Let me know if you have any specific questions or scenarios you'd like to discuss related to ecs-exec and task roles on Fargate. I'm here to help you secure your deployments!

munno000munno000

クラスターのサービスで ssm 有効化されていることを確認したが、ターミナルから 起動タスクに ssm 接続できない。

$ aws --profile dev ecs describe-services --region ap-northeast-1 --cluster hoge  --services hoge  | jq '.services[].enableExecuteCommand'
true

対象の task ID で enableExecuteCommand 確認し、false

aws --profile dev ecs describe-tasks --region ap-northeast-1 --cluster hoge --tasks {id} | jq '.tasks[].enableExecuteCommand'
false

deploy された task の task definition の task role のポリシーは正しくアタッチされていることを確認

Force new deploymentにチェックをつけてサービス再デプロイ

enableExecuteCommand:true 有効化されていることを確認

aws --profile dev ecs describe-tasks --region ap-northeast-1 --cluster hoge --tasks {id} | jq '.tasks[].enableExecuteCommand'
true

以下コマンドをターミナルで実行し、SSM 接続できたことを確認

aws --profile dev ecs execute-command --region ap-northeast-1 --cluster hoge --task {id} --container hoge --interactive --command "/bin/sh"

The Session Manager plugin was installed successfully. Use the AWS CLI to start a session.
Starting session with SessionId: {SessionId}
/app #

参考
https://qiita.com/ritya/items/15f4a35d77566acff063
https://qiita.com/craftect/items/7c81c89e00f39e6c95ed
https://kenzo0107.github.io/2021/07/26/2021-07-27-ecs-execute-command-agent-not-running/#google_vignette

munno000munno000

B / G deployment の場合は以下コマンドで有効化する

aws --profile dev ecs update-service
--region ap-northeast-1
--cluster hoge
--enable-execute-command
--service hoge
--desired-count 1

aws --profile dev ecs describe-services --region ap-northeast-1 --cluster hoge --services hoge | jq '.services[].enableExecuteCommand'

参考
https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UpdateService.html

For services using the blue/green (CODE_DEPLOY) deployment controller, only the desired count, deployment configuration, health check grace period, task placement constraints and strategies, enable ECS managed tags option, and propagate tags can be updated using this API. If the network configuration, platform version, task definition, or load balancer need to be updated, create a new AWS CodeDeploy deployment. For more information, see CreateDeployment in the AWS CodeDeploy API Reference.
このスクラップは2024/08/23にクローズされました