如何将 linux bash 脚本文件添加到 terraform 代码中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47614905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:40:19  来源:igfitidea点击:

How can i add linux bash script file into terraform code?

linuxbashterraform

提问by Devendra Date

My requirement is I need to create 3 aws instances using terraform and run a 3 different bash scripts in it. All files are on same server.

我的要求是我需要使用 terraform 创建 3 个 aws 实例并在其中运行 3 个不同的 bash 脚本。所有文件都在同一台服务器上。

I already have terraform code to create an infrastructure and 3 bash script ready to use.

我已经有了 terraform 代码来创建一个基础设施和 3 个准备使用的 bash 脚本。

resource "aws_instance" "master" {
  instance_type = "t2.xlarge"
  ami = "${data.aws_ami.ubuntu.id}"
  key_name = "${aws_key_pair.auth.id}"
  vpc_security_group_ids = ["${aws_security_group.public.id}"]
  subnet_id = "${aws_subnet.public1.id}"
}

this is my terraform code to create an AWS instance

这是我创建 AWS 实例的 terraform 代码

But i am not sure how i can integrate both.

但我不确定如何整合两者。

Also can i use Aws instance ip value as a variable value in linux bash script? If yes how can i pass that ip value to one of my linux bash script variable? Thank you

我也可以使用 Aws 实例 ip 值作为 linux bash 脚本中的变量值吗?如果是,我如何将该 ip 值传递给我的 linux bash 脚本变量之一?谢谢

回答by TJ Biddle

If you only need to run your script once; then pairing with AWS' user-data scriptsis perfect for this.

如果您只需要运行一次脚本;那么与 AWS 的用户数据脚本配对是完美的。

Throw your script into the file templates/user_data.tpl, use the template providerto then create the template. And then you'll just want to pass the rendered script into the user_dataargument for your aws_instanceresource.

将您的脚本放入文件中templates/user_data.tpl,然后使用模板提供程序创建模板。然后您只需要将呈现的脚本传递到您的资源的user_data参数中aws_instance

Modify as necessary.

根据需要进行修改。

templates/user_data.tpl

模板/user_data.tpl

#!/bin/bash
echo ${master_ip}

terraform_file.tf

terraform_file.tf

resource "aws_instance" "master" {
  instance_type          = "t2.xlarge"
  ami                    = "${data.aws_ami.ubuntu.id}"
  key_name               = "${aws_key_pair.auth.id}"
  vpc_security_group_ids = ["${aws_security_group.public.id}"]
  subnet_id              = "${aws_subnet.public1.id}"
}

resource "aws_instance" "slave" {
  instance_type          = "t2.xlarge"
  ami                    = "${data.aws_ami.ubuntu.id}"
  key_name               = "${aws_key_pair.auth.id}"
  vpc_security_group_ids = ["${aws_security_group.public.id}"]
  subnet_id              = "${aws_subnet.public1.id}"

  user_data = "${data.template_file.user_data.rendered}"
}

data "template_file" "user_data" {
  template = "${file("templates/user_data.tpl")}"

  vars {
    master_ip = "${aws_instance.master.private_ip}"
  }
}