Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Introduction and use of common modules in Ansible

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

This article shares with you the introduction and use of common modules in Ansible. The article covers the list of inventory hosts, the introduction of YAML language, the implementation of playbook script and so on. I hope you can get something through this article.

Inventory host list ansible default host list is / etc/ansible/hosts file, which can be set manually or dynamically generated through Dynamic Inventory. The general host name is defined by FQDNvim / etc/ansible/hosts [webserver] # square brackets set group name www1.example.org #, which can be either the host name or the IP address. The hostname needs to be modified / etc/hosts file www2.example.org:2222 # define the remote connection port after the colon. The default is port 22 of ssh if it is a host with a similar name You can use a list to identify each host [webserver] www [01:50] .example.org ansible_ssh_user=root ansible_ssh_pass= 123456 [dbbservers] db- [aburef] .example.orginventory variable host variable [webserver] www1.magedu.com http_port=80 maxRequestsChild=808www2.magedu.com http_port=8080 maxRequestsChild=909 group variable [servers:vars] ntp_server=ntp.example.orgnfs_server=nfs.example.org group nested [apache] http1.example.orghttp2.example.org [nginx] ngx1.example The parameter parameter of the .orgngx2.example.org [webservers:children] apachenginxinventory variable indicates the remote hostname to which ansible_ssh_host will connect. If it is different from the alias of the host you want to set, you can set the ansible_ssh_portssh port number through this variable. If it is not the default port number, use this variable to set ansible_ssh_user 's default ssh username ansible_ssh_passssh password (this is not secure, we strongly recommend using-- ask-pass or SSH key) the private key file used by ansible_ssh_private_key_filessh. For situations where you have multiple keys and you do not want to use the SSH proxy, ansible_ssh_common_args this setting is attached to the default command line of sftp,scp and ssh, ansible _ sftp_extra_args, this setting is appended to the default sftp command line, ansible _ scp_extra_args, this setting is appended to the default scp command line, ansible _ ssh_extra_args, this setting is appended to the default ssh command line, ansible _ ssh_pipelining, to determine whether or not to use SSH pipes. This can override the shell type of the ansible_shell_type target system that has to be set in ansible.cfg. By default, the command is executed using the 'sh' syntax and can be set to the python path of the target host' csh' or 'fish'ansible_python_interpreter. Applicable: there are multiple Python in the system, or the command path is not "/ usr/bin/python", such as * BSD, or / usr/bin/pythonansible_*_interpreter. The "*" here can be an interpreter of ruby or perl or other languages, acting like ansible_python_interpreter, which is similar to ansible_shell_executable. This will set the shell that the ansible controller will use on the target machine, overriding the configuration in ansible.cfg. The default is / bin/shYAML markup language YAML: another markup language. Is a language used to write configuration files, very concise and powerful. YAML syntax is similar to other languages in that it can also express data structures such as hash tables and scalars. The structure is shown by spaces; the configuration items in the sequence are represented by -; the key values in Map are separated by:; the extension of YAML is yaml

Basic grammatical rules

