Jenkins – Active Choice: CheckBox – Working with an Array

When working with the Active Choice CheckBox parameter, the parameter values are written to the variable, separated by commas. To work with them as separate elements, you need to save them in an array. For example, there is the following Active Choice, which displays a list of environments in the form of a CheckBox.

Pipeline:

properties([
  parameters([
    [$class: 'CascadeChoiceParameter', 
      choiceType: 'PT_CHECKBOX', 
      description: 'Select Environment',
      filterLength: 1,
      filterable: false,
      name: 'Environment', 
      script: [
        $class: 'GroovyScript', 
        script: [
          classpath: [], 
          sandbox: false, 
          script: 
            'return[\'Development\',\'QA\',\'Staging\',\'Production\']'
        ]
      ]
    ]
  ])
])

 

It looks like this:

 

Choose two environments, "Development" and "QA"

 

The value of the variable "Environment" will be the following: "Development, QA". We will save these values to an array for further work with it.

String[] Env_Array = "${params.Environment}".split(',');

 

Completely Pipeline will have the following form

Pipeline:

properties([
  parameters([
    [$class: 'CascadeChoiceParameter', 
      choiceType: 'PT_CHECKBOX', 
      description: 'Select Environment',
      filterLength: 1,
      filterable: false,
      name: 'Environment', 
      script: [
        $class: 'GroovyScript', 
        script: [
          classpath: [], 
          sandbox: false, 
          script: 
            'return[\'Development\',\'QA\',\'Staging\',\'Production\']'
        ]
      ]
    ]
  ])
])

pipeline {
  agent any
  stages {
    stage('Check env') {
      steps {
        script {
          if ( env.Environment.isEmpty() ) {
            echo "Environment not specified."
            autoCancelled = true
            error('Aborting the build.')
          }
          else {
            echo "Environment total: ${env.Environment}"
            String[] Env_Array = "${params.Environment}".split(',');
            for (x in Env_Array) {
              echo "ENV: ${x}"
            }
          }
        }
      }
    }
  }
}

 

The result of the Jenkins job:

Jenkins – Active Choice: Pipeline examples

 

A few examples of how Active Choices parameters in Pipeline as a code

Example 1

Single selection from the list provided. A drop-down list of environments, by default, the first item in the list is selected.

Pipeline:

properties([
  parameters([
    [$class: 'CascadeChoiceParameter', 
      choiceType: 'PT_SINGLE_SELECT', 
      description: 'Select environment',
      filterLength: 1,
      filterable: false,
      name: 'Environment', 
      script: [
        $class: 'GroovyScript', 
        script: [
          classpath: [], 
          sandbox: false, 
          script: 
            'return[\'Development\',\'Production\']'
        ]
      ]
    ]
  ])
])

 

Continue reading "Jenkins – Active Choice: Pipeline examples"

Jenkins – Username

In order to find out Jenkins username, you need a plugin user build vars

Go to Jenkins settings

 

Section "Manage Plugins"

 

Go to the "Available" tab and specify "user build vars" in the search.

Install it.

 

An example of using a plugin from Pipeline:

pipeline {
  agent any
  stages {
    stage('Output') {
      steps {
        script {
          wrap([$class: 'BuildUser']) {
            echo "Build was started by user: ${BUILD_USER}"
          }
        }
      }
    }
  }
}

 

The module also has the following variables:

  • BUILD_USER - Full name (first name + last name)
  • BUILD_USER_FIRST_NAME - First name
  • BUILD_USER_LAST_NAME - Last name
  • BUILD_USER_ID - Jenkins user ID
  • BUILD_USER_EMAIL - Email address

Jenkins – Active Choice: Git branch

 

For a parameterized build with branch selection, you will need a plugin Active Choices

Go to Jenkins settings

 

Section "Manage Plugins"

 

Go to the "Available" tab and specify "Active Choice" in the search.

Install it.

Create a "New Item" - "Pipeline", indicate that it will be a parameterized project, and add the parameter "Active Choices Reactive Parameter"

 

We indicate that this is "Groovy Script" and paste the following into it:

def gettags = ("git ls-remote -t -h ssh://git-codecommit.eu-west-1.amazonaws.com/v1/repos/artem-services.git").execute()
return gettags.text.readLines().collect { 
  it.split()[1].replaceAll('refs/heads/', '').replaceAll('refs/tags/', '').replaceAll("\\^\\{\\}", '')
}

 

Where "ssh: //git-codecommit.eu-west-1.amazonaws.com/v1/repos/artem-services.git" is the path to your repository. Jenkins must have access to this repository over SSH

 

 

Now, when building with parameters, there will be a branch selection

Jenkins – Change default language

 

By default, Jenkins uses your browser’s settings language. In order to force change it, you can use the Locale plugin

Go to Jenkins settings

 

Section "Manage Plugins"

 

Go to the "Available" tab and specify "Locale" in the search.

 

Install it. And back to Jenkins settings, tab "Configure System"

 

Find the "Locale" block and specify the desired language. We also check the box to ignore browser settings.

 

Done. Save changes.

FIX ERROR – Ansible AWS SSM: AnsibleError: An unhandled exception occurred while templating

