Physical interaction of robots with their environment is a challenging problem because of the exchanged forces. Hybrid position/force control schemes often exhibit problems during the contact phase, whereas impedance control appears to be more simple and reliable, especially when impedance is shaped to be energetically passive. Even if recent technologies enable shaping the impedance of a robot, how best to plan impedance parameters for task execution remains an open question. In this paper we present an optimization-based approach to plan not only the robot motion but also its desired end-effector mechanical impedance. We show how our methodology is able to take into account the transition from free motion to a contact condition, typical of physical interaction tasks. Results are presented for planar and three-dimensional open-chain manipulator arms. The compositionality of mechanical impedance is exploited to deal with kinematic redundancy and multi-arm manipulation.