Friday, 27 January 2023

Jenkins

Available Environment Variables

//See a list of environment variables
https://jenkins.mycomany.dev/env-vars.html/

//access environment variable in Jenksfile
build = "Build:${BUILD_NUMBER}"

See work place

cd /home/jenkins/workspace 

Check which docker image used by stack

In template file, image is mapped to BuildVersion.

  • go to Cloudformation
  • find the stack
  • click parameters
  • check BuildVersion

withCredentials explained

When the withCredentials block is executed, the specified credentials are made available only within that block by injecting enviornment variables. Once the block execution is complete, the environment variables are no longer available, ensuring the secrets are not exposed outside the block

stages {
        stage('Example') {
            steps {
                // Wrap steps with the credentials
                withCredentials([usernamePassword(credentialsId: 'my-credentials-id', 
                                                  usernameVariable: 'USER', 
                                                  passwordVariable: 'PASS')]) {
                    // Use the credentials. It shows we can access env variables USER and PASS
                    // because these two env variables have been injected by withCredentials
                    // in real life, you will not echo these credentials, but use it in your codes
                    sh 'echo "Username: $USER"'
                    sh 'echo "Password: $PASS"'
                }
            }
        }
    }

To manage credentials in Jenkins, go to Manage Jenkins; go to Manage Credentials

Run bash in Jenkins

sh "rm -rf composer/composer.json composer/composer.lock composer/vendor"
sh "composer.phar require aws/aws-sdk-php ^3.69 --ignore-platform-reqs --working-dir=composer"

Tuesday, 24 January 2023

Magic function __invoke

In PHP, __invoke() method is called when a script tries to call an object as a function

//example 1
<?php
class CallableClass
{
    public function __invoke($x)
    {
        var_dump($x);
    }
}
$obj = new CallableClass;

//treat object as function. Here var dump 5
$obj(5);

//will get true
var_dump(is_callable($obj));

//example 2
<?php
class CallableClass
{
    public function __invoke($x)
    {
        return $x + 100;
    }
}
$obj = new CallableClass;

$ans = $obj(5);

//Here var dump 105
var_dump($ans);