6

Started to learn ansible yesterday, so I believe I may risk XY problem here, but still…

The main yml:

- hosts: localhost

  vars_files:
    [ "users.yml" ]
  tasks:
    - name: manage instances
      #include_tasks: create_instance.yml
      include_tasks: inhabit_instance.yml
      with_dict: "{{users}}"
      register: res
    - name: print
      debug: msg="{{res.results}}"

inhabit_instance.yml:

- name: Get instance info for {{ item.key }}
  ec2_instance_facts:
    profile: henryaws
    filters:
      "tag:name": "{{item.key}}"
      instance-state-name: running
  register: ec2
- name: print
  debug:
    msg: "IP: {{ec2.instances.0.public_ip_address}}"

So that's that IP that I'd like to have on the top level. Haven't found anything right away about return values of the include block…

2 Answers 2

4

Well, I've found some way that suits me, maybe it's even canonical?

main.yml:

- hosts: localhost

  vars_files:
    [ "users.yml" ]
  vars: 
    ec_results: {}
  tasks:
    - name: manage instances
      #include_tasks: create_instance.yml
      include_tasks: inhabit_instance.yml
      with_dict: "{{users}}"
      register: res

inhabit_instance.yml:

- name: Get instance info for {{ item.key }}
  ec2_instance_facts:
    profile: henryaws
    filters:
      "tag:name": "{{item.key}}"
      instance-state-name: running
  register: ec2
- name: update
  set_fact:
    ec_results: "{{ ec_results|combine({ item.key: ec2.instances.0.public_ip_address }) }}"
1
  • It save my day. Thank you!
    – Vitalii T
    Commented Jun 27, 2019 at 8:39
2

Thanks for you answer - this helped me to find an answer to my issue when my task was called in a loop - my solution was just to use lists so for your example above, the solution would be:

The main yml:

- hosts: localhost

  vars_files:
    [ "users.yml" ]
  vars: 
    ec_results: []
  tasks:
    - name: manage instances
      #include_tasks: create_instance.yml
      include_tasks: inhabit_instance.yml
      with_dict: "{{users}}"
 
    - name: print
      debug: msg="{{ec_results}}"

inhabit_instance.yml:

- name: Get instance info for {{ item.key }}
  ec2_instance_facts:
    profile: henryaws
    filters:
      "tag:name": "{{item.key}}"
      instance-state-name: running
  register: ec2

- name: Add IP to results
  set_fact:
    ec_results: "{{ ec_results + [ec2.instances.0.public_ip_address] }}"

In my code, include_tasks was in a loop so then ec_results contained a list of the results from each iteration of the loop

Not the answer you're looking for? Browse other questions tagged or ask your own question.