Class: VagrantPlugins::Rimu::Actions::SetupUser

Inherits:
AbstractAction show all
Includes:
SshUtils
Defined in:
lib/vagrant-rimu/actions/setup_user.rb

Instance Method Summary collapse

Methods included from SshUtils

#public_key, #upload_key

Methods inherited from AbstractAction

#call

Constructor Details

#initialize(app, env) ⇒ SetupUser

Returns a new instance of SetupUser.



12
13
14
15
16
# File 'lib/vagrant-rimu/actions/setup_user.rb', line 12

def initialize(app, env)
  @app = app
  @machine = env[:machine]
  @logger = Log4r::Logger.new('vagrant::rimu::setup_user')
end

Instance Method Details

#create_user(env, user) ⇒ Object

def upload_key(user)

path = @machine.config.ssh.private_key_path
path = path[0] if path.is_a?(Array)
path = File.expand_path(path, @machine.env.root_path)
pub_key = public_key(path)
@machine.communicate.execute(<<-BASH)
  if ! grep '#{pub_key}' /home/#{user}/.ssh/authorized_keys; then
    echo '#{pub_key}' >> /home/#{user}/.ssh/authorized_keys;
  fi

  chown -R #{user} /home/#{user}/.ssh;
BASH

end



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/vagrant-rimu/actions/setup_user.rb', line 59

def create_user(env, user)
  env[:ui].info I18n.t('vagrant_rimu.creating_user', {
    :user => user
  })
  
  @machine.communicate.execute(<<-BASH)
    if ! (grep ^#{user}: /etc/passwd); then
      useradd -m -s /bin/bash #{user};
    fi
  BASH

  # grant user sudo access with no password requirement
  @machine.communicate.execute(<<-BASH)
    if ! (grep #{user} /etc/sudoers); then
      echo "#{user} ALL=(ALL:ALL) NOPASSWD: ALL" >> /etc/sudoers;
    else
      sed -i -e "/#{user}/ s/=.*/=(ALL:ALL) NOPASSWD: ALL/" /etc/sudoers;
    fi
  BASH
end

#execute(env) ⇒ Object

rubocop:disable Metrics/AbcSize



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/vagrant-rimu/actions/setup_user.rb', line 19

def execute(env)
  # check if setup is enabled
  return @app.call(env) unless @machine.provider_config.setup?

  # check if a username has been specified
  return @app.call(env) unless @machine.config.ssh.username

  # override ssh username to root temporarily
  user = @machine.config.ssh.username
  @machine.config.ssh.username = 'root'

  # create user account
  create_user(env, user)

  # create the .ssh directory in the users home
  @machine.communicate.execute("su #{user} -c 'mkdir -p ~/.ssh'")

  # add the specified key to the authorized keys file
  upload_key(env, user)

  # reset username
  @machine.config.ssh.username = user

  @app.call(env)
end