在使用Terraform创建EC2时,如果想要在初次启动时执行脚本,可以使用User Data字段来进行设置

首先

可以在Terraform文件中定义EC2的第一次启动时使用的用户数据(User Data),并且可以将自定义的Shell脚本文件定义为用户数据,并引用该文件。

要将Terraform的环境变量传递给Shell脚本文件,可以使用数据源。
例如,可以将来自Terraform环境变量的S3、EFS或ECR的信息传递给Shell脚本。

本次,我們將Shell腳本文件放置在用戶數據(User Data)中,並從Terraform的環境變量中將桶名(Bucket Name)和對象名稱(Object Name)傳遞給該腳本。

我們將通過放置在用戶數據(User Data)中的腳本,介紹如何從S3下載文件到EC2上的方法。

创建文件

    • variables.tf

 

    • main.tf

 

    • script.sh

 

    outputs.tf

variables.tf 的意思是变量设置文件。


variable "ami" {
  description = "Amazon Machine Image ID"
  type        = string
  default     = "ami-xxxxxxxxxxxxxxxx" # Replace with your actual AMI ID
}

variable "InstanceType" {
  description = "EC2 instance type"
  type        = string
  default     = "t2.micro" # Replace with your desired instance type
}

variable "az" {
  description = "Availability Zone"
  type        = string
  default     = "us-east-1a" # Replace with your desired availability zone
}

variable "subnets" {
  description = "List of subnet IDs"
  type        = list(string)
  default     = ["subnet-xxxxxxxxxxxxxxxx", "subnet-yyyyyyyyyyyyyyyy"] # Replace with your subnet IDs
}

variable "security_groups" {
  description = "List of security group IDs"
  type        = list(string)
  default     = ["sg-xxxxxxxxxxxxxxxx", "sg-yyyyyyyyyyyyyyyy"] # Replace with your security group IDs
}

variable "key_name" {
  description = "SSH key pair name"
  type        = string
  default     = "your-key-pair" # Replace with your key pair name
}

variable "bucket_name" {
  description = "BucketName"
  type        = string
  default     = "common-storage"
}
 
variable "s3_file_name" {
  description = "s3 file name to download"
  type        = string
  default     = "object1"
}

主.tf


data "template_file" "user_data" {
  template = "${file("./script.sh")}"
  #template = "${file("${path.module}/script.sh")}" # 必要に応じてmoduleディレクトリに対し、shellスクリプトが存在するパスを変えてください。
  vars = {
      bucket_name = "${var.bucket_name}"
      s3_file_name = "${var.s3_file_name}"
 
  }
}
 
resource "aws_instance" "ec2" {
  #ami                         = var.ami
  #instance_type               = var.InstanceType
  #availability_zone           = var.az
  #subnet_id                   = var.subnets
  #vpc_security_group_ids      = var.security_groups
  #key_name                    = var.key_name
  #そのたのattributes
  user_data = "${data.template_file.user_data.rendered}"
}

script.sh 的中文意思是“脚本.sh”。

#その他のコード
aws s3 cp s3://${bucket_name}/${s3_file_name} .          #aws s3 cp s3://バケット名/オブジェクト名 /保存先を指定する(例:/s3/bucket)今回は保存先"."にしましたので、ec2-userのホームディレクトリにS3ファイルがダウンロードされます。
#その他のコード

其输出.tf

output "public_ip_of_ec2" {
  description = "public ip of ec2"
  value = "${aws_instance.ec2.public_ip}"
}

讲解

data “template_file” “user_data” 块用于使用Terraform中定义的变量和资源值来生成模板文件。具体而言,这个数据源会读取被 template 属性指定的模板文件(在这里是 script.sh),并将其中的变量(例如:${var.bucket_name}和${var.s3_file_name})替换为Terraform变量。
vars 块用于指定模板内对应的Terraform变量值。在这个示例中,bucket_name 和 s3_file_name 对应于这些变量。
具体用法是,在 resource “aws_instance” “ec2” 块中引用 user_data 属性作为这个数据源的参考。这样,在启动EC2实例时,User Data 会以嵌入Terraform变量的形式提供给模板文件 script.sh。
简而言之,data “template_file” 是使用Terraform变量生成文件并在其他资源中使用的功能。
有关详细信息,请参考data-sources。

    • variables.tf: お使いの環境に合わせて必要な変数を定義します。

 

    • main.tf: template_fileデータソースを使用して、Shellスクリプトに変数を埋め込みます。

 

    • script.sh: S3からファイルをダウンロードするShellスクリプトです。

 

    outputs.tf: EC2のパブリックIPアドレスを出力します。

使用此文件结构来执行Terraform,将会启动EC2实例并下载指定的S3文件。这样可以将Terraform的环境变量传递给Shell脚本。
以上是将User Data定义在另一个Shell脚本中,并将Terraform的环境变量传递给Shell脚本的方法说明。请根据需要进行修改和添加,以适应您的环境。