These words are found near the opening of the final scene in the play and foreshadow the resolution of conflict. The meaning is best examined in full context:
let us know
Our indiscretion sometimes serves us well
When our deep plots do pall, and that should teach us
There’s a divinity that shapes our ends,
Rough-hew them how we will— (V.ii.7-11)
Hamlet has certainly been involved in both "deep plots" and in "indiscretion" as the plot has unfolded. He mistakenly murdered the father of his former lover. He has used Ophelia to further his own plans. He has ordered the execution of Rosencrantz and Guildenstern, his former friends. And he has allowed Claudius to live until the final scene, second-guessing the ghost of his father for several scenes.
At this point, Hamlet sort of steps back from all of it, looking at how everything has brought him to this moment. He comes to believe that no matter what he has plotted, destiny has brought him to his point. However it turns out, God ("divinity") will create the "ending" that He desires.
Hamlet repeats this same sentiment later in the same scene when Horatio urges him not to fight if he has a bad feeling about how things will turn out:
Not a whit. We defy augury. There’s a special
providence in the fall of a sparrow. If it be now, ’tis
not to come. If it be not to come, it will be now. If it
be not now, yet it will come—the readiness is all.
Since no man of aught he leaves knows, what is ’t to
leave betimes? Let be. (V.ii.220-225)
Here, Hamlet is reiterating that God is ultimately in control of his life and therefore of the outcome of this fight. If God wishes him to die, he will die. And if God wishes him to die later, he will not die during this fight. His only job is to be ready to meet death when it comes.
In the end, the plotting of Hamlet, Claudius, and Laertes does not bring the victory they originally desired. Claudius and Gertrude die. Hamlet and Laertes die. In the midst of the carnage, Fortinbras swoops in to claim the Danish crown. Hamlet would therefore say that it was the destiny of Fortinbras and the favor of God that brought him to that victory.