Noob
Noob

Reputation: 752

Ansible export variable not working as expected

Inside my Ansible role i'd like to create an export variable which can be used by another script later in the task. But the export is not working for some reason, what am I missing?

- name: export php1_release
  shell: export php1_release=8.0

- name: Echo my_env_var again
  shell: echo $php1_release
  register: php

- debug: var=php

I see the following output:

ok: [example.com] => {
    "php": {
        "changed": true,
        "cmd": "echo $php1_release",
        "delta": "0:00:00.003415",
        "end": "2022-10-14 20:43:48.084293",
        "failed": false,
        "msg": "",
        "rc": 0,
        "start": "2022-10-14 20:43:48.080878",
        "stderr": "",
        "stderr_lines": [],
        "stdout": "",
        "stdout_lines": []
    }
}

Upvotes: 0

Views: 372

Answers (1)

larsks
larsks

Reputation: 312038

Setting an environment only affects the current process and any subprocesses that it spawns. Each shell task in your playbook starts a new, unrelated shell process, so environment variables set in one won't be visible in another (this isn't an Ansible issue; that's just how environment variables work).

You can set the variables with Ansible instead. Here, we set the variables at the play level so they will be visible in all tasks:

- hosts: somehost
  environment:
    php1_release: "8.0"
  tasks:
  - name: Echo my_env_var again
    shell: echo $php1_release
    register: php

  - debug:
      var: php.stdout

Which will output:

TASK [debug] ********************************************************************************************
ok: [localhost] => {
    "php.stdout": "8.0"
}

You can also set environment variables per task:

- hosts: localhost
  tasks:
  - name: Echo my_env_var again
    shell: echo $php1_release
    register: php
    environment:
      php1_release: "8.0"

  - debug:
      var: php.stdout

This will produce the same output, but the environment variable is only visible in the Echo my_env_var again task.

Upvotes: 1

Related Questions