Machiavelli is most famous for writing The Prince, a short manuscript completed in 1513 as a way of introducing himself for employment to the Medici family, rulers of Florence. Earlier, under the previous administration, he had been a diplomat in several European courts. Falsely accused of plotting against the Medici, he was arrested and tortured, his political career ruined, and forced into retirement.
The Prince was written as a guide for how a ruthless and cunning leader might seize the moment and unify all of Italy under his command (at the time, Italy was divided into city-states and partly occupied by mercenaries, with corruption, cruelty, and injustice being the norm). Drawing upon his extensive study of history and close observation of politicians of the day, Machiavelli argued in The Prince that a successful ruler must always do what is necessary. He never said, "the end justifies the means," but he did write that "in the actions of all men, and especially of princes, where there is no impartial arbiter, one must consider the final result."
For generations which followed, The Prince has stood as a treatise for leaders inclined to seize and use power by any means to ensure their survival and political control. It is a very well reasoned argument for autocratic rule, a near perfect paradigm of political realism.
One of the ironies of Machiavelli's life is that, while The Prince was written hurriedly in search of a job, his more exhaustive (and never completed) political work -- The Discourses -- has been largely ignored. In The Discourses, Machiavelli argues in favor of a democratic and republican form of government, expressing political ideals that did not become a reality until the 19th and 20th centuries.
Hence, in Machiavelli himself, we see the dynamic tension between doing whatever is necessary to achieve one's political goals and doing what is right in order to improve one's character and the well-being of the people.