Ruby (Chef) Unable to pass a hash array into a Chef resource - ruby

I'm trying to create a recipe to deploy Remote Desktop Services to Windows Servers, everything is working as expected apart from the Application deployment resource I created - it's a simple resource but I'm having a lot of issues passing the applications to be deployed as a hash array.
attributes\default.rb
default['app']['app_options'] = [{
app1:{
connection_broker: 'serv-01',
options: {
collectionname: 'Terminal Services', alias: 'Acrobat', displayname: 'Adobe Acrobat', filepath: 'C:\\Program Files (x86)\\Adobe\\Acrobat 11.0\\Acrobat\\Acrobat.exe', filevirtualpath: 'C:\\Program Files (x86)\\Adobe\\Acrobat 11.0\\Acrobat\\Acrobat.exe', ommandlinesetting: 'DoNotAllow', iconindex: 0, iconpath: '\\\\serv-01\\C$\\Program Files (x86)\\Adobe\\Acrobat 11.0\\Acrobat\\Acrobat.exe', usergroups: ['domain\\group'], showinwebaccess: 1
}
},
app2:{
connection_broker: 'serv-01',
options: {
collectionname: 'Terminal Services', alias: 'Accounts', displayname: 'Accounts', foldername: 'Accounts', filepath: 'D:\\Accounts\\Accounts.bat', filevirtualpath: 'D:\\Accounts\\Accounts.bat', commandlinesetting: 'DoNotAllow', iconindex: 0, iconpath: 'C:\\Windows\\System32\\cmd.exe', usergroups: ['domain\\group'], showinwebaccess: 1
}
}
}]
recipes\remote_desktop.rb
rdapps = node.read('app', 'app_options') || []
rdapps.each do |app|
remote_desktop_apps app['options']['alias'] do
action :create
connection_broker app['connection_broker']
app_options app['options']
end
end
resources\remote_desktop_apps.rb
resource_name :remote_desktop_apps
property :connection_broker, String,
desired_state: false
property :app_options, [String, Hash, Array],
desired_state: false
action :create do
app_options.each do |k,v|
script << "New-RDRemoteApp -ConnectionBroker "#{connection_broker}" {-#{k.to_s.capitalize} #{v}}.join(' ')}"
end
end
When running the recipe in Test Kitchen, I get the below error:
================================================================================
Recipe Compile Error in C:/Users/ADMINI~1/AppData/Local/Temp/kitchen/cache/cookbooks/windows_/recipes/remote_desktop.rb
================================================================================
NoMethodError
-------------
undefined method `[]' for nil:NilClass
Edit
Thanks to #seshadri_c for the help past the first hurdle, I've hit another issue which seems related to the attributes.
Here is the output of a kitchen converge
================================================================================
Error executing action `create` on resource 'remote_desktop_apps[Acrobat]'
================================================================================
Chef::Exceptions::ValidationFailed
----------------------------------
name is a required property
Resource Declaration:
---------------------
# In C:/Users/ADMINI~1/AppData/Local/Temp/kitchen/cache/cookbooks/rh_windows/recipes/remote_desktop.rb
76: remote_desktop_apps app['options']['alias'] do
77: action :create
78: connection_broker app['connection_broker']
79: app_options app['options']
80: end
81: end
Compiled Resource:
------------------
# Declared in C:/Users/ADMINI~1/AppData/Local/Temp/kitchen/cache/cookbooks/rh_windows/recipes/remote_desktop.rb:76:in `block in from_file'
remote_desktop_apps("Acrobat") do
action [:create]
default_guard_interpreter :default
declared_type :remote_desktop_apps
cookbook_name "windows_"
recipe_name "remote_desktop"
connection_broker "serv-01"
app_options {"collectionname"=>"Terminal Services", "alias"=>"Acrobat", "displayname"=>"Adobe Acrobat", "filepath"=>"C:\\Program Files (x86)\\Adobe\\Acrobat 11.0\\Acrobat\\Acrobat.exe", "filevirtualpath"=>"C:\\Program Files (x86)\\Adobe\\Acrobat 11.0\\Acrobat\\Acrobat.exe", "commandlinesetting"=>"DoNotAllow", "iconindex"=>"0", "iconpath"=>"\\\\serv-01\\C$\\Program Files (x86)\\Adobe\\Acrobat 11.0\\Acrobat\\Acrobat.exe", "usergroups"=>["domain\\group"], "showinwebaccess"=>"1"}
end
Then there's this message at the end of the run:
FATAL: Chef::Exceptions::ValidationFailed: remote_desktop_apps[Acrobat] (rh_windows::remote_desktop line 76) had an error: Chef::Exceptions::ValidationFailed: name is a required property
$$$$$$ Exception calling "Read" with "3" argument(s): "Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection."
At line:100 char:11
$$$$$$ + if ($fs.Read($bytes, 0, $fs.Length) -gt 0) {
$$$$$$ + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentException

The reason for this error is that the array of hashes has different keys app1 and app2. So each time we iterate over rdapps we'll get a different key. This way we won't be able get the sub-elements such as app['options']['alias'].
So you can adjust the attribute to something like:
default['app']['app_options'] = [
{
connection_broker: 'serv-01',
options: {
collectionname: 'Terminal Services',
alias: 'Acrobat',
displayname: 'Adobe Acrobat',
filepath: 'C:\\Program Files (x86)\\Adobe\\Acrobat 11.0\\Acrobat\\Acrobat.exe',
filevirtualpath: 'C:\\Program Files (x86)\\Adobe\\Acrobat 11.0\\Acrobat\\Acrobat.exe',
ommandlinesetting: 'DoNotAllow',
iconindex: 0,
iconpath: '\\\\serv-01\\C$\\Program Files (x86)\\Adobe\\Acrobat 11.0\\Acrobat\\Acrobat.exe',
usergroups: ['domain\\group'],
showinwebaccess: 1
}
},
{
connection_broker: 'serv-01',
options: {
collectionname: 'Terminal Services',
alias: 'Accounts',
displayname: 'Accounts',
foldername: 'Accounts',
filepath: 'D:\\Accounts\\Accounts.bat',
filevirtualpath: 'D:\\Accounts\\Accounts.bat',
commandlinesetting: 'DoNotAllow',
iconindex: 0,
iconpath: 'C:\\Windows\\System32\\cmd.exe',
usergroups: ['domain\\group'],
showinwebaccess: 1
}
}
]
Then we can get this working as expected:
rdapps = node.read('app', 'app_options') || []
rdapps.each do |app|
remote_desktop_apps app['options']['alias'] do
action :create
connection_broker app['connection_broker']
app_options app['options']
end
end

Related

Create empty file using Drive API

I create this code, using this reference https://developers.google.com/drive/api/quickstart/ruby
class Drive
def initialize
#drive_service = Google::Apis::DriveV3::DriveService.new
#drive_service.client_options.application_name = APPLICATION_NAME
#drive_service.authorization = authorize
end
def create_file
data = { 'name': "My new Sheet #{Time.now.strftime('%d/%m/%Y %H:%M')}",
'mimeType': 'application/vnd.google-apps.spreadsheet' }
#drive_service.create_file(data).execute
end
def share_file
"to be filled"
end
def list_files
response = #drive_service.list_files(page_size: 10, fields: 'nextPageToken, files(id, name)')
puts 'Files:'
puts 'No files found' if response.files.empty?
response.files.each do |file|
puts "#{file.name} (#{file.id})"
end
end
end
The method list_files works well, but the create_file return me this error:
Traceback (most recent call last):
2: from quickstart.rb:79:in `<main>'
1: from quickstart.rb:60:in `create_file'
/home/vagrant/.rvm/gems/ruby-2.7.2/gems/google-api-client-0.53.0/generated/google/apis/drive_v3/service.rb:895:in `create_file': unknown keywords: :name, :mimeType (ArgumentError)
I created it based on this create method reference: https://googleapis.dev/ruby/google-api-client/latest/Google/Apis/DriveV3/DriveService.html#create_file-instance_method
but I still can't get it to work, what could be wrong?
I tried changing the creation to: #drive_service.create_file(file_object = data).execute
Let's compare your code,
data = { 'name': "My new Sheet ...
#drive_service.create_file(data).execute
vs. the documented method signature.
`create_file(file_object = nil, enforce_single_parent: nil, ignore_default_visibility: nil, include_permissions_for_view: nil, keep_revision_forever: nil, ocr_language: nil, supports_all_drives: nil, supports_team_drives: nil, use_content_as_indexable_text: nil, fields: nil, quota_user: nil, user_ip: nil, upload_source: nil, content_type: nil, options: nil) {|result, err| ... } ⇒ Google::Apis::DriveV3::File`
- file_object (Google::Apis::DriveV3::File) (defaults to: nil)
The first argument should be an instance of Google::Apis::DriveV3::File, but you are passing a Hash.
According to this documentation:
When supplying hashes for request objects. If it is the last argument
to a method, some versions of Ruby will interpret the hash as keyword
arguments. To prevent this, appending an empty hash as an extra
parameter will avoid misinterpretation.
file = {id: '123', title: 'My document', labels: { starred: true }}
file = drive.create_file(file) # Raises ArgumentError: unknown keywords: id, title, labels
file = drive.create_file(file, {}) # Returns a Drive::File instance
In your code, just add {} as 2nd parameter for create_file.
From:
#drive_service.create_file(data)
To:
#drive_service.create_file(data, {})
Let me know if this works on your end.

include and If statement inside a for each

Clients can upload up to three files. I want to set the status of the file based on the description they choose. The upload works fine and a static status is fine, but a dynamic one raises an error.
def build_document_objects
[:first, :second, :third].each do |doc|
d = "#{doc}_document"
if self.send("#{d}_type") == "this Type"
doc_status = 'one'
else
doc_status = 'two'
self.send("#{d}=", user.documents.new(
description: "Foo",
file: self.send("#{d}_file"),
document_type: self.send("#{d}_type"),
status: doc_status
))
end
end
end
When I run this, I get the following exception:
undefined method `save'' for nil:NilClass'))
If I do this:
def build_document_objects
[:first, :second, :third].each do |doc|
# "first_document"
d = "#{doc}_document"
if self.send("#{d}_type") == "this Type"
doc_status = 'one'
else
doc_status = 'two'
end # change where the IF ends
self.send("#{d}=", user.documents.new(
description: "Foo",
file: self.send("#{d}_file"),
document_type: self.send("#{d}_type"),
status: doc_status
))
end
end
if the file description is not this type, the records will be saved. However, with:
if self.send("#{d}_type") == "this Type"
I get the exception. The record will not be saved as there is no status present.
It appears I am nuts
def build_document_objects
[:first, :second, :third].each do |doc|
# "first_document"
d = "#{doc}_document"
if self.send("#{d}_type") == "this Type"
doc_status = 'one'
else
doc_status = 'two'
end # change where the IF ends
self.send("#{d}=", user.documents.new(
description: "Foo",
file: self.send("#{d}_file"),
document_type: self.send("#{d}_type"),
status: doc_status
))
end
end
works fine
the if just needs to be in the method properly.

Error: $cron_values is false, not a hash or array

Vagrant installs and starts the Centos 6.6 VM up correctly, but fails to provision it with this error message:
Error: $cron_values is false, not a hash or array at /tmp/vagrant-puppet/manifests-893fcda21077f5a583c2dbbba8515c0a/nodes/Cron.pp:3 on node localhost.localdomain
Just before that this was displayed:
==> default: Running provisioner: puppet...
==> default: Running Puppet with site.pp...
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/composer/lib/facter/composer_home.rb
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/concat/lib/facter/concat_basedir.rb
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/firewall/lib/facter/ip6tables_version.rb
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/firewall/lib/facter/iptables_persistent_version.rb
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/firewall/lib/facter/iptables_version.rb
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/git/lib/facter/git_exec_path.rb
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/git/lib/facter/git_version.rb
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/php/lib/facter/php_fact_extension_dir.rb
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/php/lib/facter/php_fact_version.rb
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/puppi/lib/facter/last_run.rb
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/puppi/lib/facter/puppi_projects.rb
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/puppi/lib/facter/windows_common_appdata.rb
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/rabbitmq/lib/facter/rabbitmq_erlang_cookie.rb
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/rvm/lib/facter/rvm_installed.rb
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/rvm/lib/facter/rvm_version.rb
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/staging/lib/facter/staging_http_get.rb
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/staging/lib/facter/staging_windir.rb
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/stdlib/lib/facter/facter_dot_d.rb
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/stdlib/lib/facter/pe_version.rb
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/stdlib/lib/facter/puppet_vardir.rb
==> default: Info: Loading facts in /tmp/vagrant-puppet/modules-419a158586c48436c8f5c2349fe39c11/stdlib/lib/facter/root_home.rb
Honestly, I'm not sure where to even look for the problem. I can SSH into the VM and that part seems to work correctly. Apache doesn't seem to be installed yet as the host does not resolve.
I'm also not sure if there is more information that could be of benefit? If so, I am more than happy to provide it. There does not seem to be very many people at all who have experienced this problem. Even if you don't know the solution, I'd be grateful if you could at least provide some direction on where to look for perhaps a more verbose log (I ran vagrant provision --debug but the error logs didn't make much more sense there), or something that could get me started?
I am running this machine with Parallels as the provider.
Any ideas?
Update:
The VagrantFile is generated by puppet (or really PuPHPet). Here is the config.yaml file:
vagrantfile-local:
vm:
box: puphpet/centos65-x64
box_url: puphpet/centos65-x64
hostname: ''
memory: '512'
cpus: '1'
chosen_provider: parallels
network:
private_network: 192.168.58.101
forwarded_port:
48IqH2aTQkz4:
host: '9321'
guest: '22'
post_up_message: ''
provider:
virtualbox:
modifyvm:
natdnshostresolver1: on
vmware:
numvcpus: 1
parallels:
cpus: 1
provision:
puppet:
manifests_path: puphpet/puppet
manifest_file: site.pp
module_path: puphpet/puppet/modules
options:
- '--verbose'
- '--hiera_config /vagrant/puphpet/puppet/hiera.yaml'
- '--parser future'
synced_folder:
jzVfnoa6cO3T:
owner: ''
group: ''
source: ./
target: /Users/myname/Sites/website/
sync_type: nfs
rsync:
auto: 'false'
usable_port_range:
start: 10200
stop: 10500
ssh:
host: null
port: null
private_key_path: null
username: vagrant
guest_port: null
keep_alive: true
forward_agent: false
forward_x11: false
shell: 'bash -l'
vagrant:
host: detect
server:
install: '1'
packages:
- ImageMagick
- vim-common
- php-soap
firewall:
install: '1'
rules: null
apache:
install: '1'
settings:
user: www-data
group: www-data
default_vhost: true
manage_user: false
manage_group: false
sendfile: 0
modules:
- rewrite
vhosts:
MvR5v9C4Vsuh:
servername: myserver.mag
serveraliases:
- www.awesome.dev
docroot: /Users/myname/Sites/sitename/base/
port: '80'
setenv:
- 'APP_ENV dev'
override:
- All
options:
- Indexes
- FollowSymLinks
- MultiViews
engine: ''
custom_fragment: ''
ssl_cert: ''
ssl_key: ''
ssl_chain: ''
ssl_certs_dir: ''
mod_pagespeed: 0
php:
install: '1'
version: '55'
composer: '1'
composer_home: ''
modules:
php:
- cli
- intl
- mcrypt
pear: { }
pecl:
- pecl_http
- imagick
ini:
display_errors: On
error_reporting: '-1'
session.save_path: /var/lib/php/session
timezone: America/Chicago
mod_php: 0
xdebug:
install: '1'
settings:
xdebug.default_enable: '1'
xdebug.remote_autostart: '0'
xdebug.remote_connect_back: '1'
xdebug.remote_enable: '1'
xdebug.remote_handler: dbgp
xdebug.remote_port: '9000'
ruby:
install: '1'
versions: { }
nodejs:
install: '0'
npm_packages: { }
python:
install: '1'
packages: { }
versions: { }
mysql:
install: '1'
override_options: { }
root_password: root
adminer: 0
databases:
ouWYyTlD0olg:
grant:
- ALL
name: db_name
host: localhost
user: user_name
password: password
sql_file: ../databases/output.sql
redis:
install: '1'
settings:
conf_port: '6379'
VagrantFile:
require 'yaml'
dir = File.dirname(File.expand_path(__FILE__))
configValues = YAML.load_file("#{dir}/puphpet/config.yaml")
data = configValues['vagrantfile-local']
Vagrant.require_version '>= 1.6.0'
Vagrant.configure('2') do |config|
config.vm.box = "#{data['vm']['box']}"
config.vm.box_url = "#{data['vm']['box_url']}"
if data['vm']['hostname'].to_s.strip.length != 0
config.vm.hostname = "#{data['vm']['hostname']}"
end
if data['vm']['network']['private_network'].to_s != ''
config.vm.network 'private_network', ip: "#{data['vm']['network']['private_network']}"
end
data['vm']['network']['forwarded_port'].each do |i, port|
if port['guest'] != '' && port['host'] != ''
config.vm.network :forwarded_port, guest: port['guest'].to_i, host: port['host'].to_i
end
end
if !data['vm']['post_up_message'].nil?
config.vm.post_up_message = "#{data['vm']['post_up_message']}"
end
if Vagrant.has_plugin?('vagrant-hostmanager')
hosts = Array.new()
if !configValues['apache']['install'].nil? &&
configValues['apache']['install'].to_i == 1 &&
configValues['apache']['vhosts'].is_a?(Hash)
configValues['apache']['vhosts'].each do |i, vhost|
hosts.push(vhost['servername'])
if vhost['serveraliases'].is_a?(Array)
vhost['serveraliases'].each do |vhost_alias|
hosts.push(vhost_alias)
end
end
end
elsif !configValues['nginx']['install'].nil? &&
configValues['nginx']['install'].to_i == 1 &&
configValues['nginx']['vhosts'].is_a?(Hash)
configValues['nginx']['vhosts'].each do |i, vhost|
hosts.push(vhost['server_name'])
if vhost['server_aliases'].is_a?(Array)
vhost['server_aliases'].each do |x, vhost_alias|
hosts.push(vhost_alias)
end
end
end
end
if hosts.any?
if config.vm.hostname.to_s.strip.length == 0
config.vm.hostname = 'puphpet-dev-machine'
end
config.hostmanager.enabled = true
config.hostmanager.manage_host = true
config.hostmanager.ignore_private_ip = false
config.hostmanager.include_offline = false
config.hostmanager.aliases = hosts
end
end
if Vagrant.has_plugin?('vagrant-cachier')
config.cache.scope = :box
end
data['vm']['synced_folder'].each do |i, folder|
if folder['source'] != '' && folder['target'] != ''
sync_owner = !folder['sync_owner'].nil? ? folder['sync_owner'] : 'www-data'
sync_group = !folder['sync_group'].nil? ? folder['sync_group'] : 'www-data'
if folder['sync_type'] == 'nfs'
config.vm.synced_folder "#{folder['source']}", "#{folder['target']}", id: "#{i}", type: 'nfs'
if Vagrant.has_plugin?('vagrant-bindfs')
config.bindfs.bind_folder "#{folder['target']}", "/mnt/vagrant-#{i}"
end
elsif folder['sync_type'] == 'smb'
config.vm.synced_folder "#{folder['source']}", "#{folder['target']}", id: "#{i}", type: 'smb'
elsif folder['sync_type'] == 'rsync'
rsync_args = !folder['rsync']['args'].nil? ? folder['rsync']['args'] : ['--verbose', '--archive', '-z']
rsync_auto = !folder['rsync']['auto'].nil? ? folder['rsync']['auto'] : true
rsync_exclude = !folder['rsync']['exclude'].nil? ? folder['rsync']['exclude'] : ['.vagrant/']
config.vm.synced_folder "#{folder['source']}", "#{folder['target']}", id: "#{i}",
rsync__args: rsync_args, rsync__exclude: rsync_exclude, rsync__auto: rsync_auto, type: 'rsync', group: sync_group, owner: sync_owner
elsif data['vm']['chosen_provider'] == 'parallels'
config.vm.synced_folder "#{folder['source']}", "#{folder['target']}", id: "#{i}",
group: sync_group, owner: sync_owner, mount_options: ['share']
else
config.vm.synced_folder "#{folder['source']}", "#{folder['target']}", id: "#{i}",
group: sync_group, owner: sync_owner, mount_options: ['dmode=775', 'fmode=764']
end
end
end
config.vm.usable_port_range = (data['vm']['usable_port_range']['start'].to_i..data['vm']['usable_port_range']['stop'].to_i)
if data['vm']['chosen_provider'].empty? || data['vm']['chosen_provider'] == 'virtualbox'
ENV['VAGRANT_DEFAULT_PROVIDER'] = 'virtualbox'
config.vm.provider :virtualbox do |virtualbox|
data['vm']['provider']['virtualbox']['modifyvm'].each do |key, value|
if key == 'memory'
next
end
if key == 'cpus'
next
end
if key == 'natdnshostresolver1'
value = value ? 'on' : 'off'
end
virtualbox.customize ['modifyvm', :id, "--#{key}", "#{value}"]
end
virtualbox.customize ['modifyvm', :id, '--memory', "#{data['vm']['memory']}"]
virtualbox.customize ['modifyvm', :id, '--cpus', "#{data['vm']['cpus']}"]
if data['vm']['provider']['virtualbox']['modifyvm']['name'].nil? ||
data['vm']['provider']['virtualbox']['modifyvm']['name'].empty?
if data['vm']['hostname'].to_s.strip.length != 0
virtualbox.customize ['modifyvm', :id, '--name', config.vm.hostname]
end
end
end
end
if data['vm']['chosen_provider'] == 'vmware_fusion' || data['vm']['chosen_provider'] == 'vmware_workstation'
ENV['VAGRANT_DEFAULT_PROVIDER'] = (data['vm']['chosen_provider'] == 'vmware_fusion') ? 'vmware_fusion' : 'vmware_workstation'
config.vm.provider :vmware_fusion do |v, override|
data['vm']['provider']['vmware'].each do |key, value|
if key == 'memsize'
next
end
if key == 'cpus'
next
end
v.vmx["#{key}"] = "#{value}"
end
v.vmx['memsize'] = "#{data['vm']['memory']}"
v.vmx['numvcpus'] = "#{data['vm']['cpus']}"
if data['vm']['provider']['vmware']['displayName'].nil? ||
data['vm']['provider']['vmware']['displayName'].empty?
if data['vm']['hostname'].to_s.strip.length != 0
v.vmx['displayName'] = config.vm.hostname
end
end
end
end
if data['vm']['chosen_provider'] == 'parallels'
ENV['VAGRANT_DEFAULT_PROVIDER'] = 'parallels'
config.vm.provider 'parallels' do |v|
data['vm']['provider']['parallels'].each do |key, value|
if key == 'memsize'
next
end
if key == 'cpus'
next
end
v.customize ['set', :id, "--#{key}", "#{value}"]
end
v.memory = "#{data['vm']['memory']}"
v.cpus = "#{data['vm']['cpus']}"
if data['vm']['provider']['parallels']['name'].nil? ||
data['vm']['provider']['parallels']['name'].empty?
if data['vm']['hostname'].to_s.strip.length != 0
v.name = config.vm.hostname
end
end
end
end
ssh_username = !data['ssh']['username'].nil? ? data['ssh']['username'] : 'vagrant'
config.vm.provision 'shell' do |s|
s.path = 'puphpet/shell/initial-setup.sh'
s.args = '/vagrant/puphpet'
end
config.vm.provision 'shell' do |kg|
kg.path = 'puphpet/shell/ssh-keygen.sh'
kg.args = "#{ssh_username}"
end
config.vm.provision :shell, :path => 'puphpet/shell/install-ruby.sh'
config.vm.provision :shell, :path => 'puphpet/shell/install-puppet.sh'
config.vm.provision :puppet do |puppet|
puppet.facter = {
'ssh_username' => "#{ssh_username}",
'provisioner_type' => ENV['VAGRANT_DEFAULT_PROVIDER'],
'vm_target_key' => 'vagrantfile-local',
}
puppet.manifests_path = "#{data['vm']['provision']['puppet']['manifests_path']}"
puppet.manifest_file = "#{data['vm']['provision']['puppet']['manifest_file']}"
puppet.module_path = "#{data['vm']['provision']['puppet']['module_path']}"
if !data['vm']['provision']['puppet']['options'].empty?
puppet.options = data['vm']['provision']['puppet']['options']
end
end
config.vm.provision :shell do |s|
s.path = 'puphpet/shell/execute-files.sh'
s.args = ['exec-once', 'exec-always']
end
config.vm.provision :shell, run: 'always' do |s|
s.path = 'puphpet/shell/execute-files.sh'
s.args = ['startup-once', 'startup-always']
end
config.vm.provision :shell, :path => 'puphpet/shell/important-notices.sh'
customKey = "#{dir}/files/dot/ssh/id_rsa"
vagrantKey = "#{dir}/.vagrant/machines/default/#{ENV['VAGRANT_DEFAULT_PROVIDER']}/private_key"
if File.file?(customKey)
config.ssh.private_key_path = [
customKey,
"#{ENV['HOME']}/.vagrant.d/insecure_private_key"
]
if File.file?(vagrantKey) and ! FileUtils.compare_file(customKey, vagrantKey)
File.delete(vagrantKey)
end
if ! File.directory?(File.dirname(vagrantKey))
FileUtils.mkdir_p(File.dirname(vagrantKey))
end
if ! File.file?(vagrantKey)
FileUtils.cp(customKey, vagrantKey)
end
end
if !data['ssh']['host'].nil?
config.ssh.host = "#{data['ssh']['host']}"
end
if !data['ssh']['port'].nil?
config.ssh.port = "#{data['ssh']['port']}"
end
if !data['ssh']['username'].nil?
config.ssh.username = "#{data['ssh']['username']}"
end
if !data['ssh']['guest_port'].nil?
config.ssh.guest_port = data['ssh']['guest_port']
end
if !data['ssh']['shell'].nil?
config.ssh.shell = "#{data['ssh']['shell']}"
end
if !data['ssh']['keep_alive'].nil?
config.ssh.keep_alive = data['ssh']['keep_alive']
end
if !data['ssh']['forward_agent'].nil?
config.ssh.forward_agent = data['ssh']['forward_agent']
end
if !data['ssh']['forward_x11'].nil?
config.ssh.forward_x11 = data['ssh']['forward_x11']
end
if !data['vagrant']['host'].nil?
config.vagrant.host = data['vagrant']['host'].gsub(':', '').intern
end
end
I recently came across this problem myself and here is how I fixed it. When you create a Puphpet config file, and do not specify any cron jobs, this error is created.
To fix it make your cron key in config.yaml look like one of these:
Option #1 (for kicking off the Magento cron job):
cron:
install: '1'
jobs:
cj_lfgowfjsb51y:
name: magento
user: ''
command: '/bin/sh /var/www/sites/cron.sh'
minute: '*/5'
hour: '*'
weekday: '*'
month: '*'
monthday: ''
Option #2
cron:
install:'1'
jobs: []

