Skip to content

Instantly share code, notes, and snippets.

@kuredev
Last active September 18, 2020 07:57
Show Gist options
  • Save kuredev/ba8bc7542457fe440aa5ab6367e7546e to your computer and use it in GitHub Desktop.
Save kuredev/ba8bc7542457fe440aa5ab6367e7546e to your computer and use it in GitHub Desktop.
セキュリティグループに自身のIPアドレスのみを許可しつつ、EC2インスタンスを起動するスクリプト
require "net/http"
require "uri"
require "aws-sdk-ec2"
# 以下を実行し、EC2インスタンスを起動します
# 1. 指定のセキュリティグループのInboundルールをすべて削除
# 2. 現在のグローバルIPアドレスの全Allowルールを指定のセキュリティグループに追加
# 3. EC2インスタンス起動
#
# 制約事項
# 既存のルールの対象ポート番号はすべて-1(すべて許可)とします
SECURITY_GROUP_NAME = "xxxxx" # TO rewrite
INSTANCE_ID = "i-xxxxxx" # To rewrite
# 自分のIPアドレスの許可ルールをセキュリティグループに追加します
def add_my_ip_rule
puts "自分のIPアドレスの許可ルールをセキュリティグループに追加します"
client.authorize_security_group_ingress(
group_name: SECURITY_GROUP_NAME,
cidr_ip: my_cidr,
ip_protocol: "-1"
)
end
# 指定のセキュリティグループのInboundルールをすべて削除します
def cleanup
# FIX ME
ip_permissions = security_group.ip_permissions[0]
return if ip_permissions.nil?
cidr_ips = ip_permissions.ip_ranges.map(&:cidr_ip)
delete_rule(cidr_ips)
end
# Aws::EC2::Client インスタンスを返します
#
# @return [Aws::EC2::Client]
def client
@client ||= Aws::EC2::Client.new
end
# 引数のIPアドレスのInboundルールを削除します
#
# @param cidr_ips [Array<String>] ["182.166.90.148/32", "160.86.236.24/32", "126.119.34.78/32"]
def delete_rule(cidr_ips)
puts "IPアドレス #{cidr_ips} のInboundルールを削除します"
cidr_ips.each do |ip|
client.revoke_security_group_ingress(
group_name: "allok",
cidr_ip: ip,
ip_protocol: "-1"
)
end
end
# @return [String] "x.x.x.x/32"
def my_cidr
uri = URI.parse("https://checkip.amazonaws.com")
response = Net::HTTP.get_response(uri)
"#{response.body}/32".gsub(/[\n]/,"")
end
# 指定のセキュリティグループを返します
def security_group
client.describe_security_groups(
filters: [
{
name: "group-name",
values: [SECURITY_GROUP_NAME]
}
]
).security_groups[0]
end
# EC2インスタンスを起動します
def start_instance
puts "EC2インスタンスを起動します"
client.start_instances(
instance_ids: [INSTANCE_ID]
)
end
cleanup
add_my_ip_rule
start_instance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment