title: Ansible Set Dynamic Environment Variables
body: <p>I know about Ansible's environment: command at the top of playbook, but I don't think that will work for me seeing how I don't know the variables value prior to the execution of the playbook.  I'm trying to retrieve package versions and PHP Modules and log them to a file.  I want to use regex to capture the version and store it to an environment variable.  Then I want to write that variable equals that variable's value to an environment file with a shell command.  I also want to pull an array from the environment and loop through that.  Ansible doesn't seem to persist the shell environment and the environment variable gets wiped out between commands.  This is simple in Bash.  Is this possible in Ansible?  I'm trying: </p>
  
  <pre><code>---
  - hosts: all
    become: yes
    vars:
        site_variables:
            code_directory: /home/
        dependency_versions:
            WGET_VERSION: placeholder
            PHP_MODULES: placeholder
  
    tasks: 
      - name: Retrieve Environment
        shell: export WGET_VERSION=$(wget --version | grep -o  'Wget [0-9]*.[0-9]*\+')
        shell: export PHP_MODULES=$(php -m)
        shell: echo "export {{ item }}={{ lookup('env',  item ) }}" &gt;&gt; {{ site_variables.code_directory }}/.env.log
        with_items:
          - WGET_VERSION
  
  
      - name: Write PHP Modules Out
        shell: export PHP_MODULES=$(php -m)
        shell: export PHP_MODULES=$(echo {{ lookup('env',  'PHP_MODULES') }} | sed 's/\[PHP Modules\]//g')
        shell: export PHP_MODULES=$(echo {{ lookup('env',  'PHP_MODULES') }} | sed 's/\[Zend Modules\]//g')
        shell: export PHP_MODULES=({{ lookup('env',  'PHP_MODULES') }}) 
        shell: echo "#  - {{ item.0 }}" &gt;&gt; {{ site_variables.code_directory }}/.env.log
        with_items:
          - "{{ lookup('env',  'PHP_MODULES') }}"
  </code></pre>