1

From this:

cat /etc/hosts
172.26.42.112 test.foobar
172.26.42.112 elastic.foobar

- vars:
    - docker_add_end: ['elastic', 'test']

To this:

- ansible.builtin.shell: |
    IP=$(cut -d ' ' -f 1 <<< "$(grep {{ item }} /etc/hosts)")
    FQDNHOST=$(cut -d ' ' -f 2 <<< "$(grep {{ item }} /etc/hosts)")
    echo -e "${FQDNHOST} $(cut -d '.' -f 1 <<< ${FQDNHOST})%${IP}"
  register: end_find
  with_items: "{{ docker_add_end }}"'

Then split the found result and add to a list (or dict ??):

- ansible.builtin.set_fact:
    end_add: "{{ end_add|default([]) + [ item.stdout.split('%')[0] + ':' + item.stdout.split('%')[1] ] }}"
  with_items: "{{ end_find.results }}"

With the follow result:

ok: [integration] => {
    "msg": [
        "elastic.foobar elastic:172.26.42.112",
        "test.foobar test:172.26.42.112"
    ]
}

But, when pass it to docker:

- community.docker.docker_container:
    etc_hosts: "{{ end_add }}"

I got:

 FAILED! => {"changed": false, "msg": "argument 'etc_hosts' is of type <class 'list'> and we were unable to convert to dict: <class 'list'> cannot be converted to a dict"}

So I try another approach:

- ansible.builtin.set_fact:
    end_add: "{{ end_add|default({}) | combine( {  item.stdout.split('%')[0] : item.stdout.split('%')[1] } ) }}"
  with_items: "{{ end_find.results }}"
ok: [integration] => {
    "msg": {
        "elastic.foobar elastic": "172.26.42.112",
        "test.foobar test": "172.26.42.112"
    }
}

And end with the same error:

fatal: [integration]: FAILED! => {"changed": false, "msg": "argument 'etc_hosts' is of type <class 'list'> and we were unable to convert to dict: <class 'list'> cannot be converted to a dict"}

community.docker.docker_container

etc_hosts 
dictionary

Dict of host-to-IP mappings, where each host name is a key in the dictionary. Each host name will be added to the container’s /etc/hosts file.

1 Answers1

0

Ho man, I made a mistake in a var name when wrote the playbook. The question above show's the right way to do it in the second example.

cat /etc/hosts
172.26.42.112 test.foobar
172.26.42.112 elastic.foobar

- vars:
    - docker_add_end: ['elastic', 'test']

- ansible.builtin.shell: |
    IP=$(cut -d ' ' -f 1 <<< "$(grep {{ item }} /etc/hosts)")
    FQDNHOST=$(cut -d ' ' -f 2 <<< "$(grep {{ item }} /etc/hosts)")
    echo -e "${FQDNHOST} $(cut -d '.' -f 1 <<< ${FQDNHOST})%${IP}"
  register: end_find
  with_items: "{{ docker_add_end }}"'

- ansible.builtin.set_fact:
    end_add: "{{ end_add|default({}) | combine( {  item.stdout.split('%')[0] : item.stdout.split('%')[1] } ) }}"
  with_items: "{{ end_find.results }}"

- community.docker.docker_container:
    etc_hosts: "{{ end_add }}"

When I ran the tests, I rename the var: "end_add" to "end_add_someshit" and screwed it all.