Setup Jenkins with Bitbucket on EC2

Jenkins CI is the leading open-source continuous integration server.

A. Requirement

  • Java
  • Maven
  • Git
  • Tomcat

B. Install

  1. Download Jenkins
  2. Copy jenkins.war to tomcat webapps

C. Config

1. Configure System (Jenkins > Manage Jenkins > Configure System)


2. Configure Global Security (Jenkins > Manage Jenkins > Configure Global Security)

  • Enable Enable security
  • Security Realm: Jenkins' own user database
  • Authorization: Logged-in users can do anything

3. Install Plugins (Jenkins > Manage Jenkins > Manage Plugins)

  • Update all plugin installed
  • Install: Bitbucket Plugin

4. Config Credentials (Jenkins > Credentials)

a. Config Linux

# Gen ssh key for tomcat. IMPORTANT: leave passphrase empty
ssh-keygen -f tomcat -t rsa
# Change owner to tomcat
sudo chown tomcat $HOME/.ssh/tomcat
sudo chown tomcat $HOME/.ssh/
# Add public key to authorized_keys
cat $HOME/.ssh/ >> $HOME/.ssh/authorized_keys
# Move tomcat private key to jenkins master and change name to id_rsa
# eg TOMCAT_HOME=/usr/share/tomcat7
sudo mv $HOME/.ssh/tomcat $TOMCAT_HOME/.ssh/id_rsa

b. Config Bitbucket: Add tomcat public key to SSH keys

c. Config Jenkins (Jenkins > Credentials > Global credentials)

  • Click on Add Credentials
  • Kind: SSH Username with private key
  • Scope: Global
  • Username: tomcat
  • Private Key: From the Jenkins master ~/.ssh

5. Setup Jenkins Hook on Bitbucket

a. Jenkins Information Requirement

  • Get User's API Token: (Jenkins > People > Username > Configure > API Token)
  • Get Jenkins Server Host: (Jenkins > Manage Jenkins > Configure System > Jenkins Location)

b. Jenkins Hook Management on Bitbucket

  1. Go to the repository's settings
  2. Click Hooks in the left-hand navigation
  3. Select the Jenkins hook from the Hook dropdown
  4. Click Add hook
  5. Enter the following information
    • Token: The token from the build job I want to run
    • Project name: The build project name
    • Endpoint: <username>:<api token>@<jenkins server host>

Key points:

  • The usertoken in the URL is the token for the user account, not the password, and not the same token used for the job
  • The endpoint URL is not the full URL. Bitbucket adds on the /build/jobname?token=token, using the other fields you enter

6. Create Maven Jenkins Job (Jenkins > New Item)

a. Source Code Management: Git

  • Repository URL:
  • Credentials: tomcat

b. Build Triggers

  • Enable Build when a change is pushed to BitBucket
  • Credentials: tomcat

c. Build

  • Root POM: pom.xml
  • Goals and options: clean compile war:inplace war:war
  • MAVEN_OPTS: -Dmaven.test.skip=true

d. Post Steps

  • Choose Run only if build succeeds
  • Execute shell
    rm -rf /usr/share/tomcat7/webapps/myweb /usr/share/tomcat7/webapps/myweb.war
    mv target/myweb.war /usr/share/tomcat7/webapps/myweb.war

D. Bitbucket IP

Inbound (bound to Outbound (for hooks like POST)


Popular posts from this blog