

# 在启动 Amazon ECS Linux 容器实例时运行脚本
<a name="start_task_at_launch"></a>

您可能需要在每个容器实例上运行一个特定容器以处理操作或安全问题，例如监控、安全性、指标、服务发现或日志记录。

为此，可以将容器实例配置为在启动时或在某些 init 系统（如 Upstart 或 **systemd**）中使用用户数据脚本调用 **docker run** 命令。虽然此方法可行，但它有一些缺点，因为 Amazon ECS 不了解容器并且无法监控 CPU、内存、端口或已使用的任何其他资源。要确保 Amazon ECS 可正确了解所有任务资源，请为要在容器实例上运行的容器创建任务定义。然后，使用 Amazon ECS 在启动时利用 Amazon EC2 用户数据放置任务。

以下过程中的 Amazon EC2 用户数据脚本使用 Amazon ECS 自检 API 来确定容器实例。然后，它将使用 Amazon CLI 和 **start-task** 命令在启动期间对自身运行指定任务。

**在容器实例启动时启动任务**

1. 修改您的 `ecsInstanceRole` IAM 角色以便为 `StartTask` API 操作添加权限。有关更多信息，请参阅《Amazon Identity and Access Management 用户指南》**中的[更新角色的权限](https://docs.amazonaws.cn//IAM/latest/UserGuide/id_roles_update-role-permissions.html)。

1. 使用经 Amazon ECS 优化的 Amazon Linux 2 AMI，启动一个或多个容器实例。启动新的容器实例，并在 EC2 用户数据中使用以下示例脚本。将 *your\$1cluster\$1name* 替换为要注册到的容器实例的集群，并将 *my\$1task\$1def* 替换为要在启动时在实例上运行的任务定义。

   有关更多信息，请参阅 [启动 Amazon ECS Linux 容器实例](launch_container_instance.md)。
**注意**  
以下 MIME 分段内容使用 Shell 脚本设置配置值和安装程序包。它还将使用 Upstart 作业在 **ecs** 服务已在运行且自检 API 可用后启动任务。

   ```
   Content-Type: multipart/mixed; boundary="==BOUNDARY=="
   MIME-Version: 1.0
   
   --==BOUNDARY==
   Content-Type: text/x-shellscript; charset="us-ascii"
   
   #!/bin/bash
   # Specify the cluster that the container instance should register into
   cluster=your_cluster_name
   
   # Write the cluster configuration variable to the ecs.config file
   # (add any other configuration variables here also)
   echo ECS_CLUSTER=$cluster >> /etc/ecs/ecs.config
   
   START_TASK_SCRIPT_FILE="/etc/ecs/ecs-start-task.sh"
   cat <<- 'EOF' > ${START_TASK_SCRIPT_FILE}
   	exec 2>>/var/log/ecs/ecs-start-task.log
   	set -x
   	
   	# Install prerequisite tools
   	yum install -y jq aws-cli
   	
   	# Wait for the ECS service to be responsive
   	until curl -s http://localhost:51678/v1/metadata
   	do
   		sleep 1
   	done
   
   	# Grab the container instance ARN and Amazon Region from instance metadata
   	instance_arn=$(curl -s http://localhost:51678/v1/metadata | jq -r '. | .ContainerInstanceArn' | awk -F/ '{print $NF}' )
   	cluster=$(curl -s http://localhost:51678/v1/metadata | jq -r '. | .Cluster' | awk -F/ '{print $NF}' )
   	region=$(curl -s http://localhost:51678/v1/metadata | jq -r '. | .ContainerInstanceArn' | awk -F: '{print $4}')
   
   	# Specify the task definition to run at launch
   	task_definition=my_task_def
   
   	# Run the Amazon CLI start-task command to start your task on this container instance
   	aws ecs start-task --cluster $cluster --task-definition $task_definition --container-instances $instance_arn --started-by $instance_arn --region $region
   EOF
   
   # Write systemd unit file
   UNIT="ecs-start-task.service"
   cat <<- EOF > /etc/systemd/system/${UNIT}
         [Unit]
         Description=ECS Start Task
         Requires=ecs.service
         After=ecs.service
    
         [Service]
         Restart=on-failure
         RestartSec=30
         ExecStart=/usr/bin/bash ${START_TASK_SCRIPT_FILE}
   
         [Install]
         WantedBy=default.target
   EOF
   
   # Enable our ecs.service dependent service with `--no-block` to prevent systemd deadlock
   # See https://github.com/aws/amazon-ecs-agent/issues/1707
   systemctl enable --now --no-block "${UNIT}"
   --==BOUNDARY==--
   ```

1. 验证您的容器实例是否启动到正确的集群中以及您的任务是否已启动。

   1. 在 [https://console.aws.amazon.com/ecs/v2](https://console.amazonaws.cn/ecs/v2) 打开控制台。

   1. 在导航栏中，选择您的集群所在的区域。

   1. 在导航窗格中，选择 **Clusters** 并选择托管您的容器实例的集群。

   1. 在**集群**页面上，选择**任务**，然后选择您的任务。

      您启动的每个容器实例都应运行您的任务。

      如果没有看到任务，可以使用 SSH 登录容器实例，在 `/var/log/ecs/ecs-start-task.log` 文件中查看调试信息。