[Vagrant](box作成) macOS Sierra(10.12.3)仮想マシン作成 (Packer使用) 

![image.png](https://qiita-image-store.s3.amazonaws.com/0/75594/bd8a714c-2345-cf3d-ff01-f168459d2116.png)
macOS Sierraを Vagrant Up !

## 概要

- \[Vagrant\](box作成) macOS Sierra(10.12.3)仮想マシン作成 (Packer使用) 
- キホン、boxcutterさんのとこのテンプレート使用<br>https://github.com/boxcutter/macos
- だが、そのまま、作ったdmgではうまく動かなかった。
- コレ↓と組み合わせて、isoイメージを作れば、いいんじゃね？<br>=> [インストールISOイメージ作成：macOS Sierra (10.12)](http://qiita.com/mt08/items/0e22d636206f27e3e5f5)

## 環境
- OSX / macOS　実行環境
- Virtualbox <font color='red'>**5.0.x**</font> (5.1系はだめっぽい)

    ```shell-session
bash-3.2$ packer --version
0.12.2
bash-3.2$ VBoxManage --version
5.0.32r112930
bash-3.2$ vagrant --version
Vagrant 1.9.1
```

## 手順
1. SierraのインストーラーをAppStoreからダウンロード<br>=> "`/Applications/Install macOS Sierra.app/`"
2. iso作成スクリプトの取得

    ```bash:こぴぺ
WORK_DIR=${HOME}/work
# rm -rfv ${WORK_DIR}
mkdir -p ${WORK_DIR}
cd ${WORK_DIR}
curl -O https://raw.githubusercontent.com/kholia/OSX-KVM/master/create_install_iso.sh
curl -O https://raw.githubusercontent.com/kholia/OSX-KVM/master/pbzx
chmod +x ./create_install_iso.sh
chmod +x ./pbzx
```


3. スクリプトに手を加える

    ```bash:create_install_iso.sh
	stage_start "Replacing Packages symlink with real files"
	rm -f "$OSX_inst_img_rw_mnt/System/Installation/Packages" || exit_with_error "Deleting Packages symlink failed"
	cp -pPR "$OSX_inst_inst_dmg_mnt/Packages" "$OSX_inst_img_rw_mnt/System/Installation/" || exit_with_error "Copying Packages failed"
	stage_end_ok

	# --- mt08 : CUT from HERE ---

	stage_start "Adding automated components.."
	SCRIPT_DIR="$work_dir/macos/prepare_iso"
	SUPPORT_DIR="$SCRIPT_DIR/support"

	USER="vagrant"
	PASSWORD="vagrant"
	IMAGE_PATH="$SUPPORT_DIR/vagrant.jpg"

	# Flags
	DISABLE_REMOTE_MANAGEMENT=0
	DISABLE_SCREEN_SHARING=0
	DISABLE_SIP=0

	# payload items
	mkdir -p "$SUPPORT_DIR/pkgroot/private/var/db/dslocal/nodes/Default/users"
	mkdir -p "$SUPPORT_DIR/pkgroot/private/var/db/shadow/hash"
	BASE64_IMAGE=$(openssl base64 -in "$IMAGE_PATH")
	# Replace USER and BASE64_IMAGE in the user.plist file with the actual user and image

	eval "echo \"$(cat "$SUPPORT_DIR/user.plist")\"" > "$SUPPORT_DIR/pkgroot/private/var/db/dslocal/nodes/Default/users/$USER.plist"

	USER_GUID=$(/usr/libexec/PlistBuddy -c 'Print :generateduid:0' "$SUPPORT_DIR/user.plist")
	# Generate a shadowhash from the supplied password
	"$SUPPORT_DIR/generate_shadowhash" "$PASSWORD" > "$SUPPORT_DIR/pkgroot/private/var/db/shadow/hash/$USER_GUID"

	# postinstall script
	mkdir -p "$SUPPORT_DIR/tmp/Scripts"
	cat "$SUPPORT_DIR/pkg-postinstall" \
		| sed -e "s/__USER__PLACEHOLDER__/${USER}/" \
		| sed -e "s/__DISABLE_REMOTE_MANAGEMENT__/${DISABLE_REMOTE_MANAGEMENT}/" \
		| sed -e "s/__DISABLE_SCREEN_SHARING__/${DISABLE_SCREEN_SHARING}/" \
		| sed -e "s/__DISABLE_SIP__/${DISABLE_SIP}/" \
			  > "$SUPPORT_DIR/tmp/Scripts/postinstall"
	chmod a+x "$SUPPORT_DIR/tmp/Scripts/postinstall"

	# build it
	BUILT_COMPONENT_PKG="$SUPPORT_DIR/tmp/veewee-config-component.pkg"
	BUILT_PKG="$SUPPORT_DIR/tmp/veewee-config.pkg"
	pkgbuild --quiet \
			 --root "$SUPPORT_DIR/pkgroot" \
			 --scripts "$SUPPORT_DIR/tmp/Scripts" \
			 --identifier com.vagrantup.veewee-config \
			 --version 0.1 \
			 "$BUILT_COMPONENT_PKG"
	productbuild \
		--package "$BUILT_COMPONENT_PKG" \
		"$BUILT_PKG"
	rm -rf "$SUPPORT_DIR/pkgroot"

	MNT_BASE_SYSTEM="$OSX_inst_img_rw_mnt"
	PACKAGES_DIR="$MNT_BASE_SYSTEM/System/Installation/Packages"

	CDROM_LOCAL="$MNT_BASE_SYSTEM/private/etc/rc.cdrom.local"
	cat > $CDROM_LOCAL <<EOF
	diskutil eraseDisk jhfs+ "Macintosh HD" GPTFormat disk0
	if [ "\$?" == "1" ]; then
		diskutil eraseDisk jhfs+ "Macintosh HD" GPTFormat disk1
	fi
	EOF
	chmod a+x "$CDROM_LOCAL"
	mkdir "$PACKAGES_DIR/Extras"
	cp "$SUPPORT_DIR/minstallconfig.xml" "$PACKAGES_DIR/Extras/"
	cp "$SUPPORT_DIR/OSInstall.collection" "$PACKAGES_DIR/"
	cp "$BUILT_PKG" "$PACKAGES_DIR/"
	rm -rf "$SUPPORT_DIR/tmp"
	stage_end_ok

	# --- mt08 : CUT to HERE ---

	stage_start "Configuring image as bootable"
	OSX_inst_img_rw_CoreSrv="$OSX_inst_img_rw_mnt/System/Library/CoreServices" || exit_with_error
```
    - `https://github.com/boxcutter/macos/blob/master/prepare_iso/prepare_iso.sh`を元に、インストール時自動実行される部分をごにょごにょするとこを抽出して、`create_install_iso.sh`につっこんでる。

4. isoイメージ作成<br>`time sudo ./create_install_iso.sh -n -m 2`
5. 待つ

    ```shell-session:こんなのができる。
bash-3.2$ pwd
/Users/mt08/work
bash-3.2$ ls -l "Install_macOS_Sierra_(OS_X_10.12.3).iso" 
-rw-r--r--  1 mt08  staff  6286895104 Jan 25 10:12 Install_macOS_Sierra_(OS_X_10.12.3).iso
bash-3.2$ 
```

6. packer作成スクリプト取得して、`macos1012.json`に手を加える

    ```bash:取得
cd ${WORK_DIR}
git clone https://github.com/boxcutter/macos.git
cd ${WORK_DIR}/macos
```

    ```diff:macos1012.json__isoイメージファイル指定の変更
@@ -4,7 +4,7 @@
   "desktop": "true",
   "cpus": "1",
   "disk_size": "62536",
-  "iso_url": "dmg/OSX_InstallESD_10.12_16A323.dmg",
+  "iso_url": "../Install_macOS_Sierra_(OS_X_10.12.3).iso",
   "memory": "4096",
   "parallels_guest_os_type": "win-8",
   "vagrantfile_template": "tpl/vagrantfile-macos1012.tpl",
```

7. packer実行、<br>`time packer build -only=virtualbox-iso -var-file=macos1012.json macos.json`

8. 待つ。

    ```shell-session:こんなのができる。
bash-3.2$ pwd
/Users/mt08/work/macos/box/virtualbox
bash-3.2$ ls -l
total 14056336
-rw-r--r--  1 mt08  staff  7196839942 Jan 25 17:36 macos1012-0.1.0.box
bash-3.2$ 
```

### 使う

```
# box追加
vagrant box add macos1012-0.1.0.box --name 'macos1012'
# Vagrantfile作成
vagrant init -m macos1012
# Vagrant Up !
vagrant up
# sshログイン.
vagrant ssh
```
- Vagrantfileをいじって、VMのメモリを増やしたほうがいいかも。

    ```rb:Vagrantfile(参考:brewでちょいとインストールする)
	# Vagrantfile
	# :: mt08

	VB_NAME="MacOS 10.12.3"
	VM_MEMORY=4096
	VM_CORES=3

	Vagrant.configure("2") do |config|
		config.vm.box = "macos1012-1"
		config.vm.network "public_network", bridge: 'Intel(R) Ethernet Connection I217-LM'
		config.vm.synced_folder ".", "/vagrant", disabled: true

		config.vm.provider "virtualbox" do |vb|
			vb.gui = false
			vb.name = VB_NAME
			vb.memory = VM_MEMORY
			vb.cpus = VM_CORES
			#vb.customize ["modifyvm", :id, "--hardwareuuid", "12345678-1234-5678-0123-456789abcdef", "--macaddress1", "080027112233", "--macaddress2", "080027445566"]
			#
	 
			#vb.customize ["modifyvm", :id, "--graphicscontroller", "vboxvga"]
			vb.customize ["setextradata", :id, "VBoxInternal2/EfiGopMode", "1"]
			#0 – 640×480
			#1 – 800×600
			#2 – 1024×768
			#3 – 1280×1024
			#4 – 1440×900
			#5 – 1920x1200
		end

		config.vm.provision "shell", inline: <<-SHELL
			whoami # => root
			defaults write /Library/Preferences/com.apple.screensaver loginWindowIdleTime 0
		SHELL

		config.vm.provision "shell", privileged: false, inline: <<-SHELL
			defaults -currentHost write com.apple.screensaver idleTime 0
			#defaults -currentHost read com.apple.screensaver idleTime
			osascript -e 'tell application "Finder" to set desktop picture to POSIX file "/Library/Desktop Pictures/Solid Colors/Solid Aqua Blue.png"'
			#sqlite3 "${HOME}/Library/Application Support/Dock/desktoppicture.db" "update data set value = '/Library/Desktop Pictures/Solid Colors/Solid Aqua Blue.png'";
			#killall Dock

			#whoami # => vagrant 
			if ! type "brew" > /dev/null; then
				/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
				brew analytics off
			fi
			brew install wget
			brew install htop
			brew install byobu
			mkdir -p /Users/vagrant/Library/Python/2.7/lib/python/site-packages
			echo 'import site; site.addsitedir("/usr/local/lib/python2.7/site-packages")' >> /Users/vagrant/Library/Python/2.7/lib/python/site-packages/homebrew.pth
			brew cask install google-chrome         # Chrome
			#brew cask install xampp
		SHELL

		config.vm.provision "shell", privileged: false, run: "always", inline: <<-SHELL
			#whoami # => vagrant 
			brew analytics off
			uname -a
		SHELL
	end
```

    <!-- 
			vb.customize [ "modifyvm", :id, "--cpuidset","00000001","000106e5","00100800","0098e3fd","bfebfbff"]
			vb.customize [ "setextradata", :id, "VBoxInternal/Devices/efi/0/Config/DmiSystemProduct", "iMac11,3"]
			vb.customize [ "setextradata", :id, "VBoxInternal/Devices/efi/0/Config/DmiSystemVersion","1.0"]
			vb.customize [ "setextradata", :id, "VBoxInternal/Devices/efi/0/Config/DmiBoardProduct","Iloveapple"]
			vb.customize [ "setextradata", :id, "VBoxInternal/Devices/smc/0/Config/DeviceKey","ourhardworkbythesewordsguardedpleasedontsteal(c)AppleComputerInc"]
			vb.customize [ "setextradata", :id, "VBoxInternal/Devices/smc/0/Config/GetKeyFromRealSMC", "1"]
-->


    ```shell-session:実行例
	bash-3.2$ mkdir -p ~/macos1012/
	bash-3.2$ cd ~/macos1012/
	bash-3.2$ vagrant init -m macos1012
	A `Vagrantfile` has been placed in this directory. You are now
	ready to `vagrant up` your first virtual environment! Please read
	the comments in the Vagrantfile as well as documentation on
	`vagrantup.com` for more information on using Vagrant.
	bash-3.2$ 
	bash-3.2$ vi ./Vagrantfile    ##編集.
	bash-3.2$ 
	bash-3.2$ vagrant up
	Bringing machine 'default' up with 'virtualbox' provider...
	==> default: Importing base box 'macos1012'...
	==> default: Matching MAC address for NAT networking...
	==> default: Setting the name of the VM: MacOS 10.12.3
	==> default: Clearing any previously set network interfaces...
	==> default: Preparing network interfaces based on configuration...
		default: Adapter 1: nat
	==> default: Forwarding ports...
		default: 22 (guest) => 2222 (host) (adapter 1)
	==> default: Running 'pre-boot' VM customizations...
	==> default: Booting VM...
	==> default: Waiting for machine to boot. This may take a few minutes...
		default: SSH address: 127.0.0.1:2222
		default: SSH username: vagrant
		default: SSH auth method: private key
		default: 
		default: Vagrant insecure key detected. Vagrant will automatically replace
		default: this with a newly generated keypair for better security.
		default: 
		default: Inserting generated public key within guest...
		default: Removing insecure key from the guest if it's present...
		default: Key inserted! Disconnecting and reconnecting using new SSH key...
	==> default: Machine booted and ready!
	==> default: Checking for guest additions in VM...
		default: No guest additions were detected on the base box for this VM! Guest
		default: additions are required for forwarded ports, shared folders, host only
		default: networking, and more. If SSH fails on this machine, please install
		default: the guest additions and repackage the box to continue.
		default: 
		default: This is not an error message; everything may continue to work properly,
		default: in which case you may ignore this message.
	bash-3.2$ vagrant ssh
	Last login: Thu Jan 26 10:12:11 2017
	osx-10_12:~ vagrant$ uname -a
	Darwin osx-10_12.vagrantup.com 16.4.0 Darwin Kernel Version 16.4.0: Thu Dec 22 22:53:21 PST 2016; root:xnu-3789.41.3~3/RELEASE_X86_64 x86_64
	osx-10_12:~ vagrant$ 
```


## その他
1. macOS用のGuestAdditionsはない、っぽい
2. Virtualboxの画面解像度って、つかえるものの中からしか選べない??
3. 共有フォルダ(Guest:`/vagrant` <-> Host: Vagranfileあるフォルダ)の同期はどうするのがいい？
3. VMWareのboxも同様につくれるが、つかうには、Vagrantの有料ライセンスが必要. <br>=> https://www.vagrantup.com/vmware/
    - VMware Fusion 8 or lower (Mac OS X)
    - VMware Workstation 12 or lower (Linux and Windows) <br>それぞれ、$79。なので、試していない。
2. Win某sのVirtualboxでは... ごにょごにょして、起動確認。