Rufus scheduler syntax error

Original code:
require 'oci8'
SCHEDULER.every '10s', :first_in => 0 do |job|
begin
conn = OCI8.new('apps','apps');
mylist = Hash.new
conn.exec("select full_name, count(*) from per_all_people_f
where rownum < 6 group by first_name") do |r|
mylist[r[0]] = { label: r[0], value: r[1].to_i.to_s }
end
send_event('emp-list', { items: mylist.values })
conn.logoff
rescue Exception => e
puts e.message
end
end
Running ruby oratest1.rb gives following errors:
oratest1.rb:11: syntax error
mylist[r[0]] = { label: r[0], value: r[1].to_i.to_s }
^
oratest1.rb:11: syntax error
mylist[r[0]] = { label: r[0], value: r[1].to_i.to_s }
^
oratest1.rb:11: syntax error
oratest1.rb:13: syntax error
send_event('emp-list', { items: mylist.values })
^
oratest1.rb:13: syntax error
send_event('emp-list', { items: mylist.values })
^
oratest1.rb:17: syntax error
rescue Exception => e
^
oratest1.rb:21: syntax error
You are probably using ruby 1.8. This hash syntax was included on 1.9 onwards.
To make sure, run ruby -v and check the output.
If you using ruby prior to 1.9, you must use the following syntax for hashes:
mylist[r[0]] = { :label => r[0], :value => r[1].to_i.to_s }
The syntax that you are using is valid in ruby 1.9 and onwards!

report error when GetoptLong::REQUIRED_ARGUMENT is not input in Ruby

I have this very simple Ruby code:
#!/res/software/pkg/ruby-2.0.0/bin/ruby -w
require( 'getoptlong' )
opts = GetoptLong.new( [ '--netlist_file', GetoptLong::REQUIRED_ARGUMENT ] )
puts 'error in getting netlist' << opts.error_message.to_s()
The output is:
cs059:Florida_domains$ ~/test.rb
error in getting netlist
How can I error out when any argument that is GetoptLong::REQUIRED_ARGUMENT is NOT input?
Is there a generic way?
Thanks.
require( 'getoptlong' )
begin
opts = GetoptLong.new( [ '--netlist_file', GetoptLong::REQUIRED_ARGUMENT ] )
opts.each do |option, arg|
case option
when "--netlist_file"
#assign the argument to my_var or do whatever you need to do with it
my_var = arg
end
rescue => e
puts "Error in arguments"
puts e.to_s
end

Resources