To be completely accurate, the sun doesn't produce any energy, it converts energy from one form (rest mass) to another form (electromagnetic radiation), increasing entropy in the process in keeping with the second law. That conversion process itself requires an input of energy (though one less than the energy output by said process) to initialize and sustain, and that energy is in turn supplied, in the form of kinetic energy, by conversion from yet another form (gravitational potential energy) spontaneously, precisely because of the second law of thermodynamics.
At one time in the history of science, it was thought that all of the energy of the sun was converted more or less directly from gravitational potential energy: a cloud of hydrogen collapses under gravity, converting its potential energy into kinetic energy, rendered macroscopically as temperature, causing the ball of collapsing gas to glow incandescently. The problem was that that process can't last for very long, so the sun (and consequently the whole solar system) would have to be pretty young, relatively (still massively old on a human scale) if that's what's making the sun glow. When we discovered that the Earth itself, and space rocks, are much older than the sun would have to be according to that theory, it required that something else be powering the sun on a longer scale. The introduction of nuclear fusion to the model solved that problem, and nowadays almost nobody even remembers that we once thought the sun was just, in effect, gravity-powered.