Skip to content

Instantly share code, notes, and snippets.

@maxwellimpact
Created March 12, 2016 15:05
Show Gist options
  • Save maxwellimpact/8bd9f64338b9e98ffc3a to your computer and use it in GitHub Desktop.
Save maxwellimpact/8bd9f64338b9e98ffc3a to your computer and use it in GitHub Desktop.
Dynamically add custom ip and domains to host file.
#!sudo /usr/bin/env ruby
# -----------------------
# HOSTS FILE
#------------------------
# get the ip from a param
container_ip = ARGV[0]
if !container_ip
exit
end
# domain list seperated by spaces
domains = "example.dev test.example.dev another.example.dev"
# setup the hosts file config
start_tag = "\n#CUSTOM-DOCKER-IP-START\n"
end_tag = "\n#CUSTOM-DOCKER-IP-END\n"
hostConfig = start_tag + container_ip + " " + domains + end_tag
# replace the hosts config
file_name = "/private/etc/hosts"
contents = File.read(file_name)
if contents.match(/#{start_tag}.*#{end_tag}/m)
new_contents = contents.gsub(/#{start_tag}.*#{end_tag}/m, hostConfig)
else
new_contents = contents + hostConfig
end
# output the change for temporary
# puts new_contents
File.open(file_name, "w") {|file| file.puts new_contents }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment