使用 Terraform 将 rds 端点提供给用户数据

Give rds endpoint to user data using Terraform

我想将端点从 rds 传递到 bash 脚本,如何将它传递到我正在使用 terraform 的 bash 脚本。我正在使用模块结构,从 rds 模块获取输出并将其从主模板提供给 ec2 模块,但是如何在 bash 脚本中使用端点。我想在 dbserver

中提供 rds 端点

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 将此信息呈现到您的 EC2 实例的用户数据中。

userdata.sh 进行以下更改,插入名为 rds_endpoint 的变量:

sudo echo "<?php
define('DB_SERVER', '${rds_endpoint}');
define('DB_USERNAME', 'mysqldb');
define('DB_PASSWORD', 'mysql123a');
define('DB_DATABASE', 'mysqldb');
?>" > dbinfo.inc

然后,在您的 aws_instance 资源中:

user_data = templatefile("${path.module}/template/userdata.sh", { rds_endpoint = "(your rds endpoint value here)"})

现在您应该能够将此 rds_endpoint 值设置为您的 RDS 端点 - 想想 aws_db_instance address or endpoint 值。