Playbook understanding of the Ansible module in python

Playbook

In the previous section, we detailed some of the commonly used modules provided by Ansible.You can see that each module in Ansible focuses on a certain aspect of functionality.Although the functions implemented by each module are relatively simple, the more complex functions can be achieved by combining the modules.In Ansible, the file that combines the modules is a configuration file in YAML format.This configuration file is called Playbook in Ansible.

In this section, we will introduce Playbook in Ansible step by step. First, we will introduce the definition of Playbook, then how to use Playbook to complete the remote server deployment. Then, we will detail the basic syntax of Playbook, which enables most deployment tasks to be accomplished using Playbook's basic terminology.

In this section, we will show you how to deploy nginx and MongoDB using Playbook's basic syntax. Finally, we will introduce some of Playbook's advanced syntax.

1. Definition of Playbook

Playbook is more powerful than any other remote server using a single module.If you only use the basic functions of Playbook, Playbook is a very simple system to deploy, manage, and deploy.In addition, Playbook can perform advanced functions such as specifying the order in which tasks are performed, delegating other hosts to perform a task, and interacting with the monitoring server and load balancing components.

A good analogy is that modules in Ansible are like commands on Linux, and Playbook in Ansible is like shell script files on Linux.Shell script files combine Linux commands to achieve complex functionality, and Playbook combines modules to achieve complex deployment functionality.In shell scripts, in addition to calling Linux commands, there are some basic syntax, such as variable definitions, if statements, for loops, and so on.In Playbook, on the one hand, definitions in YAML format improve the readability and maintainability of Playbook and reduce the learning burden of engineers; on the other hand, Ansible offers several options that can be applied in Playbook to enable engineers to achieve more advanced functionality.

A Playbook can contain one or more Plays, each of which is a complete deployment task.In Play, we need to specify which remote servers to perform operations on and what to do with those remote servers.

Here's a first_Playbook.ymlPlaybook.In this Playbook, we define two Plays, the former for deploying MongoDB on a database server and the latter for deploying "applications" on a web server.This is just a demonstration of the Playbook, and it doesn't really deploy the app.

[root@python ~]# vim first_playbook.yml

---
- hosts: dbservers
  become: yes
  become_method: sudo
  tasks:
  - name: install mongodb
    yum: name=mongodb-server state=present

- hosts: webservers
  tasks:
  - name: copy file
    copy: src=/tmp/data.txt dest=/tmp/data.txt

  - name: change mode
    file: dest=/tmp/data.txt mode=655 owner=root group=root

This Playbook contains two Plays.A Playbook can contain one or more Plays, so even if the Playbook median value contains one Play, it needs to be defined as a list.In YAML syntax,'-'before'- hosts' represents a list of definitions.

In Ansible, a Play must contain the following two items:

1. hosts: Which remote servers do you need to operate on
 2. tasks: List of tasks that need to be performed on these servers

For example, when deploying a web server, we only used the hosts and tasks options.The former indicates which servers to perform operations on, and the latter indicates which operations to perform on the server.The software needs to be installed when deploying the database server, so become and become_are usedMethod has two options for installing a MongoDB database as an administrator.

A Play can contain one or more tasks, so task must also be defined as a list of YAML.You can see that in this example, only one task is included when operating on a database server and two tasks are included when deploying a web server.

In Ansible, task has two definitions:

1. action: module options
2. module: options

The former is the old version syntax of Ansible, the second is the new version syntax, using the name of the module as the key and the parameters of the module as the value.As follows:

- name: install httpd
  yum: name=httpd update_cache=yes state=present

In the example of installing Apache,'name=httpd update_cache=yes state=present"is a complete string, not a dictionary.Only the value of the string is a parameter in the form of "key=value".

In order to make Playbook more readable when there are many parameters, we can also define a task as follows:

- name: install httpd
  yum: >
    name=httpd
    update_cache=yes
    state=present

In Ansible, when the parameter is long, you can use indented blocks in addition to folding and wrapping with'>':

- name: install httpd
  yum: 
    name: httpd
    update_cache: yes
    state: present

