how to debug stack scripts
When is the script run, and how do I debug it?
Is the script run when the image is created or when the server is first booted? It can't be when the image is created, as the server is not auto-started unfortunately.
Is there some sort of log file or way to view the output? I cant see this information in the stack script guide unfortunately.
Also, it would be great if linode itself would maintain some official key scripts, e.g. tying down the firewall to just 80/443/22/25 or similar. For those of us who struggle with iptables this would be a great help.
thanks for any help or suggestions.
3 Replies
However, this is sometimes useless as it has no history, and the required info quickly scrolls off the page.
Is there any log file or way to capture the script output?
I just ran into this and have a fix that works for me and might help others.
#!/bin/bash -e
exec > >(tee -i /var/log/stackscript.log)
Top of StackScript with output logging
- Create instance with the StackScript changes above.
- Once the console shows "Running"
- Launch Console
- Glish
- Login as root
tail -f /var/log/stackscript.log
I wanted to add another bash
debugging trick that I use in addition to @moon0440's exec
trick, and has saved me a lot of time and headache when writing new StackScripts:
Use the set
built-in
Near the top of your StackScript, add a line like the following:
set -xeo pipefail
The most important part of this is -x
, as it enables debugging output for your script. You can view the output in realtime via LISH. The other flags add some desirable behaviors that also make debugging much easier in the long run, and may be worth adding to your scripts, as well:
-e
- this option causes the script to fail immediately on error. With-e
enabled, your script will not continue running after an error, which makes the responsible line of code much easier to identify.-o pipefail
- When a command pipeline (e.g.cat some.file | grep $some_regex
) fails, the default behavior inbash
is to return the exit status of the last command, rather than the exit status of the command in the pipeline that failed. Knowing which command caused the issue will save you a lot of time debugging messy pipelines.
You can find these tricks, and some others which you can use to aid in your debugging at this link. You likely won't need to use all of the tricks in your scripts, but each of these tips has individually come in handy for me when debugging scripts in the past.