Home > other >  parsing in Ruby returns key not value
parsing in Ruby returns key not value

Time:02-15

I don't know Ruby at all. I just need to run Vagrantfile writtne in ruby and I get wrong values from config file.

Vagrantfile:

# -*- mode: ruby -*-
# vi: set ft=ruby :

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.

require 'yaml'
current_dir = File.dirname(File.expand_path(__FILE__))
settings = YAML.load_file("#{current_dir}/vars.yaml")

Vagrant.configure("2") do |config|
  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://vagrantcloud.com/search.

  config.vm.define "testsbox" do |testsbox|
    testsbox.vm.box = "generic/rhel8"
    testsbox.vm.hostname = "testsbox"
    testsbox.vm.provision "shell", privileged: true, 
      env: {
        "LOGIN" => settings['login'],
        "PASSWORD" => settings['password']
      },
      inline: <<-SHELL
      echo ****************SUBSCRIPTION**************
      echo --username=${LOGIN} --password=${PASSWORD}
      echo ****************SUBSCRIPTION**************

And while running that I get:

--username=login --password=password

vars.yaml file looks like this:

---
login:myuser
password:mysecretpassword

I have no clue what can be wrong. Any hits are welcome. code executed on Windows 10 but under git-bash. File vars.yaml was edited under Windows but format was changed from Windnows (CR LF) to (Unix (LF)

CodePudding user response:

Your YAML file has the wrong format - missing spaces after colons. The proper one would be:

---
login: myuser
password: mysecretpassword

Fix it and your code should work.

What happens in your code? Something like the following:

  1. YAML parser parses the wrong yaml file as a non-structured string, so your settings becomes something like "login:myuser password:mysecretpassword" (just a single string)
  2. For strings [] behaves as a pattern matching to some extent - it just returns the matched substring, if any. Look:
s = "login:myuser password:mysecretpassword"
s["login"] #=> "login"
s[/login/] #=> "login" # Yes, this works too
s["foo"] #=> nil
  • Related