1. Case sensitive 2. Use indentation to represent hierarchical relationships 3. The Tab key is not allowed when indenting, only spaces are allowed. 4. The number of indented spaces is not important, as long as the elements at the same level are aligned to the left, the data structure supported by YAML. Object: a collection of key-value pairs, also known as mapping (mapping) / hash (hashes) / dictionary (dictionary) for example: name:Example Developer key value 2. Array: a group of values arranged in order, also known as sequence / list, for example:-Apple-Orange3. Scalar: a single, inseparable value such as: number:12.30 sure:trueyaml instance: name:zhangsanage:20name:lisiage:22people:-name:zhangsan age:20-name:lisiage: 22Ansible script-playbookPlaybook is a completely different way of using ansible, similar to saltstack's state state file. Ad-hoc cannot be used persistently, playbook can be used for a long time. Playbook is a list of one or more play, and the main function of play is to dress up hosts that have been merged into a group as roles defined in advance through the task in ansible. Fundamentally speaking, the so-called task is nothing more than a module that calls ansible. By organizing multiple play in a single playbook, you can combine them to accomplish a task according to a pre-scheduled mechanism. Call the template of ansible through task to run multiple play organizations in one playbook. The name of the Playbook core element means that the remote host list Tasks task set executed by Hosts, that is, the Varniables variable, built-in variable or custom variable completed by the calling module calls the Templates template in playbook, even if the template syntax file, such as configuration file, Handlers processor, is used in combination with notity, the action triggered by a specific condition is not executed until the condition is met, otherwise the tags tag is not executed and a task is specified to execute. Used to choose to run part of the code in playbook Roles role Playbook syntax 1, playbook uses yaml syntax format, the suffix can be yaml, can also be yml. In a single playbook file, multiple play can be distinguished by three consecutive subnumbers (- -). There are also selective three points in a row. Used to indicate the end of a play, or it can be omitted. 2. When the line starts to write the content of the playbook normally, it will generally write down the function of the playbook. 3. Use # to annotate the code. 4. Indentation must be unified, and spaces and tab cannot be mixed. The level of indentation must also be consistent, the same indentation represents the same level, and the program determines the level of configuration through indentation combined with line feeds. 5. The content of the YAML file is consistent with the case judgment method of the Linux system, which is case-sensitive. The value of KBV needs to be case-sensitive. 6. The value of KBV can be written in the same line or in a new line. Peer use: separation. V can be a string or a listing 7, a complete code block function requires a minimum of elements including name: task example demonstration: vim a.yaml-hosts: webserver # defined host group That is, the task performed by the applied host vars: # defines the variable http_port: 80 max_clients: 200 user: root tasks: #-name: ensure apache is at the latest version yum: pkg=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: # processor-name: restart apache service: name=httpd state=restarted executes a playbook format ansible-playbook [yaml file name]

Example demonstration:

# execute screenplay ansible-playbook ping.yaml

Parameters:

-k (- ask-pass) is used to enter ssh password interactively-K (- ask-become-pass) is used to interactively enter sudo password-u specifies the user

Supplementary command:

# check whether the syntax of the yaml file is correct ansible-playbook nginx.yaml-- syntax-check# check tasks task ansible-playbook nginx.yaml-- list-task# check valid host ansible-playbook nginx.yaml-- list-hosts# specify to run ansible-playbook nginx.yaml from a certain task-- introduction to start-at-task='Copy Nginx.conf'hosts and users

Example demonstration:

Vim a.yaml-hosts: webserver # specifies the host group, which can be one or more groups. Remote_user: root # specifies the user name of the remote host execution # execution script ansible-playbook a.yaml defines the remote execution user for each task on the original basis! vim- hosts: mysql remote_user: root tasks:-name: test connection ping: remote_user: mysql# specifies that the running user of the remote host executing tasks executes playbook for mysql# Script ansible-playbook ping.yml-k # validation syntax ansible-playbook a.yml-- syntax-check# executes script ansible-playbook a.yml to specify remote host sudo switching users! vim- hosts: mysql remote_user: root become: yes # parameters after version 2.6 It used to be sudo, meaning that the switched user runs become_user: mysql# specifies that the sudo user executes the playbook script ansible-playbook ping.yml-K# execution script for mysql#. The main part of the ansible-playbook a.yml tasks list and action1.Play is the task list, and each task in the task list is executed one by one on the host specified in hosts, that is, the first task is completed on all hosts before starting the second task. When running playbook (from top to bottom), if a host fails to execute task, the entire tasks will be rolled back, please correct the error in playbook, and then execute it again. The purpose of Task is to execute the module with specified parameters, while variables can be used in module parameters, which means that multiple execution is safe because the results are consistent. two。 Each task must have a name name, so that when you run playbook, you can tell which task it belongs to from the task execution information it outputs. If the value of name,'action' is not defined, it will be used as the tag-specific task in the output information. 3. Define a task, common format: "module: options" for example: yum: name=httpd4.ansible in the built-in module, command module and shell module do not need to use key=value format

Example demonstration:

In the instance 1vim a.yml-hosts: webserver remote_user: root tasks:-name: disable selinux command:'/ sbin/setenforce 0'-name: make sure apache is running service: name=httpd state=started#play, an error will be reported as long as the return value of the command executed is not 0. Tasks stops # check syntax ansible-playbook a.yml-- syntax-check# executes script ansible-playbook a.yml # check result rpm-Q httpd

