• Stars
    star
    193
  • Rank 193,898 (Top 4 %)
  • Language
    Java
  • License
    MIT License
  • Created over 8 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Amazon EC2 Container Service Plugin for Jenkins

Amazon Elastic Container Service (ECS / Fargate) Plugin for Jenkins

Build Status Join the chat at https://gitter.im/jenkinsci/amazon-ecs-plugin

About

This Jenkins plugin uses Amazon Elastic Container Service to host jobs execution inside docker containers.

Jenkins delegates to Amazon ECS the execution of the builds on Docker based agents. Each Jenkins build is executed on a dedicated Docker container that is wiped-out at the end of the build.

Installation & configuration

The scope of the plugin is only using existing and pre-configured AWS Infrastructure. It does not create any of the needed infrastructure on its own. Use tools like CloudFormation or Terraform for this task.

Requirements

  • Jenkins with at least version 2.289.1
  • AWS Account

Plugin install

Use the Jenkins plugin manager to install the Amazon Elastic Container Service plugin

Configuration

Examples

There are currently the following example setups (also in this repo):

Amazon ECS cluster

As a pre-requisite, you must have created an Amazon ECS cluster with associated ECS instances. These instances can be statically associated with the ECS cluster or can be dynamically created with Amazon Auto Scaling.

The Jenkins Amazon EC2 Container Service plugin will use this ECS cluster and will create automatically the required Task Definition.

Jenkins System Configuration

Navigate to the "Configure System" screen.

In the "Jenkins Location" section, ensure that the "Jenkins URL" is reachable from the the container instances of the Amazon ECS cluster. See the section "Network and firewalls" for more details.

If the global Jenkins URL configuration does not fit your needs (e.g. if your ECS agents must reach Jenkins through some kind of tunnel) you can also override the Jenkins URL in the Advanced Configuration of the ECS cloud.

At the bottom of the screen, click on "Add a new Cloud" and select "Amazon EC2 Container Service Cloud".

Amazon EC2 Container Service Cloud

Then enter the configuration details of the Amazon EC2 Container Service Cloud:

  • Name: name for your ECS cloud (e.g. ecs-cloud)
  • Amazon ECS Credentials: Amazon IAM Access Key with privileges to create Task Definitions and Tasks on the desired ECS cluster
  • ECS Cluster: desired ECS cluster on which Jenkins will send builds as ECS tasks
  • ECS Template: click on "Add" to create the desired ECS template or templates

Advanced configuration

Tunnel connection through: tunnelling options (when Jenkins runs behind a load balancer). Alternative Jenkins URL: The URL used as the Jenkins URL within the ECS containers of the configured cloud. Can be used to override the default Jenkins URL from global configuration if needed.

ECS Agent Templates

