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.