Jenkins Configure Global Security from bash script - bash

I'd like to configure Jenkins from a bash script.
The action is to enable global security and use Unix user/group database for it.
Can I just copy some configuration XMLs and restart the server? Or there is a groovy script to do that?

That's it:
import jenkins.model.*
import hudson.security.*
def instance = Jenkins.getInstance()
def unixRealm = new PAMSecurityRealm("ssh")
instance.setSecurityRealm(unixRealm)
instance.setAuthorizationStrategy(new FullControlOnceLoggedInAuthorizationStrategy())
instance.save()

Related

No environment configuration found. DefaultAzureCredential()

I am trying to use this python sample to authenticate a client with an Azure Service
# pip install azure-identity
from azure.identity import DefaultAzureCredential
# pip install azure-mgmt-compute
from azure.mgmt.compute import ComputeManagementClient
# pip install azure-mgmt-network
from azure.mgmt.network import NetworkManagementClient
# pip install azure-mgmt-resource
from azure.mgmt.resource import ResourceManagementClient
SUBSCRIPTION_ID = creds_obj['SUBSCRIPTION_ID']
# Create client
# For other authentication approaches, please see: https://pypi.org/project/azure-identity/
resource_client = ResourceManagementClient(
credential=DefaultAzureCredential(),
subscription_id=SUBSCRIPTION_ID
)
network_client = NetworkManagementClient(
credential=DefaultAzureCredential(),
subscription_id=SUBSCRIPTION_ID
)
compute_client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id=SUBSCRIPTION_ID
)
I keep getting No environment configuration found.
The code sample is directly from the microsoft github: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/resources/azure-mgmt-resource/azure/mgmt/resource/resources/_resource_management_client.py. Ideally I would like to manage this configuration using environment variables or a config file. Is there any way to do this?
When using Azure Identity client library for Python, DefaultAzureCredential attempts to authenticate via the following mechanisms in this order, stopping when one succeeds:
You could set Environment Variables to fix it.
from azure.identity import DefaultAzureCredential
credential=DefaultAzureCredential()
Or set the properties in config and use ClientSecretCredential to create credential.
from azure.identity import ClientSecretCredential
subscription_id = creds_obj["AZURE_SUBSCRIPTION_ID"]
tenant_id = creds_obj["AZURE_TENANT_ID"]
client_id = creds_obj["AZURE_CLIENT_ID"]
client_secret = creds_obj["AZURE_CLIENT_SECRET"]
credential = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
I was having somewhat similar trouble following this Azure key vault tutorial which brought me here.
The solution I found was overriding the default values in the DefaultAzureCredential() constructor.
https://learn.microsoft.com/en-us/python/api/azure-identity/azure.identity.defaultazurecredential?view=azure-python
For reasons people far smarter than me will be able to explain I found that even though I had credentials from the azure cli it was not using those and instead looking for environment_credentials, which I did not have. So it threw an exception.
Once I set the exclude_environment_credential argument to True it then looked instead for the managed_identity_credentials, again which I did not have.
Eventually when I force excluded all credentials other than those from the cli it worked ok for me
I hope this helps someone. Those with more experience please feel free to edit as you see fit

Setup RedisCache on IKS

I have setup IKS and logged in to one of the container's command line.
I need to execute a script on that container that connects to RedisCache's client.
Here is the script (testScript.py) I want to execute -
import redis
r = redis.Redis(host=‘master.some.path.of.redis.url.amazonaws.com’, port=6323, password=‘somePassword’, ssl=True)
r.set(‘foo’, ‘bar’)
value = r.get(‘foo’)
print(value)
I need help in understanding how to be able to setup Redis on the IKS.

Jenkins ver. 2.121.3 - Delete file from workspace

In Jenkins ver. 2.121.3 using pipeline trying to delete the file. Its giving script not permitted error message.
Is there a alternate way to delete the file in Jenkins with-out using OS command?
Scripts not permitted to use method java.io.File delete. Administrators can decide whether to approve or reject this signature.
[Pipeline] End of Pipeline
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method java.io.File delete
Pipeline code
stage('Delete test.zip file') {
if (fileExists('test.zip')) {
new File('test.zip').delete()
} else {
println "test.zip file not found"
}
}
There are several alternative ways:
By means of jenkins shared library you can wrap this code up to function or class:
#!/usr/bin/groovy
package org.utils
class PipelineUtils {
static def deleteFile(String name) { new File(name).delete() }
}
in your pipeline script, you need to import the library:
#Library('your-jenkins-library')_
import static org.utils.PipelineUtils.*
deleteFile('test.zip')
As #Sean has suggested to approve the script via "Manage Jenkins > In-process Script Approval".
There is File Operations Plugin:
fileOperations([script.fileDeleteOperation(excludes: '', includes: 'test.zip')])
There is Workspace Cleanup Plugin, but you need to find suitable exclude-patterns, otherwise this will clean all files:
def new_exclude_patterns = [[pattern: ".git/**", type: 'EXCLUDE']]
cleanWs deleteDirs: false, skipWhenFailed: false, patterns: new_exclude_patterns
If you are running pipeline on linux slave (or windows slave with sh in path), you may use the below call to avoid interactive prompts.
sh(""" rm -rf "$directory" """)
Navigate to /scriptApproval/ (Manage Jenkins > In-process Script Approval) and approve the script.
Another way since Java 1.7/Groovy ?.? is:
Files.delete(Path.of(FQFN))