Although literally, the two ways of specifying parameters are not very different.However, from the syntax of YAML, these are two completely different methods.The former is a longer string and the latter is a dictionary.

name is optional in the task definition.Therefore, it is perfectly legal to define task as follows:

- yum: name=httpd update_cache=yes state=present

The purpose of name is to display the Playbook as a comment when it is executed so that the user knows what step is being executed.Therefore, when you define a task, you generally define the name field.

In practice, although a Playbook can contain more than one Play, we usually only write one Play in the Playbook for readability and maintainability.For example, for the example here, we can put first_Playbook.ymlThis Playbook is split into two Playbooks namedDb.ymlandWeb.yml.Where,Db.ymlThe file contains deployment tasks related to the database server.Web.ymlThe file contains deployment tasks related to the web server.

When we need to deploy a database server and a web server, we can do this firstDb.ymlFile, then executeWeb.ymlFile.In addition, Ansible provides a convenient way to handle this situation.For example, we could write a nameAll.yml Playbook, which has the following contents:

---
- include: db.yml
- include: web.yml

The include option is provided by Ansible to import other Playbooks in one Playbook.In Ansible, you only need to import other Playbook files using the include option, and when you execute this Playbook, the imported Playbooks execute in turn.

The Playbook definition of Ansible is detailed above, which is a relatively simple but complete Playbook example.The Playbook used in practice is no more complex than this one.

We'll show you how to execute Playbook using the ansible-playbook command, followed by other syntax for Playbook.

2. ansible SplitPlaybook.yml

Check to see if the required file is correct

[root@python ~]# cat hosts 
127.0.0.1
[webservers]
192.168.1.60
[dbservers]
192.168.1.80
[common:children]
dbservers
webservers
[root@python ~]# cat /etc/ansible/ansible.cfg 
[defaults]
remote_user = root
remote_port = 22
inventory = /root/hosts

splitPlaybook.yml

[root@python ~]# cat db.yml 
---
- hosts: dbservers
  become: yes
  become_method: sudo
  tasks:
  - name: install mongodb
    yum: name=mongodb-server state=present  #mongodb-server can celebrate other services such as (git)
[root@python ~]# cat web.yml 
---
- hosts: webservers
  tasks:
  - name: copy file
    copy: src=/tmp/data.txt dest=/opt/data.txt 
  - name: change mode
    file: dest=/opt/data.txt mode=655 owner=root group=root
[root@python ~]# cat all.yml 
---
- include: db.yml
- include: web.yml
[root@python ~]# touch /tmp/data.txt
[root@python ~]# touch /opt/data.txt

3. Use Ansible-playbook to execute Playbook

In the previous section, we briefly introduced the definition of Playbook.So, when we have a Playbook file, how do we execute it to complete the application deployment?We know that there are several command line tools that can be executed after the Ansible installation is complete, of which ansible-playbook is the command line tool used to execute Playbook.

The ansible-playbook is executed as follows:

ansible-playbook first_playbook.yml

The ansible-playbook command also has several command line options, some of which are the same as the ansible command.There are also some command line options specific to ansible-playbook in Ansible.

The ansible-playbook command has the same command-line options as the ansible command:

-T--timeout: Timeout for establishing SSH connection
 --key-file --private-key: Private key file to establish SSH connection
 -i --inventory-file: Specify the Inventory file, default is/etc/ansible/hosts
 -f --forks: Number of processes executed concurrently, defaulting to 5
 --list-hosts:playbooks Matching Server List.

ansible-playbook also has an option called--list-hosts, which lists matching servers.For example, in our Playbook example, the hosts file contains the following:

127.0.0.1
[webservers]
192.168.1.60
[dbservers]
192.168.1.80
[common:children]
dbservers
webservers

We know that Play in Ansible defines which servers need to be operated on, that is, each Play can specify a matching remote server.In our Playbook example, MongoDB is installed on a database server and Apply is deployed on a web server.As a result, the output of the ansible-playbook command will be significantly different from that of the --list-hosts option of the ansible command.The results from the --list-hosts option of the ansible-playbook command are as follows:

