Skip to end of metadata
Go to start of metadata

Plugin Information

View Ansible on the plugin site for more information.

Older versions of this plugin may not be safe to use. Please review the following warnings before using an older version:

 

 This plugin allows to execute Ansible tasks as a job build step.

Table of Contents

Global Configuration

Ansible needs to be on the PATH for the build job in order to be used. This can be done through either Jenkins Global Tool Configuration or including Ansible on the OS User PATH variable.

Global Tool Configuration

Configuring Ansible through the Global Tool Configuration in Jenkins (Jenkins → Manage Jenkins → Global Tool Configuration) allows for multiple Ansible installations to be present and used by different Jenkins jobs.

  1. Click Add Ansible
  2. Configure the name and path

    Field name

    Description

    Name

    Symbolic name used to identify a specific Ansible installation when multiple installations are configured

    Path to ansible executables directory

    Directory containing the ansible, ansible-playbook, and ansible-vault binaries

  3. Repeat for any additional desired installations

 

OS User PATH

Ansible can also be added to the PATH user used by the Jenkins executor instead of configured through Global Tool Configuration. This is done through normal OS tools outside of Jenkins and is not covered by this guide.

 


Adhoc

Adhoc commands allow for simple operations to be done without writing a full playbook. This allows for a convenient way of doing quick tasks with Ansible.

Examples

Scripted

Due to JENKINS-43782 and JENKINS-49056, adhoc commands cannot be run with a pipeline job.

Declarative

 

Arguments

See also jenkins.io documentation.

Freestyle NamePipeline NameDescription
Ansible installation Ansible installation to use for the playbook invocation
Host pattern The host pattern to manage. See Ansible Patterns for details.
Module CLI arg: -m
Module arguments or command to execute CLI arg: -a
Inventory file or host list 

See the Inventory section for additional details.

CLI arg: -i

Inventory Inline content 

See the Inventory section for additional details.

CLI arg: -i

Credentials 

The Jenkins credential to use for the SSH connection. See the Authentication section for additional details.

Vault Credentials 

The Jenkins credential to use as the vault credential. See the Vault Credentials section for additional details.

CLI arg: --vault-password-file

sudo CLI arg: -s
sudo user CLI arg: -U
Number of parallel processes CLI arg: -f
Check host SSH key 

Toggle checking of the host key.

Sets the environment variable ANSIBLE_HOST_KEY_CHECKING, similar to the recommendations for running with Vagrant.

Unbuffered stdout 

Toggle buffering of standard out.

Sets the environment variable PYTHONUNBUFFERED, similar to the recommendations for running with Vagrant.

Colorized stdout 

Toggle color codes in console text. See Colorized Output section for example usage.

Sets the environment variable ANSIBLE_FORCE_COLOR, similar to the recommendations for running with Vagrant.

Extra Variables CLI arg: -e
Additional parameters String passed to the Ansible Command Line invocation as-is

 


Playbook

 

Ansible playbook operations can be run with the plugin. The plugin provides several conveniences such as easily using credentials from the Jenkins credential store, unbuffered color output in the log, etc. 

Examples

Scripted

Jenkinsfile
ansiblePlaybook credentialsId: 'private_key', inventory: 'inventories/a/hosts', playbook: 'my_playbook.yml'

 

Declarative

Jenkinsfile
ansiblePlaybook(credentialsId: 'private_key', inventory: 'inventories/a/hosts', playbook: 'my_playbook.yml')

 

Additional scripted and declarative pipeline examples can be found on the plugin's GitHub readme.

Arguments

jenkins.io documentation

Freestyle NamePipeline NameDescription
Ansible installationinstallationAnsible installation to use for the playbook invocation
Playbook pathplaybookMandatory. The name of the playbook to run.
Inventory file or host listinventory

See the Inventory section for additional details.

CLI arg: -i

Inventory Inline contentinventoryContent

See the Inventory section for additional details.

CLI arg: -i

CredentialscredentialsId

The Jenkins credential to use for the SSH connection. See the Authentication section for additional details.

