Examples of Ansible for system administration

Examples of Ansible for system administration. To modify the OpenSSH-Server configuration with Ansible, you must first create a playbooks.yml file in the directory where the ansible files are stored. The playbooks.yml file contains several tasks to run through Ansible:

Update server configuration.

This ansible code performs several tasks:

  • name: Editing_the_sshd_config_file: set the task name to “Editing the sshd_config file”.
  • become: true: indicates that the task must be run with superuser privileges.
  • lineinfile:: indicates that the ansible lineinfile module is to be used, which allows you to edit specific lines of a file.
  • dest: /etc/ssh/sshd_config: specifies the file to be edited, in this case the OpenSSH configuration file (/etc/ssh/sshd_config).
  • regexp: "{{ item }}": specifies a regular expression to be used to search for the line to edit in the file. The variable item will be replaced by each of the elements of the listwith_items.
  • line: "{{ item }} {{ value }}": specifies the new line to be written to the file. The variable item will be replaced by each of the elements of the listwith_items and the variable value will be replaced by the value associated with that element.
  • with_items:: specifies a list of key-value pairs to be processed in a loop. In this case, the list contains two elements: PermitRootLogin: no y PasswordAuthentication: no.

This code searches for the lines PermitRootLogin and PasswordAuthentication in the file /etc/ssh/sshd_config and, if found, modifies them so that they have the value no. If they are not found, they are appended to the end of the file. The task is executed with superuser privileges and therefore it is necessary to provide the superuser password or use a private key to authenticate.

  - name: Editing_the_sshd_config_file
    become: true
    lineinfile: dest=/etc/ssh/sshd_config regexp="{{ item }}" line="{{ item }} {{ value }}"
    with_items: 
      - PermitRootLogin: no
      - PasswordAuthentication: no

Restart SSH server

This ansible code performs a task that aims to restart the SSH (Secure Shell) service and enable it to run automatically at system startup. The task is performed with superuser privileges. (become: true).

To perform the task, Ansible’s the module used is service , which allows you to manage system services. The parameters of the task are:

  • name: Rebooting_ssh_service: set the task name to “Rebooting_ssh_service”..
  • name: ssh: specifies the name of the service to be managed. In this case, it is the SSH service.
  • state: restarted: indicates that the service must be restarted.
  • enabled: yes: indicates that the service should be enabled to run automatically at system startup.

This task restarts the SSH service and enables the service to run automatically at system startup. It runs with superuser privileges and therefore it is necessary to provide the superuser password or use a private key to authenticate.

  - name: Rebooting_ssh_service
    become: true  
    service : name=ssh state=restarted enabled=yes

Once we have saved the playbooks.yml file, we can run it with the ansible-playbook command. This tells Ansible to run all the tasks contained in that file to configure and restart OpenSSH-Server.

Changing a user’s password in Linux

This ansible code performs a task that aims to change the password of the “admin” user. The task is performed using the user module of ansible, which allows to manage system users. The parameters of the task are:

  • name: Change_admin_user_password: set the task name to “Change admin user password”.
  • name: admin: specifies the name of the user whose password is to be changed.
  • update_password: always: indicates that the user’s password should always be updated. If the update_password option is not specified, ansible will not change the password if it is already set.
  • password: "{{ 'password123' | password_hash('sha512') }}":specifies the user’s new password. In this case, the ansible password_hash filter is used to generate a hash of the password using the SHA-512 algorithm. This is necessary because ansible stores user passwords as hashes rather than in clear text, to prevent them from being read by unauthorized persons.

This task changes the password of the user “admin” to the password “password123”. The password_hash filter is used to generate a hash of the password using the SHA-512 algorithm and the update_password: always option is set to force ansible to always update the password.

Ejemplo:

- name: Change_admin_user_password 
  user: 
    name: admin   # Nombre de usuario a cambiar su password. 
    update_password: always     # Esta opción forzará a Ansible para actualizar siempre la contraseña del usuario en cuestión.  		      # La longitud debe ser al menos 8 caracteres.
    password: "{{ 'password123' | password_hash('sha512') }}"  # Esta línea es para establecer una contraseña segura.

Create new users with Ansible

This ansible code performs a task that aims to create a new user in the system named “Bob”. The task is performed using the ansible user module, which allows to manage system users. The parameters of the task are:

  • name: Create_a_new_user_named_Bob: set the task name to “Create a new user named ‘Bob'”.
  • name: Bob:specifies the name of the new user to be created.
  • password: "{{ 'password123' | password_hash('sha512') }}": specifies the password for the new user. In this case, the ansible password_hash filter is used to generate a hash of the password using the SHA-512 algorithm. This is necessary since ansible stores user passwords as hashes rather than in clear text, to prevent them from being read by unauthorized persons.Example:
- name: Create_a_new_user_named_Bob  		   # Nombre de la tarea en nuestro playbook.
  user:   			# Este es el módulo que vamos a utilizar para creación de usuarios.  
    name: Bob   		# Nombre del usuario que vamos a crear.
    password: "{{ 'password123' | password_hash('sha512') }}"  # Esta línea es para establecer una contraseña segura.

To summarize, this task creates a new user named “Bob” with the password “password123”. It uses the password_hash filter to generate a hash of the password using the SHA-512 algorithm. If the user “Bob” already exists, ansible will not perform any action.

Removing users in Linux with Ansible

This ansible code performs a task that aims to remove the user “Bob” from the system. The task is performed using the user module of ansible, which allows to manage system users. The parameters of the task are:

  • name: Delete_Bob_user: set the task name to “Delete user ‘Bob'”.
  • name: Bob: specifies the name of the user to be deleted.
  • state: absent: indicates that the user should be deleted. If the state option is not specified, ansible assumes that you want to create the user.

This task removes the user “Bob” from the system. If the user “Bob” does not exist, ansible will not perform any action. It is important to note that this task does not remove files or directories owned by user “Bob”. If you want to remove these items as well, you need to use other ansible tasks or modules.

Example:

- name: Delete_Bob_user  		# Nombre de la tarea en nuestro playbook.
  user:   			# Este es el módulo que vamos a utilizar para eliminar usuarios.  
    name: Bob     # Nombre del usuario que vamos a eliminar.
    state: absent  # Esta opción indica al módulo de Ansible que queremos eliminar al usuario en cuestión.

Upgrading PHP

To upgrade PHP to version 8.2 using Ansible, you can use the following code:

---
# Este es un ejemplo de cómo utilizar Ansible para actualizar PHP
# a la versión 8.2 si está instalada una versión inferior.

- name: php_version_check
  command: php -v
  register: result

- name: upgrade_php_to_8.2
  become: true
  apt:
    name: "{{ packages }}"
    state: latest
  vars:
    packages:
      - php8.2
  when: result.stdout | version_compare('8.2', '<')
  • In the first task, the php -v command is executed to obtain information about the PHP version installed on the system. The output of the command is stored in the result variable.
  • In the second task, the ansible aptmodule is used to update the PHP packages to the latest available version. The apt module will be run with superuser privileges (become: true) and the php8.2 package (which is PHP version 8.2) will be installed.
  • The whenoption is used to specify that the PHP upgrade task will only be executed if the installed PHP version is older than version 8.2. To do this, the ansible version_compare filter is used, which compares the PHP version obtained with the php -v command (stored in the resultvariable) with version 8.2 and returns trueif it is earlier.

It is important to note that this code assumes that the php8.2package is available in the package repository used by the system and that the actual php package is installed via a distribution package (such as apt or yum). If this is not the case, you may need to make some changes to the code to adapt it to your environment.

Upgrading Python

To upgrade Python to version 3.11 using ansible, you can use the following code:

---
# Este es un ejemplo de cómo utilizar ansible para actualizar Python
# a la versión 3.11 si está instalada una versión inferior.

- name: python_version_check
  command: python3 --version
  register: result

- name: upgrade_python_to_3.11
  become: true
  package:
    name: "{{ packages }}"
    state: latest
  vars:
    packages:
      - python3.11
  when: result.stdout | version_compare('3.11', '<')

Explanation of the code:

  • In the first task, the python3 --version command is executed to obtain information about the version of Python 3 installed on the system. The output of the command is stored in the result variable.
  • In the second task, the ansible package module is used to update the Python package to the latest available version. The packagemodule will be run with superuser privileges (become: true) and the python3.11 package (which is Python version 3.11) will be installed.
  • The whenoption is used to specify that the Python upgrade task will only be run if the Python version installed is earlier than version 3.11. To do this, the ansible version_comparefilter is used, which compares the Python version obtained with the python3 --version command (stored in the resultvariable) with version 3.11 and returns trueif it is earlier.

As in the above code for PHP, remember that it is important to note that this code assumes that the python3.11 package is available in the package repository used by the system and that the actual python3 package is installed via a distribution package (such as apt or yum). If this is not the case, you may need to make some changes to the code to adapt it to your environment.

Leave a Reply