[root@python ~]# ansible-playbook all.yml --list-hosts

The ansible-playbook command has some unique options, as shown below:

--list-tasks: List tasks
 --step: Stop after each task and wait for user confirmation
 --syntax-check: Check Playbook syntax
 -C--check: Checking if the current Playbook modifies the remote server is equivalent to predicting the results of Playbook execution.

Several of the options here, with the exception of --step, do not perform tasks in Playbook.These options exist primarily to facilitate debugging of the Playbook.For example, --list-tasks option, which displays the list of tasks in the current Playbook.This is a quick way to view the task list when the Playbook is large.As follows:

[root@python ~]#  ansible-playbook  all.yml --list-tasks
playbook: all.yml

  play #1 (dbservers): dbservers    TAGS: []
    tasks:
      install mongodb   TAGS: []

  play #2 (webservers): webservers  TAGS: []
    tasks:
      copy file TAGS: []
      change mode   TAGS: []

When we look at the task list, the name of the task is the name field of the task.Therefore, the definition of name needs to be descriptive so that the user can know what the task needs to do by name.

The--step option is similar to step debugging in a programming language.When we execute the Playbook with the --step option, ansible-playbook stops before each task and waits for the server user to enter yes, no, or continue.As follows:

[root@python ~]# ansible-playbook all.yml --step
[DEPRECATION WARNING]: 'include' for playbook includes. You should use 
'import_playbook' instead. This feature will be removed in version 2.12. 
Deprecation warnings can be disabled by setting deprecation_warnings=False in 
ansible.cfg.

PLAY [dbservers] ***************************************************************
Perform task: TASK: Gathering Facts (N)o/(y)es/(c)ontinue: y

Perform task: TASK: Gathering Facts (N)o/(y)es/(c)ontinue: *********************

TASK [Gathering Facts] *********************************************************
ok: [192.168.1.80]
Perform task: TASK: install mongodb (N)o/(y)es/(c)ontinue: y

Perform task: TASK: install mongodb (N)o/(y)es/(c)ontinue: *********************

TASK [install mongodb] *********************************************************
changed: [192.168.1.80]

PLAY [webservers] **************************************************************
Perform task: TASK: Gathering Facts (N)o/(y)es/(c)ontinue: y

Perform task: TASK: Gathering Facts (N)o/(y)es/(c)ontinue: *********************

TASK [Gathering Facts] *********************************************************
ok: [192.168.1.60]
Perform task: TASK: copy file (N)o/(y)es/(c)ontinue: y

Perform task: TASK: copy file (N)o/(y)es/(c)ontinue: ***************************

TASK [copy file] ***************************************************************
changed: [192.168.1.60]
Perform task: TASK: change mode (N)o/(y)es/(c)ontinue: y

Perform task: TASK: change mode (N)o/(y)es/(c)ontinue: *************************

TASK [change mode] *************************************************************
changed: [192.168.1.60]

PLAY RECAP *********************************************************************
192.168.1.60               : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.1.80               : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

When yes is entered, the task continues and stops at the next task, waiting for the user to continue typing.When we enter continue, Ansible executes the current Play, stops when it reaches the next Play, and waits for user input.

2. Playbook's detailed syntax

So far, we've learned how to write and run a Playbook.However, we have only introduced the simplest Playbook.In this section, we'll show you how Playbook provides a wide range of functionality with different options.Flexible use of these options enables you to write Playbooks in a variety of formats to cope with situations in your automated deployment.

When defining Play, only hosts and tasks are required options, and other options are added as needed.In this section.We'll look at the different features that Playbook offers, and take the functionality of Playbook as a clue to the options that Play and task can use.

(1) Permissions

In Ansible, the current user is used by default to connect to the remote server to perform operations.We can alsoAnaible.cfgThe file configures the default user to connect to the remote server.In addition, if different users use different types of remote servers, you can also specify the user who connects to the remote server in Playbook's Play definition.For example, we can specify a user to execute Play:

---
- hosts: webservers
  remote_user: root

Users can subdivide each task as follows:

