Moment For Technology

The practice of Ansible

Posted on Dec. 2, 2022, 7:20 p.m. by Kashvi Sane
Category: The back-end Tag: operations The back-end

Environment introduction

Red hat test questions, which can be used to practice Ansible

system The IP address Ansible role
bastion 172.25.250.254 Ansible control node
workstation 172.25.250.9 A graphics workstation for system administration
servera 172.25.250.10 Hosts managed using Ansible
serverb 172.25.250.11 Hosts managed using Ansible
serverc 172.25.250.12 Hosts managed using Ansible
serverd 172.25.250.13 Hosts managed using Ansible

The Ansible PlayBook written with important information will be applied by running as user Greg from the /home/gobb/ansible directory on the control node. After the PlayBook runs, your managed nodes are evaluated to see if they are configured as specified

Enter foundation [[email protected] ~]$rht-vmctl status all bastion DEFINED workstation DEFINED servera DEFINED serVerb DEFINED serverc DEFINED serverd DEFINED [[email protected] ~]$ rht-vmctl start all Starting bastion. Starting workstation. Starting servera. Starting serverb. Starting serverc. Starting serverd. ISO2. Ios on foundation0 [[email protected] init]$SSH [email protected]'yum -y install/run/media/kiosk / 20191229 _164114 / ex300v8-1.3.0-191229. The x86_64. RPM'

cd/ home/kiosk/ex300 / roles/init/files will be two Ansible Galaxy roles and hardware report template copy into the catalogue of materials [kiosk @ foundation0 files] $SSH [email protected]'cp /home/kiosk/ex300/roles/init/files/haproxy.tar /home/kiosk/ex300/roles/init/files/phpinfo.tar / home/kiosk/ex300 / roles/init/files/hwreport empty/content/courses/rh294 rhel8.0 / materials/'[kiosk @ foundation0 files] $ls/content/courses/rh294 rhel8.0 / materials Ansible - Tower - license. TXT dynamic jinja2 roles-library yum ansible-vim.tar.gz grading labs solutions yum.conf.d classroom haproxy.tar phpinfo.tar tower docs Hwreport. empty Playbooks Troubleshooting connection bastion SSH [email protected] [[email protected] ~]# yum install ansibleCreate Greg [[email protected] ~]# useradd greg
[[email protected] ~]# passwd greg
Copy the code

Test requirements

Install and configure Ansible

Install and configure Ansible on the controller node 172.25.250.254 as follows:

  • Install the required software packages

  • Create called/home/Greg/ansible/inventory list of static files, in order to meet the following requirements:

    • 172.25.250.9 is a member of the dev host group

    • 172.25.250.10 is a member of host group Test

    • 172.25.250.11 and 172.25.250.12 belong to the PROD host group

    • 172.25.250.13 is a member of the Balancers host group

    • The Prod group is a member of the WebServers host group

  • Create called/home/Greg/ansible/ansible CFG configuration file, to meet the following requirements:

    • Host listing file for/home/Greg/ansible/inventory

    • The locations of the roles used in the Playbook include /home/gobb/ansible-roles

answer

[[email protected] ~]# su - gregCreate an Ansible directory [[email protected] ~]$mkdir ansible View the Ansible version [[email protected] ansible]$ansible --version ansible 2.8.0 config File = /etc/ansible/ansible. CFG = /etc/ansible/ansible. The ansible configuration file has four priority parameters: command  current directory configuration file  home directory configuration file  /etc/configuration file. Therefore, we copy the configuration file to the home directory [[email protected] ansible]$cp /etc/ansible/ansible.cfg. / Simultaneously search for the host list path [[email protected] ansible]$RPM -qc ansible /etc/ansible/ansible.cfg /etc/ansible/hosts Copy the host list [[email protected] ansible]$cp /etc/ansible/hosts. /inventory [[email protected] ansible]$ansible - version ansible 2.8.0 config file = / home/Greg/ansible/ansible CFG configuration file change priority home directory to the directory to create characters [Greg @ bastion ansible] $ mkdir roles [[email protected] ansible]$ vim ansible.cfg# Host list
inventory      = /home/greg/ansible/inventory
# Role directory
roles_path    = /home/greg/ansible/roles
# indicates the identity of the controlled end when executing the command issued by the main control end. Therefore, it is root
remote_user = root
If host key checking is disabled, SSH key authentication will not be performed on the management end
host_key_checking = False
# Control side to execute ansible user empowerment parameters[Privilege_Escalation] Become =True become_Method =sudo become_user=root BECOMe_ask_pass =False Host configuration list [[email protected] Ansible]$vim inventory [dev] 172.25.250.9 [test] 172.25.250.10 [prod] 172.25.250.11 172.25.250.12 [balancers] 172.25.250.13 [webservers:children] prod [[email protected] Ansible] $ansible - the inventory - graph @ all: | - @ balancers: | | - 172.25.250.13 | - @ dev: | | - 172.25.250.9 | - @test: | | - 172.25.250.10 | - @ ungrouped: | - @ webservers: | | - @ prod - | | | - 172.25.250.11 | | | - 172.25.250.12 host list has been configured We can test server - ping node k is input password verify password is redhat [Greg @ bastion ansible] $ Ansible all - m ping - k SSH password: 172.25.250.12 | SUCCESS =  {"ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false."ping": "pong"} Add the password for automatic connection [[email protected] ansible]$vim inventory [all:vars] ansible_password=redhat to the host listCopy the code

