Class: VagrantPlugins::DigitalOcean::Actions::SetupUser

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant-digitalocean/actions/setup_user.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, env) ⇒ SetupUser

Returns a new instance of SetupUser.



5
6
7
8
9
# File 'lib/vagrant-digitalocean/actions/setup_user.rb', line 5

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

Instance Method Details

#call(env) ⇒ Object



11
12
13
14
15
16
17
18
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/vagrant-digitalocean/actions/setup_user.rb', line 11

def call(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'

  env[:ui].info I18n.t('vagrant_digital_ocean.info.creating_user', {
    :user => user
  })

  # create user account
  @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

  # 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
  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 = DigitalOcean.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

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

  @app.call(env)
end