Home > Mobile >  Copy directory from local to ec2 using terraform
Copy directory from local to ec2 using terraform

Time:05-22

I am trying to copy the local directory to ec2 instance. It works fine if I copy a single file not for directory. Any help would be appreciated.

resource "null_resource" "cp_ansible" {
  depends_on = [null_resource.provisioner]

  triggers = {
    always_run = timestamp()
  }

  provisioner "file" {
    source      = "../ansible/"
    destination = "/home/ec2-user/ansible/"

    connection {
      type        = "ssh"
      host        = aws_instance.bastion.public_ip
      user        = "ec2-user"
      private_key = file("/tmp/keys/ec2-key")
      insecure    = true
    }
  }
}

Error:

│ Error: file provisioner error
│ 
│   with null_resource.cp_ansible,
│   on inventory.tf line 68, in resource "null_resource" "cp_ansible":
│   68:   provisioner "file" {
│ 
│ Upload failed: scp: /home/ec2-user/ansible/: Is a directory

CodePudding user response:

You should use:

provisioner "file" {
  source      = "../ansible"
  destination = "/home/ec2-user"

  connection {
    type        = "ssh"
    host        = aws_instance.bastion.public_ip
    user        = "ec2-user"
    private_key = file("/tmp/keys/ec2-key")
    insecure    = true
  }
}

From the documentation:

The existence of a trailing slash on the source path will determine whether the directory name will be embedded within the destination, or whether the destination will be created. For example:

  • If the source is /foo (no trailing slash), and the destination is /tmp, then the contents of /foo on the local machine will be uploaded to /tmp/foo on the remote machine. The foo directory on the remote machine will be created by Terraform.
  • Related