One or several ECS agent templates can be defined for the Amazon EC2 Container Service Cloud. The main reason to create more than one ECS agent template is to use several Docker image to perform build (e.g. java-build-tools, php-build-tools...)

  • Template name is used (prefixed with the cloud's name) for the task definition in ECS.
  • Label: agent labels used in conjunction with the job level configuration "Restrict where the project can be run / Label expression". ECS agent label could identify the Docker image used for the agent (e.g. docker for the jenkinsci/inbound-agent). Multiple, space delimited labels can be specified(e.g. java11 alpine). Label expressions within a job such as java11 && alpine or java11 || alpine are not currently supported. Filesystem root: working directory used by Jenkins (e.g. /home/jenkins/). Memory: number of MiB of memory reserved for the container. If your container attempts to exceed the memory allocated here, the container is killed.
  • The number of cpu units to reserve for the container. A container instance has 1,024 cpu units for every CPU core. Advanced Configuration
  • Override entrypoint: overwritten Docker image entrypoint. Container command can't be overriden as it is used to pass jenkins agent connection parameters.
  • JVM arguments: additional arguments for the JVM, such as -XX:MaxPermSize or GC options.

Network and firewalls

Running the Jenkins master and the ECS container instances in the same Amazon VPC and in the same subnet is the simplest setup and default settings will work out-of-the-box.

Firewalls If you enable network restrictions between the Jenkins master and the ECS cluster container instances,

Fix the TCP listen port for JNLP agents of the Jenkins master (e.g. 5000) navigating in the "Manage Jenkins / Configure Global Security" screen Allow TCP traffic from the ECS cluster container instances to the Jenkins master on the listen port for JNLP agents (see above) and the HTTP(S) port.

Network Address Translation and Reverse Proxies In case of Network Address Translation rules between the ECS cluster container instances and the Jenkins master, ensure that the JNLP agents will use the proper hostname to connect to the Jenkins master doing on of the following:

Define the proper hostname of the Jenkins master defining the system property hudson.TcpSlaveAgentListener.hostName in the launch command Use the advanced configuration option "Tunnel connection through" in the configuration of the Jenkins Amazon EC2 Container Service Cloud (see above).

IAM Permissions

To work the plugin needs some IAM permissions. Assign a role with those permissions to the instance / container you are running the master on.

Here is an example of a role in CloudFormation, make sure to modify it for your needs.

TaskRole:
    Type: AWS::IAM::Role
    Properties:
        RoleName: !Sub ${AWS::StackName}-task-role
        Path: /
        AssumeRolePolicyDocument:
            Version: 2012-10-17
            Statement:
                - Effect: Allow
                  Principal:
                      Service:
                          - ecs-tasks.amazonaws.com
                  Action: sts:AssumeRole
        Policies:
            - PolicyName: !Sub ecs-${AWS::StackName}
              PolicyDocument:
                  Version: "2012-10-17"
                  Statement:
                      - Action:
                            - "ecs:RegisterTaskDefinition"
                            - "ecs:ListClusters"
                            - "ecs:DescribeContainerInstances"
                            - "ecs:ListTaskDefinitions"
                            - "ecs:DescribeTaskDefinition"
                            - "ecs:DeregisterTaskDefinition"
                            - "ecs:ListTagsForResource"
                        Effect: Allow
                        Resource: "*"
                      - Action:
                            - "ecs:ListContainerInstances"
                            - "ecs:DescribeClusters"
                        Effect: Allow
                        Resource:
                            - !Sub "arn:aws:ecs:${AWS::Region}:${AWS::AccountId}:cluster/<clusterName>"
                      - Action:
                            - "ecs:RunTask"
                        Effect: Allow
                        Condition:
                            ArnEquals:
                                ecs:cluster:
                                    - !Sub "arn:aws:ecs:${AWS::Region}:${AWS::AccountId}:cluster/<clusterName>"
                        Resource: !Sub "arn:aws:ecs:${AWS::Region}:${AWS::AccountId}:task-definition/*"
                      - Action:
                            - "ecs:StopTask"
                        Effect: Allow
                        Condition:
                            ArnEquals:
                                ecs:cluster:
                                    - !Sub "arn:aws:ecs:${AWS::Region}:${AWS::AccountId}:cluster/<clusterName>"
                        Resource: !Sub "arn:aws:ecs:*:*:task/*" # "arn:aws:ecs:${AWS::Region}:${AWS::AccountId}:task/*"
                      - Action:
                            - "ecs:DescribeTasks"
                        Effect: Allow
                        Condition:
                            ArnEquals:
                                ecs:cluster:
                                    - !Sub "arn:aws:ecs:${AWS::Region}:${AWS::AccountId}:cluster/<clusterName>"
                        Resource: !Sub "arn:aws:ecs:*:*:task/*" # "arn:aws:ecs:${AWS::Region}:${AWS::AccountId}:task/*"
                      - Action:
                            - "elasticfilesystem:DescribeAccessPoints"
                            - "elasticfilesystem:DescribeFileSystems"
                        Effect: Allow
                        Resource: !Sub "arn:aws:elasticfilesystem:${AWS::Region}:${AWS::AccountId}:file-system/*"

Agent

The Jenkins Amazon EC2 Container Service Cloud can use for the agents all the Docker image designed to act as a Jenkins JNLP agent. Here is a list of compatible Docker images:

You can easily extend the images or also build your own.

Declarative Pipeline

Declarative Pipeline support requires Jenkins 2.66+

Declarative agents can be defined like shown below. You can also reuse pre-configured templates and override certain settings using inheritFrom to reference the Label field of the template that you want to use as preconfigured. Only one label is expected to be specified.

When using inheritFrom, the label will not copied. Instead, a new label will be generated based on the following schema {job-name}-{job-run-number}-{5-random-chars} e.g. "pylint-543-b4f42". This guarantees that there will not be conflicts with the parent template or other runs of the same job, as well as making it easier to identify the labels in Jenkins.

If you want to override the label, ensure that you are not going to conflict with other labels configured elsewhere. Templates for dynamic agents exist until the agent dies, meaning other jobs requesting the same label (including dynamic agents on other runs of the same job!) run the chance of provisioning the dynamic agent's ECSTask.

Note: You have to configure list of settings to be allowed in the declarative pipeline first (see the Allowed Overrides setting). They are disabled by default for security reasons, to avoid non-privileged users to suddenly be able to change certain settings.

If Jenkins is unexpectedly shut down there is a good chance that ECS Tasks for dynamic agents will not be cleaned up (de-registered) in AWS. This should not cause issues, but may come as a surprise when looking at the console.

Usage

The ECS agents can be used for any job and any type of job (Freestyle job, Maven job, Workflow job...), you just have to restrict the execution of the jobs on one of the labels used in the ECS Agent Template configuration. You can either restrict the job to run on a specific label only via the UI or directly in the pipeline.

pipeline {
  agent none

  stages {
       stage('PublishAndTests') {
          environment {
              STAGE='prod'
          }
          agent {
            label 'build-python36'
          }
      }
      steps {
        sh 'java -version'
      }
    }
  }
pipeline {
  agent none

  stages {
    stage('Test') {
        agent {
            ecs {
                inheritFrom 'label-of-my-preconfigured-template'
                cpu 2048
                memory 4096
                image '$AWS_ACCOUNT.dkr.ecr.$AWS_REGION.amazonaws.com/jenkins/java8:2019.7.29-1'
                logDriver 'fluentd'
                logDriverOptions([[name: 'foo', value:'bar'], [name: 'bar', value: 'foo']])
                portMappings([[containerPort: 22, hostPort: 22, protocol: 'tcp'], [containerPort: 443, hostPort: 443, protocol: 'tcp']])
            }
        }
        steps {
            sh 'echo hello'
        }
    }
  }
}

Scripted Pipeline examples

def dynamic_label = "${JOB_NAME}_${env.sha}"
ecsTaskTemplate(
    cloud: 'CloudNameAsConfiguredInManageClouds',
    label: dynamic_label,
    name: dynamic_label, // Reusing the label as a name makes sense as long as it's unique
    containerUser: 'ubuntu',
    remoteFSRoot: '/home/ubuntu',
    overrides: [],
    agentContainerName: 'java',    
    taskDefinitionOverride: "arn:aws:redacted:redacted:task-definition/${env.task}"
) {
  node(dynamic_label) {
    stage("I dunno why you say goodbye"){
      sh 'echo hello'
    }
  }
}
pipeline{
    agent {
        ecs {
          inheritFrom 'ecs_test'
          cpu 1000
        } 
    }
    stages{
        stage("Here goes nothin"){
          sh 'echo hello'
        }
    }
}

FAQ

My parallel jobs don't start at the same time

Actually, there can be multiple reasons:

  • The plugin creates a new agent only when the stage contains an agent definition. If this is missing, the stage inherits the agent definition from the level above and also re-uses the instance.

  • Also, parallel stages sometimes don't really start at the same time. Especially, when the provided label of the agent definition is the same. The reason is that Jenkins tries to guess how many instances are really needed and tells the plugin to start n instances of the agent with label x. This number is likely smaller than the number of parallel stages that you've declared in your Jenkinsfile. Jenkins calls the ECS plugin multiple times to get the total number of agents running.

  • If launching of the agents takes long, and Jenkins calls the plugin in the meantime again to start n instances, the ECS plugin doesn't know if this instances are really needed or just requested because of the slow start. That's why the ECS plugin subtracts the number of launching agents from the number of requested agents (for a specific label). This can mean for parallel stages that some of the agents are launched after the previous bunch of agents becomes online.

There are options that influence how Jenkins spawns new Agents. You can set for example on your master the following to improve the launch times:

-Dhudson.slaves.NodeProvisioner.initialDelay=0 -Dhudson.slaves.NodeProvisioner.MARGIN=50 -Dhudson.slaves.NodeProvisioner.MARGIN0=0.85

Who runs this & Resources

If you are running a interesting setup or have public posts abour your setups using this plugins, please file a PR to get it added here.

Maintainers

Andreas Sieferlinger (GitHub Twitter)
Philipp Garbe (GitHub, Twitter)
Marky Jackson (GitHub, Twitter)
Stephen Erickson (GitHub)

Developing

Building the Plugin

  java -version # Need Java 1.8, earlier versions are unsupported for build
  mvn -version # Need a modern maven version; maven 3.2.5 and 3.5.0 are known to work
  mvn clean install

Running locally

To run locally, execute the following command and open the browser http://localhost:8080/jenkins/

  mvn -e hpi:run

Debugging the plugin in an editor

IntelliJ IDEA

In the Maven dialog right click hpi:run and select Debug. The IDE will stop at any breakpoints you have set inside the plugin.

Other

the

    @Rule
    public JenkinsRule j = new JenkinsRule();

Will actually invoke code that will bootstrap a local installation of jenkins.war. This will allow you to debug with with breakpoints and such. However, to do it you will need to set some system properties or be aware how it tries to auto-configure. It will attempt to look for a .jenkins directory recursively with an already exploded war, So, theoretically you explode it, and git ignore it, right in this space. Alternatively, you can set a System property: -Djth.jenkins-war.path=${PATH}/jenkins.war

Make sure to include this rule in any tests that touch Jenkins specific resources like: Jenkins.instance()

Releasing the Plugin

 mvn clean release:prepare release:perform

further checks to aid with development

Check for additional or forgotten dependencies:

mvn dependency:analyze

Check if javadoc works fine (usually only executed on release)

mvn org.apache.maven.plugins:maven-javadoc-plugin:2.10.4:jar

More Repositories

1

jenkins

Jenkins automation server
Java
21,381
star
2

docker

Docker official jenkins repo
Dockerfile
6,144
star
3

pipeline-examples

A collection of examples, tips and tricks and snippets of scripting for the Jenkins Pipeline plugin
Groovy
4,117
star
4

blueocean-plugin

Blue Ocean is a reboot of the Jenkins CI/CD User Experience
Java
2,872
star
5

configuration-as-code-plugin

Jenkins Configuration as Code Plugin
Java
2,521
star
6

kubernetes-plugin

Jenkins plugin to run dynamic agents in a Kubernetes/Docker environment
Java
2,206
star
7

job-dsl-plugin

A Groovy DSL for Jenkins Jobs - Sweeeeet!
Groovy
1,851
star
8

pipeline-plugin

Obsolete home for Pipeline plugins
1,711
star
9

JenkinsPipelineUnit

Framework for unit testing Jenkins pipelines
Groovy
1,426
star
10

gitlab-plugin

A Jenkins plugin for interfacing with GitLab
Java
1,418
star
11

jenkinsfile-runner

A command line tool to run Jenkinsfile as a function
Java
1,114
star
12

java-client-api

A Jenkins API client for Java
Java
888
star
13

jenkins-scripts

Scripts in Groovy, shell, Ruby, Python, whatever for managing/interacting with Jenkins
Groovy
880
star
14

build-monitor-plugin

Jenkins Build Monitor Plugin
Java
722
star
15

slack-plugin

A Jenkins plugin for posting notifications to a Slack channel
Java
664
star
16

git-plugin

Git repository access for Jenkins jobs
Java
660
star
17

pipeline-model-definition-plugin

Groovy
557
star
18

ghprb-plugin

github pull requests builder plugin for Jenkins
Java
495
star
19

docker-workflow-plugin

Jenkins plugin which allows building, testing, and using Docker images from Jenkins Pipeline projects.
Java
492
star
20

docker-plugin

Jenkins Cloud Plugin that uses Docker
Java
482
star
21

docker-inbound-agent

Docker image for a Jenkins agent which can connect to Jenkins using TCP or Websocket protocols
PowerShell
466
star
22

helm-charts

Jenkins helm charts
Mustache
448
star
23

pipeline-aws-plugin

Jenkins Pipeline Step Plugin for AWS
Java
423
star
24

jenkins.rb

Deprecated, see https://www.jenkins.io/jep/7
Ruby
394
star
25

generic-webhook-trigger-plugin

Can receive any HTTP request, extract any values from JSON or XML and trigger a job with those values available as variables. Works with GitHub, GitLab, Bitbucket, Jira and many more.
Java
377
star
26

email-ext-plugin

Jenkins Email Extension Plugin
Java
338
star
27

dingtalk-plugin

Dingtalk for jenkins
Java
336
star
28

warnings-ng-plugin

Jenkins Warnings Plugin - Next Generation
Java
323
star
29

plugin-installation-manager-tool

Plugin Manager CLI tool for Jenkins
Java
301
star
30

mesos-plugin

Mesos Cloud Jenkins Plugin
Java
291
star
31

github-plugin

Jenkins GitHub plugin
Java
286
star
32

ec2-plugin

Jenkins ec2 plugin
Java
282
star
33

ssh-steps-plugin

Jenkins pipeline steps which provides SSH facilities such as command execution or file transfer for continuous delivery.
Java
273
star
34

ansicolor-plugin

Jenkins ANSI Color Plugin
Java
253
star
35

pipeline-utility-steps-plugin

Small, miscellaneous, cross platform utility steps for Jenkins Pipeline jobs.
Java
237
star
36

docker-agent

Base Docker image for Jenkins Agents
PowerShell
231
star
37

ansible-plugin

Jenkins Ansible plugin
Java
223
star
38

workflow-cps-global-lib-plugin

Java
223
star
39

lib-file-leak-detector

Java agent that detects file handle leak
Java
217
star
40

hashicorp-vault-plugin

Jenkins plugin to populate environment variables from secrets stored in HashiCorp's Vault.
Java
214
star
41

bitbucket-branch-source-plugin

Bitbucket Branch Source Plugin
Java
213
star
42

remoting

Jenkins Remoting module
Java
212
star
43

workflow-aggregator-plugin

211
star
44

gerrit-trigger-plugin

Java
209
star
45

android-emulator-plugin

Android Emulator plugin for Jenkins
Java
207
star
46

docker-slaves-plugin

A Jenkins plugin to run builds inside Docker containers
Java
205
star
47

pipeline-stage-view-plugin

Visualizes Jenkins pipelines
JavaScript
204
star
48

jenkinsfile-runner-github-actions

Jenkins single-shot pipeline execution in a GitHub Action POC
Shell
199
star
49

github-branch-source-plugin

GitHub Branch Source Plugin
Java
193
star
50

trilead-ssh2

Patched trilead-ssh2 used in Jenkins
Java
193
star
51

cucumber-reports-plugin

Jenkins plugin to generate cucumber-jvm reports
Java
192
star
52

docker-build-publish-plugin

Java
192
star
53

performance-plugin

Performance Test Running and Reporting for Jenkins CI
Java
188
star
54

jira-plugin

Jenkins jira plugin
Java
168
star
55

gitea-plugin

This plugin provides the Jenkins integration for Gitea.
Java
168
star
56

embeddable-build-status-plugin

Embed build status of Jenkins jobs in web pages
Java
167
star
57

stashnotifier-plugin

A Jenkins Plugin to notify Atlassian Stash|Bitbucket of build results
Java
166
star
58

docker-ssh-agent

Docker image for Jenkins agents connected over SSH
PowerShell
162
star
59

workflow-cps-plugin

Java
160
star
60

http-request-plugin

This plugin does a request to an url with some parameters.
Java
154
star
61

stapler

Stapler web framework
Java
154
star
62

kubernetes-pipeline-plugin

Kubernetes Pipeline is Jenkins plugin which extends Jenkins Pipeline to provide native support for using Kubernetes pods, secrets and volumes to perform builds
Java
154
star
63

tfs-plugin

Jenkins tfs plugin
Java
145
star
64

jep

Jenkins Enhancement Proposals
Shell
144
star
65

kubernetes-cd-plugin

A Jenkins plugin to deploy to Kubernetes cluster
Java
140
star
66

jacoco-plugin

Jenkins JaCoCo Plugin
Java
139
star
67

qy-wechat-notification-plugin

企业微信Jenkins构建通知插件
Java
138
star
68

swarm-plugin

Jenkins swarm plugin
Java
133
star
69

git-client-plugin

Git client API for Jenkins plugins
Java
130
star
70

subversion-plugin

Jenkins subversion plugin
Java
126
star
71

dependency-check-plugin

Jenkins plugin for OWASP Dependency-Check. Inspects project components for known vulnerabilities (e.g. CVEs).
Java
125
star
72

role-strategy-plugin

Jenkins Role-Strategy plugin
Java
120
star
73

groovy-sandbox

(Deprecated) Compile-time transformer to run Groovy code in a restrictive sandbox
Java
120
star
74

jenkins-design-language

Styles, assets, and React classes for Jenkins Design Language
TypeScript
116
star
75

acceptance-test-harness

Acceptance tests cases for Jenkins and its plugins based on selenium and docker.
Java
116
star
76

scm-sync-configuration-plugin

Jenkins scm-sync-configuration plugin
Java
116
star
77

gitlab-branch-source-plugin

A Jenkins Plugin for GitLab Multibranch Pipeline jobs and Folder Organization
Java
115
star
78

git-parameter-plugin

Jenkins plugin for chosing Revision / Tag before build
Java
115
star
79

publish-over-ssh-plugin

Java
114
star
80

pipeline-as-yaml-plugin

Jenkins Pipeline As Yaml Plugin
Java
114
star
81

selenium-plugin

Jenkins selenium plugin
Java
112
star
82

docker-build-step-plugin

Java
111
star
83

code-coverage-api-plugin

Deprecated Jenkins Code Coverage Plugin
Java
111
star
84

jira-trigger-plugin

Triggers a build when a certain condition is matched in JIRA
Groovy
111
star
85

cobertura-plugin

Jenkins cobertura plugin
Java
110
star
86

gradle-plugin

Jenkins gradle plugin
Java
109
star
87

credentials-plugin

Provides Jenkins with extension points to securely store, manage, and bind credentials data to other Jenkins plugins, builds, pipelines, etc.
Java
107
star
88

jira-steps-plugin

Jenkins pipeline steps for integration with JIRA.
Java
104
star
89

artifactory-plugin

Jenkins artifactory plugin
Java
104
star
90

build-flow-plugin

A plugin to manage job orchestration
Groovy
103
star
91

throttle-concurrent-builds-plugin

Java
101
star
92

github-oauth-plugin

Jenkins authentication plugin using GitHub OAuth as the source.
Java
99
star
93

pipeline-graph-view-plugin

Java
99
star
94

promoted-builds-plugin

Jenkins Promoted Builds Plugin
Java
96
star
95

ssh-slaves-plugin

SSH Build Agents Plugin for Jenkins
Java
96
star
96

github-pr-coverage-status-plugin

Nice test coverage icon for your pull requests just from Jenkins
Java
93
star
97

jenkins-test-harness

Unit test framework for Jenkins core and its plugins
Java
92
star
98

opentelemetry-plugin

Monitor and observe Jenkins with OpenTelemetry.
Java
90
star
99

localization-zh-cn-plugin

Chinese Localization for Jenkins
HTML
89
star
100

workflow-remote-loader-plugin

Load Pipeline scripts from remote locations (e.g. Git) - replaced by Pipeline: Groovy Libraries plugin
Java
88
star