To constrain the formation history of an exoplanet, we need to know its chemical composition1-3. With an equilibrium temperature of about 4,050 kelvin4, the exoplanet KELT-9b (also known as HD 195689b) is an archetype of the class of ultrahot Jupiters that straddle the transition between stars and gas-giant exoplanets and are therefore useful for studying atmospheric chemistry. At these high temperatures, iron and several other transition metals are not sequestered in molecules or cloud particles and exist solely in their atomic forms5. However, despite being the most abundant transition metal in nature, iron has not hitherto been detected directly in an exoplanet because it is highly refractory. The high temperatures of KELT-9b imply that its atmosphere is a tightly constrained chemical system that is expected to be nearly in chemical equilibrium5 and cloud-free6,7, and it has been predicted that spectral lines of iron should be detectable in the visible range of wavelengths5. Here we report observations of neutral and singly ionized atomic iron (Fe and Fe+) and singly ionized atomic titanium (Ti+) in the atmosphere of KELT-9b. We identify these species using cross-correlation analysis8 of high-resolution spectra obtained as the exoplanet passed in front of its host star. Similar detections of metals in other ultrahot Jupiters will provide constraints for planetary formation theories.