---
- hosts: werbservers
  remote_user: root
  tasks:
    - name: test connection
      ping:
        remote_user: yourname

Many times, instead of connecting to a remote server with a specific user, we need to use an administrator to perform operations when higher-level privileges are required.In ansible, you can use become with become_Method option implementation:

---
- hosts: werbservers
  remote_user: root
  become: yes

With remote_Similar to the user option, we can also use administrator privileges for a single task as follows:

---
- hosts: werbservers
  remote_user: yourname
  tasks:
    - name: installed nginx
      service: name=nginx state=started
      become: yes
      become_method: sudo

Example

Modify the test permissions in the remote server first (0:0)

[root@192 ~]# vim /etc/passwd
test:x:0:0::/home/test:/bin/bash
[root@python ~]# chown test:root /etc/ansible/*
[root@python ~]# su test
[test@python root]$ cd 
[test@python ~]$ vim hosts
[db]
192.168.1.60

[test@python ~]$ vim db.yml

---
- hosts: db
  remote_user: root             #Users logged on to remote servers
  tasks:
    - name: installed nginx
      become: yes
      become_method: sudo
      ping:
        remote_user: root         #Users logged on to remote servers
[test@python ~]$ vim /etc/ansible/ansible.cfg 

[defaults]
inventory = /home/test/hosts

Execute once

[test@python ~]$ sudo ansible-playbook db.yml --step

We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:

    #1) Respect the privacy of others.
    #2) Think before you type.
    #3) With great power comes great responsibility.

[sudo] password for test: 

PLAY [db] **********************************************************************
Perform task: TASK: Gathering Facts (N)o/(y)es/(c)ontinue: y

Perform task: TASK: Gathering Facts (N)o/(y)es/(c)ontinue: *********************

TASK [Gathering Facts] *********************************************************
Enter passphrase for key '/root/.ssh/id_rsa': 
ok: [192.168.1.60]
Perform task: TASK: installed nginx (N)o/(y)es/(c)ontinue: 

Perform task: TASK: installed nginx (N)o/(y)es/(c)ontinue: *********************

PLAY RECAP *********************************************************************
192.168.1.60               : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

(2) Notification

In Ansible, modules are idempotent.For example, we want to create a user on a remote server. If the user already exists, Ansible will not delete the user and recreate it later. Instead, Ansible will return directly to success and use the changed field to indicate whether the remote server has been modified.

Consider the need to modify Apache's configuration file through Ansible and restart the Apache service for the new configuration file to take effect.Since Ansible's modules are idempotent, when we modify Apache's configuration file, Ansible does nothing if the content of the configuration file is already the same as what we want to modify (for example, if we accidentally execute Ansible twice).Since Apache's configuration file hasn't really been modified, we shouldn't restart Apache's server either.In Ansible, this functionality is achieved through notify and handler mechanisms.

In the following example, we first attempt to install Apache, then modify the Apache configuration file.If the configuration file is modified, the handler is notified with the notify option for subsequent processing.

Handler is the conditional mechanism provided by Ansible and, like tasks, does something.However, handlers will only execute if triggered by notify, and will not execute if not.In Playbook, if there is a notify option behind the task, then when Ansible recognizes that the task has changed the state of the system, it triggers the handler through the notify.

What conditions does Ansibie use to determine which handler notify triggers?Simply, in Ansible, task uses the name of the handler as an argument to trigger a specific handler.For example, in our example here, notify triggers the "restart apache" handler, and there is also a handler named "restart apache" in handlers.

---
- hosts: webservers
  tasks:
  - name: ensure apache is at the latest version
    yum: name=httpd state=latest

  - name: write the apache config file
    template: src=/srv/httpd.j2 dest=/etc/httpd.conf
    notify:
    - restart apache

  - name: ensure apache is running
    service: name=httpd state=started

  handlers:
    - name: restart apache
      service: name=httpd state=restarted

It is important to note that the handler will only execute after all tasks have been executed.Moreover, even if a handler is triggered multiple times, it will only execute once.Handler is not executed immediately when triggered, but in the order defined in Play.Typically, handlers are at the end of the Play, meaning they are executed after all tasks have been executed.

