Child pages
  • Ansible Tower Plugin
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.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

 

24 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.

Write a comment…