Skip to content

Instantly share code, notes, and snippets.

@akm
Created November 9, 2018 13:27
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 akm/8377581b9873ecaa16d7ad0fcc542fdf to your computer and use it in GitHub Desktop.
Save akm/8377581b9873ecaa16d7ad0fcc542fdf to your computer and use it in GitHub Desktop.
# Usage:
# $ GCP_PROJECT=... ruby update-fwrules4appsscript.rb
#
# See https://cloud.google.com/appengine/kb/#static-ip
APP_ENGINE_IP_RANGE = (8000...9000)
def run(cmd)
puts cmd
raise "Failed to #{cmd}" unless system(cmd)
end
def nslookup(host, pattern)
r = `nslookup -q=TXT #{host} 8.8.8.8`
line = r.lines.detect{|line| line =~ /\A#{Regexp.escape(host)}/}
line.scan(pattern).flatten
end
hosts1 = nslookup("_cloud-netblocks.googleusercontent.com", /include:([^\s]+)/)
ranges = hosts1.map{|host1| nslookup(host1, /ip4:([^\s]+)/) }.flatten
priority2range = Hash[*`gcloud app firewall-rules list --project #{ENV['GCP_PROJECT']}`.scan(/^(\d+)\s+ALLOW\s+([^\s]+)/).flatten]
range2priority = priority2range.invert.select{|_,v| APP_ENGINE_IP_RANGE.include?(v.to_i) }
used_priorities = range2priority.values.map(&:to_i)
deleted_ranges = range2priority.keys - ranges
deleted_ranges.each do |range|
priority = range2priority[range]
used_priorities.remove(priority.to_i)
run("gcloud app firewall-rules delete #{priority} --project #{ENV['GCP_PROJECT']}")
end
def inc(i, used)
while used.include?(i)
i += 1
end
used.push(i)
i
end
priority = APP_ENGINE_IP_RANGE.first
added_ranges = ranges - range2priority.keys
added_ranges.each do |range|
priority = inc(priority, used_priorities)
run("gcloud app firewall-rules create #{priority} --action=ALLOW --source-range=#{range} --description='For App Engine' --project #{ENV['GCP_PROJECT']}")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment