如何使用CloudFormation将卷附加和装载到EC2实例

时间:2016-12-10 09:09:05

标签: amazon-web-services amazon-ec2 amazon-cloudformation

我找不到使用cloudformation附加和装载卷的方法。

我可以使用VolumeAttachment附加卷;但是,当我的EC2实例处于运行状态后执行lsblk时,我将此附加实例视为已卸载。

有没有办法从Cloudformation文件挂载此实例?我可以使用linux命令安装它,但是更好地处理来自cloudformation的所有内容。

这是我到目前为止:

"MyEc2Instance" : {
   "Type" : "AWS::EC2::Instance",
   "Properties" : {
      "KeyName" : { "Ref" : "KeyName" }
   }
},
    "MyVolume" : {
      "Type" : "AWS::EC2::Volume",
      "Properties" : {
        "Size" : "50",
        "AvailabilityZone" : "xyz"
      }
    },
    "attachment" : {
      "Type" : "AWS::EC2::VolumeAttachment",
      "Properties" : {
        "InstanceId" : { "Ref" : "MyEc2Instance" },
        "VolumeId"  : { "Ref" : "MyVolume" },
        "Device" : "/dev/sdh"
      }
    }

当我在实例上lsblk时,这就是我看到的结果:

xvda    202:0    0   8G  0 disk
└─xvda1 202:1    0   8G  0 part /
xvdh    202:112  0  50G  0 disk

请注意,即使我将设备名称指定为'sdh',它也显示为'xvdh'。这是为什么?正如你所看到的,这是未安装的。我该怎么装?

2 个答案:

答案 0 :(得分:11)

正如helloV所提到的,当使用UserData启动实例时,您需要安装它。我发现CloudFormation模板的新YAML格式更容易,但我也把这个例子放在JSON中。

JSON:

"UserData"       : { "Fn::Base64" : { "Fn::Join" : ["", [
    "#!/bin/bash -xe\n",
    "# create mount point directory\n",
    "mkdir /mnt/xvdh\n",
    "# create ext4 filesystem on new volume\n",    
    "mkfs -t ext4 /dev/xvdh\n",
    "# add an entry to fstab to mount volume during boot\n",
    "echo \"/dev/xvdh       /mnt/xvdh   ext4    defaults,nofail 0       2\" >> /etc/fstab\n",
    "# mount the volume on current boot\n",
    "mount -a\n"
]]}}

YAML:

UserData:
    'Fn::Base64': !Sub
      - |
        #!/bin/bash -xe
        # create mount point directory
        mkdir /mnt/xvdh
        # create ext4 filesystem on new volume           
        mkfs -t ext4 /dev/xvdh
        # add an entry to fstab to mount volume during boot
        echo "/dev/xvdh       /mnt/xvdh   ext4    defaults,nofail 0       2" >> /etc/fstab
        # mount the volume on current boot
        mount -a

答案 1 :(得分:3)

附加卷可以在虚拟机管理程序级别完成,因此您可以使用CF附加卷。

但是安装卷是在操作系统级别,CF无法知道/执行它。这与询问How can I create a directory in cloudformation after launching an instance?

相同

你如何解决这个问题? CF具有名为UserData的EC2Instance属性。您提供了装入附加卷的命令。这是一个example

{
   "Type" : "AWS::EC2::Instance",
   "Properties" : {
        ....
        "InstanceType"   : { "Ref" : "InstanceType" },
        "KeyName"        : { "Ref" : "KeyName" },
        "UserData"       : { "Fn::Base64" : { "Fn::Join" : ["", [
             "#!/bin/bash -xe\n",
             "yum install -y aws-cfn-bootstrap\n",

             "# Install the files and packages from the metadata\n",
             "/opt/aws/bin/cfn-init -v ",
             "         --stack ", { "Ref" : "AWS::StackName" },
             "         --resource WebServerInstance ",
             "         --configsets Install ",
             "         --region ", { "Ref" : "AWS::Region" }, "\n"
        ]]}}
      }
    },