The whole point of Soviet foreign policy after World War I was to stall for time. The Soviet leadership wanted to spread communism across the world, but it was worried that the West might attack it before it was strong enough to spread communism. Because of this, the Soviets tried to stave off attack from the outside as they became stronger.
The pact with Nazi Germany could be seen as the culmination of this effort. Germany was the most dangerous potential invader because of its ideology and because of its location near to the Soviet Union. Stalin wanted more time to build his power so as to be able to withstand an attack by Hitler. It was for this reason that he entered into the nonaggression pact with Germany.