Rom 1.18 ff tells us that God gives us what we want and permits us to wallow in the consequences when we choose against his will.
God makes his will clear. Balaam wishes to go anyway. God stops him to remind him that his choice opposes God.
When Balaam feigns a repentance, God permits him to go to teach him although Balaam thinks that he is in charge of his own destiny, that God does not permit the consequences of his disobedience to work against God's purposes.
We have free will, but whatever we choose, God still controls the outcome. God said he created calamity/evil . It is like a giant switch statement. All the cases are pre-programmed with consequences. We get to choose which one we experience with our choices. But no matter what our choice, God has it covered. He has created the prototype (is that the right word for programmers?) of calamity but we implement it by our choice.
This story prefigures Herod as Balaam, the compromiser with Rome, bringing destruction on Israel by mixing with Rome. And John the Baptist as his donkey (donkeys always represent prophets). As such it suggests that Herod knew he was opposing God, but that God worked out his will in spite of Herod's choices.
Side Note: The purpose of calamity in the world is that it drives us all to declare that 'it' is not supposed to be this way. 'It' is supposed to be better than this. And by so proclaiming, we acknowledge that there is a God and we aren't Him. Rom 1.18.
God created the whole system of consequences, and the system is "Very Good" and we collectively make the experience in this world what it is by our choices.
 Isa 45:7 I form the light, and create darkness: I make peace, and create evil: I the LORD do all these things.