Skip to end of metadata
Go to start of metadata

Plugin Information

View Ansible Tower on the plugin site for more information.

 

This plugin connects Jenkins to Ansible Tower, allowing you to execute job templates.

Configuration

After installing the plugin you can configure Ansible Tower servers in the Jenkins Global Configuration under the section Ansible Tower by clicking the add button.

 

The fields are as follows:

Field NameDescription
NameThe name that this Ansible Tower installation will be referenced as.
URLThe base URL of the Ansible Tower server.
CredentialsThe credentials within Jenkins to be used to connect to the Ansible Tower server. These should be "Username with password" type credentials.
Force Trust Cert

If your Ansible Tower instance is using an https cert that Jenkins does not trust, and you want the plugin to trust the cert anyway, you can click this box.

You should really understand the implications if you are going to use this option. Its meant for testing purposes only.

 

Enable Debugging

This will allow the plugin to write detailed messages into the jenkins.log for debugging purposes. It will show show requests to the server and payloads. This can contain a lot of data. All messages are prefixed with \[Ansible-Tower\].

For Example:

[Ansible-Tower] building request to https://192.168.56.101/api/v1/workflow_jobs/200/workflow_nodes/
[Ansible-Tower] Adding auth for admin
[Ansible-Tower] Forcing cert trust
[Ansible-Tower] {"count":4,"next":null ...

Once the settings are completed, you can test the connection between Jenkins and Ansible Tower by clicking on the Test Connection button.

 

Adding a Build Step

In a freestyle project a new build step called Ansible Tower is now available:

FieldDescription
Tower ServerThe predefined Ansible Tower server to run the template on.
Job TemplateThe name or numerical ID of the job template to be run on the Ansible Tower server.
Extra Vars

Additional variables to be passed to the job. I.e.:
---
my_var: This is a variable called my_var 

Job TagsAny job tags to be passed to Ansible Tower.
LimitThe servers to limit the invocation to.
InventoryThe name or numeric ID of the inventory to run the job on.
CredentialThe name or numeric ID of the credentials to run the job with.
VerboseAdd additional messages to the Jenkins console about the job run.
Import Tower OutputPull all of the logs from Ansible Tower into the Jenkins console.
Remove ColorWhen importing the Ansible Tower output, strip off the ansi color codings.

Pipeline support

Tower jobs can be executed from workflow scripts.
The towerServer and jobTemplate are the only required parameters.

Pipeline Example
node {
    stage('MyStage') {
        ansibleTower(
            towerServer: 'Prod Tower',
            templateType: 'job',
            jobTemplate: 'Simple Test',
            importTowerLogs: true,
            inventory: 'Demo Inventory',
            jobTags: '',
            limit: '',
            removeColor: false,
            verbose: true,
            credential: '',
            extraVars: '''---
my_var:  "Jenkins Test"'''
        )
    }
}

Expanding Env Vars

The fields passed to Tower (jobTemplate, extraVars, limit, jobTags, inventory, credential) can have Jenkins Env Vars placed inside of them and expanded. For example, if you had a job parameter as TAG you could expand that in the Extra Vars like this:

---
my_var: "$TAG"

Console Color

You need to install another plugin like [AnsiColor plugin](https://wiki.jenkins-ci.org/display/JENKINS/AnsiColor+Plugin) to output a colorized Ansible log.

Pipeline Example With AnsiColor
node {
	wrap([$class: 'AnsiColorBuildWrapper', colorMapName: "xterm"]) {
		ansibleTower(
			towerServer: 'Prod Tower',
			jobTemplate: 'Simple Test',
			importTowerLogs: true,
			inventory: 'Demo Inventory',
			jobTags: '',
			limit: '',
			removeColor: false,
			verbose: true,
			credential: '',
			extraVars: '''---
			my_var: "Jenkins Test"'''
		)
	}
}

If you do not have a plugin like AnsiColor or want to remove the color from the log set removeColor: true.

Returning Data

The plugin supports sending data back to Jenkins as environment variables via the EnvInject plugin. First be sure the plugin is installed (its not a dependency for this plugin, it needs to be installed separately).

If you try to export a variable but don't have the EnvInject plugin installed the Tower plugin will let you know with a message like:

    Found environment variables to inject but the EnvInject plugin was not found

 

There are two method for exporting data: Purpose Driven Logging and Setting Stats

Purpose Driven Logging

Then, in your Tower job simply include a debugging statement like:

    - name: Set a Jenkins variable
  debug:
msg: "JENKINS_EXPORT VAR_NAME=value"
 

The Tower plugin will recognize this message and use EnvInject plugin to add an environment variable named VAR_NAME with a value of "value" into the pipeline for consumption by downstream tasks.

Setting Stats

Another option is to use the set_stats module in Ansible like:

    - name: Set a jenkins variable for with stat
      set_stats:
        data:
          JENKINS_EXPORT:
            - some_name: var_value
            - some_other_var : Another value
        aggregate: yes
        per_host: no

The Tower plugin will look for variables under JENKINS_EXPORT and use EnvInject plugin to add an environment variables into the pipeline for consumption by downstream tasks. In the previous example two variables would be created: some_name, set to var_value; and some_other_var set to "Another value".

Please reference set_stats documentation for usage and additional parameters, per_host and aggregate are not necessarily needed.

Open Issues

Key Summary T Created Updated Due Assignee Reporter P Status Resolution
Loading...
Refresh

 

Changelog

Version 0.8.5 (Jun-03-2018)

  • Decreased version dependency on EnvInject plugin due to issues. Thanks to Mikael Gaunin for the Pull Request.

Version 0.8.4 (Apr-29-2018)

  • Removed comparable since in pom.xml to prevent warning about invalid config files. [ JENKINS-51009 ] Thanks to Adrien for catching this.

Version 0.8.3 (Apr-13-2018)

Version 0.8.2 (Mar-24-2018)

  • Added help text for template ID. [ JENKINS-50239 ]
  • Notes for extra vars, job tags, limit, inventory and credential now indicate that "Prompt on Launch" in the template is required for the setting to take affect in Tower [ JENKINS-49915 ]

Version 0.8.1 (Mar-10-2018)

  • The connection will now be attempted by an authtoken first, if that fails (like on the new versions of AWX) it will revert to Basic Auth. [ JENKINS-50031 ]

Version 0.8.0 (Feb-18-2018)

  • Mostly changes when interacting with Tower:
    • Added filtered lookups of items by name to reduce time searching through the results and also prevent pagination issues.
    • Plugin now utilizes authtokens after initial login. This should decrease run times when the Tower instance is using an external authenticator (such as LDAP).
    • Changes to the logging to try and prevent pagination issues and also enhance the speed of looking up logs.
  • Contributed code enhancements:
    • Source code spelling fixes. (Josh Soref)
    • Fixes for warning if passing items (such as credentials) but the job template is not prompting for the item. (Josh Offutt)
    • Final check for log entries after the job completes running. (James McShane)

Version 0.7.0 (Jan-02-2018)

  • Fixed an issue with purpose driven logging where ending color codes could have been included in variable values
  • Added debugging option to Tower configuration
  • Added set_stats variable detection for variable export

Version 0.6.1 (Dec-20-2017)

  • Bug fixes for last release (it basically didn't work)
  • Added some checking for passed credentials and inventory (even if an ID is passed)
  • Also tries to give a better error if extra vars are bad

Version 0.6.0 (Dec-12-2017)

  • Allowed returning variables back to Jenkins via logging

Version 0.5.4 (Dec-7-2017)

  • Plugin now reports if you are passing in a value (like job tags) but prompt on launch is not configured for the job template. [ JENKINS-48377 ]
  • Workflows with inventory updates or sum updates no longer fail when pulling logs back into Jenkins. [ JENKINS-48438 ]

Version 0.5.3 (Dec-2-2017)

  • Fixed bug where existing jobs would get NullPointerExceptions when installing the new version of the plugin.

Version 0.5.2 (Dec-2-2017)

  • Added option to specify workflow or job templates
    Thanks again to Alvin Wong for the suggestion. 

Version 0.5.1 (Nov-21-2017)

  • Expanded Jenkins EnvVars in all fields being passed to Tower
    Thanks to Alvin Wong for the suggestion.

Version 0.5.0 (Nov-11-2017)

  • Initial release

 

33 Comments

  1. Thanks for this!  Do you know of any way to pass in Jenkins build parameters into the plugin? 

    Example: having a Build Parameter of TAG, value: 123, and in the extra_vars section, tag: "{{ TAG }}"

    1. Thanks for the suggestion. A new version of the plugin has been pushed which should handle this. Its uses standard Jenkins syntax so extra_vars will be:
      ---
      tag: "$TAG" 

      The update should show up in the next 24 hours. Please let me know if you have any issues.

      1. It works great, thanks a lot!  Also, to anyone who runs into issues with passing in multiple parameters into a single value, it would look like:

        ---

        tag: "$TAG1.$TAG2"

  2. Is there any way to extend functionality to specify a workflow template, instead of a job template?  I get the following:

    ERROR: Unable to request job template invocation Unable to find job template: Unable to find item named Example Workflow

    1. There is a new version which allows you to specify the template type as either a job (the default) or workflow. In the future I want to modify the input screen so the fields are dynamic since most of them don't apply when submitting a workflow template.

      The update should show up in the next 24 hours. Please let me know if you have any issues.

      1. I am able to invoke workflow templates now, thanks!

        One issue I am seeing though, is that job tags don't seem to be passing through from Jenkins to AWX.

        1. Is this for a regular job template?

          Also, if you have access, would you mind creating an issue for this in the JIRA board? 
          https://issues.jenkins-ci.org/issues/?jql=project%20%3D%20JENKINS%20AND%20component%20%3D%20ansible-tower-plugin

          I want to make sure that the wiki component monitoring JIRA is working correctly.

  3. I would also like to see the ability to specify a workflow template.

    1. All set, please try the new version and let me know if its working for you.

  4. I would like to see some programmatic way to return data from the template execution within the tower template. Perhaps being able to return specified aspects of a playbook run via variable injection back into Jenkins?

  5. Hi
    I am getting next error in my pipeline Jenkins job:

    ERROR: Unable to request job template invocation Tower recieved a bad request (400 response code). This can happen if your extre vars, credentials, inventory, etc are bad

    Here is part of my config:

    ansibleTower(
                                            credential: '',
                                            importTowerLogs: false,
                                            importWorkflowChildLogs: false,
                                            inventory: '123',
                                            jobTags: '',
                                            jobTemplate: '234',
                                            limit: '',
                                            removeColor: false,
                                            templateType: 'job',
                                            towerServer: 'AT PROD',
                                            verbose: false,
                                            extraVars: '''---
                                    FlushCache: "Yes"
                                    RepoURL: "repourl"
                                    InvalidateCloudFront: "No"
                                    InvalidationPaths: "/static/*"
                                    JiraMode: "Autodetect"
                                    JiraTicket: ""
                                    ReleaseType: "Branch"'''
                                    )

    Could you please advise how to debug the error above?

    1. Alexandr, I've created a ticket for this, you should get an email about it shortly.

      1. Thanks, John.

        You are doing a great work.

        I resolved my issue, by using extra variables like this (just moved every extra variable at the  start of the line):

        ansibleTower(
                                                credential: '',
                                                importTowerLogs: false,
                                                importWorkflowChildLogs: false,
                                                inventory: '123',
                                                jobTags: '',
                                                jobTemplate: '234',
                                                limit: '',
                                                removeColor: false,
                                                templateType: 'job',
                                                towerServer: 'AT PROD',
                                                verbose: false,
                                                extraVars: '''---
        FlushCache: "Yes"
        RepoURL: "repourl"
        InvalidateCloudFront: "No"
        InvalidationPaths: "/static/*"
        JiraMode: "Autodetect"
        JiraTicket: ""
        ReleaseType: "Branch"'''
                      )

        And it works well now.

        Anyway, I will try your fix and will give you update.

  6. Hello

    When I am trying to test connection on the configuration page, I am getting next error:

    I see nothing in Jenkins log.

    Could you please help with that?

    P.S.: Recently we upgraded ansible tower to 3.2.2, but I am not sure if its related to that.

     

    1. Interesting, I've not come across this before. I've created a ticket for you  JENKINS-48835 - Getting issue details... STATUS  and will respond from there.

  7. Hello, 

    I have installed the latest version of Ansible Tower with Jenkins (2.89.3). I am able to execute job from the Jenkins UI successfully. 

    When I try to use the DSL code above:

    steps {
            ansibleTower(
                towerServer: 'Test',
                jobTemplate: 'Simple Test',
                importTowerLogs: true,
                inventory: 'Demo Inventory',
                jobTags: '',
                limit: '',
                removeColor: false,
                verbose: true,
                credential: '',
                extraVars: '''---
    my_var: "Jenkins Test"'''
            )
    }
    I get the following error:
    ERROR: (script, line 64) No signature of method: javaposse.jobdsl.dsl.helpers.step.StepContext.ansibleTower() is applicable for argument types: (java.util.LinkedHashMap) values: [[towerServer:Test]]

     

    When I declare only the following, it creates the Ansible Tower piece in my Jenkins job without any issues:

    steps {
            ansibleTower(
                    )
               }
    My issue only occurs when I try to populate the ansibleTower job. 
    I have tried changing the syntax many times but I always end up with the same error. 
    Any advice or help would be hugely appreciated. 
    Thanks,
    Morgan 
    1. Hi Morgan, There was a typo in the wiki. Please try the following and let me know if it works:

      Updated Example
      node {
          wrap([$class: 'AnsiColorBuildWrapper', colorMapName: "xterm"]) {
              stage('MyStage') {
                   ansibleTower(
                      towerServer: 'Test',
                      templateType: 'job',
                      jobTemplate: 'Simple Test',
                      importTowerLogs: true,
                      inventory: 'Demo Inventory',
                      jobTags: '',
                      limit: '',
                      removeColor: false,
                      verbose: true,
                      credential: '',
                      extraVars: '''---
      my_var:  "Jenkins Test"'''
                  )
              }
          }
      }
      1. Hi John, 

        The above code works with Pipeline scripts. Many thanks for the updated Wiki and instructions. 

        Quick question, is this plugin compatible with freestyle jobs or just pipeline jobs?

        Thanks,
        Morgan 

        1. Thanks for confirmation. The plugin also works with Freestyle projects.

          1. Hi John, 

            I am still facing the HashMap error when I try to use Ansible Tower with a FreeStyleJob. Please see code below: 

            //Create Freestyle Jenkins Jobs

            def LinuxEC2Job = freeStyleJob(projectFolderName + "/Jenkins_Scripts/Linux/Ansible_Linux_EC2")

            // Populate Each Freestyle Jenkins Jobs


            LinuxEC2Job.with{
            description('''Testing Ansible Tower Automation with Linux EC2 Instance''')

            steps {
            ansibleTower(
            towerServer: "Test"
            )
            }
            }

             

            I have also tried to implement your code structure above but to no avail unfortunately as node and stages are not accepted options for FreeStyleJobs unfortunately. 

            If you have any suggestions, I would be very grateful. 

             

            1. Hi Morgan, sorry for the delay in response. If I am looking at the correct documentation for that pipeline step (https://jenkinsci.github.io/job-dsl-plugin/#path/freeStyleJob) it appears that plugin is used to create or modify an existing Freestyle Job. Unfortunately, I don't have enough experience with the syntax of that module to tell you how to create a freestyle job which executes an Ansible Tower call from a pipeline. Within Jenkins, if you select "New Item" and then create a "Freestyle project" you should be able to create a job that use the Ansible Tower plugin as.a step as described above in the wiki. If you need to do this through the freeStyleJob pipeline syntax you may need to reach out to the maintainers of the Job DSL Plugin for help.

  8. Hi,

    I'm having an issue whereby ansible tower isn't respecting the limit option sent by Jenkins (in declarative pipline mode). I tried this with and without a limit set in the Ansible Tower template.

    1. Amir, do you have the "prompt on launch" box checked next to Limit in your job template in Tower?

  9. I guess that'll be it - sorry. I must have missed it in the doc. Thanks!

    It's working now, it would be nice if there was a way to pass a "label" to ansible tower so from the jobs interfaces of Ansible Tower - you can have something more verbose about what job is running.

  10. I would like to specify the job type on the build step (since in our environment check is default, but i want to run jobs from Jenkins). 

    I checked out the code and wanted to modify it in order to provide a pull request. 

    Unfortunately, I am not able to build the plugin due to: 

    failed to execute goal org.apache.maven.plugins:maven-enforcer-plugin:1.3.1:display-info (display-info) on project ansible-tower: Execution display-info of goal org.apache.maven.plugins:maven-enforcer-plugin:1.3.1:display-info failed: A required class was missing while executing org.apache.maven.plugins:maven-enforcer-plugin:1.3.1:display-info: org/apache/commons/lang/SystemUtils

    Environment: 

    Maven 3.0.4 (also tried with latest version)

    JDK jdk1.8.0_66.jdk

    Mac

    If I add commons-lang to the local deps, I get an NPE. 

     

    Any help appreciated. 

     

     

    1. Apologies for the delay in a response. How are you attempting to build the plugin manually or via an IDE? And what command are you running? I'm using IntelliJ with a handful of plugins for my primary development but from command line I can see what my versions of maven and java are:

      $ mvn --version
      Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T03:58:13-04:00)
      Maven home: /usr/local/Cellar/maven/3.5.2/libexec
      Java version: 1.8.0_144, vendor: Oracle Corporation
      Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre
      Default locale: en_US, platform encoding: UTF-8
      OS name: "mac os x", version: "10.13.4", arch: "x86_64", family: "mac"


      The build command I am using "mvn package" this is generating a file called target/ansible-tower.hpi which can then be uploaded manually into Jenkins.
  11. Sorry for the delay from my side, I was on vacation (smile)

    In the meantime I cross checked the build on a Windows 7, Windows 10, Linux (Ubuntu) and my iMac. 

    Build success on all platforms, so I figure there's something weird with my MacBook Setup (strange, because all other 

    projects build with that machine, and there's a lot of them). 

     

    My Environment: 

    Idea Ultimate. Tried command line and build from IDE. Standard build command on my side is clean install. 

     

    I will finish my work, test it with my environment and provide a pull request. 

     

  12. Hi and thanks for this.

    I'm having an issue with the injection of environment variables.

    My test pipleline is quite simple:

    testPipeline
    node {
        stage ('deploy gitlab') {
            wrap([$class: 'AnsiColorBuildWrapper', colorMapName: "xterm"]) {
                ansibleTower(
                    towerServer: 'AWX',
                    jobTemplate: 'deploy_gitlab',
                    importTowerLogs: true,
                    inventory: 'Environnements de Dev',
                    jobTags: 'git-front',
                    limit: '',
                    removeColor: false,
                    verbose: true,
                    credential: '',
                    extraVars: '''---
    gitlab_update_patch: true
    '''
                )
            }
        }
        stage ('debug') {
            sh 'env'
        }
    }

     

    My playbook is passing a variable back as documented above:

    ansible task
    - name: Inject variables in jenkins job/pipeline
      set_stats:
        data:
          JENKINS_EXPORT:
            - gitlab_installed: "{{ gitlab_installed }}"
        aggregate: yes
        per_host: no

     

    The plugin reports the returned variable was correctly parsed but the variable is not in my environment

    Pipeline result
    [Pipeline] node
    Running on NODEx in /jenkins/workspace/TEST_SAM_APPUI/testGitlabDeploy
    [Pipeline] {
    [Pipeline] stage
    [Pipeline] { (deploy gitlab)
    [Pipeline] wrap
    [Pipeline] {
    [Pipeline] ansibleTower
    Beginning Ansible Tower Run on AWX
    Requesting tower to run job template deploy_gitlab
    
    [cut.....]
    
    TASK [gitlab-ce : Inject variables in jenkins job/pipeline] ********************
    ok: [SOMESERVER]
    
    PLAY RECAP *********************************************************************
    SOMESERVER                 : ok=23   changed=0    unreachable=0    failed=0   
    SOMESERVER2                : ok=2    changed=0    unreachable=0    failed=0   
    Receiving from Jenkins job 'gitlab_installed' with value '10.6.6'
    Tower completed the requested job
    [Pipeline] }
    [Pipeline] // wrap
    [Pipeline] }
    [Pipeline] // stage
    [Pipeline] stage
    [Pipeline] { (debug)
    [Pipeline] sh
    [testGitlabDeploy] Running shell script
    + env
    JENKINS_NODE_COOKIE=<cookie>
    XDG_SESSION_ID=<id>
    BUILD_URL=<uri>
    SHELL=/bin/bash
    HUDSON_SERVER_COOKIE=<cookie>
    STAGE_NAME=debug
    SSH_CLIENT=ip.ip.ip.ip 52642 22
    BUILD_TAG=jenkins-TEST_SAM_APPUI-testGitlabDeploy-2
    JOB_URL=<uri>
    WORKSPACE=/jenkins/workspace/TEST_SAM_APPUI/testGitlabDeploy
    RUN_CHANGES_DISPLAY_URL=<uri>
    USER=jenkins
    JENKINS_HOME=/var/lib/jenkins
    PATH=/usr/local/bin:/usr/bin:/opt/apache-maven-3.3.9/bin
    MAIL=/var/mail/jenkins
    RUN_DISPLAY_URL=<uri>
    _=/usr/bin/env
    PWD=/jenkins/workspace/TEST_SAM_APPUI/testGitlabDeploy
    HUDSON_URL=<uri>
    LANG=en_US.UTF-8
    JOB_NAME=TEST_SAM_APPUI/testGitlabDeploy
    BUILD_DISPLAY_NAME=#2
    BUILD_ID=2
    JENKINS_URL=<uri>
    SBT_OPTS=-Dsbt.override.build.repos=true
    JOB_BASE_NAME=testGitlabDeploy
    HOME=/home/jenkins
    SHLVL=3
    EXECUTOR_NUMBER=4
    JENKINS_SERVER_COOKIE=durable-<cookie>
    NODE_LABELS=NODEx java php71 tmc
    LOGNAME=jenkins
    HUDSON_HOME=/var/lib/jenkins
    SSH_CONNECTION=ip.ip.ip.ip 52642 ip.ip.ip.ip 22
    NODE_NAME=NODEx
    LESSOPEN=||/usr/bin/lesspipe.sh %s
    BUILD_NUMBER=2
    JOB_DISPLAY_URL=<uri>
    HUDSON_COOKIE=<cookie>
    XDG_RUNTIME_DIR=/run/user/<id>
    [Pipeline] }
    [Pipeline] // stage
    [Pipeline] }
    [Pipeline] // node
    [Pipeline] End of Pipeline
    Finished: SUCCESS
    

     

    As you can see in the "env" ouput above, there are no environment variables corresponding to the one I passed back (gitlab_installed), either capitalized or not. Anything I missed and must config in my pipeline for this to work ? Thanks.

     

    Jenkins 2.121.1

    Ansible Tower Plugin 0.8.5

    Environment  injector plugin: 2.1.5

    EnvInject API plugin: 1.5

    1. Hi Oliver, thanks for the report. I wonder if we are hitting a limitation of the Env Inject plugin (EnvInject Plugin#JenkinsPipeline). Can you try to build a standard freestyle project with these two steps and let me know if it works?

      1. Hi John,

        Just tried with a freestyle job and it works as expected in that case: the variable with its value is reported correctly with a subsequent env command after running the job on AWX. Too bad...

        One more question: the plugin configuration currently allows a single user to connect to Tower and is configured globally in jenkins. Is that a design choice ?  Are you planning to allow a per-job configuration ? In our case we have 100++ projects with 1000++ users and we would need to configure the Tower connection for at least every different project ifwe want to use this on production.


        Thanks in advance for your answer.

        1. That was just how I configured the plugin... assuming that the person building the pipeline might not know the Tower authentication information. But I am always opened to change. If we provided a credential override field at the job level would that work better? The admin would still build and test a default connection (url, default username/password) and the job template could override the username/password for the actual connection. This might get a little messy because in the near future Tower will be changing to oauthtokens so there may end up being both credential and oauth override on the job templates.

          If that works for you, please open a feature request at https://issues.jenkins-ci.org and I will work on that.

  13. is there a way to skip tags using ansible plugin pipeline code?

    1. There is not a current way to do this. Please open a feature request for the plugin at https://issues.jenkins-ci.org and I will see what I can do to make that happen. 

Write a comment…