Ansible's official documentation mentions that the only purpose of handler is to restart services and servers, as demonstrated by Find Us.

In this example, we also use the template module T.The template module is used to render the Jinja template.

(3) Variables

In the Inventory Administration section, we have described how to define variables.There are several other ways to define variables in Ansible.For a simple Playbook, the most direct way is to define variables in Playbook's vars option.As follows:

- hosts: dbservers
  vars:
    mysql_port: 3307

Define variables in Playbook that you can use when rendering templates.For example, in the example officially given by Ansible, some templates for the MySQL configuration file are as follows:

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
port={{ mysql_port }}

When there are fewer variables, there is no problem defining them in the vars option at all.When there are many variables, you can save them in a separate file and use vars_The files option references the file.As follows:

---
- hosts: all
  vars:
    favcolor: blue
  vars_files:
    - /vars/external_vars.yml

  tasks:
  - name: this is just a placeholer
    command: /bin/echo foo

The file holding the variables is a simple dictionary in YAML format, as follows:

---
# in th above example, this would be vars/external_vars.yml
somevar: somevalue
password: magic

In shell scripts, we can determine if a command was executed successfully by getting the return code of the previous command.In Ansible, we can also get the execution result of a task, save the execution result of a task in a variable most, and reference this variable later.Such a variable is obtained in Ansible using the register option, also known as a registered variable.

For example, in the following example, we execute the /usr/bin/foo command first, and get the execution result of the command through the register option, then save the result in foo_In result.In later task s, use this variable name to reference the execution result of the / usr/bin/foo command.

- hosts: web_servers
  tasks:
  - shell: /usr/bin/foo
    register: foo_result
    ignore_errors: True

  - shell: /usr/bin/bar
    when: foo_result == 5

This example also involves two new options, ignore_errors and when.The former means ignoring errors in the current task, and the latter is a conditional statement that executes the task only if the condition is true.

(4) Facts variable

There are also special variables in Ansible that can be used directly without any settings, called Facts variables.Facts variables are system information that Ansible retrieves from a remote server before it executes a remote deployment, including the name of the server, IP address, operating system, partition information, hardware information, and so on.Facts variables can be adapted to Playbook's more personalized functional needs.For example, save data from a MongoDB database in the / var/mongo-\<hostname>/directory.

We can see a list of Facts variables through the setup module, as follows:

ansible all -m setup

With the Facts variables, how do you use them in Ansible?The answer is to use it directly.We can reference a variable directly in Playbook by its name, or in the Jinja2 template by its name.Here's a test_Facts.ymlPlaybook.In this Playbook, we output the type of operating system and only perform the installation when the operating system is a RedHat-like operating system.

---
- hosts: dbservers
  tasks:
    - shell: echo {{ ansible_os_family }}
      register: myecho

    - debug: var=myecho.stdout_lines

    - name: install git on Red Hat Linux
      yum: name=git state=installed
      when: ansible_os_family == "RedHat"

The setup module categorizes and organizes the output of the module for readability of the output.Therefore, when we want to access the subattributes of complex variables, we need to use nested structures.For example, we can access an ipv4 address in Ansible in two ways:

ansible_ens33['ipv4']['address']
ansible_ens33.ipv4.address

Playbook accessing complex variables:

---
- hosts: dbservers
  gather_facts: yes
  tasks:
    - shell: echo {{ ansible_ens33['ipv4']['address'] }}
      register: myecho

    - debug: var=myecho.stdout_lines

    - shell: echo {{ ansible_ens33.ipv4.address }}
      register: myecho

    - debug: var=myecho.stdout_lines

In practice, we typically reference the Facts variable in the Jinja2 template.Use it in the same way as the example here, so it won't be repeated in order to save space.

In Playbook, you can use gather_The facts option controls whether information from the remote server is collected.The default value for this option is yes, which can be set to no to improve the efficiency of the Ansible deployment if you are sure that you do not need information from the remote server.As follows:

---
- hosts: dbservers
  gather_factes: no
  tasks:

