【问题标题】:How to precompile assets with Chef?如何使用 Chef 预编译资产?
【发布时间】:2013-06-07 20:31:30
【问题描述】:

OpsWorks 不会在部署时预编译资产。我在this thread 中找到了这个食谱,但我认为它并不完整,或者因为我收到关于找不到release_path 的错误而遗漏了一些东西。

precompile.rb:

Chef::Log.info("Running deploy/before_migrate.rb...")

Chef::Log.info("Symlinking #{release_path}/public/assets to #{new_resource.deploy_to}/shared/assets")

link "#{release_path}/public/assets" do
  to "#{new_resource.deploy_to}/shared/assets"
end

rails_env = new_resource.environment["RAILS_ENV"]
Chef::Log.info("Precompiling assets for RAILS_ENV=#{rails_env}...")

execute "rake assets:precompile" do
  cwd release_path
  command "bundle exec rake assets:precompile"
  environment "RAILS_ENV" => rails_env
end

日志:

undefined local variable or method `release_path' for ....

有什么想法吗?我根本不认识 Chef,我正在努力解决这个问题。

【问题讨论】:

  • 看来您必须提供 release_path,即您的 Rails 应用程序应驻留在指定主机上的路径。
  • 每次部署应用程序时都会发生变化。它是动态的,所以我无法对其进行硬编码。

标签: ruby-on-rails chef-infra aws-opsworks


【解决方案1】:

在 OpsWorks 支持开箱即用的资产管道之前,您可以这样做。 在您的 Rails 应用程序中创建一个包含以下内容的文件 deploy/before_symlink.rb。

run "cd #{release_path} && RAILS_ENV=production bundle exec rake assets:precompile"

如果您将 Rails 应用程序部署到不同的环境,请更改 RAILS_ENV。

如果您使用 NGINX/Unicorn 堆栈,则必须修改 /assets 资源。 只需将以下内容复制到食谱中名为 unicorn/templates/default/nginx_unicorn_web_app.erb 的文件中即可。

upstream unicorn_<%= @application[:domains].first %> {
 server unix:<%= @application[:deploy_to]%>/shared/sockets/unicorn.sock fail_timeout=0;
}

server {
  listen 80;
  server_name <%= @application[:domains].join(" ") %> <%= node[:hostname] %>;
  access_log <%= node[:nginx][:log_dir] %>/<%= @application[:domains].first %>.access.log;

  keepalive_timeout 5;

  root <%= @application[:absolute_document_root] %>;

  <% if @application[:nginx] && @application[:nginx][:client_max_body_size] %>
    client_max_body_size <%= @application[:nginx][:client_max_body_size] %>;
  <% end %>

  location / {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    # If you don't find the filename in the static files
    # Then request it from the unicorn server
    if (!-f $request_filename) {
      proxy_pass http://unicorn_<%= @application[:domains].first %>;
      break;
    }
  }

  location /nginx_status {
    stub_status on;
    access_log off;
    allow 127.0.0.1;
    deny all;
  }

  location ~ ^/assets/ {
    expires 1y;
    add_header Cache-Control public;

    add_header ETag "";
    break;
  }

  error_page 500 502 503 504 /500.html;
  location = /500.html {
    root <%= @application[:absolute_document_root] %>;
  }
}

<% if @application[:ssl_support] %>
server {
  listen   443;
  server_name <%= @application[:domains].join(" ") %> <%= node[:hostname] %>;
  access_log <%= node[:nginx][:log_dir] %>/<%= @application[:domains].first %>-ssl.access.log;

  ssl on;
  ssl_certificate /etc/nginx/ssl/<%= @application[:domains].first %>.crt;
  ssl_certificate_key /etc/nginx/ssl/<%= @application[:domains].first %>.key;
  <% if @application[:ssl_certificate_ca] -%>
  ssl_client_certificate /etc/nginx/ssl/<%= @application[:domains].first %>.ca;
  <% end -%>

  keepalive_timeout 5;

  root <%= @application[:absolute_document_root] %>;

  <% if @application[:nginx] && @application[:nginx][:client_max_body_size] %>
    client_max_body_size <%= @application[:nginx][:client_max_body_size] %>;
  <% end %>

  location / {
    proxy_set_header X-Forwarded-Proto https;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    # If you don't find the filename in the static files
    # Then request it from the unicorn server
    if (!-f $request_filename) {
      proxy_pass http://unicorn_<%= @application[:domains].first %>;
      break;
    }
  }

  location ~ ^/assets/ {
    expires 1y;
    add_header Cache-Control public;

    add_header ETag "";
    break;
  }

  error_page 500 502 503 504 /500.html;
  location = /500.html {
    root <%= @application[:absolute_document_root] %>;
  }
}
<% end %>

如果您使用 Apache2/Passenger 堆栈,则必须修改 /assets 资源。 只需将以下内容复制到食谱中名为 passenger_apache2/templates/default/web_app.conf.erb 的文件中即可。

<VirtualHost *:80>
  ServerName <%= @params[:server_name] %>
  <% if @params[:server_aliases] && !@params[:server_aliases].empty? -%>
  ServerAlias <% @params[:server_aliases].each do |a| %><%= "#{a}" %> <% end %>
  <% end -%>

  <% if @params[:mounted_at] -%>
  DocumentRoot /var/www
  <%= @params[:deploy][:passenger_handler] -%>BaseURI <%= @params[:mounted_at] %>
  <% else -%>
  DocumentRoot <%= @params[:docroot] %>
  <%= @params[:deploy][:passenger_handler] -%>BaseURI /
  <% end -%>
  <%= @params[:deploy][:passenger_handler] -%>Env <%= @params[:rails_env] %>

  <Directory <%= @params[:docroot] %>>
    Options FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
  </Directory>

  <Directory ~ "\.svn">
    Order allow,deny
    Deny from all
  </Directory>

  <Directory ~ "\.git">
    Order allow,deny
    Deny from all
  </Directory>

  <LocationMatch "^/assets/.*$">
    Header unset ETag
    FileETag None
    # RFC says only cache for 1 year
    ExpiresActive On
    ExpiresDefault "access plus 1 year"
  </LocationMatch>

  LogLevel info
  ErrorLog <%= node[:apache][:log_dir] %>/<%= @params[:name] %>-error.log
  CustomLog <%= node[:apache][:log_dir] %>/<%= @params[:name] %>-access.log combined
  CustomLog <%= node[:apache][:log_dir] %>/<%= @params[:name] %>-ganglia.log ganglia

  FileETag none

  RewriteEngine On
  Include <%= @params[:rewrite_config] %>*
  RewriteLog <%= node[:apache][:log_dir] %>/<%= @application_name %>-rewrite.log
  RewriteLogLevel 0

  # Canonical host
  #RewriteCond %{HTTP_HOST}   !^<%= @params[:server_name] %> [NC]
  #RewriteCond %{HTTP_HOST}   !^$
  #RewriteRule ^/(.*)$        http://<%= @params[:server_name] %>/$1 [L,R=301]

  RewriteCond %{REQUEST_URI} !\.(css|gif|jpg|jpeg|png)$
  RewriteCond %{DOCUMENT_ROOT}/system/maintenance.html -f
  RewriteCond %{SCRIPT_FILENAME} !maintenance.html
  RewriteRule ^.*$ /system/maintenance.html [L]

  Include <%= @params[:local_config] %>*
</VirtualHost>

<% if node[:deploy][@application_name][:ssl_support] -%>
<VirtualHost *:443>
  ServerName <%= @params[:server_name] %>
  <% if @params[:server_aliases] && !@params[:server_aliases].empty? -%>
  ServerAlias <% @params[:server_aliases].each do |a| %><%= "#{a}" %> <% end %>
  <% end -%>

  SSLEngine on
  SSLProxyEngine on
  SSLCertificateFile <%= node[:apache][:dir] %>/ssl/<%= @params[:server_name] %>.crt
  SSLCertificateKeyFile <%= node[:apache][:dir] %>/ssl/<%= @params[:server_name] %>.key
  <% if @params[:ssl_certificate_ca] -%>
  SSLCACertificateFile <%= node[:apache][:dir] %>/ssl/<%= @params[:server_name] %>.ca
  <% end -%>
  SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0

  <% if @params[:mounted_at] -%>
  DocumentRoot /var/www
  <%= @params[:deploy][:passenger_handler] -%>BaseURI <%= @params[:mounted_at] %>
  <% else -%>
  DocumentRoot <%= @params[:docroot] %>
  <%= @params[:deploy][:passenger_handler] -%>BaseURI /
  <% end -%>
  <%= @params[:deploy][:passenger_handler] -%>Env <%= @params[:rails_env] %>

  <Directory <%= @params[:docroot] %>>
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
  </Directory>

  <Directory ~ "\.svn">
    Order allow,deny
    Deny from all
  </Directory>

  <Directory ~ "\.git">
    Order allow,deny
    Deny from all
  </Directory>

  <LocationMatch "^/assets/.*$">
    Header unset ETag
    FileETag None
    # RFC says only cache for 1 year
    ExpiresActive On
    ExpiresDefault "access plus 1 year"
  </LocationMatch>

  LogLevel info
  ErrorLog <%= node[:apache][:log_dir] %>/<%= @params[:name] %>-ssl-error.log
  CustomLog <%= node[:apache][:log_dir] %>/<%= @params[:name] %>-ssl-access.log combined
  CustomLog <%= node[:apache][:log_dir] %>/<%= @params[:name] %>-ssl-ganglia.log ganglia

  FileETag none

  RewriteEngine On
  Include <%= @params[:rewrite_config] %>-ssl*
  RewriteLog <%= node[:apache][:log_dir] %>/<%= @application_name %>-ssl-rewrite.log
  RewriteLogLevel 0

  # Canonical host
  #RewriteCond %{HTTP_HOST}   !^<%= @params[:server_name] %> [NC]
  #RewriteCond %{HTTP_HOST}   !^$
  #RewriteRule ^/(.*)$        http://<%= @params[:server_name] %>/$1 [L,R=301]

  RewriteCond %{REQUEST_URI} !\.(css|gif|jpg|jpeg|png)$
  RewriteCond %{DOCUMENT_ROOT}/system/maintenance.html -f
  RewriteCond %{SCRIPT_FILENAME} !maintenance.html
  RewriteRule ^.*$ /system/maintenance.html [L]

  Include <%= @params[:local_config] %>-ssl*
</VirtualHost>
<% end -%>

如果您有任何问题,请随时提出。

最好的 丹尼尔

编辑:

或者你只是复制我快速开发的这本食谱https://github.com/neonlex/massive-octo-computing-machine。 但 OpsWorks 未来应该会默认支持这一点。

【讨论】:

  • 谢谢你,丹尼尔。我设法找出最终对我有用的东西(答案贴在下面),现在它正在起作用,我非常害怕尝试你的食谱,因为害怕破坏它。我很想知道你的答案中的独角兽步骤是什么,以及你对我提出的任何想法。谢谢!
  • @neonlex 我使用了您更新的存储库,它工作正常。我尝试用github.com/neonlex/massive-octo-computing-machine/blob/master/… 中的执行配方dsl 替换ruby shell 命令,给出错误未定义的方法“执行”。任何想法为什么它不起作用!
  • 我不需要修改 /assets 或任何烹饪书籍。简单地让 before_symlink.rb 为我工作。我在 nginx 和 unicorn 上,使用默认的 Opsworks 配方。
  • 我真的不喜欢用特定的 Deploy 配置/责任污染我的源代码...在应用程序的源代码中创建 deploy/before_symlink.rb,而不是纯粹使用 Chef 或 OpsWorks 做某事,感觉不对
【解决方案2】:

请注意,如果您使用 new OpsWorks feature 将环境变量传递给 Rails 应用程序,则需要将这些变量包含在您的 rake 调用中(因为它们不会永久来源到部署用户的环境中)。

我在deploy/before_migrate.rb 中执行以下操作(基于this article 和this recipe):

Chef::Log.info("Precompiling assets for RAILS_ENV=" \
               "#{new_resource.environment['RAILS_ENV']}...")

execute 'rake assets:precompile' do
  cwd release_path
  command 'bundle exec rake assets:precompile'
  environment new_resource.environment
end

【讨论】:

    【解决方案3】:

    我对 OpsWorks 和 Chef 知之甚少,但这就是我为使其正常工作所做的工作。

    首先,我必须创建一个在 setup 事件期间运行的 rails 配方,以便为资产创建符号链接目录。这位于 OpsWorks 可以访问的公共存储库中。

    cookbooks/rails/recipes/symlink_assets.rb:

    node[:deploy].each do |application, deploy|
      Chef::Log.info("Ensuring shared/assets directory for #{application} app...")
    
      directory "#{deploy[:deploy_to]}/shared/assets" do
        group deploy[:group]
        owner deploy[:user]
        mode 0775
        action :create
        recursive true
      end
    end
    

    然后,在我的应用中,我必须创建 deploy/before_migrate.rb:

    Chef::Log.info("Running deploy/before_migrate.rb...")
    
    Chef::Log.info("Symlinking #{release_path}/public/assets to #{new_resource.deploy_to}/shared/assets")
    
    link "#{release_path}/public/assets" do
      to "#{new_resource.deploy_to}/shared/assets"
    end
    
    rails_env = new_resource.environment["RAILS_ENV"]
    Chef::Log.info("Precompiling assets for RAILS_ENV=#{rails_env}...")
    
    execute "rake assets:precompile" do
      cwd release_path
      command "bundle exec rake assets:precompile"
      environment "RAILS_ENV" => rails_env
    end
    

    这在部署过程中被调用并编译资产。

    【讨论】:

    • 出于某种原因,这仍然会尝试重建我的一些脚本,即使我已经为共享资产目录。
    【解决方案4】:

    在 AWS Opsworks 中,我使用以下配方:

    execute 'rake assets:precompile' do
      cwd "#{node[:deploy_to]}/current"
      user 'root'
      command 'bundle exec rake assets:precompile'
      environment 'RAILS_ENV' => node[:environment_variables][:RAILS_ENV]
    end
    

    我以 root 身份运行此命令,因为实例需要正确的权限才能写入 release 路径。以deploy 用户身份运行命令会呈现权限被拒绝错误。

    【讨论】:

    • 我对权限被拒绝错误感到困惑,因为 OpsWorks 似乎将部署用户设置为 /shared 中所有内容的所有者。结果这个用户仍然使用所有者根创建它的文件(通过它的文件掩码设置),所以它创建了一个日志文件,然后不能编辑它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多