Real world applications require robots to operate in unstructured environments. This kind of scenarios may lead to unexpected environmental contacts or undesired interactions, which may harm people or impair the robot. Adjusting the behavior of the system through impedance control techniques is an effective solution to these problems. However, selecting an adequate impedance is not a straightforward process. Normally, robot users manually tune the controller gains with trial and error methods. This approach is generally slow and requires practice. Moreover, complex tasks may require different impedance during different phases of the task. This paper introduces an optimization algorithm for online planning of the Cartesian robot impedance to adapt to changes in the task, robot configuration, expected disturbances, external environment and desired performance, without employing any direct force measurements. We provide an analytical solution leveraging the mass-spring-damper behavior that is conferred to the robot body by the Cartesian impedance controller. Stability during gains variation is also guaranteed. The effectiveness of the method is experimentally validated on the quadrupedal robot ANYmal. The variable impedance helps the robot to tackle challenging scenarios like walking on rough terrain and colliding with an obstacle.