Keep Ansible DRY: How to avoid repeating variables

2019-04-29 12:17发布

问题:

Recently just started using Ansible and I have run into a problem. In one of my YAML structures I have defined something like this:

---
# file: main.yml
#
# Jenkins variables for installation and configuration

jenkins:
  debian:
    # Debian repository containing Jenkins and the associated key for accessing the repository
    repo: 'deb http://pkg.jenkins-ci.org/debian binary/'
    repo_key: 'http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key'

    # Dependencies needed for Jenkins to run properly
    dependencies:
      - 'openjdk-7-jdk'
      - 'git-core'
      - 'curl'

  port: 8080

  # Installation directory
  home: '/opt/jenkins'

  # Path to the location of the main Jenkins-cli binary
  bin_path: '{{jenkins.home}}/jenkins-cli.jar'

  # Path to the location of the Jenkins updates file
  updates_path: '{{jenkins.home}}/updates_jenkins.json'

Ansible gives me an error like this from a specific task:

"recursive loop detected in template string: {{jenkins.home}}/updates_jenkins.json"

I've narrowed it down to the problem being with the fact bin_path and updates_path both refer to 'home'. Is there a way around this? It kind of sucks that I would need to define '/opt/jenkins' multiple times.

回答1:

As far as I know that this is a limitation of jinja2 variables. it was working with the old ${} and broke since 1.4. I am not sure if they fixed that in 1.5.

My temp solution would be removing home from the "jenkins"

---
# file: main.yml
#
# Jenkins variables for installation and configuration

# Installation directory
jenkins_home: '/opt/jenkins'
jenkins:
  debian:
    # Debian repository containing Jenkins and the associated key for accessing the repository
    repo: 'deb http://pkg.jenkins-ci.org/debian binary/'
    repo_key: 'http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key'

    # Dependencies needed for Jenkins to run properly
    dependencies:
      - 'openjdk-7-jdk'
      - 'git-core'
      - 'curl'

  port: 8080



  # Path to the location of the main Jenkins-cli binary
  bin_path: '{{jenkins_home}}/jenkins-cli.jar'

  # Path to the location of the Jenkins updates file
  updates_path: '{{jenkins_home}}/updates_jenkins.json'


回答2:

This should do it:

bin_path: "{{ jenkins['home'] }}/jenkins-cli.jar"