WiSaGaN
WiSaGaN

Reputation: 48127

How to set environment in ansible task only when variable is defined

I have two kinds of machines. One kind does not have internet access (say, we call them outgoing restricted), thus need a proxy to run command like dnf install, another kind can run dnf install directly.

I would like ansible to automatically use a proxy on those outgoing restricted hosts when running dnf install, thus I have the host file and the playbook below:

outgoing_restricted:
  hosts:
    bar1.foo.com:
    bar2.foo.com:
  vars:
    # Sets up ssh forwarding for remote to use local machine
    # Need to enable and start squid with http_port 3128
    ansible_ssh_extra_args: "-R 3129:localhost:3128"
    proxy_env:
      http_proxy: "http://127.0.0.1:3129"
      https_proxy: "http://127.0.0.1:3129"
- name: install redhat-lsb-core
  dnf:
    name:
      - redhat-lsb-core
    state: present
  environment: "{{ proxy_env }}"

However, the playbook fails when running on non-outgoing restricted hosts because on those hosts proxy_env is not defined. My question is whether there is a way to specify environment only when proxy_env is defined. Adding when: proxy_env is defined under environment seems not working.

Upvotes: 3

Views: 3567

Answers (1)

ikora
ikora

Reputation: 982

The op solved it, as request I will try to elaborate a little bit. I just pointed to check this URL: Check if dict is empty or not

 - name: install redhat-lsb-core
   dnf:
     name:
       - redhat-lsb-core
     state: present
   environment: "{{ proxy_env | default ({}) }}"
   when: proxy_env is defined

With the way op proposed: Environment uses proxy_env but if it is not defined default filter will set the proxy_env to nothing so it will be able to validate that is empty correctly. (Empty or not defined). With this way he don't need to check if the variables inside the dict are defined or not, you are setting the entire dict default ({}).

Note: the op solved it by itself with my link, so credit to him also ^^.

Upvotes: 5

Related Questions