使用Terraform EC2 Userdata发布问题

时间:2017-12-08 11:31:00

标签: bash amazon-ec2 terraform

我正在部署一堆需要名为userdata的挂载的EC2实例,这是我在AWS中使用卷附加附加的单独磁盘。

现在,当我手动执行以下操作时,它工作正常,因此我使用的脚本有效但通过mkfs添加时我发现问题并且resource "aws_instance" "bastion01" { ami = "${var.aws_ami}" key_name = "a36-key" vpc_security_group_ids = ["${aws_security_group.bath_office_sg.id}","${aws_security_group.bastion01_sg.id}","${aws_security_group.outbound_access_sg.id}"] subnet_id = "${element(module.vpc.public_subnets, 0)}" instance_type = "t2.micro" tags { Name = "x_bastion_01" Role = "bastion" } } resource "aws_instance" "riak" { count = 5 ami = "${var.aws_ami}" vpc_security_group_ids = ["${aws_security_group.bastion01_sg.id}","${aws_security_group.riak_sg.id}","${aws_security_group.outbound_access_sg.id}"] subnet_id = "${element(module.vpc.database_subnets, 0)}" instance_type = "m4.xlarge" tags { Name = "x_riak_${count.index}" Role = "riak" } root_block_device { volume_size = 20 } provisioner "file" { source = "datapartition.sh" destination = "/tmp/datapartition.sh" } } resource "aws_volume_attachment" "riak_data" { count = 5 device_name = "/dev/sdh" volume_id = "${element(aws_ebs_volume.riak_data.*.id, count.index)}" instance_id = "${element(aws_instance.riak.*.id, count.index)}" provisioner "remote-exec" { inline = [ "chmod +x /tmp/datapartition.sh", "/tmp/datapartition.sh", ] connection { bastion_host = "${aws_instance.bastion01.public_ip}" bastion_user = "ubuntu" } } } 命令没有发生。

如果你看到我的terraform配置:

#!/bin/bash

if [ ! -d /data ];
then mkdir /data
fi

/sbin/mkfs -t ext4 /dev/xvdh;

while [ -e /dev/xvdh ] ; do sleep 1 ; done

mount /dev/xvdh /data

echo "/dev/xvdh /data ext4 defaults 0 2" >> /etc/fstab

然后分区脚本如下:

terraform

现在,当我通过bash script.sh执行此操作时,mkfs似乎不会发生,我在syslog中看不到明显的错误。如果我手动复制脚本并且只创建return withDefaultStatus(...),则会创建mount并按预期工作。

有没有人在这里有任何建议?

编辑:记录在用户数据下在AWS gui中添加此功能也很正常。

1 个答案:

答案 0 :(得分:2)

您可以尝试使用remote_exec而不是user_data。

User_data涉及cloud-init,它可以根据您的云提供商的图像采取不同的行动。

而且我也不确定在执行cloud-init部分之前执行等待一段时间的脚本是个好主意=>这可能导致VM考虑启动因超时而失败(取决于您的云提供商)。

Remote_exec在这里可能更好,因为你可以等到你的/ dev / xvdh被连接

See here

resource "aws_instance" "web" {
  # ...

  provisioner "file" {
    source      = "script.sh"
    destination = "/tmp/script.sh"
  }

  provisioner "remote-exec" {
    inline = [
      "chmod +x /tmp/script.sh",
      "/tmp/script.sh args",
    ]
  }
}