简体   繁体   中英

How to loop over variables in an ansible playbook

I have the following playbook that prints out a list of the plugins that are installed on three jenkins servers:

---
- hosts: all
  remote_user: user
  tasks:
      - name: Obtaining a list of Jenkins Plugins
        jenkins_script:
          script: 'println(Jenkins.instance.pluginManager.plugins)'
          url: 'http://server1.usa.com:8080/'
          user: 'admin'
          password: 'password'

      - name: Obtaining a list of Jenkins Plugins
        jenkins_script:
          script: 'println(Jenkins.instance.pluginManager.plugins)'
          url: 'http://server2.usa.com:8080/'
          user: 'admin'
          password: 'password'

      - name: Obtaining a list of Jenkins Plugins
        jenkins_script:
          script: 'println(Jenkins.instance.pluginManager.plugins)'
          url: 'http://server3.usa.com:8080/'
          user: 'admin'
          password: 'password'

However, this is clearly not the most efficient way to do this. I looked into loops and variables within ansible playbooks- but I seem to be going in circles. Here is what I have so far:

- name: Obtaining a list of Jenkins Plugins
  jenkins_script:
    script: 'println(Jenkins.instance.pluginManager.plugins)'
    url: {{ item  }}
    with_items:
      - 'http://server1.usa.com:8080/'
      - 'http://server2.usa.com:8080/'
      - 'http://server3.usa.com:8080/'
    user: 'admin'
    password: 'password'

Here is the error message:

fatal: [server]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'item' is undefined\n\nThe error appears to have been in '/home/user/varspb.yml': line 5, column 9, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n  tasks:\n      - name: Obtaining a list of Jenkins Plugins\n        ^ here\n"}

I'm sure it is a simple mistake, but does anyone see where I am going wrong?

If you start your value with a variable such as {{ item }} , then it needs to be quoted with intent to interpolate a variable "{{ item }}" . Also, you have various formatting issues in your yaml and task block. I managed to fix your task with this:

- name: Obtaining a list of Jenkins Plugins
  jenkins_script:
    script: 'println(Jenkins.instance.pluginManager.plugins)'
    url: "{{ item  }}"
    user: 'admin'
    password: 'password'
  with_items:
    - 'http://server1.usa.com:8080/'
    - 'http://server2.usa.com:8080/'
    - 'http://server3.usa.com:8080/'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM