0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

EC2で1つのinstance idを指定してインスタンスを取得する

Last updated at Posted at 2025-04-05

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}`);
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?