Vault CredentialsvaultCredentialsId

The Jenkins credential to use as the vault credential. See the Vault Credentials section for additional details.

CLI arg: --vault-password-file

sudosudoCLI arg: -s
sudo usersudoUserCLI arg: -U
Host subsetlimitCLI arg: -l
Tags to runtagsCLI arg: -t
Tags to skipskippedTagsCLI arg: --skip-tags
Task to start atstartAtTaskCLI arg: --start-at-task
Number of parallel processesforksCLI arg: -f
Check host SSH keyhostKeyChecking

Toggle checking of the host key.

Sets the environment variable ANSIBLE_HOST_KEY_CHECKING, similar to the recommendations for running with Vagrant.

Colorized stdoutcolorized

Toggle color codes in console text. See Colorized Output section for example usage.

Sets the environment variable ANSIBLE_FORCE_COLOR, similar to the recommendations for running with Vagrant.

Additional parametersextrasString passed to the Ansible Command Line invocation as-is
Extra VariablesextraVarsCLI arg: -e

Refer to the ansible-playbook manual page for details on how each command line argument is interpretted.

Authentication

SSH Keys

SSH keys are the recommended authentication method for SSH connections. The plugin supports the credential type "SSH Username with private key" configured in the Jenkins credential store through the SSH crendentials plugin.

Password

Even if using SSH keys is recommended authentication method, password authentication may sometimes be required. The plugin has supported password based authentication since 0.3.0. When using password based authentication, the sshpass binary is expected to be on the PATH. The plugin supports the credential type "Username with password" configured in the Jenkins credential store through the SSH crendentials plugin.

Vault Credentials

Vault credentials can be setup in the Jenkins credential store as either a "Secret text" or a "Secret file". 

Colorized Output

The AnsiColor plugin is needed for colorized console output. Once installed, colorized output can be enabled with the argument "colorized: true".

Jenkinsfile
ansiColor('xterm') {
    ansiblePlaybook( 
        playbook: 'path/to/playbook.yml',
        inventory: 'path/to/inventory.ini', 
        credentialsId: 'sample-ssh-key',
        colorized: true) 
}


Extra Parameters

Extra parameters is a string passed to the Ansible Command Line invocation as-is and can be useful for arguments occasionally added to an invocation at runtime, such as tags and host limits.

Inventory

File

A string path to the inventory file to use with the playbook invocation.

Inline

The provided content is used as the content of the inventory file for the playbook invocation.

Using Jenkins Environment Variables

Jenkins environment variables can be accessed from within an Ansible playbook. The Jenkins variables are injected as environment variables making them available through the Ansible lookup plugin.

The following Ansible playbook accesses the Jenkins BUILD_TAG variable:

playbook.yml
---
- hosts: example
  tasks:
    - debug: msg="{{ lookup('env','BUILD_TAG') }}"

 


Vault

Most Ansible Vault operations can be performed with the plugin. Interactive operations such as create, edit, and view are not supported through the plugin. One use case for this enabling developers to encrypt secret values while keeping the vault password a secret.

Examples

Scripted

Encrypts a File
ansibleVault action: 'encrypt', input: 'vars/secrets.yml', vaultCredentialsId: 'ansible_vault_credentials'
Encrypts a String
ansibleVault action: 'encrypt_string', content: 'secret_content', vaultCredentialsId: 'ansible_vault_credentials'

Declarative

Jenkinsfile
ansibleVault(action: 'encrypt', input: 'vars/secrets.yml', vaultCredentialsId: 'ansible_vault_credentials')
Jenkinsfile
ansibleVault(action: 'encrypt_string', content: 'secret_content', vaultCredentialsId: 'ansible_vault_password')

 

Arguments

See also jenkins.io documentation.

Freestyle NamePipeline NameDescription
Ansible installationinstallationAnsible installation to use for the vault operation
ActionactionMandatory. The name of the action to use. Interactive operations such as create, edit, and view are not supported.
Vault CredentialsvaultCredentialsId

