EC2で1つのinstance idを指定してインスタンスを取得する方法。
describe instances
で複数のインスタンスを取得しそこから絞り込む方法がよく解説されているが、RubyまたはPythonであれば1つのinstance idから1つのインスタンスを取得するAPIが用意されている。
Rubyの場合
require 'aws-sdk-ec2'
ec2 = Aws::EC2::Resource.new(region: 'ap-northeast-1')
instance = ec2.instance(id)
name = instance.tags.find { |t| t.key == 'Name' }&.value
puts "id=#{id} name=#{name}"
Pythonの場合
import boto3
ec2 = boto3.resource('ec2', region_name='ap-northeast-1')
instance = ec2.Instance(id)
tag = next((t for t in instance.tags if t['Key'] == 'Name'), None)
name = tag['Value'] if tag is not None else None
print(f'id={id} name={name}')
JavaScriptの場合
JavaScriptの場合は、RubyやPythonとは異なり1つだけインスタンスを取得するAPIが無い。
import {EC2Client, DescribeInstancesCommand} from "@aws-sdk/client-ec2";
const client = new EC2Client({region: "ap-northeast-1"});
const command = new DescribeInstancesCommand({InstanceIds: [id]});
const response = await client.send(command);
const instance = response["Reservations"][0]["Instances"][0];
const name = instance["Tags"].find(t => t["Key"] === "Name")?.["Value"];
console.log(`id=${id} name=${name}`);