Using a geometrical formalism of equilibrium thermodynamics we formulate and solve an optimal control problem for ideal gases. Thermodynamic state is given by a Legendrian manifold equipped with Riemannian structures. A problem of finding an optimal thermodynamic process maximizing the work functional leads to the integrable in Liouville's sense Hamiltonian system. We provide its exact solution by means of angle-action variables and prove a controllability of the dynamical system.