You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Amazon Linux AMI实例启动时自动启动CloudWatch Agent

实现CloudWatch Agent开机自启(Amazon Linux AMI 无systemctl环境)

Amazon Linux AMI基于SysV init系统(而非systemd),可以通过以下两种方式配置CloudWatch Agent开机自动运行:

方法一:创建标准SysV init脚本(推荐)

这种方式可以让你通过service命令管理Agent,和系统其他服务保持一致:

  1. 创建init.d启动脚本
    在/etc/init.d/目录下新建脚本文件:
sudo vi /etc/init.d/amazon-cloudwatch-agent

粘贴以下内容:

#!/bin/bash
# chkconfig: 2345 99 01
# description: Amazon CloudWatch Agent Service

AGENT_CTL="/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl"
CONFIG_PATH="file:/opt/aws/amazon-cloudwatch-agent/bin/config.json"

start() {
    echo "Starting Amazon CloudWatch Agent..."
    $AGENT_CTL -a fetch-config -m ec2 -c $CONFIG_PATH -s
}

stop() {
    echo "Stopping Amazon CloudWatch Agent..."
    $AGENT_CTL -m ec2 -a stop
}

status() {
    $AGENT_CTL -m ec2 -a status
}

case "$1" in
    start) start ;;
    stop) stop ;;
    status) status ;;
    restart) stop && sleep 2 && start ;;
    *) echo "Usage: $0 {start|stop|status|restart}" && exit 1 ;;
esac

exit 0
  1. 赋予脚本执行权限
sudo chmod +x /etc/init.d/amazon-cloudwatch-agent
  1. 注册并设置开机自启
sudo chkconfig --add amazon-cloudwatch-agent
sudo chkconfig amazon-cloudwatch-agent on
  1. 验证功能
    现在可以用service命令管理Agent了:
sudo service amazon-cloudwatch-agent start
sudo service amazon-cloudwatch-agent status

重启实例后,再次运行status命令确认Agent已自动启动。


方法二:使用rc.local(快速简易)

如果不需要标准服务管理功能,可直接将启动命令添加到开机自启文件:

  1. 编辑rc.local文件
sudo vi /etc/rc.local

在exit 0前添加启动命令:

/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c file:/opt/aws/amazon-cloudwatch-agent/bin/config.json -s
  1. 确保rc.local可执行
sudo chmod +x /etc/rc.local

重启实例后,Agent会随系统自动启动。

内容的提问来源于stack exchange,提问作者Llyod

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 21:01:40