rubyyamlazure-yaml-pipelines

Passing a JSON string as a command line argument to a Ruby script?


I'm currently working on editing an Azure DevOps pipeline script, and I've encountered a roadblock while attempting to refactor the existing implementation.

I want to pass a JSON string as an argument to a Ruby script that's invoked by the YAML.

I've tried many different ways to achieve this with no luck. My scripting skills are rusty, so there's that.

Would appreciate it if anyone can point me in the right direction?

Thank you.

JSON: {"name": "John", "age": 10, "city": "New York"}

Script:

require 'json'

namespace: test do
  task :getConfigs, [:json_string] do |task, args|
        json_string = args[:json_string]
        configs = JSON.parse(json_string)
        val1 = configs['name']
        val2 = configs['age']
        puts "#{val1} is #{val2} years old."
    end

YAML:

- script: bash -i -c 'rake test:getConfigs["$json_data"] //json_data being a Pipeline variable.

How I invoke it in Terminal locally:

 rake "test:getConfigs[\"{\"name\": \"John\", \"age\": 10, \"city\": \"New York\"}\"]"

or the other variant without escaping characters.

I keep getting the error JSON::ParserError: 767: unexpected token at 'name": "John"'


Solution

  • What you need to do here is to escape the comas also and remove the double quotes inside the square brackets.

    The below command should work.

    rake "test:getConfigs[{\"name\": \"John\"\, \"age\": 10\, \"city\": \"New York\"}]"