Create and export iSCSI LUNs with arch linux

In this scenario I am using an Arch Linux image with tgt iSCSI Target. Tgt can be installed from AUR.
As long as TGT is installed and started, this tutorial can be used on other distros as well.




# systemctl status tgtd | grep Active:
   Active: active (running)

I have to create a target to map the LUN to, and the LUN. The LUN can be a sparse file or a device. 

Tgt will read /etc/tgt/targets.conf every time it starts. 

To create a target, use a unique target ID and name.
# tgtadm --lld iscsi --op new --mode target --tid 34 -T iqn.20140912.ovi

I can also bind this target to specific initiators, so that only those initiators will be able to connect to it:

# tgtadm --lld iscsi --op bind --mode target --tid <target ID> --initiator-name <initiator IP>

# tgt-admin -s | grep Target
Target 34: iqn.20140912.ovi

Now I can create a LUN and map it. In this example i will use the truncate utility, but dd also can be used with the same effect.

# truncate -s 4G lun.img

I can now check the actual size and the apparent size of my LUN.

# du --apparent-size -h lun.img && du -h lun.img 
4.0G    lun.img
0       lun.img

To map the LUN to my target I need to know the target ID (34 in my example). I will also assign the LUN a LUN ID (non zero), which is also unique. 

# tgtadm --lld iscsi --op new --mode logicalunit --tid 34 --lun 1 -b /path_to/lun.img

To save the configuration:
# tgt-admin --dump > /etc/tgt/targets.conf

I can now use an iscsi client and mount the LUN using iscsiadm, create file systems and use them as local disks.