I want to pass the endpoint from rds to bash script how can I pass it to the bash script I am using terraform. I am using module structure, getting output from the rds module and giving it to ec2 module from the main template, but how to use the endpoint inside the bash script. I want to give the rds endpoint in dbserver
userdata.sh
#!/bin/bash
sudo yum update -y
sudo yum install -y httpd24 php56 php56-mysqlnd
sudo service httpd start
sudo chkconfig httpd on
sudo groupadd www
sudo usermod -a -G www ec2-user
sudo chgrp -R www /var/www
sudo chmod 2775 /var/www
find /var/www -type d -exec sudo chmod 2775 {} +
find /var/www -type f -exec sudo chmod 0664 {} +
cd /var/www
mkdir inc
cd inc
sudo echo "<?php
define('DB_SERVER', '**Rds endpoint**');
define('DB_USERNAME', 'mysqldb');
define('DB_PASSWORD', 'mysql123a');
define('DB_DATABASE', 'mysqldb');
?>" > dbinfo.inc
sudo aws s3 cp s3://webserver/SamplePage.php /var/www/html/SamplePage.php
ecs.tf
resource "aws_instance" "web" {
count = var.ec2_count
ami = var.ami_id
instance_type = var.instance_type
subnet_id = var.subnet_id
key_name = var.key_name
source_dest_check = false
associate_public_ip_address = true
#user_data = "${file("userdata.sh")}"1
security_groups = [aws_security_group.ec2_sg.id]
user_data = "${file("${path.module}/template/userdata.sh")}"
tags = {
Name = "Webserver"
}
}
resource "aws_security_group" "ec2_sg" {
name = "ec2-sg"
description = "Allow TLS inbound traffic"
vpc_id = var.vpc_id
ingress {
description = "incoming for ec2-instance"
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "ec2-sg"
}
}
Make use of the templatefile
function to render this information into your EC2 instance's user data.
Make the following change to userdata.sh
, inserting a variable named rds_endpoint
:
sudo echo "<?php
define('DB_SERVER', '${rds_endpoint}');
define('DB_USERNAME', 'mysqldb');
define('DB_PASSWORD', 'mysql123a');
define('DB_DATABASE', 'mysqldb');
?>" > dbinfo.inc
And then, in your aws_instance
resource:
user_data = templatefile("${path.module}/template/userdata.sh", { rds_endpoint = "(your rds endpoint value here)"})
Now you should be able to set this rds_endpoint
value to your RDS endpoint - think something like an aws_db_instance
address
or endpoint
value.