validation

[Greg @ bastion host listing ansible] $ansible - the inventory - graph @ all: | - @ balancers: | | - 172.25.250.13 | - @ dev: | | - 172.25.250.9 | - @test: | | - 172.25.250.10 | - @ ungrouped: | - @ webservers: | | - @ prod - | | | - 172.25.250.11 | | | - 172.25.250.12 ping all nodes [Greg @ bastion ansible] $ansible all -m ping 172.25.250.11 | SUCCESS =  {"ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false."ping": "pong"} 172.25.250.12 | SUCCESS =  {"ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false."ping": "pong"} 172.25.250.10 | SUCCESS =  {"ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false."ping": "pong"} 172.25.250.13 | SUCCESS =  {"ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false."ping": "pong"} 172.25.250.9 | SUCCESS =  {"ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false."ping": "pong"
}

Copy the code

Create and run Ansible temporary commands

As a system administrator, you need to install software on the managed nodes.

Please according to the text described above, create a called/home/Greg/ansible/adhoc. Sh shell script, the script will use ansible temporary command at all the managed nodes to install yum repository:

  • Repository 1:

    • The name of the repository is EX294_BASE

    • Described as EX294 Base Software

    • Base URL to http://content/rhel8.0/x86_64/dvd/BaseOS

    • The GPG signature check is enabled

    • GPG key URL to http://content/rhel8.0/x86_64/dvd/RPM-GPG-KEY-redhat-release

    • The repository is enabled

  • Repository 2:

    • The name of the repository is EX294_STREAM

    • Described as EX294 Stream Software

    • Base URL to http://content/rhel8.0/x86_64/dvd/AppStream

    • The GPG signature check is enabled

    • GPG key URL to http://content/rhel8.0/x86_64/dvd/RPM-GPG-KEY-redhat-release

    • The repository is enabled

answer

Because of the implementation of installing yum repositories, my usual practice when dealing with a module I don't know about is to look at the help documentation

In the help document filtering module associated with yum [Greg @ bastion ansible] $ansible - doc - l | grep yum yum Manages packages have the ` yum ` package manager Yum_repository Add or remove YUM Repositories yum_repository [[email protected] ansible]$ansible Yum_repository writes scripts [[email protected] ansible]$vim adhoc#! /bin/bash

ansible all -m yum_repository -a 'name = "EX294_BASE" description = "EX294 base software" baseurl = "http://content/rhel8.0/x86_64/ DVD/BaseOS" gpgcheck = yes Gpgkey = "http://content/rhel8.0/x86_64/dvd/RPM-GPG-KEY-redhat-release" enabled = yes'

ansible all -m yum_repository -a 'name = "EX294_STREAM" description = "EX294 stream software" baseurl = "http://content/rhel8.0/x86 _64 / DVD/AppStream" Gpgcheck = yes gpgkey = "http://content/rhel8.0/x86_64/dvd/RPM-GPG-KEY-redhat-release" enabled = yes'Run the [[email protected] ansible]$bash adhocCopy the code

validation