(5) Circulation

- name: Install Mysql package
  yum: name={{ item }} state=installed
  with_items:
    - mysql-server
    - MySQL-python
    - libselinux-python
    - libsemanage-python

(6) Conditions

Sometimes, whether a task is executed or not depends on the value of a variable or the result of the previous task, at which point they need conditional statements.Or, you want to skip certain elements while looping and only operate on certain operating systems when the server is deployed.All these behaviors can be solved using conditional statements.Ansible's Playbook is not a programming language, so there are no corresponding conditional statements, but Ansible offers a similar option.

Conditional statements can be executed in Playbook with the when option, which is similar to the if statement in a programming language.

Here is a simple example of when option use:

# View the Linux system version: cat/etc/redhat-release
tasks:
  - name: "System shutdown"
    command: /sbin/shutdown -t now
    when: ansible_os_family == "RedHat"    

The when option also supports multiple conditional statements, which are in YAML format:

tasks:
  - name: "shutdown CentOS 7 systems"
    command: /sbin/shutdown -t now
    when:
      - ansible_distribution == "CentOS"
      - ansible_distribution_major_version == "7"

More complex conditions can be defined using and, or, and parentheses:

tasks:
  - name: "shutdown CentOS 7 and Debian 6 systems"
    command: /sbin/shutdown -t now
    when: (ansible_distribution == "CentOS" and ansible_distribution_major_version == "7") or (ansible_distribution == "Debian" and ansible_distribution_major_version == "6")

The value of a variable can be read in the when option, for example:

vars:
  epic: true

tasks:
  - shell: echo "This certainly is epic!"
    when: epic

The when option can be used with loops to achieve filtering:

tasks:
  - command: echo {{ item }}
    with_items: [0, 2, 4, 6, 8, 10]
    when: item > 5

(7) Task Execution Strategy

In Ansible, Playbook is executed in task units.Ansible uses five processes by default to perform tasks on remote servers.In the default task execution policy (linear), Ansible executes task1 first, and waits until all servers execute task1 before starting task2, and so on.Starting with Ansible 2.0, Ansible supports a task execution policy called free, which allows faster remote servers to complete the Play deployment ahead of time without waiting for other remote servers to execute the task together.As follows:

- hosts: all
  strategy: free
  tasks:
   ......

In this section, we describe the Playbook option in Ansible in more detail.In Ansible, Play and task have many options, each of which implements different functions.Ansibie does not officially introduce different options in the form of functionality to give a complete list of options.We can also refer toHttps://github.com/lorin/ansible-quickrefQuickly understand the options in Play and task, and what each means.

4. Case: Using Playbook to Deploy nginx

In this example, we use Ansible to configure a server to run the nginx process.The laybook for deploying nginx is as follows:

---
- hosts: webservers
  become: yes
  become_method: sudo
  vars:
    worker_prosess: 4
    worker_connections: 768
    max_open_files: 65506
  tasks:
    - name: install nginx
      yum: name=nginx update_cache=yes state=present

    - name: copy nginx config file
      template: src=/home/root/test_ansible/nginx.conf.j2 dest=/etc/nginx/nginx.conf
      notify: restart nginx

    - name: copy index.html
      template:
        src: /home/root/test_ansible/index.html.j2
        dest: /usr/share/nginx/www/index.html
        mode: 0644
      notify: restart nginx
  handlers:
    - name: restart nginx
      service: name=nginx state=restarted

In this Playbook, we first specify which remote servers to perform operations through the hosts option.We then passed become and become_The method option declares sudo permissions for deployment.Next, we define three variables in the vars field that will be used in the nginx configuration file.Under the tasks option, we define a list of tasks for deploying nginx services, including software installation, template rendering, customizing the s home page, and restarting the nginx process.

To avoid restarting the nginx process without any modifications to the configuration file, Ansible's handler mechanism is used here.In this Playbook, there are two notify options and one handler option.Whether the nginx configuration file or the custom home page has been modified, we will restart the nginx process.Since we use Ansible's handlers mechanism, Ansible will not restart the nginx process without any modifications.Another advantage of using the handler mechanism is that notify executes multiple times and handler executes only once, preventing the nginx process from being restarted multiple times.

