semaphore icon indicating copy to clipboard operation
semaphore copied to clipboard

Question: Pass environment variable to a task at run

Open marcosmoraes88 opened this issue 5 months ago • 4 comments

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:

Image

Do you have any clue about that?

Related to

No response

marcosmoraes88 avatar Sep 10 '25 18:09 marcosmoraes88

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.

marcosmoraes88 avatar Sep 11 '25 18:09 marcosmoraes88

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?

bverkron avatar Oct 01 '25 05:10 bverkron

I'm able to use Variable Groups to set Environment Variables:

Image

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.

marcosmoraes88 avatar Oct 08 '25 17:10 marcosmoraes88

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"}
}

fiftin avatar Nov 04 '25 12:11 fiftin