Search code examples
terraformterraform-provider-aws

Unable to create files in $HOME directory using user_data


I've always been puzzled why I cannot create files in $HOME directory using user_data when using an aws_instance resource. Even a simple "touch a.txt" in user_data would not create the file.

I have worked around this by creating files in other directories (e.g. /etc/some_file.txt) instead. But I am really curious what's the reason behind this & if there is a way to create files in $HOME with user_data.

Thank you.

----- 1st edit ----- Sample code:

resource "aws_instance" "ubuntu" {
  ami = var.ubuntu_ami
  instance_type = var.ubuntu_instance_type
  subnet_id = aws_subnet.ubuntu_subnet.id
  associate_public_ip_address = "true"
  key_name = var.key_name
  vpc_security_group_ids = [aws_security_group.standard_sg.id]
  
  user_data = <<-BOOTSTRAP
#!/bin/bash
touch /etc/1.txt          # this file is created in /etc/1.txt
touch 2.txt               # 2.txt is not created in $HOME/2.txt
                BOOTSTRAP

  tags = {
    Name = "${var.project}_eks_master_${count.index + 1}"
  }
}


Solution

  • I think I found the answer to my own question. The $HOME environment variable does not exist at the time the user_data script is run.

    I tried to 'echo $HOME >> /etc/a.txt' and I got a blank line. And instead of creating a file using 'touch $HOME/1.txt', I tried 'touch /home/ubuntu/1.txt' and the file 1.txt was created.

    So, I can only conclude that $HOME does not exist at the time user_data was run.

    ----- Update 1 -----

    Did some further testing to support my findings above. When I ran sudo bash -c 'echo $HOME > /etc/a.txt', it gave me the result of /root in the file /etc/a.txt. But when I ran echo $HOME > /etc/b.txt, the file /etc/b.txt contained 0xA (just a single linefeed character).

    Did another test by running set > /etc/c.txt to see if $HOME was defined & $HOME didn't exist amongst the environment variables listed in /etc/c.txt. But once the instance was up, and I ran set via an SSH session, $HOME existed & had the value /home/ubuntu.

    I also wondered who was running during the initialization so I tried who am i > /etc/d.txt. And /etc/d.txt was a 0-byte file. So, now I don't know which user is running during the EC2 instantiation.