Skip to content

Instantly share code, notes, and snippets.

@shireeshj
Forked from thbar/_forward-agent-with-chef.rb
Created September 10, 2013 05:30
Show Gist options
  • Save shireeshj/6505334 to your computer and use it in GitHub Desktop.
Save shireeshj/6505334 to your computer and use it in GitHub Desktop.
# scenario:
# - you work from a dev account that has git authentication with keys in place
# - you use a sudoer account (first_user) to ssh and run chef on a server
# - the chef recipes deploy an application under a second_user
# - first_user and second_user don't have git keys in place and you want to use forwarding
# initial run (bootstrapping maybe)
include_recipe 'helper'
class Chef::Resource
include FileHelpers
end
service 'ssh' do
action :nothing
end
ruby_block "allow-ssh-auth-sock passing" do
block do
if file_replace("/etc/sudoers", /^Defaults(.*)$/, "Defaults env_keep=SSH_AUTH_SOCK")
notifies :restart, resources(:service => 'ssh'), :immediately
end
end
end
group "deploy" do
members ['root',first_user]
end
# following runs
ssh_auth_sock = ENV['SSH_AUTH_SOCK']
group "deploy" do
action :modify
members [second_user]
append true
end
bash "update-rights-for-forwarding" do
code <<-EOF
set -e
chgrp deploy #{ssh_auth_sock}
chgrp deploy #{File.dirname(ssh_auth_sock)}
chmod 770 #{File.dirname(ssh_auth_sock)}
chmod 770 #{File.expand_path(File.dirname(ssh_auth_sock+'/..'))}
EOF
only_if { File.exists?(ssh_auth_sock) }
end
bash "test-as-first-user" do
code "git ls-remote xxx@yyy:/.../git/project.git HEAD"
user first_user
end
bash "test-as-second-user" do
environment "SSH_AUTH_SOCK" => ssh_auth_sock
code "git ls-remote xxx@yyy:/.../git/project.git HEAD"
end
# alternatively to two runs, add sudo -u second_user to the last bash
module FileHelpers
def file_append(file, string)
unless File.read(file).include? string
File.open(file, 'a') { |f| f.puts string }
end
end
# return true if the file has changed
def file_replace(file, match, replace)
file_contents = File.read(file)
unless file_contents.include? replace
file_contents.gsub!(match, replace)
File.open(file, 'w') { |f| f.puts file_contents }
true
else
false
end
end
def file_remove(file, match)
file_contents = File.read(file)
if file_contents.include? match
file_contents.gsub!(match, "")
File.open(file, 'w') { |f| f.puts file_contents }
end
end
def file_write(file, string)
File.open(file, 'w') { |f| f.puts string }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment