First of all, Stalin is likely to have tried to avoid direct warfare with Hitler.
Two main reasons possibly justify Stalin taking part in a non-aggression pact with Nazi German.
It would be way expensive and difficult to mobilize troops and strategy against such a well-trained and voratious army such as the ever-conquering German. Thus, one point on favor of Stalin in the pact lies in the fact he could be buying time.
Also, and probably even more remarkable, they were settling around countries that lied between both German and Russia, with emphasis on Poland. By agreeing not to wage war against each other by then, Hitler and Stalin were also getting able to feist on the table of small countries of Eastern Europe – which, after some decades, Stalin ended up invading and controlling, in one way or another.
It’s also remarkable that the invasion of such countries would occur with little intervention from Western European countries or the USA, as it happened “behind” German’s forces, in a palce where geographically it was quite difficult for Uk, France, USA, etc. safely set an operation.
So, summarizing: buying time against a powerful enemy and peacefully acquiring new territories.