A post-buckling analysis of a constant or variable length spatial elastica constrained by a cylindrical wall is performed for a first time by adopting an optimal control methodology. Its application in a constrained buckling analysis is shown to be superior when compared to other numerical techniques, as the inclusion of the unilateral constraints is feasible without the need of any special treatment or approximation. Furthermore, the formulation is simple and the optimal configurations of the spatial elastica can be also obtained by considering the minimization condition of the Hamiltonian. We first present the optimal control formulation for the constrained buckling problem of a constant length spatial elastica, including its associated necessary optimality conditions that constitute the Pontryagin's minimum principle. This fundamental constrained buckling problem is used to validate the proposed methodology. The general buckling problem of a variable length spatial elastica is then analyzed that consists of two parts; (1) the solution of the optimal control problem that involves the inserted elastica inside the conduit and (2) the derivation of the buckling load by taking into account the generation of the configurational or Eshelby-like force at the insertion point of the sliding sleeve. A variety of examples are accordingly presented, where the effects of factors, such as the presence of uniform pressure, the clearance of the wall, and the torsional rigidity, on the buckling response of the spatial elastica, are investigated.