Creating a user

The final part of the common role is to add a user called lamp and add our public key to the user. Before we look at the task, let's look at the variable we will be using, which is defined in roles/common/defaults/main.yml:

users:
- { name: "lamp", group: "lamp", state: "present", key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}" }

As you can see, we are providing three bits of information:

  • name: This is the name of the user we want to create
  • group: This is the group we want to add our user to
  • state: If we want the user to be present or absent
  • key: Here, we are using an Ansible lookup task to read the content of the file at ~/.ssh/id_rsa.pub and use that as the value

The task in the roles/common/tasks/main.yml file for creating the user is split into three parts; the first part uses the group module to create the group:

- name: add group for our users
group:
name: "{{ item.group }}"
state: "{{ item.state }}"
with_items: "{{ users }}"

As you can see, we are using with_items to load in the users variable, as the variable contains three different items, only two of which are being used here. We can just name them, so here we are using item.group and item.state.

The second part of the task creates the user using the user module, as you can see: 

- name: add users to our group
user:
name: "{{ item.name }}"
group: "{{ item.group }}"
comment: "{{ item.name }}"
state: "{{ item.state }}"
with_items: "{{ users }}"

The final part of the task adds the user's public key to the authorized key file using the authorized_key module:

- name: add keys to our users
authorized_key:
user: "{{ item.name }}"
key: "{{ item.key }}"
with_items: "{{ users }}"

As you can see, we are using the item.name and item.key variables this time. This module creates a file called .ssh/authorized_keys in the user's home folder, which is defined by item.name, and then places the content of item.key in there, giving the holder of the private portion of the key access to the user we have just created.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.85.76