Passing parameters to Capistrano

前端 未结 5 815
感情败类
感情败类 2021-01-31 16:44

I\'m looking into the possibility of using Capistrano as a generic deploy solution. By \"generic\", I mean not-rails. I\'m not happy with the quality of the documentation I\'m f

5条回答
  •  误落风尘
    2021-01-31 17:19

    Update. Regarding passing parameters to Capistrano 3 task only.

    I know this question is quite old but still pops up first on Google when searching for passing parameters to Capistrano task. Unfortunately, the fantastic answer provided by Jamie Sutherland is no longer valid with Capistrano 3. Before you waste your time trying it out except the results to be like below:

    cap test:parameter -s branch=master 
    

    outputs :

    cap aborted!
    OptionParser::AmbiguousOption: ambiguous option: -s
    OptionParser::InvalidOption: invalid option: s
    

    and

    cap test:parameter -S branch=master 
    

    outputs:

    invalid option: -S
    

    The valid answers for Capistrano 3 provided by @senz and Brad Dwyer you can find by clicking this gold link: Capistrano 3 pulling command line arguments

    For completeness see the code below to find out about two option you have.

    1st option:

    You can iterate tasks with the key and value as you do with regular hashes:

    desc "This task accepts optional parameters"
    
    task :task_with_params, :first_param, :second_param do |task_name, parameter|
      run_locally do
        puts "Task name: #{task_name}"
        puts "First parameter: #{parameter[:first_param]}"
        puts "Second parameter: #{parameter[:second_param]}"
      end
    end
    

    Make sure there is no space between parameters when you call cap:

    cap production task_with_params[one,two]
    

    2nd option:

    While you call any task, you can assign environmental variables and then call them from the code:

    set :first_param, ENV['first_env'] || 'first default'
    set :second_param, ENV['second_env'] || 'second default'
    
    desc "This task accepts optional parameters"
    task :task_with_env_params do
      run_locally do
        puts "First parameter: #{fetch(:first_param)}"
        puts "Second parameter: #{fetch(:second_param)}"
      end
    end
    

    To assign environmental variables, call cap like bellow:

    cap production task_with_env_params first_env=one second_env=two
    

    Hope that will save you some time.

提交回复
热议问题