diff --git a/lib/ansible/runner/credential.rb b/lib/ansible/runner/credential.rb index 30813a97f88a..b62784a07c92 100644 --- a/lib/ansible/runner/credential.rb +++ b/lib/ansible/runner/credential.rb @@ -36,6 +36,10 @@ def write_config_files private + def initialize_password_data + File.exist?(password_file) ? YAML.load_file(password_file) : {} + end + def password_file File.join(env_dir, "passwords") end diff --git a/lib/ansible/runner/credential/machine_credential.rb b/lib/ansible/runner/credential/machine_credential.rb index 35d369483324..c131d44ab879 100644 --- a/lib/ansible/runner/credential/machine_credential.rb +++ b/lib/ansible/runner/credential/machine_credential.rb @@ -29,12 +29,14 @@ def become_args } end + SSH_KEY = "^SSH [pP]assword:".freeze + BECOME_KEY = "^BECOME [pP]assword:".freeze + SSH_UNLOCK_KEY = "^Enter passphrase for [a-zA-Z0-9\-\/]+\/ssh_key_data:".freeze def write_password_file - password_hash = { - "^SSH [pP]assword:" => auth.password, - "^BECOME [pP]assword:" => auth.become_password, - "^Enter passphrase for [a-zA-Z0-9\-\/]+\/ssh_key_data:" => auth.ssh_key_unlock - }.delete_blanks + password_hash = initialize_password_data + password_hash[SSH_KEY] = auth.password if auth.password + password_hash[BECOME_KEY] = auth.become_password if auth.become_password + password_hash[SSH_UNLOCK_KEY] = auth.ssh_key_unlock if auth.ssh_key_unlock File.write(password_file, password_hash.to_yaml) if password_hash.present? end diff --git a/spec/lib/ansible/runner/credential/machine_credential_spec.rb b/spec/lib/ansible/runner/credential/machine_credential_spec.rb index 22be280497f0..90d2940ea2c2 100644 --- a/spec/lib/ansible/runner/credential/machine_credential_spec.rb +++ b/spec/lib/ansible/runner/credential/machine_credential_spec.rb @@ -101,6 +101,40 @@ def password_hash expect(password_hash["^SSH [pP]assword:"]).to eq(password) end + + context "with an existing password_file" do + let(:ssh_unlock_key) { "^Enter passphrase for [a-zA-Z0-9\-\/]+\/ssh_key_data:" } + def existing_env_password_file(data) + cred # initialize the dir + File.write password_file, data.to_yaml + end + + it "clobbers existing ssh key unlock keys" do + existing_data = { ssh_unlock_key => "hunter2" } + expected_data = { + "^SSH [pP]assword:" => "secret", + "^BECOME [pP]assword:" => "othersecret", + ssh_unlock_key => "keypass" + } + existing_env_password_file(existing_data) + cred.write_config_files + + expect(password_hash).to eq(expected_data) + end + + it "appends data if not setting ssh_unlock_key" do + auth.update!(:auth_key_password => nil) + existing_data = { ssh_unlock_key => "hunter2" } + added_data = { + "^SSH [pP]assword:" => "secret", + "^BECOME [pP]assword:" => "othersecret" + } + existing_env_password_file(existing_data) + cred.write_config_files + + expect(password_hash).to eq(existing_data.merge(added_data)) + end + end end end end