Question: Pass environment variable to a task at run
Question
Hi, everyone!
I would like to pass variables to a Task at runtime, but it's not working.
---
- name: Debug Variable
hosts: localhost
gather_facts: no
tasks:
- name: Print Environment Variable
ansible.builtin.debug:
msg: "NEW_VAR={{ lookup('env', 'NEW_VAR') }}"
I'm using this curl to run the Task:
curl -v 'https://semaphore-url/api/project/112/tasks' \
-H "Authorization: Bearer $TOKEN"
-H "accept: application/json"
-H "Content-Type: application/json"
-d '{"template_id":108,"environment":"{\"NEW_VAR\": \"VALUE1\"}","project_id":112}'`
But the variable NEW_VAR value is not printed in the playbook:
Do you have any clue about that?
Related to
No response
We don't need to use lookup('env', var) to get the var values. The variables are already available to tasks in Ansible, like this:
- name: Print Env Var
ansible.builtin.debug:
msg: "NEW_VAR={{ NEW_VAR }}"
But is there any way to inject environment variables into tasks at runtime? In order to use AWS dynamic inventory in different accounts, I would like to inject specific credentials at each run.
Are you talking about environment vars on the host or set somewhere in the Semaphore UI or other?
I am trying to pass a secret to the playbook and set it into an environment variable (my CLI too reads the secret from an env var) but have had no luck. The UI and nomenclature seems to be different for me than this answer and I am not having luck using Environment -> Secrets without success. Though I'm on an older version so maybe it's now called Variable Groups like that stack overflow answer?
I'm able to use Variable Groups to set Environment Variables:
These variables are available in the host: setting AWS credentials, for example, enables a dynamic inventory.
But using the API to run Tasks and passing variables in environment field does not work in the same way:
-d '{"template_id":108,"environment":"{\"SOME_KEY_NAME\": \"VALUE\"}","project_id":112}'. I can use it in ansible playbooks (like "{{ SOME_KEY_NAME }}", but not in the host.
For dynamic inventories, I can get around this limitation by specifying a iam_role_arn in the inventory (and allowing the runner to assume that role). But I imagine there are other use cases that are still hampered by this behavior.
Hi @marcosmoraes88 thank you for your question. It is really useful feature which missed.
What we need to add in 2.18:
{
"vars": {"var1": 452345}, // "environment" -> "vars"
"envs": {"ENV1": "test"}
}