【问题标题】:how to automatically create a backup plan to my ec2 instances using terraform如何使用 terraform 自动为我的 ec2 实例创建备份计划
【发布时间】:2020-10-27 16:04:54
【问题描述】:

鉴于我有 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 为他们创建备份计划?

【问题讨论】:

    标签: amazon-web-services terraform backup terraform-provider-aws


    【解决方案1】:

    所以解决方案是创建一个aws_backup_plan 并创建一个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_selection 创建aws_backup_plan 的方式:

    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"
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-13
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 2018-07-25
      • 2021-11-17
      • 2021-08-19
      • 2019-08-13
      相关资源
      最近更新 更多