amazon-ecs-plugin

amazon-ecs-plugin

Amazon ECS插件实现Jenkins构建任务Docker容器化

此Jenkins插件利用Amazon ECS在Docker容器中执行构建任务。它将构建委托给ECS,每个任务在独立容器中运行并自动清理。支持EC2和Fargate集群,提供灵活配置,兼容Jenkins流水线。简化了AWS上Jenkins构建能力的扩展,保证环境隔离和一致性。

JenkinsAmazon ECSDocker容器化CI/CDGithub开源项目

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 in this repo:

Additionally there is an example setup here: Terraform Jenkins AWS ECS Fargate

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 images 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.
  • CPU units: 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

编辑推荐精选

蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI助手AI工具AI写作工具AI辅助写作蛙蛙写作学术助手办公助手营销助手
Trae

Trae

字节跳动发布的AI编程神器IDE

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

热门AI工具生产力协作转型TraeAI IDE
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

聊天机器人AI助手热门AI工具AI对话
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

热门AI工具AI办公办公工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

模型训练热门AI工具内容创作智能问答AI开发讯飞星火大模型多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

AI助手热门AI工具AI创作AI辅助写作讯飞绘文内容运营个性化文章多平台分发
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

下拉加载更多