multipleCompilationError when parsing config file using ConfigSlurper - groovy

I need to access config file in my groovy code using ConfigSlurper as am using blocks inside the file to access each one depending on the user info !
so i need to use the properties in one block in the file ( based in the user info ) and set it to an object in my code !
I used something like this
def pc = ConfigSlurper().parse(newFile(configManager.config.priceInfo.filepath).toURI().toURL())
my file contains closures as blocks as following :
employee {
sth = 1
other =2
}
student {
sth = 10
other =20 }
default
{
sth = 100
other =200
}
I get multipleCompilationError exception when parsing the file !

i was using a block in my file with the name default !
employee {
sth = 1
other =2
}
student {
sth = 10
other =20
}
default{
sth = 100
other =200
}
This was causing this exception ! it seems like default is a keyword for a class in Groovy ! i changed 'default' to other name and it works now for me anyhow :)

Related

How to access a local using a variable in Terraform

I have the following code.
mymodule
variable "senses" {
type = string
}
locals {
sounds = {
"cat" = "meow"
"dog" = ["bark", "woof"]
}
}
output "noise" {
value = local[var.senses]["cat"]
}
call mymodule
module "mymodule" {
source = "../../../modules/mymodule"
senses = "sound"
}
returns error:
Error: Invalid reference
on ../../../modules/mymodule/outputs.tf line 62, in output "noise":
62: value = local[var.senses]["cat"]
The "local" object cannot be accessed directly. Instead, access one of its
attributes.
my code can't seem to handle
value = local[var.senses]["cat"]
Any suggestions on how i can get this to work?
I don't believe it's possible to use a variable to switch which local you're reading. I.e. local[var.senses] is the root of the issue.
If you refactor slightly and put your values inside a single, known, value--such as local.senses it should then let you do a key lookup within that value.
So, if you modify your locals to place your values in a senses key:
locals {
senses = {
"sounds" = {
"cat" = "meow"
"dog" = ["bark", "woof"]
}
}
}
and update your lookup to use that field:
value = local.senses[var.senses]["cat"]
Then I believe it will work, since your are doing a key lookup against a specific local rather than trying to dynamically select the local.

PHPmailer parseAddresses - How to get rid of "notice" messages

I'm trying to get rid of the following message in one of my scripts when using the PHPmailer parseAddresses function:
Notice: Unknown: Must use comma to separate addresses: xxx (errflg=3) in Unknown on line 0
$mailer = new PHPMailer(true);
try {
$a = $mailer->parseAddresses('aaa#aaa.aaa xxx');
}
finally {
...
}
I'm using PHP 7.0.8 with the following error handling presets:
declare(strict_types = 1);
error_reporting(E_ALL);
ini_set('display_errors', 'stdout');
I know that I can just stop the errors from being displayed but this doesn't seem to be the proper way to do. And of course I know that the provided email addresses in my example are not correct...
I'm not sure what you're complaining about: it's telling you you have malformed input when you provide malformed input! The way to avoid the error is not to pass in malformed input!
As the error says, it's expecting one or more addresses in comma-delimited RFC822 format (not what you provided), which might be something like:
xxx <aaa#aaa.aaa>, yyy <bbb#aaa.aaa>
If you don't provide data in that format, it will complain, as you're seeing. This is covered in the docs on the parseAddress method.
Are you expecting it to do something else?
PHPMailer writes notices to output, so you could start an output buffer and just flush it after your call. Something like:
$mailer = new PHPMailer(true);
try {
ob_start();
$a = $mailer->parseAddresses('aaa#aaa.aaa xxx');
//$notices = ob_get_contents();
ob_end_clean();
}
finally {
...
}
I had to deal with the same issues. Simply created a homemade solution that does mostly the same thing in a more flexible way. For anyone that is interested:
/**
* split_addresses Split a list of email addresses with potential validation
* Similar concept as PHPMailer->parseAddresses, but more forgiving
* #param $list - a list of comma delimited email addresses in simple or RFC822 format
* #param $default_name an optional name to add if not present
* #param $validate logical var to indicate to only accept validated emails
* #author Jacques Amar
* #copyright 2019 Amar Micro Inc.
*/
function split_addresses($list, $default_name='', $validate=true) {
$valid_arr = [];
if (empty($list)) { return $valid_arr; }
$split_arr = preg_split('/\s*,\s*/', $list);
foreach ($split_arr as $email_candidate) {
// Validate email_candidate if the form "first last <adrs#email.com>"
$actual_name = $default_name;
$actual_email = $email_candidate;
if (preg_match('/\s*(.+)\s*\<\s*([^#]+#.+)\s*\>/', $email_candidate, $actual_emails) == 1) {
$actual_name = $actual_emails[1];
$actual_email = $actual_emails[2];
}
if ($validate) {
if (filter_var($actual_email, FILTER_VALIDATE_EMAIL)) {
$valid_arr[] = ['address' => $actual_email, 'name' => $actual_name];
}
} else {
$valid_arr[] = ['address' => $actual_email, 'name' => $actual_name];
}
}
return $valid_arr;
}
Should be self explanatory

puppet defined types and variables

I am new to puppet and I am trying to write a module to manage .bashrc file of 10 users. The following code is ok to manage the file of 1 user. However, I am unable to change the code to manage files for 10 users. I tried using defined types and variable with no luck. Can sombody please suggest me the right way to do this.
init.pp:
class profile (
$bashrc = $profile::params::bashrc,
$bashrc_host = $profile::params::bashrc_host,
) inherits profile::params {
anchor { 'profile::begin': } ->
class { '::profile::config': } ->
anchor { 'profile::end': }
}
config.pp:
class profile::config inherits profile {
file { $bashrc:
ensure => file,
source => "puppet:///$bashrc_host",
}
params.pp:
class profile::params {
$bashrc_host = "modules/profile/$fqdn_user1_bashrc"
}
case $::osfamily {
'RedHat': {
$bashrc = '/home/user1/.bashrc'
}
}
This is not at all a job for a class. As you noted yourself in your most recent comment, this calls for a define actually.
Please don't use verbs in the names of your defines. Instead of defineuser, just do
define profile::user($host_name) {
}
Off the top of my hat, I'm not aware of a good pattern to use module parameters in your defines. You can however use the following pattern:
class profile(
$default_shell = $profile::params::default_shell,
$default_prompt = $profile::params::default_prompt,
$users = {}
) inherits profile::params {
$defaults = { shell => $default_shell, prompt => $default_prompt }
create_resources('profile::user', $users, $defaults)
}
What happens is
values are taken from params, or hiera, or the invoking manifest
these values are gathered in the $defaults array
for any resource in the $users hash that has no shell or prompt, this default is used
If your aim of this module is to learn puppet then:
Add a param user to your class profile::params
class profile::params {
$bashrc_host = "modules/profile/$fqdn_user1_bashrc"
$user = 'user1',
}
case $::osfamily {
'RedHat': {
$bashrc = "/home/$user/.bashrc"
}
}
After this, you can use a combination of array or hiera and ensure_resource This still is not the most elegant solution, but baby steps.
If your intend is to actually manage the bashrc for various users, I would recommend using a pre existing module such as account

How can I retrieve the build parameters from a queued job?

I would like to write a system groovy script which inspects the queued jobs in Jenkins, and extracts the build parameters (and build cause as a bonus) supplied as the job was scheduled. Ideas?
Specifically:
def q = Jenkins.instance.queue
q.items.each { println it.task.name }
retrieves the queued items. I can't for the life of me figure out where the build parameters live.
The closest I am getting is this:
def q = Jenkins.instance.queue
q.items.each {
println("${it.task.name}:")
it.task.properties.each { key, val ->
println(" ${key}=${val}")
}
}
This gets me this:
4.1.next-build-launcher:
com.sonyericsson.jenkins.plugins.bfa.model.ScannerJobProperty$ScannerJobPropertyDescriptor#b299407=com.sonyericsson.jenkins.plugins.bfa.model.ScannerJobProperty#5e04bfd7
com.chikli.hudson.plugin.naginator.NaginatorOptOutProperty$DescriptorImpl#40d04eaa=com.chikli.hudson.plugin.naginator.NaginatorOptOutProperty#16b308db
hudson.model.ParametersDefinitionProperty$DescriptorImpl#b744c43=hudson.mod el.ParametersDefinitionProperty#440a6d81
...
The params property of the queue element itself contains a string with the parameters in a property file format -- key=value with multiple parameters separated by newlines.
def q = Jenkins.instance.queue
q.items.each {
println("${it.task.name}:")
println("Parameters: ${it.params}")
}
yields:
dbacher params:
Parameters:
MyParameter=Hello world
BoolParameter=true
I'm no Groovy expert, but when exploring the Jenkins scripting interface, I've found the following functions to be very helpful:
def showProps(inst, prefix="Properties:") {
println prefix
for (prop in inst.properties) {
def pc = ""
if (prop.value != null) {
pc = prop.value.class
}
println(" $prop.key : $prop.value ($pc)")
}
}
def showMethods(inst, prefix="Methods:") {
println prefix
inst.metaClass.methods.name.unique().each {
println " $it"
}
}
The showProps function reveals that the queue element has another property named causes that you'll need to do some more decoding on:
causes : [hudson.model.Cause$UserIdCause#56af8f1c] (class java.util.Collections$UnmodifiableRandomAccessList)

Testing URLs in groovy

How can we check whether urls are working or not in groovy?
when we click a button, i will get all the urls from existing db from 'urls' table and need to check which url is working
Ex:
http://baldwinfilter.com/products/start.html - not working
http://www.subaru.com/ - working
and so many urls from db.
My aim is to get all urls and check which one is working and which is not .
do we need to check on the status it returns ??
Can any one help me giving idea ...
thanks in advance
sri...
You could use HttpBuilder like so:
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0-RC2' )
import groovyx.net.http.HTTPBuilder
def urls = [
"http://baldwinfilter.com/products/start.html",
"http://www.subaru.com/"
]
def up = urls.collect { url ->
try {
new HTTPBuilder( url ).get( path:'' ) { response ->
response.statusLine.statusCode == 200
}
}
catch( e ) { false }
}
println up

Resources