Measurements of heavy flavour hadrons in PbPb collisions provide information about the heavy quark dynamics inside the quark-gluon plasma (QGP). Heavy quarks are sensitive to the transport properties of the medium and may interact with the QCD matter differently from light quarks. At low pT, heavy quarks provide a direct window on the in-medium QCD force. At high pT, the comparison of results for light and heavy particles provides insights into the expected flavor dependence of in-medium parton energy loss. Recently, the CMS collaboration established a comprehensive heavy flavor program in heavy ion collisions including the detection of charm and beauty mesons. Using the large statistics heavy ion data samples collected during LHC Run2, high precision open charm and beauty measurements are performed over a wide transverse momentum range. In this talk, the first measurement of the radial distributions of D0 mesons in jets in PbPb and pp collisions is presented, sensitive to the energy loss and diffusion of charm quarks in the QGP. Such effects for the bottom quarks are probed with the measurement of D0 mesons from b hadron decays in pp and PbPb collisions. In addition, the hadronisation of charm quarks and the importance of coalescence are constrained with the study of Lambda_c baryons in pp and PbPb collisions. Finally, results on Ds and Bs production are reported and compared to D0 and B+ production, respectively, with implications on the importance of the recombination mechanism due to strangeness enhancement.