diff --git a/lib/chef/knife/ec2_server_create.rb b/lib/chef/knife/ec2_server_create.rb index ff9b2356..ed15da71 100644 --- a/lib/chef/knife/ec2_server_create.rb +++ b/lib/chef/knife/ec2_server_create.rb @@ -1177,7 +1177,7 @@ def create_volume_tags(hashed_volume_tags) end def create_key_pair - key_name = "#{config[:connection_user]}-#{SecureRandom.hex(10)}" + key_name = "#{config[:connection_user].delete(".\\")}-#{SecureRandom.hex(10)}" key_pair = ec2_connection.create_key_pair({ key_name: key_name, }) diff --git a/spec/unit/ec2_server_create_spec.rb b/spec/unit/ec2_server_create_spec.rb index 89bfe74d..99e14cf8 100644 --- a/spec/unit/ec2_server_create_spec.rb +++ b/spec/unit/ec2_server_create_spec.rb @@ -527,6 +527,22 @@ end end + shared_examples "create keypair" do + let(:file_path) { "/root/.chef/#{keypair.key_name}.pem" } + let(:file_like_object) { double(path: file_path) } + before do + Chef::Config[:knife].delete(:ssh_key_name) + allow(File).to receive(:open).with(file_path, "w+").and_return(file_like_object) + end + + it "calls create_key_pair method and Generate new keypair" do + expect(ec2_connection).to receive(:create_key_pair).and_return(keypair) + knife_ec2_create.plugin_validate_options! + expect(Chef::Config[:knife][:ssh_key_name]).to eq(keypair.key_name) + expect(Chef::Config[:knife][:ssh_identity_file]).to eq(file_path) + end + end + describe "S3 secret test cases" do before do Chef::Config[:knife][:s3_secret] = @@ -627,21 +643,28 @@ key_name: "ubuntu-07f692a0d8d1fcc4a086" ) end - let(:file_path) { "/root/.chef/#{keypair.key_name}.pem" } - let(:file_like_object) { double(path: file_path) } before do knife_ec2_create.config[:connection_user] = "ubuntu" - Chef::Config[:knife].delete(:ssh_key_name) - allow(File).to receive(:open).with(file_path, "w+").and_return(file_like_object) end - it "should be call create_key_pair method and Generate new keypair" do - expect(ec2_connection).to receive(:create_key_pair).and_return(keypair) - knife_ec2_create.plugin_validate_options! - expect(Chef::Config[:knife][:ssh_key_name]).to eq(keypair.key_name) - expect(Chef::Config[:knife][:ssh_identity_file]).to eq(file_path) + it_behaves_like "create keypair" + end + + context "when user name is passed with system domain (.\\) and ssh_key_name option is not provided on the CLI" do + let(:keypair) do + Aws::EC2::Types::KeyPair.new( + key_fingerprint: "a9:00:ec:1d:bd:80:ae:00", + key_material: "test private key", + key_name: "a_local_user-07f692a0d8d1fcc4a086" + ) end + + before do + knife_ec2_create.config[:connection_user] = ".\\a_local_user" + end + + it_behaves_like "create keypair" end context "when ssh_key_name option is passed on the CLI" do