If you're looking to set the hostname for a system using Ansible then look no further. There are two modules that you can use to configure the hostname: hostname and lineinfile.

The first module, hostname, is used to set the system's hostname. Per the documentation, the module will not adjust /etc/hosts which means you will get warning messages when you execute sudo commands. The module is straightforward. Simple set the name property to what you want the new hostname to be. In this case it gets set to 'webserver'.

- name: change hostname to myserver
  hostname:
    name: "webserver"

The second module, lineinfile, is used to modify the localhost line in /etc/hosts. This module is great for either modifying a single line, or appending it to a file if it is not present. In the example below /etc/hosts will search for a line that contains the phrase 127.0.0.1 localhost and replace it with a line that has 127.0.0.1 localhost webserver.

- name: add myself to /etc/hosts
  lineinfile:
    dest: /etc/hosts
    regexp: '^127\.0\.0\.1[ \t]+localhost'
    line: '127.0.0.1 localhost webserver'
    state: present