Automating with Scripts
1. Creating Bash Setup Scripts
| Script Type | Description | Usage |
|---|---|---|
| provisioning.sh | Shell script for provisioning VMs | vagrant provision |
| bootstrap.sh | Initial setup script for guest OS | Run on first boot |
Example: Basic provisioning script
#!/bin/bash
set -e
# Update package list
apt-get update
# Install Nginx
apt-get install -y nginx
# Start and enable service
systemctl start nginx
systemctl enable nginx
Example: Multi-step bootstrap script
#!/bin/bash
# Step 1: Update system
apt-get update && apt-get upgrade -y
# Step 2: Install dependencies
apt-get install -y git curl nodejs npm
# Step 3: Setup Node.js app
cd /home/vagrant/app
npm install
# Step 4: Start application
npm start &>/dev/null && echo "App started successfully"
Note: Scripts must be executable (
chmod +x) and placed in the same directory as Vagrantfile or referenced via full path.
2. Using PowerShell Automation
| Property | Description | Example |
|---|---|---|
| powershell_script | Executes a PowerShell script on the guest machine | config.vm.provision "shell", path: "script.ps1" |
| powershell_elevated_interactive | Enables interactive elevated PowerShell execution | config.vm.provision "shell", path: "script.ps1", elevated_interactive: true |
| powershell_env | Sets environment variables for the PowerShell script | config.vm.provision "shell", path: "script.ps1", env: { "VAR" => "value" } |
Example: Setting Environment Variables
config.vm.provision "shell", path: "setup.ps1", env: { "ENV_VAR" => "value" }
Note: PowerShell scripts must be executable on the guest machine and have appropriate permissions.
3. Implementing Pre-Up Hooks
Pre-up hooks in Vagrant execute before the vagrant up command completes, allowing for custom setup or validation logic.
| Hook Type | Description | Usage |
|---|---|---|
| pre_up | Executes before the VM is created or started | Use for environment checks, logging, or preparing external resources |
Example: Pre-Up Hook Script
#!/bin/bash
echo "Running pre-up hook..."
# Example: Validate required environment variables
if [ -z "$DATABASE_URL" ]; then
echo "Error: DATABASE_URL is not set"
exit 1
fi
echo "Pre-up hook completed successfully"
Note: The pre-up hook runs in the context of the host machine and must be executable. It is not tied to any specific VM state.
4. Using Post-Up Scripts
Post-up scripts in Vagrant run after the VM is created and provisioned. These scripts are useful for performing actions that require the VM to be fully initialized.
| Script Type | Description | File Location | Execution Context |
|---|---|---|---|
| post-up | Runs after the VM is created and provisioned | vagrant-post-up.sh |
Inside the VM |
Example: Post-Up Script
#!/bin/bash
echo "Post-up script executed"
# Example: Set up environment variables or run initial setup tasks
Note: The post-up script runs inside the VM, so it has access to all the VM's environment and installed packages.
5. Automating Provisioner Updates
| Provisioner | Update Method | Notes |
|---|---|---|
| shell | vagrant provision |
Runs the provisioner script again. Does not reinstall packages. |
| ansible | vagrant provision --provision-with ansible |
Re-runs the Ansible playbook. Requires playbook to be updated. |
| chef-solo | vagrant provision --provision-with chef-solo |
Re-runs the Chef configuration. Requires updated cookbooks. |
| puppet | vagrant provision --provision-with puppet |
Re-runs the Puppet manifest. Requires updated manifests. |
6. Creating Cleanup Scripts
Cleanup scripts in Vagrant are used to automate the removal of temporary files, logs, and other artifacts that may accumulate during development or testing. These scripts help maintain a clean environment and ensure reproducibility.
| Script Type | Description | Usage Example |
|---|---|---|
| provisioning.sh | Shell script executed during provisioning to clean up temporary files. | rm -rf /tmp/* |
| cleanup.sh | Custom script for cleaning up after Vagrant operations. | find /var/log -name "*.log" -delete |
Example: Cleanup Script for Log Files
#!/bin/bash
# Remove all log files in /var/log except system logs
find /var/log -type f -name "*.log" ! -path "/var/log/syslog*" -delete
echo "Log cleanup completed."
Note: Ensure that cleanup scripts do not interfere with running services or critical system files.
Warning: Be cautious when deleting files in production environments. Always test cleanup scripts in a development environment first.
7. Implementing Health Checks
| Check Type | Description | Implementation | Notes |
|---|---|---|---|
| HTTP Health Check | Verifies if a web service is responding to HTTP requests | curl -f http://localhost:8080/health && echo "Healthy" |
Use -f to fail silently on HTTP errors |
| Database Connection | Ensures the application can connect to its database | pg_isready -h db.host -p 5432 -U user |
Works with PostgreSQL; similar tools exist for MySQL, MongoDB |
| Service Status | Checks if a service (e.g., Redis) is running | systemctl is-active redis |
Requires systemd; alternative for SysV init exists |
| File Existence | Validates that critical files or directories exist | test -f /var/log/app.log && echo "Log file exists" |
Useful for verifying log paths or config files |
Example: Health Check Script in Vagrant
#!/bin/bash
set -e
echo "Running health checks..."
# Check HTTP endpoint
curl -f http://localhost:8080/health && echo "✓ HTTP service is up" || echo "✗ HTTP service is down"
# Check database
pg_isready -h db.host -p 5432 -U app_user && echo "✓ Database is accessible" || echo "✗ Database connection failed"
# Check log file
test -f /var/log/app.log && echo "✓ Log file exists" || echo "✗ Log file missing"
echo "Health check completed."
Note: Health checks should be lightweight and not impact application performance.
Warning: Avoid complex logic in health checks that might mask real issues or cause cascading failures.
8. Using Cron for Updates
| Task | Cron Expression | Description |
|---|---|---|
| Update Vagrant Box | 0 2 * * * |
Runs daily at 2 AM to check for and update the base box |
| Refresh Plugin List | 0 3 * * 1 |
Weekly on Monday at 3 AM to refresh plugin list |
| Cleanup Old Boxes | 0 4 1 * * |
Monthly on the 1st at 4 AM to remove outdated boxes |
Example: Cron Job Setup
# Add to crontab using "crontab -e"
0 2 * * * vagrant box update
0 3 * * 1 vagrant plugin list --local | grep -v "vagrant-" | xargs -I {} vagrant plugin update {}
0 4 1 * * vagrant box list | grep -v "current" | awk '{print $1}' | xargs -I {} vagrant box remove {}
Note: Ensure the Vagrant user has appropriate permissions to execute these commands without prompting for input.
Warning: Cron jobs should be tested in a non-production environment first to avoid unintended updates or removals.
9. Automating Snapshot Management
| Command | Description | Options | Notes |
|---|---|---|---|
| vagrant snapshot save | Saves a snapshot with the given name | --force - Overwrite existing snapshot |
Creates a new snapshot of the current state |
| vagrant snapshot list | Lists all snapshots for the current VM | --machine-readable - Output in machine-readable format |
Shows snapshot names and timestamps |
| vagrant snapshot restore | Restores the VM to a previous snapshot | --no-destroy - Do not destroy VM before restore |
Reverts to the specified snapshot state |
| vagrant snapshot delete | Deletes a specific snapshot | --force - Delete without confirmation |
Removes the snapshot from disk |
Note: Snapshots are stored in the
.vagrant/ directory and can be managed manually or via scripts.
Warning: Restoring snapshots will discard any changes made since the snapshot was created.
10. Integrating with Configuration Management
| Tool | Description | Integration Method | Notes |
|---|---|---|---|
| Ansible | Automation platform for configuration management and deployment | Vagrant uses Ansible provisioner to run playbooks | Supports both local and remote execution |
| Chef | Infrastructure automation platform | Vagrant uses Chef Solo or Chef Client provisioner | Can manage nodes via Chef Infra |
| Puppet | Configuration management tool | Vagrant uses Puppet provisioner to apply manifests | Supports both local and remote Puppet environments |
| SaltStack | Configuration management and remote execution engine | Vagrant uses Salt provisioner to execute salt states | Supports orchestration and remote execution |
Example: Using Ansible with Vagrant
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/focal64"
config.vm.provision :ansible do |ansible|
ansible.playbook = "playbook.yml"
ansible.verbose = ""
end
end
Note: Configuration management tools can be used to automate setup and deployment of complex environments in Vagrant.
Warning: Ensure that your configuration management scripts are idempotent to avoid unexpected behavior during repeated provisioning.