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.
I already have terraform code to create an infrastructure and 3 bash script ready to use.
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
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
Advertisement
Answer
If you only need to run your script once; then pairing with AWS’ user-data scripts is perfect for this.
Throw your script into the file templates/user_data.tpl
, use the template provider to then create the template. And then you’ll just want to pass the rendered script into the user_data argument for your aws_instance
resource.
Modify as necessary.
templates/user_data.tpl
#!/bin/bash echo ${master_ip}
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}" } }