TransWikia.com

Running ansible playbook commands inside docker image using jenkins pipeline

Server Fault Asked by khyathi on January 27, 2021

I have a requirement to create docker ansible image and running playbook using jenkins pipeline.

I have created docker image, but I don’t understand how docker ansible ssh keys are copied to remote ansible host. Does that setup need to be done in advance?

One Answer

You mentioned you are using Jenkins to do this. There is a plugin called "SSH Agent" which allows you to run your scripts within SSH private key context even inside a docker container.

First of all, make sure plugin is installed in Jenkins

Next, register SSH private key in Jenkins Secrets

Then you can reuse secret ID in your job like shown in example below:

pipeline {
  agent {
    label "docker"
  }

  environment {
    ANSIBLE_VAULT_PASSWORD = credentials('ANSIBLE_VAULT_PASSWORD')
  }

  options {
    timeout(time: 60, unit: "MINUTES")
  }

  stages {
    stage('Run Ansible playbook') {
      agent {
        docker {
          image 'hippolab/ansible'
          args '-u 0:0'
          reuseNode true
        }
      }
      steps {
        sshagent(credentials : ['MY_SSH_KEY_SECRET_ID']) {
          sh '''
            ansible-galaxy install -r requirements.yml
            echo ${ANSIBLE_VAULT_PASSWORD} | ansible-playbook 
              --inventory-file hosts 
              --extra-vars ansible_ssh_common_args='"-o StrictHostKeyChecking=no -o ServerAliveInterval=30"' 
              --ask-vault-pass 
              my_playbook.yml
          '''
        }
      }
    }
  }

  post {
    always {
      deleteDir()
    }
  }

}

Author experience:

  • If Ansible Vault is used, the password can be passed to ansible-playbook tool using shell pipe
  • StrictHostKeyChecking=no is crucial unless you set up your slaves statically and has all the nodes keys preaccepted manually which is not the case in 99% of occasions
  • ServerAliveInterval=30 can be omitted unless you have strict SSH server on that side which terminates connections due to innactivity. Help if some Ansible tasks take long to complete

Answered by Владимир Тюхтин on January 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP