Skip to content

Instantly share code, notes, and snippets.

@aoyama-val
Last active June 13, 2018 23:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aoyama-val/7bdd1a375960dec6f018a57f2b6493d4 to your computer and use it in GitHub Desktop.
Save aoyama-val/7bdd1a375960dec6f018a57f2b6493d4 to your computer and use it in GitHub Desktop.
セキュリティグループで許可するIPアドレスを入れ替えるスクリプトのサンプル
require "aws-sdk"
require "aws-sdk-core/errors"
# セキュリティグループで許可するIPアドレスを入れ替えるスクリプトのサンプル
#
# 許可すべきIPアドレスをホワイトリスト指定しているが、そのリストがときどき変わる
# というような場合に利用する。
#
# 対象のセキュリティグループに存在するルールを全て削除し、
# new_ip_addressesで指定されたIPアドレスを許可するルールを追加する。
def add_ip_range(sg_id:, ip_addresses:, ip_protocol:, from_port:, to_port:)
sg = Aws::EC2::SecurityGroup.new(sg_id, region: @region)
if @dry_run
result = "DRY_RUN"
else
begin
sg.authorize_ingress(
ip_permissions: [
{
ip_protocol: ip_protocol,
from_port: from_port,
to_port: to_port,
ip_ranges: ip_addresses.map {|ip_address|
{
cidr_ip: "#{ip_address}/32",
description: "AUTO_ADDED",
}
},
ipv_6_ranges: [ {} ],
prefix_list_ids: [ {} ],
}
]
)
result = "SUCCESS"
rescue Aws::Errors::ServiceError => e
puts e.message
result = "ERROR"
end
end
puts "[#{result}] Add #{sg_id}: #{ip_addresses.join(',')}"
end
def remove_ip_range(sg_id:, permission:, range:)
sg = Aws::EC2::SecurityGroup.new(sg_id, region: @region)
if @dry_run
result = "DRY_RUN"
else
begin
unless @dry_run
sg.revoke_ingress(
ip_permissions: [
{
ip_protocol: permission.ip_protocol,
from_port: permission.from_port,
to_port: permission.to_port,
ip_ranges: [range],
ipv_6_ranges: [ {} ],
prefix_list_ids: [ {} ],
}
]
)
end
result = "SUCCESS"
rescue Aws::Errors::ServiceError => e
puts e.message
result = "ERROR"
end
end
puts "[#{result}] Remove #{sg_id}: #{permission.ip_protocol}/#{permission.from_port}/#{range.cidr_ip}/#{range.description}"
end
@dry_run = true
@region = "ap-northeast-1"
@sg_id = "sg-0ef6d56b" # このセキュリティグループを対象とする
# 許可すべき新しいIPアドレスリスト
new_ip_addresses = %w[
1.1.1.5
1.1.1.6
]
ec2 = Aws::EC2::Client.new(region: @region)
ec2.describe_security_groups.data.security_groups.each do |sg|
next unless sg.group_id == @sg_id
sg.ip_permissions.each do |perm|
perm.ip_ranges.each do |range|
if range.description.to_s.include?("AUTO_ADDED")
remove_ip_range(sg_id: sg.group_id, permission: perm, range: range)
end
end
end
add_ip_range(sg_id: @sg_id, ip_addresses: new_ip_addresses, ip_protocol: "tcp", from_port: "22", to_port: "22")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment