Ansible Vault & Common users use Ansible | Cloud computing

Posted by predhtz on Tue, 04 Jan 2022 08:22:14 +0100

1. Comprehensive exercise (automatic deployment of Web cluster)

1.1 problems

Evening self-study extracurricular comprehensive exercises, create a role called cluster and complete a comprehensive project. The specific requirements are as follows:

  • Create Role and complete the project through Role
  • Deploy Nginx scheduler
  • Deploy 2 http servers

1.2 scheme

The list of hosts required for the comprehensive exercise experiment is shown in TABLE-1.

TABLE-1 host list

Step 1: deploy two back-end http servers

1) Create role

[root@control ansible]# ansible-galaxy  init  ~/ansible/roles/http

2) Modify the role configuration file and prepare materials for 2 http websites

Install httpd and copy a web page file.

[root@control ansible]# vim roles/http/tasks/main.yml
- name: install httpd
    name: httpd
    state: present
- name: create index.html
    content: "{{ansible_hostname}}"
    dest: /var/www/html/index.html
- name: set firewalld
    service: http
    state: enabled
    permanent: yes
    immediate: yes
- name: start httpd
    name: httpd
    state: started
    enabled: yes
#The file contains multiple tasks. Each task can have a name (or no name)
#The first task calls the yum module to install the httpd package
#The second task calls the copy module to create a new web page file (index.html)
#When calling the copy module, you can directly use content to specify the contents of the file without a source file
#Copy the content directly to a file on the managed host (/ var/www/html/index.html)
#The third task calls the firewalld module to set firewall rules to allow access to http services
#The fourth task calls the service module to start the httpd service and set the startup self startup.

3) Write Playbook, call role, and execute Playbook.

[root@control ansible]# vim web.yml
- hosts: webserver
    - http
[root@control ansible]# ansible-playbook web.yml

Step 2: deploy nginx proxy server

1) Create role

[root@control ansible]# ansible-galaxy  init  ~/ansible/roles/proxy

2) Prepare the materials required by the proxy server

Copy the nginx source package and write a shell script for compiling and installing nginx.

[root@control ansible]# cp  lnmp_soft/nginx-1.17.6.tar.gz  \
[root@control ansible]# vim ~/ansible/roles/proxy/files/
yum -y install gcc pcre-devel openssl-devel make tar
cd /tmp
tar -xf /tmp/nginx-1.17.6.tar.gz
cd nginx-1.17.6
./configure --with-http_ssl_module
make install

Create a new profile template for the Nginx proxy server.

[root@control ansible]# vim ~/ansible/roles/proxy/files/nginx.conf
worker_processes  2;
#error_log  logs/error.log;
events {
    worker_connections  65535;
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    tcp_nopush     on;
    keepalive_timeout  65;
    #gzip  on;
upstream webs {
    server {
        listen       80;
        server_name  localhost;
        location / {
            proxy_pass http://webs;
            root   html;
            index  index.html index.htm;
        error_page  404              /404.html;
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;

3) Modify the role profile.

[root@control ansible]# vim roles/proxy/tasks/main.yml
- name: copy nginx-1.17.6.tar.gz to proxy.
    src: nginx-1.17.6.tar.gz
    dest: /tmp/
#Copy source package software
- name: install nginx through shell script.
    creates: /usr/local/nginx/sbin/nginx
#Execute the source compilation installation script. If nginx is already installed, the installation script will not be executed
#args is a keyword. Set the parameters of the script module and judge through the create parameter. creates is also a keyword
#Creates is followed by the file name. If creates determines that the file exists, it will no longer execute the command corresponding to the script module.
- name: copy nginx.conf to destination host.
    src: nginx.conf
    dest: /usr/local/nginx/conf/nginx.conf
- name: run nginx service.
  shell: /usr/local/nginx/sbin/nginx
    creates: /usr/local/nginx/logs/ exists, indicating that nginx has been started. If the file exists, nginx will no longer be started.
- name: set firewalld
    service: http
    state: enabled
    permanent: yes
    immediate: yes

4) Write Playbook, call role, and execute Playbook.

[root@control ansible]# vim proxy.yml
- hosts: proxy
    - proxy
[root@control ansible]# ansible-playbook proxy.yml

2. Encrypt sensitive data

2.1 problems

This case requires that sensitive data be encrypted with ansible vault. The specific requirements are as follows:

  • Manage sensitive data with ansible vault

2.2 steps

To implement this case, you need to follow the following steps.

Step 1: use ansible vault to process sensitive data

1) Encrypt sensitive data.

encrypt, decrypt, view, and rekey.

[root@control ansible]# echo 123456 > data.txt               #New test file
[root@control ansible]# ansible-vault encrypt data.txt      #Encrypted file
[root@control ansible]# cat data.txt
[root@control ansible]# ansible-vault view data.txt         #View encrypted files

2) Change password (rekey)

[root@control ansible]# ansible-vault rekey data.txt             #Change Password
Vault password: <Old password>
New Vault password: <New password>
Confirm New Vault password:<Confirm new password>

3) Decrypt file

[root@control ansible]# ansible-vault decrypt data.txt      #Decrypt file
[root@control ansible]# cat data.txt

4) Use password file

It is troublesome to enter the password every time for encryption and decryption. You can write the password to the file.

[root@control ansible]# echo "I'm secret data" > data.txt       #Sensitive data requiring encryption
[root@control ansible]# echo 123456 > pass.txt                   #Encrypted password
[root@control ansible]# ansible-vault  encrypt --vault-id=pass.txt  data.txt 
[root@control ansible]# cat data.txt
[root@control ansible]# ansible-vault decrypt --vault-id=pass.txt data.txt
[root@control ansible]# cat data.txt

3. Configure sudo permissions

3.1 problems

In this case, sudo is required to enhance the permissions of ordinary users. The requirements are as follows:

  • Create system accounts for all managed hosts
  • The account name is alice and the password is 123456
  • Modify the sudo configuration so that alice can execute any management command

3.2 scheme

sudo (superuser or other do) allows ordinary users to execute commands as super administrators or others.

The basic process of sudo is as follows:

  1. The administrator needs to authorize first (modify the / etc/sudoers file)
  2. Ordinary users execute commands in the form of sudo

Modify / etc/sudoers as follows:

  1. visudo (with syntax check, no color prompt by default)
  2. vim /etc/sudoers (without syntax check, with color prompt by default)

The authorization format is as follows:
User or group host list = (authorization identity) [NOPASSWD]: command list

Note: the command needs to write an absolute path. For group authorization, you need to add% before the group name.

[root@control ~]# cat  /etc/sudoers         #Don't change it. The following is just an example of the syntax format
... ...
root           ALL=(ALL)       ALL
tom            ALL=(root)      /usr/bin/systemctl
%wheel         ALL=(ALL)       ALL

3.3 steps

To implement this case, you need to follow the following steps.

Step 1: configure sudo authorization

1) All managed hosts remotely create system accounts in batches, with the account name alice and password 123456.

[root@control ansible]# ansible all -m user -a "name=alice \
password={{'123456' | password_hash('sha512')}}"

2) Configure the alice account to execute all commands (control batch authorization, node1 host verification).

Use the lineinfile module to modify the / etc/sudoers file of the remote managed end host. The content after line = is the specific content that needs to be added to the end of the file.

Equals to adding a line at the end of the / etc/sudoers file: alice ALL=(ALL) NOPASSWD:ALL

[root@control ansible]# ansible all -m lineinfile \
-a "path=/etc/sudoers line='alice  ALL=(ALL) NOPASSWD:ALL'"

How to verify? You can use alice on the node1 computer to execute the sudo restart command to see if it is successful.

[root@control ~]# ssh alice@node1
[alice@node1 ansible]$ sudo systemctl restart sshd       #No password is required
[alice@node1 ansible]$ exit

4. Modify Ansible configuration

4.1 problems

Following exercise 1, modify the ansible configuration to use the remote controlled end host of ordinary users. The specific requirements are as follows:

  • Modify master profile
  • Set the easy remote managed end host account to alice
  • Set the mode of enabling remote management to sudo
  • Modify host manifest file
  • Modify the host list configuration file and add SSH parameters

4.2 steps

To implement this case, you need to follow the following steps.

Step 1: configure ordinary users to remotely manage other hosts

1) Modify the main configuration file. For the contents of the configuration file, refer to / etc / ansible / ansible cfg.

[root@control ansible]# vim ~/ansible/ansible.cfg
inventory = ~/ansible/inventory
remote_user = alice                #What user is used to remotely manage the host (the user name of the managed host)
become = true                    #alice doesn't have privileges. Do you need to switch users to upgrade permissions
become_method = sudo                #How to switch users (for example, you can switch users with su, here is sudo)
become_user = root                #What user to switch to (lift alice to the root account)
become_ask_pass = no                #Do I need to enter a password when I execute sudo command for authorization


If host A ssh remotely accesses host B, which host's user name and corresponding password should be entered?

If Zhang San wants to go to Li Si's house, whose key should he use to open whose door?

2) The alice user of the remote managed host needs to configure the SSH key in advance.

[root@control ansible]# for i in node1  node2  node3  node4  node5
  ssh-copy-id    alice@$i

Verification effect:

[root@control ansible]# ssh alice@node1            #Remote all hosts in turn to see if a password is required
#Note: if you log in to node1 remotely, you should enter the password of alice account on node1 computer. There is no alice user in control
[root@node1 ~]# exit                                #Exit remote connection
[root@control ansible]# ansible all -m command -a  "who"              #Test effect
[root@control ansible]# ansible all -m command -a  "touch /test"     #Test effect

Common error reports (refer to if there is a problem, and ignore if there is no problem):

node1 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: alice@node1: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).",
    "unreachable": true
Problem analysis:
English Vocabulary: Failed(Failure), connect(Connection), to(To), host(Host), via((adopted)
permission(Permissions), denied((rejected)
Failed to connect to host via ssh alice@node1(adopt ssh use alice Remote connection to host failed)
Permission denied(An error is reported (permission is denied) because the connection cannot be made
 Solution: Manual ssh alice@Host name (if any) node1),See if you can log in without password.
          Ansible The principle is based on ssh Remote management, if not possible alice Password free login, the experiment will fail!
        How to realize password free login, you can refer to the command above the case or the relevant knowledge of the first stage.

3) Modify the inventory host list configuration file (for reference, no operation is required).

What should I do if the accounts of individual hosts are different?

What if some hosts need to use remote passwords? What if the SSH port of some hosts is not 22?

[root@control ~]# cat  ~/ansible/inventory
node1           ansible_ssh_port=Port number                      #Custom remote SSH port
node2           ansible_ssh_user=user name                    #Custom remote connection account name
node[3:4]       ansible_ssh_pass=password                     #Customize the password for remote connections

Additional mind map, as shown in figure-1:



1. What is the command of ansible vault to encrypt data?

# Ansible vault encrypt < filename >

2. What is the command of ansible vault to decrypt data?

# Ansible vault decrypt < filename >

3. What is the command of ansible vault to change the password?

# Ansible vault rekey < filename >

4. What keywords can be used to authorize ordinary users through sudo to execute sudo without password?


In case of infringement, please contact the author to delete

Topics: Linux Operation & Maintenance network server cloud computing