如何在应用期间使用 terraform 创建 ec2 后运行 scriptps?

Jac*_*ury 14 amazon-web-services terraform terraform-provider-aws

在 terraform 中有一个在 aws 中创建 EC2 机器的示例。

# Create a new instance of the latest Ubuntu 20.04 on an
# t3.micro node with an AWS Tag naming it "HelloWorld"
provider "aws" {
  region = "us-west-2"
}

data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  owners = ["099720109477"] # Canonical
}

resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"

  tags = {
    Name = "HelloWorld"
  }
}
Run Code Online (Sandbox Code Playgroud)

但我也可以在里面运行一些脚本吗?比如安装詹金斯?安装 docker,或者只是运行命令:sudo yum update -y在 terraform apply 操作期间?

如果是这样,我会非常适合类似的例子或指导资源。

Mar*_*cin 13

是的你可以。在 AWS 中,您将UserData用于以下用途:

可用于执行常见的自动化配置任务,甚至在实例启动后运行脚本。

在 terraform 中,对应的属性是user_data

要使用它来安装 Jenkins,您可以尝试以下操作:

resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"

  user_data = <<-EOL
  #!/bin/bash -xe

  apt update
  apt install openjdk-8-jdk --yes
  wget -q -O - https://pkg.jenkins.io/debian/jenkins.io.key | sudo apt-key add -
  echo "deb https://pkg.jenkins.io/debian binary/" >> /etc/apt/sources.list
  apt update
  apt install -y jenkins
  systemctl status jenkins
  find /usr/lib/jvm/java-1.8* | head -n 3  
  EOL

  tags = {
    Name = "HelloWorld"
  }
}
Run Code Online (Sandbox Code Playgroud)

请注意,上面的代码是示例,我不能保证它可以在 Ubuntu 20.04 上运行。但它在 18.04 上有效。此外,Jenksis 在端口 8080 上工作,因此如果您想直接访问 jenkins,而不需要 ssh 隧道,您的安全组需要允许它。