Jenkins – Active Choice: S3 – Return necessary key value from JSON file

For a parameterized assembly with an image tag selection, you will need the Active Choices plugin

Go to "Manage Jenkins"

 

Section "Manage Plugins"

 

Go to the "Available" tab and select "Active Choices" in the search.

Install it.

 

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

 

 

 

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

import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.S3Object;
import com.cloudbees.plugins.credentials.Credentials;
import com.cloudbees.plugins.credentials.CredentialsNameProvider;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import com.cloudbees.jenkins.plugins.awscredentials.AmazonWebServicesCredentials;
import groovy.json.JsonSlurper;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
import jenkins.model.*
  
def AWS_REGION = 'eu-west-1'
def BUCKET_NAME = 'artem.services'
def INFO_FILE = 'info.json'

credentialsId = 'aws_credentials'

def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(AmazonWebServicesCredentials.class, Jenkins.instance, null, null ).find({it.id == credentialsId});


AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withCredentials(creds).withRegion(AWS_REGION).build(); 

S3Object s3Object = s3Client.getObject(BUCKET_NAME, INFO_FILE)

try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(s3Object.getObjectContent()))
    s3Data = reader.lines().collect(Collectors.joining("\n"));
} catch (Exception e) {
    System.err.println(e.getMessage());
    System.exit(1);
}

def json = new JsonSlurper().parseText(s3Data)

return json.instance.ip

 

Where is the value of the variables, "credentialsId" – Jenkins Credentials ID with AWS Access Key and AWS Secret Key (if the Jenkins instance does not use IAM Role, or it is not deployed in AWS Cloud);

"AWS_REGION" – AWS region where S3 Bucket is located;

"BUCKET_NAME" – S3 bucket name;

"INFO_FILE" – the key of the object in the bucket, in our case a JSON file;

"return json.instance.ip" – return key value instance: {'ip': "1.2.3.4}

 

Tagged: Tags

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments