@@ -277,7 +277,7 @@ def _run_auth_playbook(plan, ansible_context, action, working_directory):
277277 auth_pairs .update ({
278278 (target_host , config .source_host , config .source_user ) for config in source_configs
279279 })
280-
280+ keys_to_delete = set ()
281281 for target_host , source_host , source_user in auth_pairs :
282282 _set_auth_key (
283283 AnsibleContext (None , plan .source_env ),
@@ -288,6 +288,13 @@ def _run_auth_playbook(plan, ansible_context, action, working_directory):
288288 working_directory ,
289289 remove = (action == 'remove' ),
290290 )
291+ if action == 'remove' :
292+ keys_to_delete .add (os .path .join (working_directory , 'id_rsa_{}.pub' .format (target_host )))
293+
294+ # Delete key files only after all authorized_key removals are complete
295+ for key_file in keys_to_delete :
296+ if os .path .exists (key_file ):
297+ os .remove (key_file )
291298
292299
293300def _set_auth_key (source_context , source_host , source_user ,
@@ -303,6 +310,3 @@ def _set_auth_key(source_context, source_host, source_user,
303310 state = 'absent' if remove else 'present'
304311 args = "user={} state={} key={{{{ lookup('file', '{}') }}}}" .format (source_user , state , key_path )
305312 run_ansible_module (source_context , source_host , 'authorized_key' , args )
306-
307- if remove :
308- os .remove (key_path )
0 commit comments