Problem: How could a holy God punish someone for following His orders?
Answer: In 2 Samuel 24:1-25 we find the story of king David and the illegal census. In this passage we learn that Israel had once again provoked God to anger.
“Now again the anger of the Lord burned against Israel, and it incited David against them to say, 'Go, number Israel and Judah.'” [2 Samuel 24:1/NASB]
The “it” indicated in this verse is nonspecific and requires careful interpretation. The New King James Version renders “He”, suggesting that Yahweh was the one who incited David, but this is inconsistent with the parallel passage found in 1 Chronicles.
“Then Satan stood up against Israel and moved David to number Israel.” [1 Chronicles 21:1/NASB]
There can be no doubt that Satan was the one who prompted David to violate Exodus 30:12 and count the people without appropriate sacrifice. These sacrifices were a sign of God's ownership over Israel. For David to count the people without following the instructions of the law, was tantamount to claiming personal ownership of Israel – and that's a no no. The only question, then, is the nature of Yahweh's involvement. Did God cause David to sin, or simply permit Satan to incite David?
I believe the latter is more consistent with the testimony of Scripture. Firstly, God does not tempt anyone to break His law [James 1:13]. Secondly, given Satan's obvious involvement, it is reasonable to conclude that God gave him permission to incite David [Job 1:12; 2:6], in the same way God gave him permission to harm Job.
As for why God punished Israel for David's sins --- He really didn't. Rather, God orchestrated a scenario through which Israel would be punished for their own sins. David's sin was merely a vehicle for God's wrath. While David rightly took responsibility for illegally counting the people, you will notice that God was angry with Israel before David ordered the census.
Hope this helps.