How does Mg obey the octet rule? How does N obey the octet rule?

12Mg is 1s2 2s2 2p6 3s2 loses the two 4s electrons so the n = 2 shell has 8.

7N is 1s2 2s2 2p3 gains 3 electrons to fill the 2p shell and make n = 2 with 8 electrons