The Jenkins credential to use as the vault credential. See the Vault Credentials section for additional details.

CLI arg: --vault-password-file

New Vault CredentialsnewVaultCredentialsId

The Jenkins credential to use as the vault credential. See the Vault Credentials section for additional details.

CLI arg: --new-vault-password-file

ContentcontentThe content to encrypt with the encrypt_string action
InputinputThe file to encrypt with the encrypt action
OutputoutputCLI arg: --output

Vault Credentials

Vault credentials can be setup in the Jenkins credential store as either a "Secret text" or a "Secret file". 

 


Open Issues

T Key Summary Assignee Reporter Status Created
Loading...
Refresh

See also All Open Items

 


Changelog

Version 1.0 (26 March 2018)

      • Fix security issue: Do not disable host key verification by default. This may break existing configurations as host key verification will be enabled everywhere by default.

Version 0.8.0 (16 Jan 2018) 

Version 0.6.2 (3 Jan 2017) 

Version 0.6.1 (1 Jan 2017)

      • Use latest parent project definition in order to deploy plugin (thanks to alecharp for the help and the PR)

Version 0.6 (31 Dec 2016)

WARN: 0.6.x version will be the last one to support Jenkins 1.xxx and Ansible 1.x - The 0.7.x and next releases will require Jenkins 2.32.1 (or higher) and Ansible 2.2 (or higher)

      • Add a "do not specify" option for inventory [JENKINS-34627]
      • Support inventoryContent in pipeline (thanks to leewin12 for the PR)
      • Add support of extra variables in jobdsl (thanks to pawbur for the PR)
      • Support empty forks (number of parallel processes) parameter [JENKINS-39438]
      • Escape '%' character in private key path (thanks to ewollesen for the PR) 
      • Omit ansible option when expanded environment variable is empty (thanks to vjestin for the PR) 
      • Add the --forks parameter configurable in pipeline step (thanks to anguswilliams for the PR)
      • Fix usage of environment variable in ansiblePlaybook pipeline step (thanks to thomasKalmar and barthorre for the PR) [JENKINS-38289]

Version 0.5 (5 May 2016) 

      • Add support for ansible extra variables [JENKINS-29863]
      • Improve Pipeline plugin integration [JENKINS-32911]
      • Add the possibility to use the default inventory file (thanks to Johann Schmitz for the PR)
      • Add colorized output in pipeline jobs (thanks to Kirill Merkushev for the PR)
      • Make Jenkins build variables available as environment variables for ansible (thanks to Kevin Mooney for the PR) [JENKINS-29284]

Version 0.4 (25 December 2015) 

      • Support for password protected SSH keys [JENKINS-30656]
      • Initial support for the workflow plugin [JENKINS-30398]
      • Add support for Job DSL plugin (thanks to Kirill Merkushev for the PR) [JENKINS-31790]

Version 0.3.1 (15 July 2015) 

Version 0.3 (20 June 2015) 

      • Add support for password based SSH authentication (with sshpass)
      • Environment variables can be used in Module and Module arguments text field in Ad-hoc command builder
      • Environment variables can be used in inline inventory text box [JENKINS-28547]

Version 0.2 (11 May 2015) 

      • Fix NullPointerException when no credentials are selected
      • Fix --skippedTags parameter configuration which was ignored
      • Fix NullPointerException and print an error message in the build console when the inventory is not set in the job configuration

Version 0.1 (01 May 2015)

      • Initial version