When trying to get a value from AWS SSM, Ansible Playbook using Python3 as an interpreter generates the following error:

fatal: [localhost-py3]: FAILED! => {"changed": false, "msg": "AnsibleError: An unhandled exception occurred while templating '{{ lookup('aws_ssm', 'server_listeners', decrypt=false, region='eu-west-1') }}'. Error was a <class 'ansible.errors.AnsibleError'>, original message: An unhandled exception occurred while running the lookup plugin 'aws_ssm'. Error was a <class 'ansible.errors.AnsibleError'>, original message: botocore and boto3 are required for aws_ssm lookup."}

The Ansible documentation says that dependencies are needed for PIP:

  • boto3
  • botocore

But the error was still present until the "ansible" module was added to the PIP dependency

Solution:

---
- name: Ensure boto3, botocore and ansible modules are installed
  pip:
    name: 
      - boto3
      - botocore
      - ansible
    executable: /usr/bin/pip3

CodeCommit – Git

HTTPS

In order to be able to work with the Git repository in CodeCommit using the AIM role, AWS Cli must be installed on the instance. You will also need "credential-helper", for this we create a configuration file for Git:

~/.gitconfig

 

And copy the following into it:

[credential]
    helper = !aws codecommit credential-helper [email protected]
    UseHttpPath = true

 

Now you can work with CodeCommit over HTTPS without specifying a username/password.

 

SSH

To use the SSH protocol, you need an IAM user with rights to CodeCommit. You also need to add the SSH Public Key, for this, in the IAM settings of the user, go to the "Security Credentials" tab and go down to the "SSH keys for AWS CodeCommit" block

 

And upload the public key. After which you will see the "SSH Key ID" of your key, it is needed to work with CodeCommit:

git clone ssh://{YOUR_ID_FOR_SSH_KEY}@git-codecommit.us-east-1.amazonaws.com/v1/repos/artem-test

 

But in order not to constantly indicate it, you can specify it in the SSH configuration:

vim ~/.ssh/config

 

Copy the following contents:

Host git-codecommit.*.amazonaws.com
User {YOUR_ID_FOR_SSH_KEY}
IdentityFile ~/.ssh/id_rsa # path to your private ssh key

 

And we ask him the necessary permission:

chmod 600 ~/.ssh/config

Now you can work with CodeCommit without specifying "SSH Key ID"

Jenkins – Checking if a string value is set to a parameter

 

Check if the value of the variable "GIT_COMMIT_ID" is set, if so, then do a checkout by the hash of the commit, if not, then do a checkout by the name of the branch. The variable "GIT_BRANCH_NAME" is taken from the Active Choice parameter.

Jenkinsfile:

pipeline {
  agent any
  parameters {
    string(defaultValue: '', description: 'If you need to build a specific commit, enter it in this field.', name: 'GIT_COMMIT_ID')
  }
  stages {
    stage('Checkout') {
      steps {
        script {
          if ( env.GIT_COMMIT_ID.isEmpty() ) {
            sh "echo Checkout branch: $GIT_BRANCH_NAME"
            checkout([
              $class: "GitSCM",
              branches: [[name: "${GIT_BRANCH_NAME}"]],
              userRemoteConfigs: [[url: "${GIT_URI}"]]
            ])
          }
          else {
            sh "echo Checkout commit: $GIT_COMMIT_ID"
            checkout([
              $class: "GitSCM",
              branches: [[name: "${GIT_COMMIT_ID}"]],
              userRemoteConfigs: [[url: "${GIT_URI}"]]
            ])       
          }
        }
      }
    }
  } 
}  

AWS Cli – Search EC2 instances by tag and state

 

To get the IP addresses of all instances with the "Application" tag and its value "Frontend", and also filter by state to display information about only those instances that are in the "running" state.

aws ec2 describe-instances --filter "Name=tag:Application,Values=Frontent" "Name=instance-state-name,Values=running" --query "Reservations[*].Instances[*][NetworkInterfaces[0].PrivateIpAddresses[0].PrivateIpAddress]" --output text

 

To display the name of the istans along with the IP address:

aws ec2 describe-instances --filter "Name=tag:Application,Values=Frontend" "Name=instance-state-name,Values=running" --query "Reservations[*].Instances[*][Tags[?Key=='Name'].Value[],NetworkInterfaces[0].PrivateIpAddresses[0].PrivateIpAddress]" --output text

Ansible – Get the IP address of another host from the hosts file

An example of how to get the IP address of another host from the "hosts" file by performing a task on another host.

 

  • server1 - our Playbook will be executed on it
  • server2 - we need its IP address in the Playbook

 

hosts:

[default]
server1 ansible_host=192.168.1.101
server2 ansible_host=192.168.1.102

 

In order to get the IP address, we will use "hostvars", where we indicate the name of the server we need, in our case it is "server2"

Playbook:

---
 
- name: example
  gather_facts: No
  hosts: server1
  
  tasks:
    - name: get-ip-from-server2
      debug:
        msg: "Server2 IP address is {{ hostvars[ 'server2' ].ansible_default_ipv4.address }}"

 

Output:

ok: [server1] => {
    "msg": "Server2 IP address is 192.168.1.102"
}