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.
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.