12 Comments

  1. I love it, thank you!

    Support for ansible-vault credentials passed via Jenkins credentials would be great.

    1. Thank you. The support of ansible vault via the credential plugin is on the roadmap.

      1. This is good to hear Jean-Christophe. Is there an open issue you can point me to so that I can follow the Ansible Vault support?

         

        Thanks

  2. Hello,

    I see that support for 'Environment variables being used in inline inventory text box' was added in V0.3 but I am not able to get it to work in V0.5. I am using it like this:

    [ami-test]
    $amitest_PrivateIP

    where amitest_PrivateIP is the output returned by a CloudFormation stack; thanks in advance.
    fatal: [$amitest_PrivateIP]: UNREACHABLE! =>

    Unknown macro: {"changed"}
  3. Seems like a BUG in "Ansible Plugin" (Jenkins) or may be I misunderstood.

    http://stackoverflow.com/questions/40498752/ansible-playbook-command-line-jenkins-ansible-plugin-parameter-not-accepting/40500190#40500190 

    When a variable (containing a list of hosts is has comma, comma+spaces around comma character) and if I read ansible / ansible-playbook documentation for "-i" option, then this plugin is not letting me use $

    Unknown macro: {variable}

    for "inline content" or it doesn't provide a way to specify those hosts info (like I mentioned above) as a 3rd radio button. I under inline content would mean, inside the file, you are putting something but as --help documentation provides comma separated options, this plugin should provide that feature as well. Using "inline content" is not working when $

    is specified in it and where $

    Unknown macro: {variable}

    contains hosts info like: "host1,host2,  host3,    host4    ,host5      ,host6,etc,etc1"

  4. J F

    Have happily used this plugin extensively in Freestyle Projects, however now as I migrate to Pipelines I am finding limitation (or lack of documentation) with ad-hoc commands. Are pipeline ad-hoc commands supported, if not are they a planned feature?

    1. Looks like ad-hoc is supported in piplelines and docummented only on github readme: https://github.com/jenkinsci/ansible-plugin

      1. J F

        Hey Pablo, thanks. However I had looked in the github before making my previous comment, they give a DSL example of ad-hoc but no pipeline groovy examples. Trying to user the DSL examples in a regular pipleine fails :-/

  5. What I fail to see here is what are the benefits of using the Ansible plugin instead of just using Ansible from CLI.

  6. Hi,

    We are running some ansible playbooks over a changing inventory. And not always are all hosts "REACHABLE". I think it would be very useful feature to choose when an "Ansible" build will be stated as "FAILURE".

    The idea is that we can choose in the Build - Invoke Ansible Playbook and choose which exit codes end in a failure of the build.

    So for my case it would be - ignore exit code 3 (UNREACHABLE).

    I think these are the Ansible exit codes.

        except AnsibleOptionsError as e: 
            cli.parser.print_help() 
            display.error(str(e), wrap_text=False) 
            sys.exit(5) 
        except AnsibleParserError as e: 
            display.error(str(e), wrap_text=False) 
            sys.exit(4) 
        except AnsibleHostUnreachable as e: 
            display.error(str(e)) 
            sys.exit(3) 
        except AnsibleHostFailed as e: 
            display.error(str(e)) 
            sys.exit(2) 
        except AnsibleError as e: 
            display.error(str(e), wrap_text=False) 
            sys.exit(1) 
        except KeyboardInterrupt: 
            display.error("User interrupted execution") 
            sys.exit(99) 
        except Exception as e: 
            display.error("Unexpected Exception: %s" % str(e), wrap_text=False) 
            sys.exit(250) 

    Thanks a lot for this awesome plugin.

    Regards

    David

  7. Can anyone suggest how to make this plugin work with multiple versions of ansible?I tried using virtualenv and pip. I couldn't get that to work.

    virtualenv installs into ~/.virtualenvs/env_name - and specifying a tool path of /.virtualenvs/env_name ended up with the plugin trying to find ansible in /var/lib/jenkins/tools/ansible/~/.virtualenvs/env_name - which wasn't really very useful and probably a bug. So I gave up and tried a different approach.

    Do a checkout of source and sourcing the ./hacking/env-setup file. However, that source sets up a load of stuff like PYTHONPATH which I have no way of passing to the plugin when it runs ansible. So, it can run the binary, but the binary cannot find any of it's environment.

    It feels like this "multiple version" feature has just been stolen from a different plugin without any thought about how to make it work with Ansible? Or am I wrong and missing something obvious?

    1. Damn wiki markup removed some ~~ from that... "tool path of ~/.virtualenvs/env_nam"