I put the following commands in user data of an EC2 running RedHat 8 AMI (
ami-0fc841be1f929d7d1), when they run, the mkdir tries to create .kube at root which looks to me like
$HOME is not set at the time.
mkdir -p $HOME/.kube sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config sudo chown $(id -u):$(id -g) $HOME/.kube/config
Following are log from
+ mkdir -p /.kube + sudo cp -i /etc/kubernetes/admin.conf /.kube/config ++ id -u ++ id -g + sudo chown 0:0 /.kube/config
When I SSH to the instance, the
$HOME is set correctly to /home/ec2-user.
Could you advise what I did wrong here?
$HOME refers to the home directory of the logged in user. Userdata runs under the root user, and the root user
/. That is the result you are seeing.
Instead of the variable
$HOME, your script should refer to
/home as a literal.
You are running as sudo which is known to change environment variables that are established with your users shell (such as
$HOME) as well as shell context based such as
Generally you can ensure this persists when you run sudo by adding it to the
env_keep settings in your sudoers configuration by adding the below line within
/etc/sudoers. More information is available here, be careful about modifying this file.
Otherwise if you don't want to make the above change, ensure you have the permissions to carry this out without running
sudo or pass an absolute path value in.
I would generally stay clear of user data for important configuration anyway, instead build a pre-baked AMI ahead of time with the configuration how you want it, using a configuration tool such as Ansible, Chef, Puppet.
Alternatively as this is within the User Data anyway, it is unlikely you have already configured the sudoers configuration, you should instead just specify the path.
When your EC2 server is provisioned, the user data script runs as user root, so $HOME is empty. What you could do, is to define the HOME env var at the top of your user data script, like this (insert your user's home directory here):
I've tried it and it works (I install NVM, SDKMAN, sbt, java, git, docker; all works fine). You might need to do some chown at the end of your user data script to change the owner of some files back to your user. For example, if your user data sets up some files in your home directory:
chown ubuntu ~/.foo/bar.properties