I am deploying Amazon Linux 2023 with Terraform. I would like to automate the installation of Kubernetes and Helm so that I can restart my VM and have all the pieces up and running. The following code in the user_data script which works when I enter it manually in the VM does not run in the user_data script. I would like to know what is wrong.
echo "Installing Kubernetes ..."
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl.sha256"
chmod +x kubectl
sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
mkdir -p $HOME/bin && cp ./kubectl $HOME/bin/kubectl && export PATH=$HOME/bin:$PATH
echo 'export PATH=$HOME/bin:$PATH' >> ~/.bashrc
To get your user_data script running as expected, start by adding #!/bin/bash at the top. This line is necessary for user_data scripts to run properly, as it tells the system which shell to use. Also, place each command on its own line, or link them with && so they execute one after the other. Since user_data scripts run as root, using $HOME might not work as expected, so it’s best to use /root directly to avoid any issues.
I’ll update your script to:
#!/bin/bash
echo “Installing Kubernetes …”
curl -LO “https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl”
curl -LO “https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl.sha256”
chmod +x kubectl
sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
mkdir -p /root/bin && cp ./kubectl /root/bin/kubectl
echo ‘export PATH=/root/bin:$PATH’ >> /root/.bashrc
After launching the instance, you can check /var/log/cloud-init-output.log for any messages or errors from the script. This log can give you insights into what worked and where adjustments might still be needed.