Check the yum database directory [[email protected] ansible]$ansible all -m shell -a'ls /etc/yum.repos.d'172.25.250.12 | CHANGED | rc = 0   EX294_BASE. Repo EX294_STREAM. Repo redhat. Repo rhel_dvd. Repo 172.25.250.13 | CHANGED | Rc = 0   EX294_BASE. Repo EX294_STREAM. Repo redhat. Repo rhel_dvd. Repo 172.25.250.11 | CHANGED | rc = 0   EX294_BASE. Repo EX294_STREAM. Repo redhat. Repo rhel_dvd. Repo 172.25.250.10 | CHANGED | rc = 0   EX294_BASE. Repo EX294_STREAM. Repo Redhat. Repo rhel_dvd. Repo 172.25.250.9 | CHANGED | rc = 0   additional. Repo EX294_BASE. Repo EX294_STREAM. Repo redhat. Repo Rhel_dvd. repo each receiving node has EX294_BASE. Repo and EX294_STREAM. Repo can also be checked with an adhoc command. Check the yum repository [[email protected] ansible]$ansible all -a'yum repolist'172.25.250.10 | CHANGED | rc = 0   'id' name status EX294_BASE EX294 base software 1658 EX294_STREAM EX294 Stream Software 4672 RHEL-8.0-for-x86_64-AppStream-RPMS Red Hat Enterprise Linux 8.0 AppStream 4672 Rhel-8.0-for-x86_64-baseos-rpms Red Hat Enterprise Linux 8.0 BaseOS (D 1,658Last metadata expiration check: 0:44:42 ago on Tue 27 Apr 2021 08:22:41 PM CST.Copy the code

Installing Software Packages

  • Create a called/home/Greg/ansible/packages. Yml playbook:

    • Install the PHP and Mariadb packages on the hosts in the dev, Test, and Prod host groups

    • Install the RPM Development Tools software package group on the hosts in the dev host group

    • Update all software packages on the hosts in the dev host group to the latest version

answer

[[email protected] ansible]$ansible-doc yum EXAMPLES: - name: install the latest version of Apache yum: Name: HTTPD state: latest creation script [Greg @ bastion ansible] $vim/home/Greg/ansible/packages. Yml - hosts: devtest prod
  tasks:
    - name: ensure a list of packages installed
      yum:
        name: "{{ packages }}"
      vars:
        packages:
          - php
          - mariadb

- hosts: dev
  tasks:
    - name: install package group
      yum:
        name: "@RPM Development Tools"
        state: present
    - name: upgrade all packages
      yum:
        name: The '*'
        state: latest
Copy the code

validation

Run the [[email protected] ansible]$ansible-playbook packages.yml script to verify the installation of PHP [[email protected] ansible]$ansible all -m shell -a'rpm -qa | grep php'172.25.250.12 | CHANGED | rc = 0   PHP - cli - 7.2.11-1. The module + el8 + 2561 + 1 aca3413 x86_64 PHP - common - 7.2.11-1. The module + el8 + 2561 + 1 aca3413 x86_64 PHP - FPM - 7.2.11-1. The module + el8 + 2561 + 1 aca3413 x86_64 PHP - 7.2.11-1. The module + el8 + 2561 + 1 aca3413 x86_64 172.25.250.11 | CHANGED | rc = 0   The PHP cli - 7.2.11-1. The module + el8 + 2561 + 1 aca3413. X86_64 PHP - common - 7.2.11-1. The module + el8 + 2561 + 1 aca3413. X86_64 PHP - FPM - 7.2.11-1. The module + el8 + 2561 + 1 aca3413 x86_64 PHP - 7.2.11-1. The module + el8 + 2561 + 1 aca3413 x86_64 172.25.250.13 | FAILED | rc=1  non-zeroreturnCode 172.25.250.10 | CHANGED | rc = 0   PHP - cli - 7.2.11-1. The module + el8 + 2561 + 1 aca3413 x86_64 PHP - common - 7.2.11-1. The module + el8 + 2561 + 1 aca3413 x86_64 PHP - FPM - 7.2.11-1. The module + el8 + 2561 + 1 aca3413 x86_64 PHP - 7.2.11-1. The module + el8 + 2561 + 1 aca3413 x86_64 172.25.250.9 | CHANGED | rc = 0   PHP - common - 7.2.11-1. The module + el8 + 2561 + 1 aca3413 x86_64 PHP - 7.2.11-1. The module + el8 + 2561 + 1 aca3413 x86_64 Module +el8+2561+1aca3413.x86_64 phP-cli-7.2.11-1.module +el8+2561+1aca3413.x86_64 The server except the balancers group is not installed All others have the verification installation development kit [[email protected] ansible]$Ansible dev -m shell -a installed'yum grouplist'172.25.250.9 | CHANGED | rc = 0   Last metadata expiration check: 0:58:46 ago on Tue 27 Apr 2021 08:22:18 PM CST. Available Environment Groups: Server with GUI Server Minimal Install Virtualization Host Custom Operating System Installed Environment Groups: Workstation Installed Groups: RPM Development Tools Available Groups: Container Management .NET Core Development Smart Card Support Development Tools Graphical Administration Tools Headless Management Legacy UNIX Compatibility Network Servers Scientific Support Security Tools System ToolsCopy the code

Use the RHEL system role

Install RHEL system software package, and create the playbook meet the following conditions/home/Greg/ansible/timesync yml:

  • Runs on all managed nodes

  • Use the Timesync role

  • Configure the role to use a valid NTP provider

  • Configure this role to use the time server 172.25.254.254

  • Configure this role to enable the iBurst parameters

answer

When the PLAYbook is used to synchronize NTP time, system roles are required. Therefore, install the RHEL-system-roles package of RHEL first

[[email protected] ansible]# yum -y install rhel-system-roles.noarchUsing the role timesync, which is the timesync role in the installed RHEL system role, we find the RHEL system role, And the role of the timesync copy to our character roles directory [Greg @ bastion ansible] $cp - r/usr/share/ansible/roles/rhel - system - roles. Timesync / / home/Greg/ansible/roles/timesync roles [Greg @ bastion ansible] $ansible - galaxy list# /home/greg/ansible/roles- timesync, (unknown version) write playbook script, here playbook is let us configure NTP server, We can help we just copy timesync help documentation in this directory for reference [Greg @ bastion ansible] $vim/home/Greg/ansible/timesync yml -- -- -- -- name: NTP service hosts: all vars: timesync_bTP_servers: - hostname: 172.25.254.254 iburst: yes roles: - timesync iburst Indicates whether to enable fast synchronization. [[email protected] ansible]$Ansible-playbook timesync.yml PLAY RECAP * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 172.25.250.10: OK =16 changed=0 unreachable=0 failed=0 bounce =18 axle =0 ignored=6 172.25.250.11: Ok =16 changed=0 unreachable=0 failed=0 bounce =18 rescued=0 ignored=6 172.25.250.12: Ok =16 changed=0 unreachable=0 failed=0 bounce =18 rescued=0 ignored=6 172.25.250.13: Ok =16 changed=0 unreachable=0 failed=0 bounce =18 rescued=0 ignored=6 172.25.250.9: ok=16 changed=0 unreachable=0 failed=0 skipped=18 rescued=0 ignored=6Copy the code

validation

Check whether the time synchronization server address [[email protected] ansible]$ansible all -m shell -a exists in /etc/chrony.conf-rht'grep '172.25.254.254' /etc/chrony.conf-rht '172.25.250.10 | CHANGED | rc = 0   server 172.25.254.254 iburst 172.25.250.12 | CHANGED | rc = 0   server 172.25.254.254 Iburst 172.25.250.13 | CHANGED | rc = 0   server 172.25.254.254 iburst 172.25.250.11 | CHANGED | rc = 0   server 172.25.254.254 iburst 172.25.250.9 | CHANGED | rc = 0   server 172.25.254.254 iburstCopy the code

Use Ansible Galaxy to install roles

Use Ansible Galaxy and the request file/home/Greg/Ansible/roles/requirements. Yml. Download the roles from the following URL and install them to /home/gobb/ansible/roles:

  • http://materials/haproxy.tar, this role is the name of the balancer

  • The character's name shall be as a phpinfo at http://materials/phpinfo.tar

answer

Create a Playbook script that specifies the name of the role to download and the download link

[[email protected] ansible]$ vim /home/greg/ansible/requirements.yml --- - name: balancer src: http://materials/haproxy.tar - name: phpinfo src: http://materials/phpinfo.tar with ansible - galaxy command to install the role, the -r option to specify the device file, the -p specify the location of the installation, Because the first topic defines ansible role position in/home/student/ansible/roles / [Greg @ bastion ansible] $ansible - galaxy install - r requirements. Yml - p  /home/greg/ansible/roles/ [[email protected] roles]$ ls balancer phpinfo timesyncCopy the code

validation

[[email protected] ansible]$ ansible-galaxy list
# /home/greg/ansible/roles
- timesync, (unknown version)
- balancer, (unknown version)
- phpinfo, (unknown version)

Copy the code

Create and use roles

Create a role named apache in /home/gobby.ansible/roles based on the following requirements:

  • The HTTPD package is installed and set to enable and start on system startup

  • The firewall is enabled and running with rules that allow access to the Web server

  • The template file index.html.j2 already exists to create the file /var/www/html/index.html with the following output:

    • Welcome to HOSTNAME on IPADDRESS

    • HOSTNAME is the fully qualified domain name of the managed node and IPADDRESS is the IP address of the managed node.

answer

Ansible-galaxy init role name == This command must be executed in the roles directory

[[email protected] roles]$ ansible-galaxy init apache - apache was created successfully [[email protected] roles]$ ll total 0 drwxrwxr-x. 10 greg greg 135 Apr 26 04:37 apache drwxrwxr-x. 9 greg greg 122 Apr 26 17:02 balancer drwxrwxr-x. 9 greg Greg 118 Apr 26 17:02 phpInfo drwxr-xr-x. 10 Greg Greg 188 Apr 26 04:17 timesync To write our task, the files that need to be edited are the two [[email protected] roles]$cdApache / [[email protected] apache]$ls defaults files Handlers meta readme. md Tasks templates tests Vars Tasks [[email protected] roles]$ansible-doc template Write role tasks [[email protected] apache]$vim tasks/main.yml  [[email protected] apache]$ vim tasks/main.yml --- - name: install the latest version of Apache yum: name: httpd state: Latest name: firewalld firewalld: service: HTTP state: enabled Permanent: yes Immediate: yes Run immediately. - name: firewalld: service: HTTP state: enabled Permanent: yes Template a file template: src: index.html.j2 dest: /var/www/html/index.html owner: apache group: apache mode:'0644'

- name: start service httpd
  service:
    name: "{{ item }}"state: restarted enabled: yes loop: -httpd-firewalld next write the template file index.html.j2 in the template folder (created with vim and edited with vim). The template directory is empty. [[email protected] ansible]$ansible dev -m setup -a'filter=*fqdn*'172.25.250.9 | SUCCESS =  {"ansible_facts": {
        "ansible_fqdn": "workstation.lab.example.com"."discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false} Query IPADDRESS [[email protected] ansible]$ansible dev -m setup -a'filter=*ipv4*'The IP magic parameter is ansible_default_ipv4.address [[email protected] templates]$vim index.html.j2 Welcome to {{ansible_hostname}} on {{ansible_default_ipv4.address}} Playbook script using apache role [[email protected] ansible]$vim apache.yml --- - name: Apache hosts: webservers roles: - apache Run the script [[email protected] ansible]$ansible-playbook apache.ymlCopy the code

validation

When the PlayBook script is executed, the hosts in the WebServers host group have the index.html home page file. Access their interface to see if it matches the content of the file we sent with the Template

[[email protected] ansible]$curl http://serverb Welcome to serverb on 172.25.250.11 [[email protected] ansible]$curl http://serverc Welcome to serverc on 172.25.250.12Copy the code

Use roles from Ansible Galaxy

According to the following requirements, create a called/home/Greg/ansible/roles. Yml playbook:

  • The Playbook contains a play that runs on a host in the Balancers host group and uses the Balancer role.

    • This role configures a service to balance the load of Web server requests among hosts in the WebServers host group.

    • Browsing to a host in the Balancers host group (such as http://172.25.250.13) will generate the following output:

        Welcom to serverb.lab.example.com on 172.25.250.11
      Copy the code
    • Reloading the browser will generate output from another Web server:

        Welcom to serverc.lab.example.com on 172.25.250.12
      Copy the code
  • The PlayBook contains a play that runs on a host in the WebServers host group and will use the phpInfo role.

    • Browsing to the host in the WebServers host group using the URL /hello.php will generate the following output:

        Hello PHP World from FQDN
      Copy the code
    • Where, FQDN is the fully qualified name of the host.

        Hello PHP World from
        serverb.lab.example.com
      Copy the code
    • There are also various details of the PHP configuration, such as the VERSION of PHP installed, etc.

  • Similarly, browse to http://172.25.250.12/hello.php will produce the following output:

      Hello PHP World from
      serverc.lab.example.com
    Copy the code
    • There are also various details of the PHP configuration, such as the VERSION of PHP installed, etc.

answer

  • balancersThe hosts in the host group are in the ==balancer role
  • webserversThe host in the host group uses the == phpInfo role ==
[[email protected] ansible]$ vim /home/greg/ansible/roles.yml --- - name: balancers hosts: balancers roles: - balancer - name: web hosts: webservers roles: - phpinfo - name: apache hosts: webservers roles: - apache Runs the script [[email protected] ansible]$ansible-playbook roles.ymlCopy the code

validation

Balance the load of Web server requests among hosts in the WebServers host group

[[email protected] ansible]$curl http://serverd Welcome to serverb on 172.25.250.11 [[email protected] ansible]$curl http://serverd Welcome to serverc on 172.25.250.12 [[email protected] ansible]$curl http://serverd Welcome to serverb on 172.25.250.11 [[email protected] ansible]$curl http://serverd Welcome to serverc on 172.25.250.12Copy the code

And the output PHP information for the hosts in the WebServers host group

[[email protected] ansible]$ curl http://serverc/hello.php
Hello PHP World from serverc.lab.example.com
Copy the code

Create and use logical volumes

Create a called/home/Greg/ansible/lv. Yml playbook, it will run on all the managed nodes in order to perform the following tasks:

  • Create a logical volume that meets the following requirements:

    • Logical volumes are created in the Research volume group

    • The logical volume name is data

    • The logical volume size is 1500 MIBs

  • Format the logical volume using the ext4 file system

  • If the requested logical volume size cannot be created, an error message is displayed

      Could not create logical volume of that size
    Copy the code
    • And use size 800 MiB instead.
  • If volume group Research does not exist, an error message is displayed

      Volume group done not exist
    Copy the code
  • Do not mount a logical volume in any way

answer

  • Create a logical volume, but if the size of the created logical volume exceeds the size of the VG, you should reduce the capacity and create it again, and display an error message if the VG volume group does not exist

  • Block rescue always is used

  • The relationship between block, rescue, and always is as follows: Rescue is executed when a block is incorrectly executed, and always is executed regardless of whether a block is successfully executed

  • If the RESEARCH VG group exists, the block,research, and always statements are executed. If the research VG group does not exist, a message is returned, indicating that the RESEARCH VG group does not exist

[[email protected] ansible]$ vim /home/greg/ansible/lv.yml

---
- name: Create a logical volume
  hosts: all
  tasks:
    - name: Create a logical volume
      block:
        - name: Create a logical volume
          lvol:
            vg: research
            lv: data
            size: 1500m

      rescue:
        - name: report size not enough
          debug:
            msg: Could not create logical volume of that size

        - name: Create a logical volume
          lvol:
            vg: research
            lv: data
            size: 800m

      always:
        - name: Create a logical volume
          filesystem:
            dev: /dev/research/data
            fstype: ext4
      when: "'research' in ansible_lvm.vgs"

    - name: judge
      debug:
        msg: Volume group does not exist
      when: "'research' not in ansible_lvm.vgs"Run the script [[email protected] ansible]$ansible-playbook lv.ymlCopy the code

validation

View the logical volume [[email protected] ansible]$ansible all -m shell -a'lvs'
Copy the code

Generating host files

  • An initial template file downloaded from http://materials/hosts.j2 to/home/Greg/ansible

  • Complete the template so that you can use it to generate the following files: one line for each manifest host in the same format as /etc/hosts

  • Create called/home/Greg/ansible/hosts. Yml playbook, it will use this template in the dev main unit generated on the file/etc/hosts myhosts.

  • After the Playbook is run, the file /etc/myhosts on the hosts in the dev host group should contain one line for each managed host:

    Localdomain localhost4 localhost4. Localdomain4 ::1 localhost localhost. Localdomain Localhost6 localhost6. Localdomain6 172.25.250.9 workstation.lab.example.com workstation 172.25.250.10 Servera.lab.example.com serverA 172.25.250.11 serverB.lab.example.com serverb 172.25.250.12 serverC.lab.example.com Serverc 172.25.250.13 serverd at serverd.lab.example.comCopy the code

Note: The order in which the list host names are displayed is not important.

answer

  • Use the Template module for file transfer. Check the module usage through the help documentation
  • The file contains IP addresses, domain names, and host names. So we need to use the host's built-in variables
  • The built-in variables are checked through the Setup filter
  • In this case, the for loop is used, where groups. All is a list of the controlled hosts, that is, the 5 controlled hosts. Hostvars is the host variable, and I is taken from groups.all, so it is the name of the controlled host
  • The value of the first I is serverA and then hostVars [I] can be understood as HostVars [serverA] which represents the built-in host variable of the ServerA host
Download the template to bastion [kiosk @ foundation0 files] $SCP hosts. J2 root @ bastion: / home/Greg/ansible [Greg @ bastion ansible] $vim Hosts.j2 127.0.0.1 localhost localhost. Localdomain localHost4 localHost4. Localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 {%for i in groups.all %}
{{ hostvars[i].ansible_enp1s0.ipv4.address }} {{ hostvars[i].ansible_fqdn }} {{ hostvars[i].ansible_hostname }}
{% endfor %}

Copy the code

When writing a script, note this:

  • Reference all of the host's built-in variables first, because we call all of the host's variables in hosts.j2, but the PlayBook script will fail if we don't call all of the host's variables in the Playbook first
[[email protected] ansible]$ vim /home/greg/ansible/hosts.yml 

---
- name: vars
  hosts: all
  
- name: host
  hosts: dev
  tasks:
    - name: host
      template:
        src: hosts.j2
        dest: /etc/myhosts

[[email protected] ansible]$ ansible-playbook hosts.yml
Copy the code

validation

View the myhosts file on the dev host [[email protected] ansible]$ansible dev -m shell -a'cat /etc/myhosts'172.25.250.9 | CHANGED | rc = 0   127.0.0.1 localhost localhost. Localdomain localhost4 localhost4. Localdomain4: : 1 Localhost localhost. Localdomain localhost6 localhost6. Localdomain6 172.25.250.9 workstation.lab.example.com workstation 172.25.250.10 serverA.lab.example.com serverA 172.25.250.13 serverd.lab.example.com ServerD 172.25.250.11 Serverb.lab.example.com serverb 172.25.250.12 serverC.lab.example.com serverCCopy the code

Modifying file Contents

According to the below mentioned, create a called/home/Greg/ansible/issue. Yml playbook:

  • The PlayBook will run on all manifest hosts

  • The Playbook replaces the contents of /etc/issue with the following line of text:

    • On hosts in the dev host group, this line of text appears as: Development

    • On the hosts in the test host group, the following text is displayed: test

    • On a host in the PROD host group, this line of text appears as: Production

answer

  • Copy module. In the copy module, there is an option called content to copy the specified content to the remote file
  • To require that only hosts in a specified host group be replaced, use when and inventory_hostname for the controlled hostname, for example, serverA,serverb
Write the script [Greg @ bastion ansible] $vim/home/Greg/ansible/issue. Yml -- -- -- -- name: the content hosts: all the tasks: - name: content1 copy: content:"Development\n"
        dest: /etc/issue
      when: "inventory_hostname in groups.dev"

    - name: content2
      copy:
        content: "Test\n"
        dest: /etc/issue
      when: "inventory_hostname in groups.test"

    - name: content3
      copy:
        content: "Production\n"
        dest: /etc/issue
      when: "inventory_hostname in groups.prod"Dev = dev = dev = dev = dev = dev = dev = dev = dev = dev = dev If serverA is in the dev host group, then the task in the copy module is executed. If serverA is in the dev host group, then the task in the copy module is not executed. If serverA is in the dev host group, then the task in the copy module is not executedCopy the code

validation

[[email protected] ansible]$ ansible-playbook issue.yml 

[[email protected] ansible]$ ansible all -m shell -a 'cat /etc/issue'172.25.250.11 | CHANGED | rc = 0   Production 172.25.250.10 | CHANGED | rc = 0   Test 172.25.250.13 | CHANGED | rc = 0   \ S The Kernel on the an \ \ r m 172.25.250.12 | CHANGED | rc = 0   Production 172.25.250.9 | CHANGED | rc = 0   DevelopmentCopy the code

Create a Web content directory

According to the below mentioned, create a called/home/Greg/ansible/webcontent. Yml playbook:

  • The Playbook runs on a managed node in the Dev host group

  • Create a directory /webdev that meets the following requirements:

    • The owner is the Webdev group

    • Normal permissions: owner=read+write+execute, group=read+write+execute, other=read+execute

    • With special permission: Set the group ID

  • Link /var/www/ html-webdev to /webdev with a symbolic link

  • Create a file /webdev/index.html that contains a single-line file like the following: Development

  • In dev host group on a host of browsing the directory (for example, http://172.25.250.9/webdev/) produces the following output:

      Development
    Copy the code

answer

  • To create a Web directory, think of Web services first, install apache services first, and turn on the firewall and service startup
  • When creating the Web directory, remember to change the selinux value to httpd_sys_content_t, as well as the selinux value of the index.html file
  • Group is to help create user groups
[[email protected] ansible]$ vim /home/greg/ansible/webcontent.yml

---
- name: web service
  hosts: dev
  tasks:
    - name: yum httpd
      yum:
        name: httpd
        state: present

    - name: firewalld
      firewalld:
        service: http
        state: enabled
        permanent: yes
        immediate: yes

    - name: service
      service:
        name: "{{ item }}"
        state: restarted
        enabled: yes
      loop:
        - httpd
        - firewalld

    - name: Ensure group "webdev" exists
      group:
        name: webdev
        state: present

    - name: mkdir
      file:
        path: /webdev
        group: webdev
        mode: '2775'
        state: directory
        setype: httpd_sys_content_t

    - name: link
      file:
        src: /webdev
        dest: /var/www/html/webdev
        state: link

    - name: touch
      copy:
        content: "Development\n"
        dest: /webdev/index.html
        setype: httpd_sys_content_t

Copy the code

validation

[Greg @ bastion ansible] $ansible - the playbook webcontent. Yml [Greg @ bastion ansible] $curl http://172.25.250.9/webdev/ DevelopmentCopy the code

Generate hardware reports

Create a called/home/Greg/ansible/hwreport yml playbook, it will be on all the managed nodes generated output file containing the following information/root/hwreport. TXT:

  • List Host Name

  • Total memory size in MB

  • The BIOS version

  • Size of the disk device VDA

  • Size of the disk device VDB

  • Each line in the output file contains a key=value pair.

Your PlayBook should:

  • Download files from http://materials/hwreport.empty, and save it to/root/hwreport. TXT

  • Change the correct value to /root/hwreport.txt

  • If the hardware item does not exist, the associated value should be NONE

answer

  • Use setup to find variables
  • Use debug to find variables
Host name [[email protected] ansible]$ansible dev -m setup -a'filter=*host*'Get a host name variables: ansible_hostname total memory size [Greg @ bastion ansible] $ansible dev -m setup | grep mem get the total memory size variables: Ansible_memtotal_mb BIOS version [Greg @ bastion ansible] $ansible dev -m setup | grep get BIOS version BIOS variables: Ansible_bios_version Size of vDA and VDB [[email protected] ansible]$ansible dev -m setup -a'filter=*device*'Variable to get the size of vda and VDB: Ansible_devices. Vda. The size and ansible_devices. VDB. Size [Greg @ bastion ansible] $vim/home/Greg/ansible/hwreport yml -- -- -- -- name: product hardware report hosts: all tasks: - name: Download hwreport.empty get_url: url: http://materials/hwreport.empty dest: /root/hwreport.txt - name: Ensure1 lineinfile: path: /root/hwreport.txt regexp:'^HOST='
        line: HOST={{ inventory_hostname }}
    - name: Ensure2
      lineinfile:
        path: /root/hwreport.txt
        regexp: '^MEMORY='
        line: MEMORY={{ ansible_memtotal_mb }}
    - name: Ensure3
      lineinfile:
        path: /root/hwreport.txt
        regexp: '^BIOS='
        line: BIOS={{ ansible_bios_version }}
    - name: Ensure4
      lineinfile:
        path: /root/hwreport.txt
        regexp: '^DISK_SIZE_VDA='
        line: DISK_SIZE_VDA={{ ansible_devices.vda.size }}
    - name: Ensure5
      lineinfile:
        path: /root/hwreport.txt
        regexp: '^DISK_SIZE_VDB='
        line: DISK_SIZE_VDB={{ ansible_devices.vdb.size | default('NONE'.true)}} The default value is NONE, if the VDB [[email protected] ansible]$ansible-playbook hwreport.yml does not existCopy the code

validation

[[email protected] ansible]$ ansible all -a 'cat /root/hwreport.txt'172.25.250.11 | CHANGED | rc = 0  # Hardware reportHOST=172.25.250.11 MEMORY=821 BIOS=1.11.1-3.module+el8+2529+ a9686a4D DISK_SIZE_VDA=10.00 GB DISK_SIZE_VDB=5.00 GB 172.25.250.13 | CHANGED | rc = 0  # Hardware reportHOST=172.25.250.13 MEMORY=821 BIOS=1.11.1-3.module+el8+2529+ a9686a4D DISK_SIZE_VDA=10.00 GB DISK_SIZE_VDB=5.00 GB 172.25.250.12 | CHANGED | rc = 0  # Hardware reportHOST=172.25.250.12 MEMORY=821 BIOS=1.11.1-3.module+el8+2529+ a9686a4D DISK_SIZE_VDA=10.00 GB DISK_SIZE_VDB=5.00 GB 172.25.250.10 | CHANGED | rc = 0  # Hardware reportHOST=172.25.250.10 MEMORY=821 BIOS=1.11.1-3.module+el8+2529+ a9686a4D DISK_SIZE_VDA=10.00 GB DISK_SIZE_VDB=5.00 GB 172.25.250.9 | CHANGED | rc = 0  # Hardware reportHOST=172.25.250.9 MEMORY=1829 BIOS=1.11.1-3.module+el8+2529+ a9686a4D DISK_SIZE_VDA=10.00 GB DISK_SIZE_VDB=NONECopy the code

Creating a password store

Create an Ansible library to store user passwords as described below:

  • Library name called/home/Greg/ansible/locker. Yml

  • The library contains two variables named as follows:

    • Pw_developer, the value is Imadev

    • Pw_manager, the value is Imamgr

  • The password used to encrypt and decrypt the library is whenyouWishuponastar

  • Password is stored in the file/home/Greg/ansible/secret. TXT

answer

  • Create a playbook script that contains variables. The encrypted password of the playbook script is redhat, but the password is contained in the secret. TXT file
  • To encrypt playbook scriptsansible-vaultThis command is used to encrypt the script
[Greg @ bastion ansible] $vim/home/Greg/ansible/locker. Yml - pw_developer: Imadev - pw_manager: ImagerechoThe command puts redhat into the secret file. [[email protected] ansible]$echo whenyouwishuponastar  /home/greg/ansible/secret.txt
[[email protected] ansible]$ cat /home/greg/ansible/secret.txt
whenyouwishuponastar

[[email protected] ansible]$ ansible-vault encrypt --vault-id=secret.txt locker.yml
Encryption successful
Copy the code

validation

Use the Ansible-vault view file name and enter the encrypted password. [[email protected] ansible]$ansible-vault view locker. Yml Vault password: -pw_developer: Imadev - pw_manager: ImagerCopy the code

Creating a User Account

  • Download the list of users to create from http://materials/user_list.yml and save it to /home/gobb/ansible

  • Use in other place in the exam to create password library/home/Greg/ansible/locker. Yml. Create called/home/Greg/ansible/users. Yml playbook, which described in the following to create user account:

    • Users with a job description of Developer should:

      • Create it on the managed node in the dev and Test host groups

      • Assign passwords from the pw_developer variable

      • Is a member of the supplemental devOPS group

    • Users with a job description of Manager should:

      • Create on the managed node in the PROD host group

      • Assign passwords from the PW_manager variable

      • Is a member of the supplementary group OPSMGR

  • The password is in SHA512 format.

  • Your playbook should be able to use in other place in the exam to create library password file/home/Greg/ansible/secret. TXT normal operation.

answer

  • You need to use the variables that we created in the last problem, and you need to use the vars_files option to bring in the variable files and then create the user as developer according to the problem
  • That must be when. There is more than one user, so you need to create each one using a loop
Download to create a list of [kiosk @ foundation0 materials] $SCP user_list. Yml Greg @ bastion: / home/Greg/ansible / [Greg @ bastion ansible] $cat  user_list.yml users: - name: bob job: developer - name: sally job: manager - name: fred job: developer [[email protected] ansible]$ vim /home/greg/ansible/users.yml --- - name: user hosts: dev,test
  vars_files:
    - user_list.yml
    - locker.yml
  tasks:
    - name: add group
      group:
        name: devops
        state: present

    - name: add user
      user:
        name: "{{ item.name }}"
        password: "{{ pw_developer | password_hash('sha512') }}"
        groups: devops
      loop:
        "{{ users }}"
      when: item.job == 'developer'

- name: user1
  hosts: prod
  vars_files:
    - user_list.yml
    - locker.yml
  tasks:
    - name: add group
      group:
        name: opsmgr
        state: present

    - name: add user
      user:
        name: "{{ item.name }}"
        password: "{{ pw_manager | password_hash('sha512') }}"
        groups: opsmgr
      loop:
        "{{ users }}"
      when: item.job == 'manager'[[email protected] ansible]$ansible-playbook --ask-vault-pass users.yml Enter the password whenyouwishuponastarCopy the code

validation

[[email protected] ansible]$ansible dev,test -m shell -a 'tail -2 /etc/passwd'172.25.250.10 | CHANGED | rc = 0   Bob: x: 1002-1002: : / home/Bob: / bin/bash Fred: x: 1003-1003: : / home/Fred: / bin/bash 172.25.250.9 | CHANGED | rc = 0   Bob: x: 1002-1003: : / home/Bob: / bin/bash Fred: x: 1003-1004: : / home/Fred: / bin/bash [[email protected] ansible]$ ansible prod -m shell -a'tail -3 /etc/passwd'172.25.250.11 | CHANGED | rc = 0   apache: x: 48:48: apache: / usr/share/HTTPD: / sbin/nologin nginx: x: 990-986: nginx web Server: / var/lib/nginx: / sbin/nologin Sally: x: 1002-1003: : / home/Sally: / bin/bash 172.25.250.12 | CHANGED | rc = 0   apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin nginx:x:990:986:Nginx web server:/var/lib/nginx:/sbin/nologin Sally: x: : 1002-1003: / home/Sally: / bin/bash different servers of different users to create successCopy the code

Update the Ansible library key

Update the existing Ansible library keys as described below:

  • Downloaded from http://materials/salaries.yml to/home/Greg/Ansible Ansible library

  • The current database password is insecure8Sure

  • The new library password is BBs2you9527

  • The library remains encrypted with the new password

answer

  • The ansible-vault rekey command is used to change the password of encrypted files
[[email protected] materials]$ scp salaries.yml  [email protected]:/home/greg/ansible/
salaries.yml 

[[email protected] ansible]$ cat salaries.yml 
$ANSIBLE_VAULT; 1.1; AES256 30663136613361646566623236613636363637666234336639643037353861373066643366343764 3166313830316162333838623537386161353637373935300a316463633364616461636335323336 36316163656266303261343763666432623931326530623934663930393939663233306535346631 3236306163633833300a623836616639303732663833353832346435373736313230373036336132 6235 [[email protected] ansible]$ ansible-vault rekey salaries.yml Vault password: insecure8sure New Vault password: bbs2you9527 Confirm New Vault password: bbs2you9527 Rekey successfulCopy the code

validation

New password verification [[email protected] ansible]$ansible-vault view salaries. Yml Vault password: hahaCopy the code
Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.