In this Playbook where nginx services are deployed, we useNginx.conf.j2 This configuration template.This template uses the Jinja2 syntax, so the suffix is j2.The content of the template is as follows:

[root@python ~]# vim nginx.yml
worker_processes  {{ worker_prosess }};
worker_rlimit_nofile {{ max_open_files }};

events {
    worker_connections  {{ worker_connections }};
}

http {
    server {
        listen       80;

        listen  443 ssl;

        server_name  localhost;

        location / {
            root   /usr/share/nginx/www;
            index  index.html index.htm;

            tr_files $uri $uri/ =404;
        }
    }
}

Ansible renders the Jinja2 template to a real configuration file using the variables we defined in Playbook's vars field.

Our Playbook also uses a name calledIndex.htmlA template for.J2, which renders the home page of a Web site.Index.htmlThe contents of.J2 are as follows:

[root@python ~]# mkdir test_ansible
[root@python ~]# vim test_ansible/index.html.j2
<html>
    <meta charset="utf-8">
    <head>
        <title>wellcome to ansible</title>
    </head>
    <body>
        <h1>nginx, configured by ansible</h1>
        <p>If you can see this page, the instructions ansible Auto Deployment nginx Succeed!</p>

        <p>{{ ansible_hostname }}<p>
    </body>
</html>

stayIndex.htmlIn.J2, we used a named ansible_Variable of hostname.This variable is the Facts variable, which is the information Ansible gets from the remote server before executing the Playbook.Therefore, we don't need a definition, just use it.

Once you have a Playbook, deploy it using the ansible-playbook command.As follows:

[root@python ~]# pip install Jinja2
[root@python ~]# vim /etc/ansible/ansible.cfg 

[defaults]
inventory = /root/hosts

[root@bogon ~]# ansible-playbook nginx_playbook.yaml

PLAY [webservers] **********************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************
ok: [127.0.0.1]

TASK [install nginx] *******************************************************************************************************
ok: [127.0.0.1]

TASK [copy nginx config file] **********************************************************************************************
ok: [127.0.0.1]

TASK [copy index.html] *****************************************************************************************************
ok: [127.0.0.1]

PLAY RECAP *****************************************************************************************************************
127.0.0.1                  : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

[root@bogon ~]# 

If the installation fails, either the port is occupied, you can stop the service using the port, or you can change the nginx port.

[root@bogon ~]# netstat -ntlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      1/systemd           
tcp        0      0 0.0.0.0:6000            0.0.0.0:*               LISTEN      7470/X              
tcp        0      0 192.168.122.1:53        0.0.0.0:*               LISTEN      7654/dnsmasq        
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      7337/sshd           
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      7340/cupsd          
tcp        0      0 127.0.0.1:6010          0.0.0.0:*               LISTEN      31653/sshd: root@pt 
tcp        0      0 127.0.0.1:6011          0.0.0.0:*               LISTEN      31653/sshd: root@pt 
tcp        0      0 127.0.0.1:6012          0.0.0.0:*               LISTEN      31653/sshd: root@pt 
tcp6       0      0 :::111                  :::*                    LISTEN      1/systemd           
tcp6       0      0 :::80                   :::*                    LISTEN      17867/httpd         
tcp6       0      0 :::6000                 :::*                    LISTEN      7470/X              
tcp6       0      0 :::22                   :::*                    LISTEN      7337/sshd           
tcp6       0      0 ::1:631                 :::*                    LISTEN      7340/cupsd          
tcp6       0      0 ::1:6010                :::*                    LISTEN      31653/sshd: root@pt 
tcp6       0      0 ::1:6011                :::*                    LISTEN      31653/sshd: root@pt 
tcp6       0      0 ::1:6012                :::*                    LISTEN      31653/sshd: root@pt 
[root@bogon ~]# systemctl stop httpd.service

Tags: Python ansible Nginx Apache

Posted on Wed, 20 May 2020 15:28:58 -0700 by rheroux