Cant run mysql command on docker in jenkins pipeline - docker

I have this docker-compose.yml file
version: '3'
services:
# MySQL
app-name-ci-mysql-service:
image: mysql
container_name: app-name-ci-mysql-container
restart: always
environment:
MYSQL_ROOT_PASSWORD: example
expose:
- 3306
networks:
- app-name-ci-mysql-network
volumes:
- /var/www/address.co/ci/mysql/my.cnf:/my.cnf
# PHP Service
app-name-ci-php-service:
build:
context: .
dockerfile: Dockerfile
container_name: app-name-ci-php-container
working_dir: /var/www/project
volumes:
- /var/www/address.co/ci/public/.env.main:/var/www/project/.env.main
- /var/www/address.co/ci/public/.env.testing:/var/www/project/.env.testing
networks:
- app-name-ci-network
- app-name-ci-mysql-network
#Nginx Service
app-name-ci-nginx-service:
image: nginx:latest
container_name: app-name-ci-nginx-container
expose:
- 80
- 443
environment:
VIRTUAL_HOST: address.co
LETSENCRYPT_HOST: address.co
LETSENCRYPT_EMAIL: admin#address.lt
networks:
- app-name-ci-network
- nginx-proxy
volumes:
- ./nginx/conf.d/:/etc/nginx/conf.d/
#Docker Networks
networks:
app-name-ci-network:
driver: bridge
app-name-ci-mysql-network:
driver: bridge
nginx-proxy:
external: true
When I run docker-compose up -d. I can use this command to create a mysql database:
docker exec app-name-ci-mysql-container mysql --defaults-extra-file=/my.cnf -e "create database reseraco_ci_testing"
where my.cnf is file with my database credentials. And everything works fine. But when I try to move everything to jenkins, it looks weird:
This is my Jenkinsfile
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'cd ./ci && docker-compose up -d'
sh 'sleep 10'
sh "docker exec app-name-ci-mysql-container mysql --defaults-extra-file=/my.cnf -e \\\"create database reseraco_ci_testing\\\""
}
}
stage('Test'){
steps {
sh 'docker exec app-name-ci-php-container /var/www/project/vendor/bin/phpunit'
}
}
stage('Deploy') {
steps {
echo "DEPLOYING"
}
}
}
post {
always {
sh 'docker rm app-name-ci-php-container app-name-ci-nginx-container app-name-ci-mysql-container -f'
}
}
}
And when I try to run the pipeline, I get this:
Obtained Jenkinsfile from git https://github.com/resera/project-resera-co
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in /var/jenkins_home/workspace/pipeline2
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Declarative: Checkout SCM)
[Pipeline] checkout
using credential fe238fde-2a82-4f2f-992c-e6a6fcaa805c
> git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
> git config remote.origin.url https://github.com/resera/project-resera-co # timeout=10
Fetching upstream changes from https://github.com/resera/project-resera-co
> git --version # timeout=10
using GIT_ASKPASS to set credentials
> git fetch --tags --progress https://github.com/resera/project-resera-co +refs/heads/*:refs/remotes/origin/*
> git rev-parse refs/remotes/origin/master^{commit} # timeout=10
> git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10
Checking out Revision 5ff27e842bc5f4be1e35a0dc77997cd7b497de39 (refs/remotes/origin/master)
> git config core.sparsecheckout # timeout=10
> git checkout -f 5ff27e842bc5f4be1e35a0dc77997cd7b497de39
Commit message: "quotes"
> git rev-list --no-walk fb92cb934b1b9820bbf9e51f5b295b20b7d2a810 # timeout=10
[Pipeline] }
[Pipeline] // stage
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Build)
[Pipeline] sh
+ cd ./ci
+ docker-compose up -d
The Docker Engine you're using is running in swarm mode.
Compose does not use swarm mode to deploy services to multiple nodes in a swarm. All containers will be scheduled on the current node.
To deploy your application across the swarm, use `docker stack deploy`.
Creating app-name-ci-php-container ...
Creating app-name-ci-mysql-container ...
Creating app-name-ci-nginx-container ...
[1A[2K
Creating app-name-ci-nginx-container ... [32mdone[0m
[1B[3A[2K
Creating app-name-ci-php-container ... [32mdone[0m
[3B[2A[2K
Creating app-name-ci-mysql-container ... [32mdone[0m
[2B
[Pipeline] sh
+ sleep 10
[Pipeline] sh
+ docker exec app-name-ci-mysql-container mysql --defaults-extra-file=/my.cnf -e "create database reseraco_ci_testing"
mysql Ver 8.0.17 for Linux on x86_64 (MySQL Community Server - GPL)
Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Usage: mysql [OPTIONS] [database]
-?, --help Display this help and exit.
-I, --help Synonym for -?
--auto-rehash Enable automatic rehashing. One doesn't need to use
'rehash' to get table and field completion, but startup
and reconnecting may take a longer time. Disable with
--disable-auto-rehash.
(Defaults to on; use --skip-auto-rehash to disable.)
-A, --no-auto-rehash
No automatic rehashing. One has to use 'rehash' to get
table and field completion. This gives a quicker start of
mysql and disables rehashing on reconnect.
--auto-vertical-output
Automatically switch to vertical output mode if the
result is wider than the terminal width.
-B, --batch Don't use history file. Disable interactive behavior.
(Enables --silent.)
--bind-address=name IP address to bind to.
--binary-as-hex Print binary data as hex
--character-sets-dir=name
Directory for character set files.
--column-type-info Display column type information.
-c, --comments Preserve comments. Send comments to the server. The
default is --skip-comments (discard comments), enable
with --comments.
-C, --compress Use compression in server/client protocol.
-#, --debug[=#] This is a non-debug version. Catch this and exit.
--debug-check This is a non-debug version. Catch this and exit.
-T, --debug-info This is a non-debug version. Catch this and exit.
-D, --database=name Database to use.
--default-character-set=name
Set the default character set.
--delimiter=name Delimiter to be used.
--enable-cleartext-plugin
Enable/disable the clear text authentication plugin.
-e, --execute=name Execute command and quit. (Disables --force and history
file.)
-E, --vertical Print the output of a query (rows) vertically.
-f, --force Continue even if we get an SQL error.
--histignore=name A colon-separated list of patterns to keep statements
from getting logged into syslog and mysql history.
-G, --named-commands
Enable named commands. Named commands mean this program's
internal commands; see mysql> help . When enabled, the
named commands can be used from any line of the query,
otherwise only from the first line, before an enter.
Disable with --disable-named-commands. This option is
disabled by default.
-i, --ignore-spaces Ignore space after function names.
--init-command=name SQL Command to execute when connecting to MySQL server.
Will automatically be re-executed when reconnecting.
--local-infile Enable/disable LOAD DATA LOCAL INFILE.
-b, --no-beep Turn off beep on error.
-h, --host=name Connect to host.
-H, --html Produce HTML output.
-X, --xml Produce XML output.
--line-numbers Write line numbers for errors.
(Defaults to on; use --skip-line-numbers to disable.)
-L, --skip-line-numbers
Don't write line number for errors.
-n, --unbuffered Flush buffer after each query.
--column-names Write column names in results.
(Defaults to on; use --skip-column-names to disable.)
-N, --skip-column-names
Don't write column names in results.
--sigint-ignore Ignore SIGINT (CTRL-C).
-o, --one-database Ignore statements except those that occur while the
default database is the one named at the command line.
--pager[=name] Pager to use to display results. If you don't supply an
option, the default pager is taken from your ENV variable
PAGER. Valid pagers are less, more, cat [> filename],
etc. See interactive help (\h) also. This option does not
work in batch mode. Disable with --disable-pager. This
option is disabled by default.
-p, --password[=name]
Password to use when connecting to server. If password is
not given it's asked from the tty.
-P, --port=# Port number to use for connection or 0 for default to, in
order of preference, my.cnf, $MYSQL_TCP_PORT,
/etc/services, built-in default (3306).
--prompt=name Set the mysql prompt to this value.
--protocol=name The protocol to use for connection (tcp, socket, pipe,
memory).
-q, --quick Don't cache result, print it row by row. This may slow
down the server if the output is suspended. Doesn't use
history file.
-r, --raw Write fields without conversion. Used with --batch.
--reconnect Reconnect if the connection is lost. Disable with
--disable-reconnect. This option is enabled by default.
(Defaults to on; use --skip-reconnect to disable.)
-s, --silent Be more silent. Print results with a tab as separator,
each row on new line.
-S, --socket=name The socket file to use for connection.
--server-public-key-path=name
File path to the server public RSA key in PEM format.
--get-server-public-key
Get server public key
--ssl-mode=name SSL connection mode.
--ssl-ca=name CA file in PEM format.
--ssl-capath=name CA directory.
--ssl-cert=name X509 cert in PEM format.
--ssl-cipher=name SSL cipher to use.
--ssl-key=name X509 key in PEM format.
--ssl-crl=name Certificate revocation list.
--ssl-crlpath=name Certificate revocation list path.
--tls-version=name TLS version to use, permitted values are: TLSv1, TLSv1.1,
TLSv1.2, TLSv1.3
--ssl-fips-mode=name
SSL FIPS mode (applies only for OpenSSL); permitted
values are: OFF, ON, STRICT
--tls-ciphersuites=name
TLS v1.3 cipher to use.
-t, --table Output in table format.
--tee=name Append everything into outfile. See interactive help (\h)
also. Does not work in batch mode. Disable with
--disable-tee. This option is disabled by default.
-u, --user=name User for login if not current user.
-U, --safe-updates Only allow UPDATE and DELETE that uses keys.
-U, --i-am-a-dummy Synonym for option --safe-updates, -U.
-v, --verbose Write more. (-v -v -v gives the table output format).
-V, --version Output version information and exit.
-w, --wait Wait and retry if connection is down.
--connect-timeout=# Number of seconds before connection timeout.
--max-allowed-packet=#
The maximum packet length to send to or receive from
server.
--net-buffer-length=#
The buffer size for TCP/IP and socket communication.
--select-limit=# Automatic limit for SELECT when using --safe-updates.
--max-join-size=# Automatic limit for rows in a join when using
--safe-updates.
--show-warnings Show warnings after every statement.
-j, --syslog Log filtered interactive commands to syslog. Filtering of
commands depends on the patterns supplied via histignore
option besides the default patterns.
--plugin-dir=name Directory for client-side plugins.
--default-auth=name Default authentication client-side plugin to use.
--binary-mode By default, ASCII '\0' is disallowed and '\r\n' is
translated to '\n'. This switch turns off both features,
and also turns off parsing of all clientcommands except
\C and DELIMITER, in non-interactive mode (for input
piped to mysql or loaded using the 'source' command).
This is necessary when processing output from mysqlbinlog
that may contain blobs.
--connect-expired-password
Notify the server that this client is prepared to handle
expired password sandbox mode.
--network-namespace=name
Network namespace to use for connection via tcp with a
server.
Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /my.cnf ~/.my.cnf
The following groups are read: mysql client
The following options may be given as the first argument:
--print-defaults Print the program argument list and exit.
--no-defaults Don't read default options from any option file,
except for login file.
--defaults-file=# Only read default options from the given file #.
--defaults-extra-file=# Read this file after the global files are read.
--defaults-group-suffix=#
Also read groups with concat(group, suffix)
--login-path=# Read this path from the login file.
Variables (--variable-name=value)
and boolean options {FALSE|TRUE} Value (after reading options)
--------------------------------- ----------------------------------------
auto-rehash TRUE
auto-vertical-output FALSE
bind-address (No default value)
binary-as-hex FALSE
character-sets-dir (No default value)
column-type-info FALSE
comments FALSE
compress FALSE
database (No default value)
default-character-set auto
delimiter ;
enable-cleartext-plugin FALSE
vertical FALSE
force FALSE
histignore (No default value)
named-commands FALSE
ignore-spaces FALSE
init-command (No default value)
local-infile FALSE
no-beep FALSE
host (No default value)
html FALSE
xml FALSE
line-numbers TRUE
unbuffered FALSE
column-names TRUE
sigint-ignore FALSE
port 0
prompt mysql>
quick FALSE
raw FALSE
reconnect FALSE
socket (No default value)
server-public-key-path (No default value)
get-server-public-key FALSE
ssl-ca (No default value)
ssl-capath (No default value)
ssl-cert (No default value)
ssl-cipher (No default value)
ssl-key (No default value)
ssl-crl (No default value)
ssl-crlpath (No default value)
tls-version (No default value)
tls-ciphersuites (No default value)
table FALSE
user root
safe-updates FALSE
i-am-a-dummy FALSE
connect-timeout 0
max-allowed-packet 16777216
net-buffer-length 16384
select-limit 1000
max-join-size 1000000
show-warnings FALSE
plugin-dir (No default value)
default-auth (No default value)
binary-mode FALSE
connect-expired-password FALSE
network-namespace (No default value)
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Test)
Stage "Test" skipped due to earlier failure(s)
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Deploy)
Stage "Deploy" skipped due to earlier failure(s)
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] sh
+ docker rm app-name-ci-php-container app-name-ci-nginx-container app-name-ci-mysql-container -f
app-name-ci-php-container
app-name-ci-nginx-container
app-name-ci-mysql-container
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: script returned exit code 1
Finished: FAILURE
I mean, instead of creating the new database, I get this mysql help response. Trying to fix this for 5 hours. At first I tried to use -p with password, but mysql gave me a warning that it is unsafe, and I guess that warning is breaking the pipeline. So I found a solution, by adding my credentials to cnf file and specify it by using default-extra-file option. Now file is seems found, but I cant understand why Im getting mysql help instead of command executon. maybe someone can help me?

Mostly the -e parameters you are passing to the docker command is not working properly, you could try printing the values of the given parameters inside the container and see if you are reading them correctly

I had the same problem, I was able to solve it by copying the cnf configuration file in the container
Following my error in jenkins
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
Build step 'Execute shell' marked build as failure
The error occurs when you put the password in the command line
Solved by using docker cp in my job before run mysql command
https://docs.docker.com/engine/reference/commandline/cp/
docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH
or
docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH
Hope it's help :-)

Related

How to make Jenkins to use private key and passphrase to run Ansible playbook

I am using Jenkins to run some Ansible playbooks. One of the simple tests I did was to have the playbook to cat the fstab file on a remote server:
The playbook looks like this:
---
- hosts: "tesst-1-server"
tasks:
- name: dislpay /etc/fstab
shell: cat /etc/fstab
register: fstab_reg
- debug: msg="{{ fstab_reg.stdout }}"
In Jenkins, I have a freestyle project, it uses Invoke Ansible Playbook to call the above playbook, and the project credentials was setup with a different: ansible-user. This is different from the default user-jenkins that runs Jenkins. User ansible-user can ssh to all my servers. I have ansible-user setup in Jenkins Credential with its private key and passphrase. But when I run the project, I got an error:
[update_fstab] $ /usr/bin/ansible-playbook google/ansible/test-scripts/test/sub_book.yml -i /etc/ansible/hosts -f 5 --private-key /tmp/ssh14117407503194058572.key -u ansible-user
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
fatal: [test-1-server]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ansible-user#test-1-server: Permission denied (publickey).", "unreachable": true}
I am not quiet sure what exactly the error is saying as I have setup the private key and passphrase to ansible-user's credentials. What does the group names in the message mean? Because this is done through Jenkins, I am not sure how to do the -vvv as it suggested.
How can I make Jenkins to pass the private key and passphrase to the Ansible playbook?
Thanks!
I think I have found the "issue". After I switched to a different user other than ansible-user, the playbook worked. Interesting thing is that when I created the private key pairs for ansible-user, I used "-m PEM" and it should be good for Jenkins.

Getting HTTP ERROR: 404 for Jenkins after forwarding port with public IP

I have Jenkins locally running on port 8081 on a linux machine that is setup in office .
I have a public IP that I am trying to use to make Jenkins publicly available.
I have entered the public IP with port in Manage Jenkins -> Configure System -> Jenkins
URL like: http://182.156.xxx.xx:8081/
Now if I direct to http://182.156.xxx.xx:8081/ , it gives me HTTP 404 error(screenshot attached).
Note: I have setup the Jenkins in Ubuntu with below commands:
wget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo apt-key add -
sudo sh -c 'echo deb https://pkg.jenkins.io/debian-stable binary/ >
/etc/apt/sources.list.d/jenkins.list'
sudo apt-get update
sudo apt-get install jenkins
etc/default/jenkins file:
# defaults for Jenkins automation server
# pulled in from the init script; makes things easier.
NAME=jenkins
# arguments to pass to java
# Allow graphs etc. to work even when an X server is present
JAVA_ARGS="-Djava.awt.headless=true"
#JAVA_ARGS="-Xmx256m"
# make jenkins listen on IPv4 address
#JAVA_ARGS="-Djava.net.preferIPv4Stack=true"
PIDFILE=/var/run/$NAME/$NAME.pid
# user and group to be invoked as (default to jenkins)
JENKINS_USER=$NAME
JENKINS_GROUP=$NAME
# location of the jenkins war file
JENKINS_WAR=/usr/share/$NAME/$NAME.war
# jenkins home location
JENKINS_HOME=/var/lib/$NAME
# set this to false if you don't want Jenkins to run by itself
# in this set up, you are expected to provide a servlet container
# to host jenkins.
RUN_STANDALONE=true
# log location. this may be a syslog facility.priority
JENKINS_LOG=/var/log/$NAME/$NAME.log
#JENKINS_LOG=daemon.info
# Whether to enable web access logging or not.
# Set to "yes" to enable logging to /var/log/$NAME/access_log
JENKINS_ENABLE_ACCESS_LOG="no"
# OS LIMITS SETUP
# comment this out to observe /etc/security/limits.conf
# this is on by default because http://github.com/jenkinsci/jenkins/commit/2fb288474e980d0e7ff9c4a3b768874835a3e92e
# reported that Ubuntu's PAM configuration doesn't include pam_limits.so, and as a result the # of file
# descriptors are forced to 1024 regardless of /etc/security/limits.conf
MAXOPENFILES=8192
# set the umask to control permission bits of files that Jenkins creates.
# 027 makes files read-only for group and inaccessible for others, which some security sensitive users
# might consider benefitial, especially if Jenkins runs in a box that's used for multiple purposes.
# Beware that 027 permission would interfere with sudo scripts that run on the master (JENKINS-25065.)
#
# Note also that the particularly sensitive part of $JENKINS_HOME (such as credentials) are always
# written without 'others' access. So the umask values only affect job configuration, build records,
# that sort of things.
#
# If commented out, the value from the OS is inherited, which is normally 022 (as of Ubuntu 12.04,
# by default umask comes from pam_umask(8) and /etc/login.defs
# UMASK=027
# port for HTTP connector (default 8080; disable with -1)
HTTP_PORT=8081
# servlet context, important if you want to use apache proxying
PREFIX=/$NAME
# arguments to pass to jenkins.
# --javahome=$JAVA_HOME
# --httpListenAddress=$HTTP_HOST (default 0.0.0.0)
# --httpPort=$HTTP_PORT (default 8080; disable with -1)
# --httpsPort=$HTTP_PORT
# --argumentsRealm.passwd.$ADMIN_USER=[password]
# --argumentsRealm.roles.$ADMIN_USER=admin
# --webroot=~/.jenkins/war
# --prefix=$PREFIX
JENKINS_ARGS="--webroot=/var/cache/$NAME/war --httpPort=$HTTP_PORT"
In this jenkins file, I have only changed the HTTP PORT from 8080 to 8081. As on port 8080, the jenkins is already running with the same public IP.
Jenkins version : 2.289.2
Java version : 8
Ubuntu version : 20.04
jenkins_error_screenshot

Trouble mounting volume in docker within Jenkins pipeline

I'm running flyway within my Jenkins pipeline. The docker image works and flyway runs fine. I can call flyway baseline to initialize the schema and that's about as far as I can get.
I'm attempting to mount the directory "Database/migrations" in the docker image using image.withRun('-v /Database/migrations:/migrations'... as listed in the segment below, but I'm not having any luck.
// git clone
stage("Checkout") {
checkout scm
}
// db migration
stage('Apply DB changes') {
sh "ls Database/migrations"
def flyway = docker.image('flyway/flyway')
flyway.withRun('-v /Database/migrations:/migrations',
'-url=jdbc:mysql://****:3306/**** -user=**** -password=**** -X -locations="filesystem:/migrations" migrate') { c ->
sh "docker exec ${c.id} ls flyway"
sh "docker logs --follow ${c.id}"
}
}
Below is the debug from Jenkins for that stage (cleaned up for simplicity) and notice there is nothing under "migrations".
[Pipeline] { (Apply DB changes)
[Pipeline] sh
+ ls Database/migrations
V2__create_temp_table.sql
[Pipeline] isUnix
[Pipeline] sh
+ docker run -d -v /Database/migrations:/migrations flyway/flyway -url=jdbc:mysql://****:3306/**** -user=**** '-password=****' -X -locations=filesystem:/migrations migrate
[Pipeline] sh
+ docker exec 12461436e4cb1150a20d8fca13ef7691d66528a11864ab17600bb994a1248675 ls /migrations
[Pipeline] sh
+ docker logs --follow 12461436e4cb1150a20d8fca13ef7691d66528a11864ab17600bb994a1248675
DEBUG: Loading config file: /flyway/conf/flyway.conf
DEBUG: Unable to load config file: /flyway/flyway.conf
DEBUG: Unable to load config file: /flyway/flyway.conf
DEBUG: Using configuration:
DEBUG: flyway.locations -> filesystem:/migrations
Flyway Community Edition 7.5.3 by Redgate
DEBUG: Scanning for filesystem resources at '/migrations'
DEBUG: Scanning for resources in path: /migrations (/migrations)
DEBUG: Driver : MySQL Connector/J mysql-connector-java-8.0.20 (Revision: afc0a13cd3c5a0bf57eaa809ee0ee6df1fd5ac9b)
DEBUG: Validating migrations ...
Successfully validated 1 migration (execution time 00:00.033s)
Current version of schema `****`: 1
Schema `****` is up to date. No migration necessary.
Any and all advice is greatly appreciated! Thanks in advance!
Database/migrations is different from /Database/migrations
my $WORKSPACE var is actually pointing to /var/lib/jenkins/workspace/... so I needed to update the mount path to $WORKSPACE/Database/migrations:/migrations 🤦🏻‍♂️

Capistrano is failing because it cannot connect to remote git repository

I am trying to deploy using Capistrano 3.x.
I configured agent forwarding in my ~/.ssh/config file:
Host git-codecommit.*.amazonaws.com
Hostname xxxx
ForwardAgent yes
IdentityFile /path/to/codecommit_rsa
I did the same thing for my server connection with ForwardAgent yes also.
I verified my server allows agent forwarding in the /etc/ssh/sshd_config file also:
AllowAgentForwarding yes
INFO ----------------------------------------------------------------
INFO START 2017-11-18 16:09:44 -0500 cap production deploy
INFO ---------------------------------------------------------------------------
INFO [b43ed70f] Running /usr/bin/env mkdir -p /tmp as deploy#50.116.2.15
DEBUG [b43ed70f] Command: /usr/bin/env mkdir -p /tmp
INFO [b43ed70f] Finished in 1.132 seconds with exit status 0 (successful).
DEBUG Uploading /tmp/git-ssh-testapp-production-blankman.sh 0.0%
INFO Uploading /tmp/git-ssh-testapp-production-blankman.sh 100.0%
INFO [b1a90dc1] Running /usr/bin/env chmod 700 /tmp/git-ssh-testapp-production-blankman.sh as deploy#50.116.2.15
DEBUG [b1a90dc1] Command: /usr/bin/env chmod 700 /tmp/git-ssh-testapp-production-blankman.sh
INFO [b1a90dc1] Finished in 0.265 seconds with exit status 0 (successful).
INFO [b323707d] Running /usr/bin/env git ls-remote ssh://git-codecommit.us-east-1.amazonaws.com/v1/repos/fuweb HEAD as deploy#50.116.2.15
DEBUG [b323707d] Command: ( export GIT_ASKPASS="/bin/echo" GIT_SSH="/tmp/git-ssh-testapp-production-blankman.sh" ; /usr/bin/env git ls-remote ssh://git-codecommit.us-east-1.amazonaws.com/v1/repos/fuweb HEAD )
DEBUG [b323707d] Permission denied (publickey).
DEBUG [b323707d] fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
What am I missing here?
You need to make Capistrano aware that you expect it to forward your local key. This can be done by going into you project's config/deploy.rb and adding this line:
ssh_options[:forward_agent] = true
IIRC, Capistrano executes commands remotely through SSHKit, so even if you invoke the ssh-agent and add a key locally, I can't say if it will persist for the next command.
As discussed in the comments, an SSH agent must run on the remote server as well as on the local machine that contains the key because the agents at each end need to cooperate to forward the key information. The agent (ssh-agent) is different from the SSH server (sshd). The server accepts connections, while the (otherwise optional) agent manages credentials.
Some systems start an agent automatically upon login. To check if this is the case, log in to the server and run:
$ env | grep SSH
...looking for variables like SSH_AGENT_PID or SSH_AGENT_SOCK. If it isn't started, we can execute the following command to start the agent on the server:
$ eval "$(ssh-agent)"
As we can see, this evaluates the output of the ssh-agent command because ssh-agent returns a script that sets some needed environment variables in the session.
We'll need to make sure the agent starts automatically upon login so that it doesn't interfere with the deploy process. If we checked and determined that the agent does not, in fact, start on login, we can add the last command to the "deploy" user's ~/.profile file (or ~/.bash_profile).
Note also that the host specified in the local ~/.ssh/config must match the name or IP address of the host that we want to forward credentials to, not the host that ultimately authenticates using the forwarded key. We need to change:
Host git-codecommit.*.amazonaws.com
...to:
Host 50.116.2.15
We can verify that the SSH client performs agent forwarding by checking the verbose output:
$ ssh -v deploy#50.116.2.15
...
debug1: Requesting authentication agent forwarding.
...
Of course, be sure to register any needed keys with the local agent by using ssh-add (this can also be done automatically when logging in as shown above). We can check which keys the agent loaded at any time with:
$ ssh-add -l
This usually helps me:
ssh-add -D
ssh-agent
ssh-add

Not able to make Jenkins perforce plugin to work with ssh

I am not quite familiar with Jenkins but for some reason I am not able to make the perforce plugin to work. I will list down the problem and what I have tried so as to get a better understanding.
Jenkins Version - 1.561
Perforce Plugin Version - 1.3.27 (I have perforce path configured in Jenkins)
System - Ubuntu 10.04
Problem:
In the Source Code Management's Project Details section ( when you try to configure a new job ) I get "Unable to check workspace against depot" error.
P4PORT(hostname:port) - rsh:ssh -q -a -x -l p4ssh -q -x xxx.xxx.com /bin/true
Username - ialok
Password - N.A (Connection to SCM is via key authentication so left it blank)
Workspace(client) - ialok_jenkins
I let Jenkins create workspace and manage its view by checking the checkbox for both "Let Jenkins Create Workspace" and "Let Jenkins Manage Workspace View"
Client View Type is a View Map with the following mapping:
//sandbox/srkamise/... //ialok_jenkins/srkamise/...
I have the keys loaded prior to starting jenkins and the jenkins process runs as my user (ialok)
~$ ps aux | grep jenkins
ialok 16608 0.0 0.0 14132 552 ? Ss 11:08 0:00 /usr/bin/daemon --name=ialok --inherit --env=JENKINS_HOME=/var/lib/jenkins --output=/var/log/jenkins/jenkins.log --pidfile=/var/run/jenkins/jenkins.pid -- /usr/bin/java -Djava.awt.headless=true -jar /usr/share/jenkins/jenkins.war --webroot=/var/cache/jenkins/war --httpPort=8080 --ajp13Port=-1
ialok 16609 1.0 13.9 1448716 542156 ? Sl 11:08 1:04 /usr/bin/java -Djava.awt.headless=true -jar /usr/share/jenkins/jenkins.war --webroot=/var/cache/jenkins/war --httpPort=8080 --ajp13Port=-1
Additionally, I used envInject plugin and "Under Prepare an environment for the run" I added SSD_AGENT_PID, SSH_AUTH_SOCK, P4USER, P4PORT environment parameters. (I did try without envInject but faced the same issue)
It looks like some authentication problem as I double checked the path to p4 executable along with the project mapping and addition of keys to my environment.
Here is the log file indicating a failed run:
Started by user anonymous
[EnvInject] - Loading node environment variables.
[EnvInject] - Preparing an environment for the build.
[EnvInject] - Keeping Jenkins system variables.
[EnvInject] - Keeping Jenkins build variables.
[EnvInject] - Injecting as environment variables the properties content
P4CONFIG=.perforce
P4PORT=rsh:ssh -q -a -x -l p4ssh -q -x xxx.xxx.com /bin/true
P4USER=ialok
SSH_AGENT_PID=25752
SSH_AUTH_SOCK=/tmp/keyring-7GAS75/ssh
[EnvInject] - Variables injected successfully.
[EnvInject] - Injecting contributions.
Building in workspace /var/lib/jenkins/jobs/fin/workspace
Using master perforce client: ialok_jenkins
[workspace] $ /usr/bin/p4 workspace -o ialok_jenkins
Changing P4 Client Root to: /var/lib/jenkins/jobs/fin/workspace
Changing P4 Client View from:
Changing P4 Client View to:
//sandbox/srkamise/... //ialok_jenkins/srkamise/...
Saving new client ialok_jenkins
[workspace] $ /usr/bin/p4 -s client -i
Caught exception communicating with perforce. TCP receive failed. read: socket: Connection reset by peer
For Command: /usr/bin/p4 -s client -i
With Data:
===================
Client: ialok_jenkins
Description:
Root: /var/lib/jenkins/jobs/fin/workspace
Options: noallwrite clobber nocompress unlocked nomodtime rmdir
LineEnd: local
View:
//sandbox/srkamise/... //ialok_jenkins/srkamise/...
===================
com.tek42.perforce.PerforceException: TCP receive failed. read: socket: Connection reset by peer
For Command: /usr/bin/p4 -s client -i
With Data:
===================
Client: ialok_jenkins
Description:
Root: /var/lib/jenkins/jobs/fin/workspace
Options: noallwrite clobber nocompress unlocked nomodtime rmdir
LineEnd: local
View:
//sandbox/srkamise/... //ialok_jenkins/srkamise/...
===================
at com.tek42.perforce.parse.AbstractPerforceTemplate.saveToPerforce(AbstractPerforceTemplate.java:270)
at com.tek42.perforce.parse.Workspaces.saveWorkspace(Workspaces.java:77)
at hudson.plugins.perforce.PerforceSCM.saveWorkspaceIfDirty(PerforceSCM.java:1787)
at hudson.plugins.perforce.PerforceSCM.checkout(PerforceSCM.java:895)
at hudson.model.AbstractProject.checkout(AbstractProject.java:1251)
at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:604)
at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:513)
at hudson.model.Run.execute(Run.java:1709)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:88)
at hudson.model.Executor.run(Executor.java:231)
ERROR: Unable to communicate with perforce. TCP receive failed. read: socket: Connection reset by peer
For Command: /usr/bin/p4 -s client -i
With Data:
===================
Client: ialok_jenkins
Description:
Root: /var/lib/jenkins/jobs/fin/workspace
Options: noallwrite clobber nocompress unlocked nomodtime rmdir
LineEnd: local
View:
//sandbox/srkamise/... //ialok_jenkins/srkamise/...
===================
Finished: FAILURE
The P4PORT typically is of the form 'hostname.port'. Examples would be:
workshop.perforce.com:1666
myserver.mycompany.net:2500
Here's some docs: http://www.perforce.com/perforce/doc.current/manuals/cmdref/P4PORT.html

Resources