The magnetic fields of cosmic bodies like the Earth or the Sun have puzzled scientists for well over a hundred years. The basic principle is that of a self-excited dynamo, which is an electric generator where the weak permanent magnets are replaced by electromagnets. But cosmic dynamos are made of plasma with no wires and uniform conductivity, so they are prone to short-circuiting themselves. We now know of a handful of very different examples where a suitable flow geometry can exponentially amplify weak seed fields. Demonstrating this experimentally is still hard, but it did work in a few case. It is much easier on the computer. After explaining some of the examples, I will address the problem of primordial magnetic fields. For a long time, this was thought to be an alternative to galactic dynamos, but now we know that it is very much a research field in its own right. Not much is known with certainty, but there are believed to be lower observational limits on their strength. The field generation would also leave traces in relic gravitational waves, which is a rapidly growing topic that I will address at the end.