java: Add guestfs-java(3) man page.
[libguestfs.git] / ruby / examples / create_disk.rb
1 # Example showing how to create a disk image.
2
3 require 'guestfs'
4
5 output = "disk.img"
6
7 g = Guestfs::Guestfs.new()
8
9 # Create a raw-format sparse disk image, 512 MB in size.
10 File.open(output, "w") {
11   |f| f.truncate(512 * 1024 * 1024)
12 }
13
14 # Set the trace flag so that we can see each libguestfs call.
15 g.set_trace(1)
16
17 # Set the autosync flag so that the disk will be synchronized
18 # automatically when the libguestfs handle is closed.
19 g.set_autosync(1)
20
21 # Attach the disk image to libguestfs.
22 g.add_drive_opts(output, :format => "raw")
23
24 # Run the libguestfs back-end.
25 g.launch();
26
27 # Get the list of devices.  Because we only added one drive
28 # above, we expect that this list should contain a single
29 # element.
30 devices = g.list_devices()
31 if devices.length != 1 then
32   raise "error: expected a single device from list-devices"
33 end
34
35 # Partition the disk as one single MBR partition.
36 g.part_disk(devices[0], "mbr")
37
38 # Get the list of partitions.  We expect a single element, which
39 # is the partition we have just created.
40 partitions = g.list_partitions()
41 if partitions.length != 1 then
42   raise "error: expected a single partition from list-partitions"
43 end
44
45 # Create a filesystem on the partition.
46 g.mkfs("ext4", partitions[0])
47
48 # Now mount the filesystem so that we can add files.
49 g.mount_options("", partitions[0], "/")
50
51 # Create some files and directories.
52 g.touch("/empty")
53 message = "Hello, world\n"
54 g.write("/hello", message)
55 g.mkdir("/foo")
56
57 # This one uploads the local file /etc/resolv.conf into
58 # the disk image.
59 g.upload("/etc/resolv.conf", "/foo/resolv.conf")
60
61 # Because 'autosync' was set (above) we can just close the handle
62 # and the disk contents will be synchronized.  You can also do
63 # this manually by calling g#umount_all and g#sync.
64 g.close()