Write Gitlab CI Pipelines in Python Code
gitlab.com
gitlab.com
It's not an accident that we are in a deep cycle of constrained configuration languages (yaml/json/etc etc). People chose to go there because before that we had a cycle of using programming languages and people hated it, for all sorts of good reasons.
Now I see we are on the way back into adding wrappers around the static config files, to turn them back into programming languages. This is happening all over the place - because guess what, it turns out, people hate static config files too, for all sorts of good reasons.
I am not sure if we will ever reach a compromise here or if we are just going to have to put up with endless change and churn because nobody is ever happy or at least willing to just settle for things that are "ok" but not "perfect".
People might hate constrained configuration, but the idea is that you dont have to prove that what you're configuring is actually whats happening.
Doesn't your solution of replacing the possibly buggy code with configuration leave you with configuration that may or may not be buggy?
But if the code that actually goes to production is actually different to what is tested (because your rebuilt it based on a config with some runtime behavior that executed differently), you are compromising the whole thing and all bets are off.
People will try to split the difference and generate a static config with code and test that as a reproducible entity, but then you have another set of tradeoffs (not least, complexity).
I believe the answer is "it depends on how you're using it" and generally speaking, customer needs override any pre-existing consensus on how it's being used.
Further, these configs usually act as declarative languages, giving directives to pipelines, controllers, etc., typically with idempotent side-effects.
This is just good software engineering. You have some static data structure which describes some result you want to exist in the world, and your pipeline/program makes that outcome manifest. This is the essence of boundary programming/hexagonal architecture.
The important part is that the interface has to have the same semantics as a config file: atomic/transactional. For example the builder pattern does this. You can enjoy all the expressiveness and power of the high-level language, but at some point you create the final config/pipeline/job-graph, call whatever needs to be called, and the provider of the interface needs to validate that.
That's why the semantics of Terraform is better than Ansible's.
I'd much rather use python/jinja/gomplate/what-have-you, do all my fancy expressive stuff with code I can check in, and get a single snapshot of plain, structured text (which I can also check in). Not to mention locking down your invariants (I can't recall how many times I've gotten bit by interpolating docker image uris with the wrong TAG). It's actually pushed me towards first Make and then later python cli tools (cause Makefile syntax is...ugh) to generate configs, rather than relying on any runtime business logic, cause it's just so much saner, traceable, auditable, etc.
Sure, it is still Bash, it still requires selling your soul, but it's not like I was going to Haskell heaven anyway.
I hope we never settle for things that are "ok" but not "perfect".
Static analysis, even just simple parsing, is a quite common need when you need to migrate or take statistics of something related to all configurations in a given code base.
Orchestration ought not be the province of your build scripts, that should be the role of CI. If the configuration isn't capable of variadic functionality but is capable of orchestration... what do you do?
I've made a project in one of my old jobs dedicated to configuration and deployment tools used by CI jobs. At first it got some criticisms about "testing the CI that tests the software" and "testing the tests" but when the number of fires we have to take care of was cut by half it quickly became the norm.
As a developer who also dabbed in devops, I hate CI-side scripting with a passion.
The last place I've worked a few years back had about 20 interdependent Jenkins jobs per project. During a build, a job would break another job who would break another job but not successively fast enough to intervene so the majority of the time of the devops guru was spent on making hacks and fixes everywhere, thus fueling the endless cycle of madness. Middle management were aware of the problem but they never could say no to new aggressive timelines so here we were but I digress.
For me a CI server is a way to automate tasks so that 1) devs' time is saved 2) all versions are release worthy 3) human mistakes are kept to a minimum 4) a public record is kept 5) long and boring tasks such as packaging releases, generating code coverage and running the static code analyzer do not bother devs and are done periodically.
What CI should not do: 1) do things that devs can't do 2) crash 3) run nondeterministic builds and tests 4) be understandable by only one guy named Brent (wink wink Phoenix Project).
A typical CI script should limit itself to a simple workflow: checkout revision, get dependencies, build, test, release; and those should all be things that can be done, tested and modified and debugged on a common developing environment. Anything else is just loaning time from the future.
If I want non-technical people to configure something I need to write a GUI for self-serving.
Any and all attempts to munge YAML or to turn YAML into something Turing complete are signals that a scripting language would have been a better fit for the problem.
The exit to this cycle is:
* to use configuration languages for things that are genuinely configuration now and always
* scripting language APIs for things that are genuinely not configuration (e.g. build systems).
* provide both for domains that are genuinely mixed (a lot of kubernetes probably fits into this category - some things are configuration for some people and dynamic or generated for others).
It sounds simple but it is hard - the correct border between config and code is usually hard to perceive and how your tools end up being used is inherently unpredictable.
I'm pretty sure the whole point of dhall is to DRY out configuration files and to hack on type guarantees to config files.
I played with it for a bit and those are the only two use cases I could find. Those two use cases usually come encumbered with several others which it does not help with at all, but a scripting language would.
A good, refactored-to-be-DRY config file that is typesafe completely obliviates any need for dhall and if you've got a Turing complete YAML monstrosity it's not going to help much.
It reminds me a bit of XSLT (except that was accidentally Turing complete of course).
> A good, refactored-to-be-DRY config file that is typesafe completely obliviates any need for dhall and if you've got a Turing complete YAML monstrosity it's not going to help much.
Dhall is a "refactored-to-be-DRY config file that is typesafe", and the host of safety-related features ( https://docs.dhall-lang.org/discussions/Safety-guarantees.ht... ) make this practical to implement, even while evaluating untrusted & potentially malicious dhall code. These guarantees are much stronger than what nearly any other config or scripting language provides.
Hence it's a hack to circumvent badly designed / no schema.
These arguments aren't holding any water.
Coz they fucked up/didn't fix their schema designs and people keep trying to work around that?
I thought I was being very explicitly obvious about this.
Programming is a history of bad designs being worked around with awkward hacks. This is nothing new.
There are plenty of properly designed YAML schemas where people never feel the need to use something like dhall or jinja2.
Compare to dhall which publishes a complete set of dhall-k8s schema mappings which enables you to factor out any design you want down to as few configuration variables as you like, while validating the configuration generators themselves at design time. https://github.com/dhall-lang/dhall-kubernetes#more-modular-...
LOL! No, their schemas are horribly designed and half of their YAML should really be APIs.
But it's hella popular.
>Compare to dhall
Which isn't.
Systems change, and requirements of those systems change. Oh now someone wants to do more things with what used to be 'just configuration': scale it up and to work across many instances by scripting configuration templates with parameters. Look, all of this scripted automation is doing the same things that can be neatly divided into buckets, can we simplify it and turn it into a few configuration options? And so the cycle repeats. The churn is not reducible to labeling it as pointless make-work, its born of changing and growing systems.
The structure of data and code is the same.
The result is that you start with configuration. But you all ways have a nice escape hatch
When was that?
This would represent a quantum leap in software quality assurance.
Nuke [1] gets close but there are still a lot of tasks that don't have C# bindings, such as publishing build artifacts and uploading test results.
While I'm dreaming about my perfect CI, I'd also like the ability to download benchmark results from previous commits so that I can generate trend graphs and publish them in the build results.
To do this right the CI system would have to have an API using REST, GraphQL, gRPC or some such API format that generates clients in many languages. That way they don't have to maintain bindings in every language.
> Fix CI issue with blah blah blah
> Hmm that didn't work lets try something from stackoverflow
> Build fix
> Build fix please work
> Please
> I hate my life
> I am tired and hungry, I want to go home
> Stupid yaml
The CTO would call him like a week later to make sure he was okay. This happened often before we switched to Nuke. It rarely happened afterwards. It's awesome being able to debug your CI locally.
Do you wan to migrate all your third party libs to Bazel, or just hack up a few lines of CI yaml to call the authors build system?
I lean on gitlab yaml quite heavily and it feels quite effortless
Personally I use the native build system that upstream uses for most of them, and just hack in my compiler flags/options where necessary. Then I use CI triggers to rebuild my projects when the dependencies are rebuilt.
Want to do something fancy and complex? Just pull in a python image and call your python script. But you can still implement simple build steps directly in the build file. No need for a multitude of language bindings, everything you want to do is probably implemented with simple shell commands.
Bazel/Gradle/Maven/etc tend push you in the right direction, bash, etc dont.
Or to put it succinctly, you need both a build system and a CI system, they are not the same thing.
Yeah you need a k8s cluster, but even a simple kind dev cluster that you spin up in 30 seconds with one command on your laptop will work.
I like it a lot because it enforces very little structure on you and doesn't reinvent everything. Stuff like storage (either ephermeral or existing volumes), secrets, configuration, etc. are already modeled and supported by Kubernetes and tekton can use all of that natively. And since it's all k8s native stuff you have all of the power of k8s, like its entire API for manipulating and managing execution, exposing services, etc. There is very little cognitive overhead or new things to learn once you know k8s.
If you're really averse to k8s though, check out drone. It has a local execution mode that is similar and just runs whatever pipeline commands you want in docker containers. https://github.com/drone/drone Batect is another even more minimal tool that's effectively just a docker-based workflow system: https://github.com/batect/batect
For instance, if running a bunch of parallel tasks, collating results on a PV is out the window unless your cluster supports multiple writer volume types, which GKE does not. You have to bring in NFS volume types or something like that for it. In the early days of tekton they had a results primitive which synchronized an output dir to GCS, but they decommissioned that. So you are left pushing that logic into your task command. Running gsutil is easy enough, but it means you are pushing logic into your scripts and not declaring steps in the pipeline definition. You could make that command a step but I see little benefit in that.
Additionally there is no way to loop in the configuration to generate tasks, much less loop with an ordinal value. We end up just programmatically generating the resource definitions with ruby erb templates. All of our pipeline specs (including task runs, etc) creates a 2MB yaml file. We push dozens and dozens of these into k8s daily. It works but at the same time our usage of Tekton is more or less as a glorified alternative to batch jobs which works because batch jobs _still_ don't have a proper sidecar capability and also because we rely on the DAG to order dependent taskruns.
If your pipeline is simple, look at Tekton. But if your pipeline is complex... still look at Tekton but expect to do some work. Once you get a good workflow though you can you can scale your pipelines as easily as you can a deployment in k8s. We use node autoscaling and preemptibles (Tekton can retry if a task disappears due to node reclamation) to manage our CI costs quite effectively.
Some other comments here have argued for pushing as much logic as possible into your scrips, so that they can be tested without the CI system. What's the downside of doing this?
My solution is: https://github.com/rosineygp/mkdkr
I can write somethings like this:
py:
@$(dkr)
instance: python:3.8
run: pip install requests
export MKDKR_SHELL=python
run: 'import requests
r = requests.get(f"https://api.isevenapi.xyz/api/iseven/2/")
print(r.json())'Every tool I've used allows you to do this. Just write the script in the language of your choice, then run it in the pipeline.
A pipeline should be considered like "markup" around your scripts. Everything should work independently and on any system. The pipeline config just tells the scheduler which order to run it in, which bits can run in parallel, what artifacts to keep etc.
If gitlab/GitHub could just provide hooks to do this stuff for a range of scripting languages that could be easily dry run this would solve the problem.
Is this typical? All of our Gitlab CI files are well under 100 lines. What sorts of things are these pipelines doing that require so much configuration?
Our CI steps are basically:
* Build
* Run some static analysis
* Test
* Publish build artifacts
With each step taking only a few lines. Most of the “heavy lifting” is managed by other tools like npm, or some scripts we have checked into the project, and our CI process just kicks off those steps.
I never understood these project where somebody makes a very easy declarative thing and makes it imperative.
Programming in Python is order of magnitude "harder" and error prone than writing a simple YAML file.
For a simple config, sure.
But as soon as you have something more complicated, you end up with:
- a frankenstein monster DSL, with pseudo flow control + funcs backed in through a patched up templating system
- weird error messages, no stack trace, and type errors that accumulates
- no DRY
- no tooling: type checks, linting, de bugger, logger. Forget about it.
Case in point: ansible playbooks.
So unless your config is going to stay under 20 lines, just use a real programming language. If you don't want to use Python, fine. Use dhall, nix, jsonet or something else.
Debugging is definitely something I also would like to see something better coming out of Ansible than what is currently available.
CI systems will either grow into general purpose code runners or they will wither and die.
Now we’ve got a pipeline being defined by a declarative file being generated by code.
Amazon is doing the same with the Cloud Development Kit (CDK). With CDK you can code your infrastructure in a number of languages (java, csharp, .net, python, typescript), which was synthesized into cloud formation to be finally deployed. For smaller projects and teams not firm with one of those languages, plain CFN may be much better. However after learning CDK you won't create any infrastructure without it.
We're migrating our shared pipeline away from child pipelines. Maybe one day we'll do a write-up. :)
Documentation: https://docs.gitlab.com/ee/ci/parent_child_pipelines.html
GitLab 13.10 also added support for parallel matrix job execution in child pipelines, speeding up the execution once more.
https://about.gitlab.com/releases/2021/03/22/gitlab-13-10-re...
There's more to dynamic pipeline creation, collecting blog post ideas in https://gitlab.com/gitlab-com/www-gitlab-com/-/issues/11122#... :)
If all the shared pipeline jobs show up in your consumer project pipeline, you can easily extend them or overwrite them entirely.
> “What I have done is generate the yaml programmatically and this gets returned from the web server. Less than ideal but it at least allows dynamic creation”
They amount of polarization in this comment section is making me dizzy.