使用Terraform在EC2 Windows实例中初始化EBS卷

时间:2019-05-28 04:51:04

标签: terraform terraform-provider-aws

我有一个自定义Windows AMI,每当我使用它创建一个新实例时,我都希望根据要求自动初始化一个附加驱动器。我正在尝试使用Terraform来做到这一点。

我正在获取驱动器,但必须手动对其进行初始化。

创建和ec2实例并附加卷。

resource "aws_instance" "example" {
  ami           = "ami-098792953bbd38e18"
  instance_type = "t2.micro"

}

resource "aws_ebs_volume" "ebs-volume-1" {
    availability_zone = "eu-west-1a"
    size = 160
    type = "st1"
    tags {
        Name = "more volume"
    }
}

resource "aws_volume_attachment" "ebs-volume-1-attachment" {
  device_name = "/dev/sdf"
  volume_id = "${aws_ebs_volume.ebs-volume-1.id}"
   instance_id = "${aws_instance.example.id}"
}

1 个答案:

答案 0 :(得分:0)

我正在Ubuntu 18上执行此操作,因此您将不得不对其进行修改,但请注意,因为这不是显而易见的imo。

### instance.tf

resource "aws_instance" "main" {
  user_data = data.local_file.user_data
  # ...
}
### user_data.sh

DEVICE="/dev/xvdf"

# Get device id
DEVICE_FS=`sudo lsblk -o UUID -d ${DEVICE} -n`

# Create a file system on the volume if one does not already exist
 if [ "`echo -n $DEVICE_FS`" == "" ] ; then
         mkfs.ext4 ${DEVICE}
 fi

# Create a mount point directory
 sudo mkdir /data

# Backup fstab
 sudo cp /etc/fstab /etc/fstab.orig

# Setup auto mount on reboot
 echo "UUID=${DEVICE_FS} /data xfs defaults,nofail 0 2" | sudo tee -a /etc/fstab

# Unmount
 sudo umount /data

# Mount and exit on error
 sudo mount -a
 if [ $? -eq 0 ]
 then
    echo "Mounted"
 else
    exit 1
 fi