It's a complicated one, but legally it's a civil contract; if the Ukrainian government decided to stop the gas flowing, both Gazprom and all the companies "downstream" would be in their rights to sue for breach of contract and/or causing gas shortages, costing the Ukrainian government billions.
And you could wonder why they signed the contract anyway given Russia invaded/annexed Crimea 5 years prior, but, it's a lot of money, and at the time it was still considered a civil contract I presume.
The Ukraine needed (and continues to need) support from the buyers of that gas - the EU
The war has been going long enough, and the Ukrainian government would have made it very clear that thy would not be renewing the contract.. meaning that the EU had a chance to get their energy via some other route.
Btw, occupying the moral high ground even when it has a cost, sends a strong signal that you will also be trustworthy in the future, and not just when it's convenient.
Ie sometimes the cost is the point.
Just like the peacock's fancy tail needs to be biologically expensive to work.
I'd imagine the logic goes something like Ukraine believes they are benefiting and Russia is too, but they aren't sure which side is gaining more from the movement of gas through Ukraine (which, note, in real terms is supporting the economies that are arming Ukraine). In that situation, the obvious thing to do is just let things play out as contracted. If it was obvious that Russia was gaining a lot more from the deal than they are then they'd just stop.