130 points · by j3s · 2y ago · 138 comments
I sadly don't recommend it for my day job, simply because of liability. When something messes up with ansible, terraform, docker, cloudformation etc, no-one gets any blame because 'complex systems', 'it happens' etc etc; with a simple script going wrong, they would hang me high even though it probably saves a crap load in maintenance, compute etc over the 10s of years. Same reason we use clusters and IaC while of course nothing we do needs it; if an aws cluster goes down, no-one but aws gets blamed, while if the $2 postgres vps@cheapafhosting (with an higher uptime than that aws cluster by the way; human error downed it a few times, short, but still) is down even for a ping, everyone is upset and pointing fingers.
That said, it's a tool. Like any tool, it depends how you use it. People who aren't trained on the tool, or don't read the instruction manual, might get injured. I'd like to see a version of it that is safer and retains its utility without getting more complicated, but it would end up less useful in many cases. Maybe that's fine; maybe it needs to be split into multiple tools.
Here's a note from the Ubuntu recommendation: https://wiki.ubuntu.com/DashAsBinSh
but if you don't, and the tldr command isn't available, then good freakin luck.
What i really want is "python, but with really easy running of subcommands". Imagine extending python with a $ operator (prefix, applied to iterables) so that
files_iter = $('ls')
would run ls and put an iterator over its lines of output in that variable, throwing an exception if ls exits with an error status (i realise there is a rabbithole of subtleties here - getting those right would be part of this). Or contains_pattern = $?('grep', '-q', pattern, file)
to get just the exit status as a boolean. I think i'd drop bash in a heartbeat. >> files = `ls / | grep ^b`.split("\n")
=> ["bin", "books", "boot"]
>> p $?
#<Process::Status: pid 10889 exit 0>
>> `false`
=> ""
>> p $?
#<Process::Status: pid 10898 exit 1>
I don't use it a lot because I don't feel like installing Ruby just for a few scripts, and zsh solves enough of the problems for me anyway.Also parsing ls output isn't necessarily a good idea, and what you really miss is "first class globbing" like:
for f in /b*; [..]
arr=(/b*)Thinking about it, this doesn't need to be an operator, and i could probably just write this myself and start trying it.
Interesting point about globbing. My feeling is that i don't actually use it a lot in scripts - the criteria for matching are usually complicated enough that i'm much more likely to use find. In a project with 1376 non-comment lines of shell script, i found eleven uses of globbing.
cd /root
for project in $(ls go-cicd);
I think a better expression would be: for project in ./*
do [ -d "$project" ] || continue
...- Everything here is done as root. For the day that you want to build with lesser privilege, do this:
BLDUSER=~root
- That will be difficult for you, because you are moving the projects to /usr/local/bin; for the day that you stop running as root, make a subdirectory "/usr/local/bin/$BLDUSER" (owned by the namesake account) and move the projects there instead.- Very minor nitpick, use <<- and prefix tabs on the here document to make it slightly easier to read.
- Slight improvement, so this can print more than one argument:
println() { y=
for x
do printf %s%s "$y" "$x"
y=' '
done >> /root/gocicd.log
echo >> /root/gocicd.log # for the newline
}- Running ls forks an unnecessary process.
- The ls may be aliased with "-F" (or -p) which will corrupt the filenames.
- Environment variables may otherwise (unexpectedly) manipulate ls behavior.
- Files with spaces will not be evaluated correctly.
- Hostile files can be placed that mimic command line arguments.
The shell should evaluate filenames itself; it is very capable of doing so.
POSIX ls: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/l...
Given the situation and the project names, I wouldn't expect the use of `ls` described in TFA to ever be a problem, but doing it with a simple glob would still be nicer and is a good habit to get into overall since then you don't have to ask yourself "is this use of ls going to be safe?"
Then, I needed to make another machine like this, so enter Ansible. This worked well for a long time, and was relatively content with it. Along the way, I leaned about nix (and enough of it) to adopt a simple flake to pull out my tools (like golang, ansible, terraform) through. For a long time, I used it like this (e.g. still ansible, but I started building locally)
Finally, I learned enough nix to adopt NixOS. Now, I've converted my project to a nix package and a NixOS module, which allows me to totally describe the state of the machine I want. With this, remote builds and colmena (mostly for pushing secrets), I deploy a complete system, including my own software.
Shell scripts written in NetBSD sh/Debian ash will work for as long as I live.
You build script becomes:
while true; do
git pull
nixos-rebuild switch
sleep x
done
That's it. You can even do it remotely and push the new desired state to remote machines (and still build on the target machine, no cross compile required).I've completely removed Ansible as a result and no more python version mismatches, no more hunting endless task yaml syntax, no more "my god ansible is slow" deplyments.
while true
You can instead say: while :
There is actually a /bin/true, which could involve the fork of a new process for each iteration of the loop. The form that I have shown you is guaranteed not to fork.https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V...
Most of the familiar userland utilities are at that website, accessible as a (somewhat crude) Apache index:
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/
Any POSIX-compliant system is required to implement the functionality described there.
But if you could have the server into 'lame duck mode' (no new connections accepted, but existing ones can finish) / gracefull shutdown and that's a blocking call (or you could poll if it's still up etc), then you could script that before the 'nixos-rebuild switch' call. Maybe sending SIGINT to the service does that already?
nixos-rebuild switch --target-host x.example.com
(I still have a few Arch hosts using Ansible, but will migrate them in future)There's also https://github.com/zhaofengli/colmena which may be of interest to folks.
Example: this interprets the output of 'ls'. Reliability is dependent on good quoting/never introducing a project with spaces
Ansible is a nice middle ground, personally. I write the state that differs, use a library of scripting.
And it's an easy fix:
- for project in $(ls go-cicd); do
+ cd go-cicd || exit 1; for project in \*; do for project in go-cicd/*; do
project="${project#*/}"That said, if you do (ie: scratch files, things outside of control, whatever), consider the directory stack:
https://www.gnu.org/software/bash/manual/html_node/Directory...
Using 'pushd' and 'popd' can save your fingers/brain from getting lost in context.
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
or something similar at the top of the script might not come across as comparable to adopting Ansible to some people.I've been cargo-culting this for ages without thinking much about it.
This case has been handled. Others?
There isn't anything really insightful here. Someone pleased with a script has not yet grown beyond the needs of it. Yay.
The more portable/maintainable version of this is a playbook or whatever. Someone wrote and tested a better version of whatever Work Unit as a module.
Wheel enthusiast is pleased with their finely polished, but not particularly traveled, wheel. It's great, but they're commodities and not seeing much.
I would have done the same thing with 'ansible-pull' and zero code, in even less time/effort... but I also already know Ansible and bash.
Configuration management tools are excellent at managing applications and configs. Who knew.
Something else to suggest: systemd timers. At a glance info for scheduling of the job, instead of inferred from logs that may or may not have been recorded. You can also then actually declare your deployment needs networking.
Eyeroll.jpg. This is great because the bar is so low. They'll generate a ton of useless logs if they lose networking, as-is. Long enough and the disk will fill: this is trying every minute.
When I think about excellent software Ansible isn't the first that comes to mind either. Clearly it's different for you, and the person who wrote the TFA doesn't agree with me either.
It also doesn't fail immediately if many of the commands fail (instead blindly moves on to the next statement). Consider using bash and these options: https://github.com/kvz/bash3boilerplate/blob/main/main.sh#L1... for most scripts.
"consider keeping your little things little.
it worked for little old me."
The rest are details and every one of us would implement the details in a different way.
For example a similar script could be portable with non go projects by looking for a simple build-deploy.sh script that take care of each project deployment mode/instructions.
And while simple is great, the necessary features not included in OP's scripts is that I want to spin up the new instance in parallel, verify it is running correctly, and then switch nginx or the load balancer to point to the new server. You are less prone to break production and you get zero downtime deploys.
pushthis="rsync -avzh --del ~/path.local/ somedude@path.online:path.online"
How do you manage domain names, who deals with the ssl certificates, how do you set environment variables i.e. "secrets", how can you run postgres, how do you run remote commands i.e. dbmigrate.py, etc.
A friend and I have been working for a few months on a project to simplify this - we're not the first to do an open source IaC, but we're scratching our own itch on a lot of features that we've been missing. It's basically "deploy with git push to your own VPS and manage everything with a CLI".
I'd love to ask - what do people feel is mostly lacking from OP's script? Which features seem like the most important when deploying/managing a remote server? How do you choose if you're going to use Ansible or K8S or a script, or a full blown IaC i.e. Heroku? Is it price/ownership (i.e. having full control over the machine)/ease of use/speed of deployment/something else? Thanks!
http://canonical.org/~kragen/sw/dev3.git/hooks/post-update
#!/bin/sh
set -e
echo -n 'updating... '
git update-server-info
echo 'done. going to dev3'
cd /home/kragen/public_html/sw/dev3
echo -n 'pulling... '
env -u GIT_DIR git pull
echo -n 'updating... '
env -u GIT_DIR git update-server-info
echo 'done.'
dev3.git is the origin for dev3, so the `git pull` in there pulls from the bare repo that just got pushed toit doesn't have the 60-second lag and it doesn't load the server all the time. it also doesn't run `go build` or restart a server with openrc, but those would be easy things to add if i wanted them
I wouldn't use it for serious stuff, but it's been working great for my random personal projects (biggest gap is if something crashes it'll stay crashed until manual intervention currently)
It will connect over ssh, pull the code, build the containers and restart them (scripts/live is just a wrapper around docker-compose).
If the build fails, the services will keep running.
The only problem I have is that hitting CTRL+C in the very moment the containers are being restarted will leave me with the services down.
A shell script that deploys a couple config files and off you go. Use different accounts for each service for isolation and put all of your static files in your binary using embed.FS. No need for fancy configuration management or K8s.
I compile my Go projects to a binary on a github action, scp it to the server, ssh into it and restart - all done in my deploy.sh and the GHA itself only installs Go and deps (its cached) and then calls that deploy.sh script which sits right in the repo itself.
Super happy with it. Speaking as a previous DevOps guy that got sick of AWS complexities.
Don’t get me wrong, I love bash scripts like any other old hat, but Ansible scratches this exact itch.
You’ve got playbooks that can execute shell, provide logging, better management, history of execution, fleet management, and it’s light weight. And there’s a robust community of shared modules, etc.
Adding layers and layers of tooling is often overkill and it is hard to bit the simplicity of 33 lines of shell when the use case is a single person doing the code, deployment and maintenance.
In a devops workflow you "treat servers like cattle instead of pets" but your org still needs a few pets. Some host you control must either host DNS or manage your DNS provider's API key. Same for CA, IdP, git, backup and monitoring services, and the ansible machine itself. You'll have to manually configure these things before your "cattle" tools can run.
Once you're up and running, it's possible to make ansible manage it own dependencies, but this introduces circular dependencies complicates bootstrapping (consider a disaster recovery situation) and amplifies both the impact of faults and the difficulty of troubleshooting them. Do you want to be debugging python dependencies in the middle of the night so you can finally get ansible to execute the couple bash commands that will bring your ACME CA back up? I'd rather run bash directly.
At a small scale with a stable set of requirements, your core infrastructure is better served by a good operations manual and a simple deployment toolset with minimal dependencies. Plain bash fits the bill!
For years I've started using and abandoned ansible and puppet recipes for setting up my own computers and everytime the conclusion was that I would spend more time installing git, ansible and puppet in the first place and debugging my recipes than using them. Now all my setup lives in shell functions in my .bashrc.d. I still need git but I don't need ansible or puppet anymore.
Lean into the module ecosystem. Want to ensure a config file is a certain way? Jinja/template it, or use lineinfile instead of echo/shell redirects.
That's a lot of mumbo-jumbo. The point is, there's a lot of stuff scripts want to do. Ansible provides these as modules. Using the modules spares you from writing code to do something in a robust/repeatable way.
The 'line in a file' example is a good case, IMO. A shell script with redirection either requires specific code to look first, or simply endlessly append. With Ansible you don't have to do all of that.
Your script needs to do something when something changed? Ansible has you covered: handlers!
Python is right within reach too. I find it a way to write Python via YML, basically.
That is a huge lie: Declarative code is still code. Using modules is similar to reusing functions. The things is, while reusability and declarative code is nice when you want to deploy and manage multiple machines and have an automated network install that bootstrap your automated configuration tool. It is worth the effort because there are many machines but all that automation need to be tested/fixed on a regular basis (distro releases, etc). If you are reinstalling your machine from an usb pendrive, or image once every so many full moons, you need first to bootstrap ansible and the playbook. How do you that in an idempotent manner? The time you have done that you are probably already ready.
The only thing I need on my dev machines is :
- my software configs: comes with a git repo of my dotfiles.
- a dev directory: mkdir is idempotent, it will not destroy dir if it exists so no need for a declarative language
- some packages: a single package install is needed. While using a configuration tool allows you to declare package name depending on distro version and regardless of package tool, usually someone who is managing 2-3 machines stick to one OS so in my case a single `dnf install -y <list of package>` is enough.
- a few tools I curl from github or other places. I have one bash function for each of them to get latest release (a one liner) and one to compare installed version with latest release and install if needed. Ansible doesn't do a better job at it. I checked ansible-galaxy for some of the tools I download, for some no module exists, for those that have modules, they are just made of ... shell scripts called by an ansible task that is larger than my own script. See example[1]
- a few desktop files, they come with my dotfiles git repo, no need to "declare them"
- a handful of stuff that comes with an install shell script (the infamous curl | bash). Ansible don't help me much or I'd have to rewrite the install script as an ansible playbook and maintain it myself forever.
No handler necessary, none of this requires a reboot or a service restart.
Also Ansible is probably the worst example as it is an half assed declarative language that doesn't even encourage idempotence. Basically it is made by and for old unix guys who want to continue writing sequencial scripts the old and crappy way while pretending they do things in a modern way. And it is the reason it has become so popular against cfengine, puppet, chef and salt. I don't see the point of using ansible if it is to have the same low standard of quality as plain old scripts.
My experience working with teams using ansible has only reinforced my view that this language is for people who like to do things the dirtiest way anyway but wrapping it in a declarative language so they can put devops engineer in their resume.
[1] https://github.com/andrewrothstein/ansible-eksctl/tree/main
>it’s light weight
Eh, don't think that's the case for everyone.
I dabbled with Ansible at a previous job, and set up a very basic personal server setup for Nextcloud and one other app. It was much slower than if I had just written some bash scripts. Idempotency was nice, but the feedback loop wasn't great.
Polls a docker registry and automatically restarts the container with the same flags that it was started with using the latest image.
It's 2024 and you're not developing the next vim or Postgres. Use bash.
I've played around a bit with Deployer for some projects. It's decent, but feels brittle. It's very dependent on you sticking with its assumed default setup, docs are all over the place, and extending/replacing scripts I found confusing.
I moved back to bash scripts.
If the current code is behind (there are new commits), it merges them. If it fails, it stops.
If not, it runs `go build`. If it fails, it stops.
If not, it moves the binary to the right location and restarts the service.
Especially as more and more new, easy/low config tools come out like Caddy, this gets simpler over time.
I have a testbed boilerplate project for Laravel in which server provisioning & deployments are done by bash scripts over SSH. Excluding comments/spacing, the provisioning script is 35 lines of mostly installing dependencies and minor file template copies. For simpler projects not needing queue workers and/or not using more "exotic" tech like Laravel Octane, this could probably be cut down to 30.
TL;DR do the simplest thing that works for you and move on with life - the value in your project, if you intend to deploy it, is for it to be used.
> - go down
I've had cron log files get too big and causes issues.
> - require an upgrade
I can't count the number of times unattended-upgrades has broken something.
> - force me to migrate
Let's hope the OS is still receiving security updates, because installing on a VPS like this always has a high migration cost.
This sort of deployment is a fair starting point, but let's not pretend it's some perfect ideal.
....
Look. For deploying a blog, sure, but no one is deploying their blog on k8s. There is a reason why big complex deployment and orchestration systems exist, because there are use-cases for them. This is not one of them, but there's no need to stick your head in the sand over requirements and pretend they don't exist.
my script will never:
- go down
- require an upgrade
- force me to migrate
- surprise me
- keep me up at night
Oh my sweet summer child. - require direct source code access
- require go build tools
- require maintaining GitHub auth
- require upgrading build tools over time
- not be trivial to rebuild on failure