LoginSignup
0
2

More than 5 years have passed since last update.

awsrmを使ってALB配下のEC2インスタンスIDを取得する

Last updated at Posted at 2017-08-03

ALBになってから ALB -> ( Listener ) -> Target group -> EC2インスタンス というつながりになりました。

「ALB配下のEC2インスタンスについてテストをしたい」というときに少し遠いです。

こういうときに awsrm を使うと直感的にEC2のインスタンスIDを取得できます。

require 'awsrm'

instance_ids = Awsrm::AlbTargetGroup.all(alb: 'my-alb-load-balancer-name').map do |target|
  target.instance_ids
end.flatten

これで、ALB配下の複数のTarget groupの下に紐付いているEC2インスタンスのIDを取得できます。

「ALBはTagで管理している」というときにも、

require 'awsrm'

alb_id = Awsrm::Alb.one(tags: {Role: 'web'}).id
instance_ids = Awsrm::AlbTargetGroup.all(alb: alb_id).map do |target|
  target.instance_ids
end.flatten

「複数のALB(VPC内のALB全て、など)」というときにも、

require 'awsrm'

instance_ids = Awsrm::Alb.all(vpc: 'my-vpc').map do |alb|
  Awsrm::AlbTargetGroup.all(alb: alb.id).map do |target|
    target.instance_ids
  end.flatten
end.flatten

と、直感的に記述できます。

インスタンスIDが取得できれば、awspecで「ALB配下のEC2インスタンスにスケジュールイベントがないこと」というテストを書くのも簡単です。

require 'awspec'
require 'awsrm'

instance_ids = Awsrm::AlbTargetGroup.all(alb: 'my-alb-load-balancer-name').map do |target|
  target.instance_ids
end.flatten

instance_ids.each do |id|
  describe ec2(id) do
    it { should be_running }
    it { should_not have_events }
  end
end

awsrmはawspecとは独立していますので、テスト以外にも様々な用途で活用できると思います。

もし、awsrmに実装して欲しいリソースがありましたら、PR/IssueやTwitterでのメンションなどよろしくお願いします。

0
2
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
2