-
Notifications
You must be signed in to change notification settings - Fork 53
/
Vagrantfile
336 lines (279 loc) · 9.61 KB
/
Vagrantfile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# -*- mode: ruby -*-
# vi: set ft=ruby :
# VAGRANTFILE 2022-08-08
require 'yaml'
require 'mkmf'
require 'fileutils'
require 'socket'
if Vagrant.has_plugin? 'vagrant-hostsupdater'
puts ''
puts 'Your Vagrant environment seems to be from an older version of Seravo Vagrant box.'
puts 'To use the latest Seravo Vagrant box, take the following steps to clean up the old one:'
puts ''
puts '- Remove plugin "vagrant-hostsupdater", it\'s no longer supported:'
puts ' * `vagrant plugin uninstall vagrant-hostsupdater`'
puts ' * `vagrant plugin --local uninstall vagrant-hostsupdater`'
puts ''
puts '- Also be sure to destroy any old machines. You can view the existing machines:'
puts ' * `vagrant status`'
puts ' * `vagrant global-status`'
exit 1
end
# Prevent logs from mkmf
module MakeMakefile::Logging
@logfile = File::NULL
end
DIR = File.dirname(__FILE__)
# Create .vagrant folder
unless File.exist?(File.join(DIR,'.vagrant'))
FileUtils.mkdir_p( File.join(DIR,'.vagrant') )
end
# Create config file
config_file = File.join(DIR, 'config.yml')
sample_file = File.join(DIR, 'config-sample.yml')
unless File.exists?(config_file)
# Use sample instead
FileUtils.copy sample_file, config_file
puts '==> default: config.yml was not found. Copying defaults from sample configs..'
end
site_config = YAML.load_file(config_file)
# Create private ip address in file
private_ip_file = File.join(DIR,'.vagrant','private.ip')
private_ip = nil
if File.exists?(private_ip_file)
private_ip = File.open(private_ip_file, 'rb') { |file| file.read }
end
if private_ip.nil? || !private_ip.start_with?('192.168.56.')
private_ip = "192.168.56.#{rand(2..254)}"
File.write(private_ip_file, private_ip)
end
Vagrant.require_version '>= 2.2.0'
Vagrant.configure('2') do |config|
config.vagrant.plugins = ['vagrant-goodhosts']
# Use host-machine ssh-key so we can log into production
config.ssh.forward_agent = true
# Minimum box version requirement for this Vagrantfile revision
config.vm.box_version = ">= 20220800.0.0"
# Use precompiled box
config.vm.box = 'seravo/wordpress'
# Use the name of the box as the hostname
config.vm.hostname = site_config['name']
# Only use avahi if config has this
# development:
# avahi: true
if site_config['development']['avahi'] && has_internet? and is_osx?
# The box uses avahi-daemon to make itself available to local network
config.vm.network "public_network", bridge: [
"en0: Wi-Fi (Wireless)",
"en1: Wi-Fi (Wireless)",
"en0: Wi-Fi (AirPort)",
"en1: Wi-Fi (AirPort)",
"wlan0"
]
end
# Use random ip address for box
# This is needed for updating the /etc/hosts file
config.vm.network :private_network, ip: private_ip
config.vm.define "#{site_config['name']}-box"
domains = get_domains(site_config)
config.goodhosts.remove_on_suspend = true
config.goodhosts.aliases = domains - [config.vm.hostname]
# Disable default vagrant share
config.vm.synced_folder ".", "/vagrant", disabled: true
# Sync the folders
# We have tried using NFS but it's super slow compared to synced_folder
config.vm.synced_folder DIR, '/data/wordpress/', owner: 'vagrant', group: 'vagrant', mount_options: ['dmode=775', 'fmode=775']
# For Self-signed ssl-certificate
ssl_cert_path = File.join(DIR,'.vagrant','ssl')
unless File.exists? File.join(ssl_cert_path,'development.crt')
config.vm.provision :shell, :inline => "wp-generate-ssl"
end
# Add SSH Public Key from developer home folder into vagrant
if File.exists? File.join(Dir.home, ".ssh", "id_rsa.pub")
id_rsa_ssh_key_pub = File.read(File.join(Dir.home, ".ssh", "id_rsa.pub"))
config.vm.provision :shell, :inline => "echo '#{id_rsa_ssh_key_pub }' >> /home/vagrant/.ssh/authorized_keys && chmod 600 /home/vagrant/.ssh/authorized_keys"
end
vagrant_triggers(config, site_config)
config.vm.provider 'virtualbox' do |vb|
vb.memory = 1536
vb.cpus = 2
# Fix for slow external network connections
vb.customize ['modifyvm', :id, '--natdnshostresolver1', 'on']
vb.customize ['modifyvm', :id, '--natdnsproxy1', 'on']
vb.customize ['modifyvm', :id, '--uartmode1', 'file', File::NULL]
end
end
##
# Run native Vagrant triggers
# https://www.vagrantup.com/docs/triggers/usage
##
def vagrant_triggers(vagrant_config, site_config)
vagrant_config.trigger.after :up do |trigger|
trigger.ruby do |env, machine|
# Run all system commands inside project root
Dir.chdir(DIR)
# Always wait a couple of seconds before running triggers so that the
# machine internals have time to bootstrap
sleep 3
# Since neither communicate.sudo nor trigger.run_remote supports interactive
# mode (on other than some special Windows admin mode), call out to system
# to call back to Vagrant as a hacky way to get interactive mode, and thus
# wp-development-up can ask the various "pull x, y and z" questions.
# https://www.rubydoc.info/github/mitchellh/vagrant/Vagrant/Plugin/V2/Communicator#execute-instance_method
# https://www.vagrantup.com/docs/provisioning/shell
system "vagrant ssh -c wp-development-up"
# Don't activate git hooks, just notify them
if File.exists?( File.join(DIR,'.git', 'hooks', 'pre-commit') )
puts "If you want to use a git pre-commit hook please run 'wp-activate-git-hooks' inside the Vagrant box."
end
case RbConfig::CONFIG['host_os']
when /darwin/
# Do OS X specific things
# Trust the self-signed cert in keychain
ssl_cert_path = File.join(DIR,'.vagrant','ssl')
unless File.exists?(File.join(ssl_cert_path,'trust.lock'))
if File.exists?(File.join(ssl_cert_path,'development.crt')) and confirm "Trust the generated ssl-certificate in OS-X keychain?"
system "sudo security add-trusted-cert -d -r trustRoot -k '/Library/Keychains/System.keychain' '#{ssl_cert_path}/development.crt'"
# Write lock file so we can remove it too
touch_file File.join(ssl_cert_path,'trust.lock')
end
end
when /linux/
# Do linux specific things
end
# Run 'vagrant up' customizer script if it exists
if File.exist?(File.join(DIR, 'vagrant-up-customizer.sh'))
notice 'Found vagrant-up-customizer.sh and running it ...'
Dir.chdir(DIR)
system 'sh ./vagrant-up-customizer.sh'
end
end
end
vagrant_config.trigger.before [:halt, :destroy] do |trigger|
trigger.ruby do |env, machine|
# dump database when closing vagrant
if vagrant_running?
begin
# Note! This will run as root
run_command("wp-vagrant-dump-db", machine)
rescue => e
notice "Couldn't dump database. Skipping..."
end
end
end
end
end
##
# Helper function to run a command in a vagrant machine by providing the command
# and a Vagrant::Machine object as parameters. Heavily influenced by
# https://github.com/emyl/vagrant-triggers/blob/master/lib/vagrant-triggers/dsl.rb
##
def run_command(cmd, machine)
exit_code = 1
good_exit_codes = (0..255).to_a
begin
exit_code = machine.communicate.sudo(cmd, :elevated => true, :good_exit => good_exit_codes) do |channel, data|
machine.ui.send(:info, data)
end
rescue => e
machine.ui.send(:error, e.message)
end
if !good_exit_codes.include? exit_code
exit exit_code
end
return exit_code
end
##
# Custom helpers
##
def notice(text)
puts "==> trigger: #{text}"
end
##
# Dump database into file in vagrant
##
def dump_wordpress_database
if vagrant_running?
begin
run_remote "wp-vagrant-dump-db"
rescue => e
notice "Couldn't dump database. Skipping..."
end
end
end
##
# Create empty file
##
def touch_file(path)
File.open(path, "w") {}
end
##
# Generate /etc/hosts domain additions
##
def get_domains(config)
unless config['development'].nil?
domains = config['development']['domains'] || []
domains << config['development']['domain'] unless config['development']['domain'].nil?
else
domains = []
end
# The main domain
domains << config['name']+".local"
# Add domain names for included applications for easier usage
subdomains = %w( www webgrind adminer mailcatcher browsersync info )
subdomains.each do |domain|
domains << "#{domain}.#{config['name']}.local"
end
domains.uniq #remove duplicates
end
##
# Get boolean answer for question string
##
def confirm(question,default=true)
if default
default = "yes"
else
default = "no"
end
confirm = nil
until ["Y","N","YES","NO",""].include?(confirm)
print "#{question} (#{default}): "
confirm = STDIN.gets.chomp
if (confirm.nil? or confirm.empty?)
confirm = default
end
confirm.strip!
confirm.upcase!
end
if confirm.empty? or confirm == "Y" or confirm == "YES"
return true
end
return false
end
##
# This is quite hacky but for my understanding the only way to check if the current box state
##
def vagrant_running?
system("vagrant status --machine-readable | grep state,running --quiet")
end
##
# On OS X we can use a few more features like zeroconf (discovery of .local addresses in local network)
##
def is_osx?
RbConfig::CONFIG['host_os'].include? 'darwin'
end
##
# Modified from: https://coderrr.wordpress.com/2008/05/28/get-your-local-ip-address/
# Returns true/false
##
def has_internet?
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily
begin
UDPSocket.open { |s| s.connect '8.8.8.8', 1 }
return true
rescue Errno::ENETUNREACH
return false # Network is not reachable
end
ensure
Socket.do_not_reverse_lookup = orig
end