CloudWatch EC2 - 查找 EC2 服务器的实例 ID 和实例名称

CloudWatch EC2 - Finding EC2 Server's Instance ID and Instance Name

我有一个要报告的自定义 CloudWatch 指标。我的电话看起来像:

$dimensions = array(
    array(
        "Name" => "InstanceId",
        "Value" => "need instance id here"
    ),
    array(
        "Name" => "InstanceName",
        "Value" => "need instance name here"
    )
);

// API call to save cpu usage
$client->putMetricData(array(
    "Namespace" => "mynamespace",
    "MetricData" => array(
        array(
            "MetricName" => "CPU_Usage",
            "Value" => $cpu_usage,
            "Unit" => "Percent",
            "Timestamp" => time(),
            "Dimensions" => $dimensions
        )
    )
));

我想用对应于服务器 运行 脚本的值填充 InstanceId 和 InstanceName。

有没有办法通过 CloudWatch 做到这一点 API?

我使用内部 IP 调用来获取实例 ID,并使用该 ID 调用 EC2 的 describeTags 方法来获取实例名称。

$instance_id = $curl->get("http://169.254.169.254/latest/meta-data/instance-id");
$tags_result = $ec2_client->describeTags(array(
    "Filters" => array(
        array(
            "Name" => "resource-id",
            "Values" => array(
                $instance_id
            )
        ),
        array(
            "Name" => "key",
            "Values" => array(
                "Name"
            )
        )
    )
));
$instance_name = $tags_result["Tags"][0]["Value"];