Modify the following:

! vim- hosts: webserver remote_user: root tasks:-name: disable selinux command:'/ sbin/setenforce 0' ignore_errors: True # ignore errors Forced return success-name: make sure apache is running service: name=httpd state=started# check syntax ansible-playbook a.yml-- syntax-check# execute script ansible-playbook a.yml instance 2vim b.yml-hosts: webserver remote_user: root tasks:-name: create nginx group group: name=nginx system=yes gid=208-name: create nginx user user: name=nginx uid=208 group=nginx system=yes- hosts: mysql remote_user: root tasks:-name: copy file to mysql copy: Src=/etc/inittab dest=/opt/inittab.back# check syntax ansible-playbook b.yml-- syntax-check# execution script ansible-playbook b.ymlHandlers introduction Handlers is also a list of some task It is no different from the normal task. The notify is carried out by the notifier. If it is not notify, the Handlers will not be executed. If it is notify, the Handlers will be executed no matter how many notifiers have notify. After all the task execution in the play is completed, the handlers will only be executed once.

Example demonstration:

Vim c.yml-hosts: webserver remote_user: root tasks:-name: install httpd package yum: name=httpd state=latest-name: install configuration file for httpd copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf notify:-restart httpd-name: start httpd service service: enabled=true name=httpd state=started handlers:-name: restart httpd service: name=httpd state=restarted# check syntax ansible-playbook c.yml-- syntax-check# executes script ansible-playbook c.yml

Some variables can also be introduced:

