如何使用 terraform 自动为我的 ec2 实例创建备份计划

how to automatically create a backup plan to my ec2 instances using terraform

鉴于我有 2 个由 terraform 创建的实例

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

  tags = {
    Name = "web1"
  }
}

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

  tags = {
    Name = "web2"
  }
}

我如何使用 terraform 为他们创建备份计划?

所以解决方案是创建一个aws_backup_plan and create an aws_backup_selection,它使用一些标签选择附加到 ec2 实例的卷。

这里我将标签添加到 ec2 实例附加卷

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

  tags = {
    Name = "web1"
  }
  volume_tags = {
    backup = "True" # Will be used by backup_plan
  }
}

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

  tags = {
    Name = "web2"
  }
  volume_tags = {
    backup = "True" # Will be used by backup_plan
  }
}

这就是我创建 aws_backup_plan with the aws_backup_selection 的方式:

resource "aws_backup_vault" "example" {
  name        = "example_backup_vault"
}

resource "aws_backup_plan" "example" {
  name = "tf_example_backup_plan"
  rule {
    rule_name         = "tf_example_backup_rule"
    target_vault_name = "example_backup_vault"
    schedule          = "cron(0 12 * * ? *)"
    lifecycle {
      delete_after = 7 # delete after 7 days
    }
  }
}

resource "aws_iam_role" "default" {
  name               = "DefaultBackupRole"
  assume_role_policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": ["sts:AssumeRole"],
      "Effect": "allow",
      "Principal": {
        "Service": ["backup.amazonaws.com"]
      }
    }
  ]
}
POLICY
}

resource "aws_iam_role_policy_attachment" "example" {
  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForBackup"
  role       = aws_iam_role.default.name
}

resource "aws_backup_selection" "example" {
  iam_role_arn = aws_iam_role.default.arn
  name         = "tf_example_backup_selection"
  plan_id      = aws_backup_plan.example.id

  selection_tag {
    type  = "STRINGEQUALS"
    key   = "backup"
    value = "True"
  }
}