Ansible level 4 task 3 question

Hi!

So I manage to solve this ansible task but I have question:

why the task can be done like this assuming that must be done in stapp02 ?

- name: copy template file
  ansible.builtin.copy:
    src: /home/thor/ansible/role/httpd/templates/index.html.j2
    dest: /var/www/html/index.html
    owner: steve
    group: steve
    mode: '0755'
  when: inventory_hostname == 'stapp02'

And must be done like this ?

- name: deploy the webpage file
  template: 
     src: index.html.j2
     dest: /var/www/html/index.html
     owner: "{{ ansible_user }}"
     group:  "{{ansible_user }}"
     mode: '0744'

This is more like a question about what is going on under the hood, so the first one just does the task wrongly, and ended in not parsing right the jinja2 { inventory_hostname } field to steve and just write { inventory_hostname } in the html file. I’m kinda curious about why you must use this different syntax while working with roles in ansible.

Thanks in advance!

Your question refers to this, right?

d. The user/group owner of /var/www/html/index.html file must be respective sudo user of the server (for example tony in case of stapp01 ).

In general you should never hard-code anything for which a variable is available. It makes the scripts more portable.

From your two scripts above, the first one works only on stapp02. The second one would work whichever app server the question asks.

Hi @Alistair_KodeKloud , no I was wondering why the first block of code doesn’t work for the task. In this task you need to just modify one server. So you can put in the hosts variable the webapp hostname to just modify that. What I don’t understand is why in this case in which you are force to use Roles in ansible, the task can’t be done correctly with the first block of code but you can with the second.

The first block ends with this result when you curl the webapp server:

This is the message from server { inventory_hostname } 

But the second one makes you have:

This is the message from server webapp01

Which it does change the variable declared in the jinja2 template to the value of inventory_hostname

hi you can refer to my solution