0

I am using aws ec2 with ubuntu machine I would like to create a volume, and every time I create a machine I need it to be attached and mounted to the machine.

Note, this is a single existing volume, and will be mounted to one machine at a time only. I need to start a spot instance and attach and mount that volume every time is an automated way

The way I found so far, I creating the machine using aws-cli, then attaching the volume using the cli, I can't find a way to mount the volume to the machine (I don't want to use ssh to the machine) I thought about using aws run command, to try and do so, but can't find mount command there. Is there any programatic way to do so, via the cli of some other tool?

thebeancounter
  • 4,261
  • 8
  • 61
  • 109

1 Answers1

0

You can write a CloudFormation script for this. It's an Infrastructure-as-a-code tool which will enable you to create most of the AWS resource in a simple yml file.

For mounting the disks, you can attach it and then mount it to your desired directory via the user data section.

I'll add a sample code below for you.

Resources:
  server1:
    Type: 'AWS::EC2::Instance'
    Properties:
      DisableApiTermination: 'true'
      AvailabilityZone: us-east-1c
      ImageId:
        Ref: AMI
      InstanceType:
        Ref: InstanceType
      KeyName:
        Ref: KeyName
      SecurityGroupIds:
        - Ref: WebSG
      IamInstanceProfile:
        Ref: InstanceProfile
      SubnetId:
        Ref: SubnetId
      BlockDeviceMappings:
        - DeviceName: /dev/sda1
          Ebs:
            VolumeSize:
              Ref: RootVolumeSize
            VolumeType: gp2
        - DeviceName: /dev/sde
          Ebs:
            VolumeSize:
              Ref: AppVolumeSize
            VolumeType: gp2
      UserData:
        'Fn::Base64': !Sub |-
          #!/bin/bash -v
          yum update -y aws-cfn-bootstrap
          exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
          date > /home/ec2-user/starttime

          #Partition new disks
          echo -e "o\nn\np\n1\n\n\nw" |fdisk /dev/xvde

          #Make Folders to mount new disks
          mkdir /APP

          #Format disks
          mkfs.ext3 /dev/xvde1

          #Mount New Disks
          mount /dev/xvde1 /APP

          #Add mounts to FSTab so it will stick in reboot
          echo "/dev/xvde1 /APP ext3 defaults 0 2" >> /etc/fstab

          date > /home/ec2-user/stoptime
          echo END

To mount an existing volume, define the volume ID in the parameters, for example as 'AppVolume', and mount it to the instance with below code block

MountPoint:
  Type: AWS::EC2::VolumeAttachment
  Properties:
    InstanceId: !Ref 'Ec2Instance'
    VolumeId: !Ref 'AppVolume'
    Device: /dev/sdh

You can read more on this in AWS documentation

Udara Jayawardana
  • 1,073
  • 2
  • 14
  • 27