Question

I have an environment variable injected by Jenkins like:

CUSTOMERS="foo,bar"

Now i need to loop over these values. Is there any way to access these values AS items in ansible?

Any help including other suggestions how to to solve this is welcome.

Était-ce utile?

La solution

You can pass in the environment variable to ansible with --extra-vars, but that's only part of the solution, you need to get the string value into a data format that ansible understands.

One straightforward option is to write a simple Python (or your preferred language) script to convert the environment variable to a JSON list and pass the JSON file to ansible as extra vars with --extra-vars "@customers.json" (JSON file input is available in ansible 1.3), see Ansible Variable documentation.

import sys
import os
import json

DEFAULT_VAR="CUSTOMERS"

def var_to_json(var_name, list_sep = ','):
  var_dict = {var_name: os.environ[var_name].split(list_sep)}
  return json.dumps(var_dict)

var_name=DEFAULT_VAR
if len(sys.argv) > 1:
  var_name = sys.argv[1]
print var_to_json(var_name)

The script above could be generalized further (or customized to your situation). I'll have to leave it to you to hook the pieces together in your build environment.

Alternatively, as this previous answer explains, you can define a custom filter in ansible to process the input value. You could create a filter that converts the variable value to a list, then use the filter in your playbook when referencing the variable (presumably passed in via --extra-vars).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top