Skip to content

Instantly share code, notes, and snippets.

@ttuan

ttuan/Capfile Secret

Created December 22, 2019 05:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ttuan/035247d0d6282be3f2af0bebd1229ff6 to your computer and use it in GitHub Desktop.
Save ttuan/035247d0d6282be3f2af0bebd1229ff6 to your computer and use it in GitHub Desktop.
Capistrano config
require "capistrano/setup"
require "capistrano/deploy"
require "capistrano/rvm"
require "capistrano/bundler"
require "capistrano/rails/assets"
require "capistrano/rails/migrations"
require "capistrano/puma"
require "capistrano/scm/git"
require "capistrano/sidekiq"
install_plugin Capistrano::SCM::Git
install_plugin Capistrano::Puma
# Load custom tasks from `lib/capistrano/tasks` if you have any defined
Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }
# config/deploy.rb
require_relative "deploy/aws_utils"
lock "3.9.1"
set :application, "indahash-nttd"
set :repo_url, "git@github.com:framgia/indahash-nttd.git"
set :assets_roles, [:app]
set :puma_roles, [:app]
set :sidekiq_roles, [:worker]
set :deploy_ref, ENV["DEPLOY_REF"]
set :deploy_ref_type, ENV["DEPLOY_REF_TYPE"]
set :bundle_binstubs, nil
if fetch(:deploy_ref)
set :branch, fetch(:deploy_ref)
else
raise "Please set $DEPLOY_REF"
end
platform = ENV["PLATFORM"].empty? ? "aws" : ENV["PLATFORM"]
set :platform, platform
set :rvm_ruby_version, "2.6.3"
set :deploy_to, "/usr/local/rails_apps/#{fetch :application}"
set :deployer, ENV["DEPLOYER"] || "deploy"
set :instances, ec2_targets unless ENV["LOCAL_DEPLOY"]
set :deploy_via, :remote_cache
set :puma_bind, "unix://#{shared_path}/tmp/sockets/puma.sock"
set :puma_state, "#{shared_path}/tmp/pids/puma.state"
set :puma_pid, "#{shared_path}/tmp/pids/puma.pid"
set :puma_preload_app, true
set :puma_worker_timeout, nil
set :puma_init_active_record, true
set :default_env, File.read("/home/deploy/.env").split("\n").inject({}){|h,var|
k_v = var.gsub("export ","").split("=")
h.merge k_v.first.downcase => k_v.last.gsub("\"", "")
}.symbolize_keys
default_linked_files = [
"config/secrets.yml",
"config/database.yml"
]
append :linked_files, *default_linked_files
set :linked_dirs, %w(log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system public/uploads)
namespace :deploy do
desc "create database"
task :create_database do
on roles(:db) do |host|
within "#{release_path}" do
with rails_env: ENV["RAILS_ENV"] do
execute :rake, "db:create"
end
end
end
end
before :migrate, :create_database
desc "link dotenv"
task :link_dotenv do
on roles(:app, :worker) do
upload! "/home/deploy/.env", "/home/deploy/.env" if ENV["UPDATE_ENV"]
execute "ln -s /home/deploy/.env #{release_path}/.env"
end
end
after :migrate, :link_dotenv
desc "Restart application"
task :restart do
on roles(:app), in: :sequence, wait: 5 do
within release_path do
invoke! "puma:restart"
end
end
on roles(:worker), in: :sequence, wait: 5 do
within release_path do
invoke! "sidekiq:restart"
end
end
end
desc "update ec2 tags"
task :update_ec2_tags do
if fetch(:platform) == "aws"
branch = fetch(:branch)
ref_type = fetch(:deploy_ref_type)
last_commit = fetch(:current_revision)
update_ec2_tags ref_type, branch, last_commit
end
end
after :publishing, :update_ec2_tags
end
namespace :maintenance do
desc "Maintenance start"
task :start do
on roles(:app) do
within release_path do
execute :rake, "maintenance:start"
end
end
end
desc "Maintenance stop"
task :stop do
on roles(:app) do
within release_path do
execute :rake, "maintenance:end"
end
end
end
end
default: &default
adapter: mysql2
encoding: utf8mb4
charset: utf8mb4
collation: utf8mb4_bin
pool: <%= ENV.fetch("DATABASE_POOL") { 25 } %>
host: <%= ENV["DATABASE_HOSTNAME"] %>
username: <%= ENV["DATABASE_USERNAME"] %>
password: <%= ENV["DATABASE_PASSWORD"] %>
port: 3306
socket: /var/run/mysqld/mysqld.sock
development:
<<: *default
database: test-project_development
staging:
<<: *default
database: test-project_staging
test:
<<: *default
database: test-project_test
production:
<<: *default
database: <%= ENV["DATABASE_NAME"] %>
# config/environments/staging.rb
# frozen_string_literal: true
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = Uglifier.new(harmony: true)
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options)
config.active_storage.service = :local
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id, :remote_ip, lambda { |req| Time.current } ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "indahash-nttd_#{Rails.env}"
config.active_job.queue_adapter = :sidekiq
config.action_mailer.perform_deliveries = true
config.action_mailer.perform_caching = false
config.action_mailer.delivery_method = :smtp
config.action_mailer.default_url_options = {host: ENV["HOST"]}
config.action_mailer.smtp_settings = {
address: ENV["MAIL_ADDRESS"],
port: ENV["MAIL_PORT"],
domain: ENV["HOST"],
user_name: ENV["MAIL_USERNAME"],
password: ENV["MAIL_PASSWORD"],
authentication: "plain",
enable_starttls_auto: true
}
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
# config/deploy/staging.rb
if ENV["LOCAL_DEPLOY"]
server "localhost", user: "deploy", roles: %w[app db worker]
else
instances = fetch(:instances)
instances.each do |role_name, hosts|
roles = [role_name]
hosts.each_with_index do |host, i|
roles << "db" if i.zero?
server host, user: "deploy", roles: roles
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment