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

How to attach and mount volumes to an EC2 instance using 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'。这是为什么?正如您所看到的,这是未安装的。我该如何安装它?

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

但是安装卷是在 OS 级别,CF 无法 knowing/doing 它。这与询问 How can I create a directory in cloudformation after launching an instance?

相同

你是怎么解决这个问题的? CF 有 EC2Instance 属性 称为 UserData. You supply the command to mount the attached volume. Here is one 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"
        ]]}}
      }
    },

如 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