if node['ebs'] && node['ebs']['creds']
  ebs_volumes = node['ebs']['volumes']
  aws_data_bag_name = node['ebs']['creds']['databag']
  aws_data_bag_item = node['ebs']['creds']['item']

  # Defining AWS creds
  aws_creds = data_bag_item(aws_data_bag_name, aws_data_bag_item)
  aws_secret_access_key = aws_creds['aws_access_key_id']
  aws_access_key = aws_creds['aws_secret_access_key']

  if ebs_volumes
    include_recipe 'aws::default'
    package 'fio' do
      action :install
      only_if { node['basic']['init-ebs'] }
    end
    ebs_volumes.each do |mount_point, options|
      device = options['device']
      volume_id = options['volume_id']
      snapshot_id = options['snapshot_id']
      size = options['size']
      placement_availability_zone = options['placement_availability_zone']
      volume_type = options['volume_type'] || 'gp2'
      owner = options['owner'] || 'root'
      group = options['group'] || 'root'
      force_chown = options['force_chown']

      mount_options = options['mount_options']
      fstype = options['fstype']

      vol = aws_ebs_volume device do
        aws_access_key aws_secret_access_key
        aws_secret_access_key aws_access_key
        size size
        device device
        availability_zone placement_availability_zone
        volume_type volume_type
        piops piops
        action :nothing
      end

      if volume_id
        vol.volume_id(volume_id)
        vol.action(:attach)
      elsif snapshot_id
        vol.snapshot_id(snapshot_id)
        vol.action([:create, :attach])
      else
        vol.action([:create, :attach])
      end

      execute 'mkfs' do
        command "mkfs -t #{fstype} #{device}"
        only_if { fstype }
        not_if "blkid | grep #{device}"
      end

      directory mount_point do
        recursive true
        action :create
        owner owner
        group group
        mode 0755
      end

      # No fstab is needed, mtab is the leading definition
      # To add an fstab entry, :enable is needed
      mount mount_point do
        fstype fstype
        device device
        options mount_options
        pass 0
        action :mount
      end

      mount mount_point do
        fstype fstype
        device device
        options mount_options
        pass 0
        action :enable
        not_if "cat /etc/fstab | grep #{mount_point} | grep #{device}"
      end

      execute "force-#{mount_point}-ownership" do
        command "chown -R #{owner}:#{group} #{mount_point}"
        only_if { force_chown }
      end
      # Initialize each EBS volume
      execute 'Initialise-ebs' do
        command "fio --filename=#{device} --rw=randread --bs=128k --iodepth=32 --ioengine=libaio --direct=1 --name=volume-initialize"
        only_if { node['basic']['init-ebs'] }
      end
    end
  end
end
