How to execute an ansible playbook using a jenkins pipeline script?

10,026

If you have Jenkins user public key, on your target hosts authorized keys file, for the user you want to login as, ssh connection authorization should work.

This is an example of Jenkinsfile step.

ansiblePlaybook colorized: true, installation: 'Ansible', inventory: 'inventory', playbook: 'playbook.yml',tags: "" , skippedTags: "", extras: "--extra-vars ' hst=targetHost "

This is Ansible Inventory example. You can define the args at the host level as well.

[targetHost]
17.14.69.21 ansible_ssh_user=sshuser

[all:vars]
ansible_connection=ssh
ansible_ssh_common_args='-o StrictHostKeyChecking=no -oHostKeyAlgorithms=+ssh-dss'
Share:
10,026
Samy Omar
Author by

Samy Omar

Updated on September 18, 2022

Comments

  • Samy Omar
    Samy Omar almost 2 years

    We developed declarative pipeline code to execute an Ansible playbook. We tested the playbook from CLI and it is working properly. My playbook actually performs some shell commands on remote server.

    SSH configuration between two servers has been done: I have generated an ssh key and copied it to the remote server, and I am able to ping the server.

    The Error msg:

    ansible-playbook /var/lib/jenkins/workspace/test1/playbook2.yml -i 
    /var/lib/jenkins/workspace/test1/inventory.ini -b --become-user root
    [WARNING] Ansible is in a world writable directory 
    (/var/lib/jenkins/workspace/test1), ignoring it as an ansible.cfg source
    
    fatal: [17.14.69.21]: UNREACHABLE! => {"changed": false, "msg": "Failed to 
    connect to the host via ssh: Permission denied (publickey,gssapi- 
    keyex,gssapi-with-mic,password).\r\n", "unreachable": true}
    [17.14.69.21]: 
    FATAL: command execution failed
    hudson.AbortException: Ansible playbook execution failed.
    

    I have given sudo access to Jenkins user and Jenkins is running as Jenkins user.

  • Tensibai
    Tensibai over 5 years
    Please avoid using the answer section as comment, this is not an answer to the question and --become-user root is to tell ansible to sudo to user root before doing anything else, the solution is not to allow root login as it won't fix the login problem anyway..
  • Samy Omar
    Samy Omar over 5 years
    Hi, Finally i did it... Added ssh key into known_host jenkins workspace. And in inventory host given the servers details in below format. [jboss] 192.xx.xx.xx. ansible_ssh_pass=xxxxx123 ansible_ssh_user=user1
  • hakkican
    hakkican over 5 years
    In inventory file I would not put user/password. You can direct keys path in that file. "--become-user root" why do you need this ?
  • Samy Omar
    Samy Omar over 5 years
    I dont know the logc behind it. I also tried without mentioning user/password. It doesnt worked for me. After executing this i tried multiple possibilities still it only worked when i mention user/password.