Access to build environment variables from a groovy script in a Jenkins build step (Windows)

I'm using Scriptler plugin, so I can run a groovy script as a build step. My Jenkins slaves are running on windows in service mode. With scriptler, I don't need to use windows batch scripts.
But I have trouble to get the environment variables in a build step... This is working:
System.getenv("BASE")
Where BASE is part of the env-vars on jenkins startup. However, I would like to get
%JOB_NAME%
If I'm adding an "Execute Windows batch command" build step:
echo %JOB_NAME%
It works.
If I'm adding a scriptler script as a build step with the same settings:
println "JOB_NAME: " + System.getenv("JOB_NAME")
I'm getting:
JOB_NAME: null
So how can I reach the injected environment variables from a groovy script as a build step?
build and listener objects are presenting during system groovy execution. You can do this:
def myVar = build.getEnvironment(listener).get('myVar')
You might be able to get them like this:
def thr = Thread.currentThread()
def build = thr?.executable
def envVarsMap = build.parent.builds[0].properties.get("envVars")
On jenkins 2.x, with groovy plugin 2.0, running SystemGroovyScript I managed to get to build variables, as below:
def build = this.getProperty('binding').getVariable('build')
def listener = this.getProperty('binding').getVariable('listener')
def env = build.getEnvironment(listener)
println env.MY_VARIABLE
If you are using goovy from file, simple System.getenv('MY_VARIABLE') is sufficient
The Scriptler Groovy script doesn't seem to get all the environment variables of the build. But what you can do is force them in as parameters to the script:
When you add the Scriptler build step into your job, select the option "Define script parameters"
Add a parameter for each environment variable you want to pass in. For example "Name: JOB_NAME", "Value: $JOB_NAME". The value will get expanded from the Jenkins build environment using '$envName' type variables, most fields in the job configuration settings support this sort of expansion from my experience.
In your script, you should have a variable with the same name as the parameter, so you can access the parameters with something like:
println "JOB_NAME = $JOB_NAME"
I haven't used Sciptler myself apart from some experimentation, but your question posed an interesting problem. I hope this helps!
The only way I could get this to work (on Linux) was to follow this advice:
https://wiki.jenkins-ci.org/display/JENKINS/Parameterized+System+Groovy+script
import hudson.model.*
// get current thread / Executor and current build
def thr = Thread.currentThread()
def build = thr?.executable
// if you want the parameter by name ...
def hardcoded_param = "FOOBAR"
def resolver = build.buildVariableResolver
def hardcoded_param_value = resolver.resolve(hardcoded_param)
println "param ${hardcoded_param} value : ${hardcoded_param_value}"
This is on Jenkins 1.624 running on CentOS 6.7
Jenkins 2.x has the global variables. env is one of them from any script...
println env.JOB_NAME
More at https://build.intuit.com/services-config/pipeline-syntax/globals#env
One thing to note, if you are using a freestyle job, you won't be able to access build parameters or the Jenkins JVM's environment UNLESS you are using System Groovy Script build steps. I spent hours googling and researching before gathering enough clues to figure that out.
In System Groovy Script (Jenkins 2.89), I was able to use the environmental variable to disable another Jenkins job
import jenkins.*
import jenkins.model.*
def env = binding.build.environment
Jenkins.instance.getItemByFullName(env.job_name).setDisabled(false)
I also added a conditional step so as to either enable or disable another Jenkins job.
Thanks #Allan Lewis, your comment was helpful.

How to export Plone session configuration?

I'd like to export my Plone session configuration to my portal product.
The session configuration is set via the ZMI -> acl-users -> session -> properties
I have tried creating a snapshot of the site but can't locate the session configuration within the snapshot xml...
Indeed, there is no GenericSetup configuration support included in plone.session; there is currently nothing that'll export it for you, nor anything to then import the settings.
You'd have to write a setup step for it instead, and configure the session plugin manually through that.
Add an import step to your configure.zcml configuration file:
<?xml version="1.0"?>
<configure
xmlns="http://namespaces.zope.org/zope"
xmlns:genericsetup="http://namespaces.zope.org/genericsetup"
<genericsetup:importStep
name="yourpackage.a_unique_id_for_your_step"
title="Configures the plone.session plugin"
description="Perhaps an optional description"
handler="your.package.setuphandlers.setupPloneSession"
/>
</configure>
and add an empty 'sentinel' text file to the same profile directory named youpackage.setup-plonesession.txt
then add a setuphandlers.py module to your package (what handler points to in the above example):
def setupPloneSession(context):
if context.readDataFile('youpackage.setup-plonesession.txt') is None:
return
portal = context.getSite()
plugin = portal.acl_users.session
# Configure the plugin manually
plugin.path = '/'
plugin.cookie_name = '__ac'
plugin.cookie_domain = ''
# Set up a shared auth_tkt secret
plugin._shared_secret = 'YourSharedSecretKey'
plugin.mod_auth_tkt = True
Note that we first test if the sentinel file is present; if you reuse your package setup elsewhere the setup step could be run multiple times if you don't do this.
You'll need to refer to the plugin source to get an idea of what you can configure, I'm afraid.

Resources