! vim- hosts: webserver remote_user: root vars:-package: httpd-service: httpd tasks:-name: install httpd package yum: name= {{package}} state=latest-name: install configuration file for httpd copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf notify:-restart httpd-name: start httpd service service: enabled=true name= {{service} state=started handlers:-name: restart httpd service: name= {{ Service}} state=restarted# check syntax ansible-playbook c.yml-- syntax-check# 's method of using variables to execute a script ansible-playbook c.ymlplaybook

1. Pass through the ansible command

Example demonstration:

# Edit the following ymlvim a.yml-hosts: mysql remote_user: root vars:-user: tasks:-name: name= {{user}} # execute the script ansible-playbook a.yml-e "user=testvar" # execute the command to view the file ansible mysql-m command-a 'tail / etc/passwd'

two。 Define variables directly in yaml-as in the handlers example above

3. Refer directly to some variables

Example demonstration:

Reference to ansible's fixed variable vim test.yml- hosts: mysql remote_user: root tasks:-name: copy file copy: content= "{{ansible_all_ipv4_addresses}}" "dest=/opt/vars.txt# execution script ansible-playbook test.yml# views the contents of the vars.txt file on 122hosts cat / opt/vars.txt references the host variable vim / etc/ansible/hosts# adds the following after the hosts of the mysql group [mysql] 192.168.142.122 testvar=" 42.122 "# defines the value of the testvar variable as 42.122vim test.yml# adds {{testvar}} host variable-hosts: Mysql remote_user: root tasks:-name: copy file copy: content= "{{ansible_all_ipv4_addresses}} {{testvar}} "dest=/opt/vars.txt# execution script ansible-playbook test.yml# looks at the contents of the vars.txt file on the 122host cat / opt/vars.txt conditional test is used if it needs to be based on variables, facts (setup) or the execution results of previous tasks as a prerequisite for whether a task is executed or not. Conditional tests in Playbook use the conditional clause. You can use conditional testing by adding a when clause after task: the when clause supports regular expressions or syntax.

Example demonstration:

Vim when.yml- hosts: mysql remote_user: root tasks:-name: "shutdown CentOS" command: / sbin/shutdown-h now when: ansible_distribution = = "CentOS" # execute the script After execution, you will find that the 192.168.142.122 host has been shut down. Ansible-playbook when.yml Multi-condition judgment vim when.yml- hosts: mysql remote_user: root tasks:-name: "shutdown CentOS 6 systems" command: / sbin/shutdown-r now when:-ansible_distribution = = "CentOS"-ansible_distribution_major_version = = "6" # execution script ansible-playbook when.yml group condition judgment Vim when.yml- hosts: mysql remote_user: root tasks:-name: "shutdown CentOS 6 and Debian 7 systems" command: / sbin/shutdown-t now when: (ansible_distribution = = "CentOS" and ansible_distribution_major_version = = "6") or (ansible_distribution = = "Debian" and ansible_distribution_major_version = = "7") # execute script ansible-playbook when.yml custom variables for conditional testing Vim when.yml- hosts: all vars: exist: "True" tasks:-name: creaet file command: touch / tmp/test.txt when: exist | match ("True")-name: delete file command: rm-rf / tmp/test.txt when: exist | match ("False") # executes the screenplay ansible-playbook when.yml iteration when there are tasks that need to be repeated You can use an iterative mechanism. Its format is to define the content that needs to be iterated as an item variable reference, and to indicate the list of elements for the iteration through the with_items statement.

Example demonstration:

Vim d.yml-hosts: webserver remote_user: root tasks:-name: "Install Packages" yum: name= {{item}} state=latest with_items:-httpd-mysql-server-php# check syntax ansible-playbook d.yml-syntax-check# execution script ansible-playbook d.yml# checks on all hosts to see if there is a specified added user tail-5 / etc/passwd

You can also define it by yourself:

Vim e.yml-hosts: webserver remote_user: root tasks:-name: "Add users" user: name= {{item.name}} state=present groups= {{item.groups}} with_items:-{name:'test1', groups:'wheel'}-{name:'test2' Groups:'root'} # check syntax ansible-playbook e.yml-- syntax-check# execution script ansible-playbook e.yml# checks on all hosts to see if there is a specified added user tail-5 / etc/passwdTemplates module # create working directory mkdir templates# replication configuration file cp / etc/httpd/conf/httpd.conf templates/httpd.conf.02# modify httpd.conf.02 file vim templates/httpd.conf.02Listen {{http_port}} ServerName {{ansible_fqdn}} MaxClients {{maxClients}} # modify the ansible/hosts file vim / etc/ansible/ hosts [webserver] 192.168.142.121 http_port=80 maxClients=100192.168.142.122 http_port=8080 maxClients=200# write screenplay vim apache.yml- hosts: webserver remote_user: root vars:-package: httpd-service: httpd tasks:-name: install httpd package yum: name= {{package}} state=latest-name: install configuration file for httpd template: src=/ Root/templates/httpd.conf.2 dest=/etc/httpd/conf/httpd.conf notify:-restart httpd-name: start httpd service service: enabled=true name= {{service}} state=started handlers:-name: name= {{service}} state=restarted# check syntax ansible-playbook e.yml-- syntax-check# execution script ansible-playbook apache.yml# view grep-I listen / etc/httpd/conf/ on two managed servers The httpd.confgrep-I maxClient / etc/httpd/conf/httpd.confgrep-I servername / etc/httpd/conf/httpd.conftags module is in one playbook We usually define a lot of task, and we can use the tags tag function if we only want to execute one or more of the task. The format is as follows: vim hosts.yml- hosts: webserver remote_user: root tasks:-name: Copy hosts file copy: src=/etc/hosts dest=/etc/hosts tags:-only-name: touch file file: path=/opt/hosts state=touch# check grammar ansible-playbook e.yml-- syntax-check# execution script ansible-playbook hosts.yml--tags= "only" ansible-playbook hosts.ym in fact, you can not only specify the same tags for one or more task. Playbook also provides a special tags for always. The purpose is that when using always when the task of tags, no matter which tags is executed, the tags with always defined will be executed.

Example demonstration:

Vim hosts.yml

-hosts: webserver remote_user: root tasks:-name: Copy hosts file copy: src=/etc/hosts dest=/etc/hosts tags:-only-name: touch file file: path=/opt/hosts state=touch tags:-always# check syntax ansible-playbook e.yml-- syntax-check# delete the / opt/hosts file in the remote host rm-rf / opt/hosts # execution script ansible in order not to affect this operation -playbook hosts.yml-- tags= "only" # check file creation ls / opt/ on two managed servers respectively

After reading the above, do you have any further understanding of the common modules of Ansible? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report