Of course Stalin knew that the deal would be temporary. In fact when Ribbentrop met Stalin in Moscow he asked for a non aggression agreement which would last for a 100 years, which was then cut down to 10 years as Stalin said that people would not take them seriously if they signed for that long.
The main reason why Stalin agreed to a pact with Germany was because the tripartite negotiations between Britain, France and the USSR in august 1939 came to a halt after Poland refused to allow Soviet troops into their western border with Germany to contain Hitler's expansion to the East.
Then came a letter from Hitler which guaranteed him protection as well as a trade agreement which offered the Soviets more than 100 million Reichsmarks worth credit to buy German industrial goods and machinery over a period of 7 years in return for Germany buying Soviet raw matiriels.
On top of that a secret protocol guaranteed half of Poland as well as a freedom to take Finland, Baltic states and a region from Romania without German intervention. This was something that the West could not offer. So Stalin agreed to the deal.
Stalin's main assumption when he signed the deal was that Germany would get stuck in a long war of attrition with Britain and France sort of like what happened in the Great war, leaving them all bankrupt and the USSR as the sole major European power.
Even after France fell in 6 weeks much to Stalin's shock he was still convinced that Hitler would have to either defeat Britain or sign a peace treaty with them before he could turn East, as Hitler had signed a deal with the USSR a year before to prevent a 2 front war in the first place. Even when Stalin recieved letters from Churchill in early 1941 warning about German troop movements Stalin reported them to Berlin believing that Britain was pitting Germany and the USSR against each other into a war to ensure their own survival.
Hitler's reasoning to breach the pact however was the same but he had a different perspective. After Luftwaffe's failure to gain air superiority over Britain, the US entry into the war looming on the horizon and increasing disparity between Romanian oil production and German consumption leading them to be more and more dependent on Soviet oil, Hitler was convinced that the only way to prevent the US, Britain and the USSR ganging up against Germany was to finish off the Soviet Union as soon as possible.