Terraform Level 1 - Question #29

About the task Delete Backup from S3 Using Terraform, I tried using null_resource with local-exec provisioner to run two commands… One to copy the contents & the next is to delete the bucket recursively… But it’s not executing properly… Kindly assist whether am I going in the right direction or not…

Hi Vinod, Did u emptied the bucket before deletion! I have shared the syntax here. try it. Once its worked, reply me, i have some query in exercise 19 and 23.

resource “null_resource” “s3_backup_and_delete” {
provisioner “local-exec” {
command = <<EOT
mkdir -p /opt/s3-backup/
aws s3 cp s3://nautilus-bck-3485 /opt/s3-backup/ --recursive

        aws s3 rm s3://nautilus-bck-3485 --recursive

  
  aws s3api delete-bucket --bucket nautilus-bck-3485 --region us-east-1
EOT
interpreter = ["/bin/bash", "-c"]

}
}

Whenever I try to apply, it throws the below error,

null_resource.run_aws_cli (local-exec): Executing: ["/bin/bash" "-c" "      mkdir -p /opt/s3-backup/\n      \"aws s3 cp s3://xfusion-bck-28292 /opt/s3-backup/ --recursive\"\n      \"aws s3 rm s3://xfusion-bck-28292 --recursive\"\n"]
null_resource.run_aws_cli (local-exec): /bin/bash: line 2: aws s3 cp s3://xfusion-bck-28292 /opt/s3-backup/ --recursive: No such file or directory
null_resource.run_aws_cli (local-exec): /bin/bash: line 3: aws s3 rm s3://xfusion-bck-28292 --recursive: No such file or directory
╷
│ Error: local-exec provisioner error

looks like the backup directory is not creating properly. Either use my syntax or split your syntax into two. First just create a directory. If its executing fine then took a backup and delete it.

Actually the below solution worked fine,

resource "null_resource" "run_aws_cli" {
  provisioner "local-exec" {
    command = "aws s3 cp s3://xfusion-bck-28292 /opt/s3-backup/ --recursive && aws s3 rm s3://xfusion-bck-28292 --recursive"
  }
}

I think, it’s not accepting the earlier syntax to execute multiple commands… But anyway, the problem has been solved now…