Search code examples
amazon-web-servicesterraformbackupterraform-provider-aws

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


Given that I have 2 instances created by 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"
  }
}

how can I create a backup plan for them using terraform?


Solution

  • So the solution was to create an aws_backup_plan and create an aws_backup_selection which selects the volumes attached to the ec2 instances using some tag.

    Here I add the tag to the ec2 instances attached volumes

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

    and this is how I created my 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"
      }
    }