Been trying to trouble shoot this for two days. Not sure if it is a terraform or GCP issue. Or my code. I’m trying to create a VM and run some installs. It then creates a file in /var/run called flag.txt. If that file is present the startup script should exit and not run on reboots. I wrote a python script to write the date and time to the flag.txt file so I could test. However, everytime I reboot the time and date are updated in the flag.txt file showing that the startup script is running.
Here is my metadata_startup_script code
metadata_startup_script = <<-EOF
#!/bin/bash
if [ ! -f /var/run/flag.txt ];
then
sudo apt-get update
sudo apt-get install -y gcloud
echo '${local.script_content}' > /tmp/install_docker.sh
echo '${local.flag_content}' > /tmp/date_flag.py
chmod +x /tmp/install_docker.sh
chmod +x /tmp/date_flag.py
#Below command is just to show root is executing this script
#whoami >> /usr/bin/runner_id
bash /tmp/install_docker.sh
/usr/bin/python3 /tmp/date_flag.py
else
exit 0
fi
EOF
}
Here is the date_flag.py file that creates the flag.txt file
import datetime
current_datetime = datetime.datetime.now()
formatted_datetime = current_datetime.strftime("%Y-%m-%d_%H-%M-%S")
file_name = f"{formatted_datetime}.txt"
with open("/var/run/flag.txt", "w") as file:
file.write("This file was created at: " + formatted_date
Any thoughts or suggestions are welcome. This is really driving me crazy.
2
Answers
So it turns out that /var/run is symbolically linked to /run which is created at startup. I fixed this by writing the flag.txt file to /etc.
In the future, you can always run the following command from the instance to get logs on the script execution: