Search code examples
amazon-web-servicesamazon-ec2terraformterraform-provider-aws

How to mount a ebs_block_device using Terraform?


Could anyone advise on how I can auto-mount an EBS volume created using Terraform and make it available on /custom?

resource "aws_instance" "ec201" {
...
  ebs_block_device {
    device_name = "/dev/sdd"
    volume_type = "gp2"
    volume_size = 10
    delete_on_termination = true
    encrypted = true
  }
...

Is it possible to auto-mount it?

I've read these pages:

When I do a:

> lsblk
NAME        MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
...
nvme1n1     259:0    0   10G  0 disk 
nvme0n1     259:1    0  250G  0 disk 
└─nvme0n1p1 259:2    0  250G  0 part /

I have a 10GB partition that is not mounted. Would it be possible to auto-mount it using terraform?


Solution

  • As you can to see, your SO reads nvme1n1 as name of device (not /dev/sdd).

    So, you could apply an user_data with the cloud-init instructions for your EC2 instance:

    resource "aws_instance" "your-instance" {
      ..
      user_data              = file("user_data/ebs-mount.sh")
      ..
    }
    

    where user_data/ebs-mount.sh has the next content (considering that EBS disk have xfs format):

    #cloud-config
    hostname: your-instance
    
    runcmd:
    
    - sudo mkdir /custom -p
    - sudo echo '/dev/nvme1n1 /custom xfs defaults 0 0' >> /etc/fstab
    - sudo mount -a
    
    output : { all : '| tee -a /var/log/cloud-init-output.log' }