当前位置:网站首页>Ansible learning summary (7) -- ansible state management related knowledge summary

Ansible learning summary (7) -- ansible state management related knowledge summary

2022-06-23 00:42:00 Technology d life

Preface

Just like all server batch management tools (puppet Yes DSL,salt Yes state) equally ,ansible It also has its own state management component , be called playbook. All these similar concepts allow you to use a simpler language ( Instead of using scripts ) To describe what your service should look like , Then these tools will turn the server into what you want it to look like according to your description . With this level of abstraction , Service deployment and configuration become more cross platform , It also improves reusability . But please pay attention to ,playbook Not everything , because playbook The bottom layer is using modules to complete tasks , Because the modules are limited , So many times you still need to write shell Script (ansible Provides script modular ) To complete . Explain in advance to use ansible What you need to learn about state management :

  • YAML grammar ,playbook Very little grammar is used , This part of the learning cost is very low ;
  • playbook The basic instructions of , This is the foundation. ;
  • Usage of modules , This focus ;
  • jinja2 grammar , Whether in the playbook Still template We all support jinja2 grammar .

Concept

  • yaml, Data exchange format , similar json and xml, But more readable than them , Usually used as a configuration file for a program .ansible Of playbook Configuration and use yaml Format to express .
  • task, A unit task completed by a module , Such as modifying files or starting services .
  • play, A group of task Set ,ansible Will execute from top to bottom .
  • handler,task Can trigger certain events , And the task That is to say handler.
  • host, application play Host range of .
  • user, What users are running on these hosts playbook.
  • role, role , A group of playbook And the elements that match it (vars, files etc. ) Set

Example

---
- hosts: webservers
  vars:
    http_port: 80
    max_clients: 200
  remote_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:
    - name: restart apache
      service: name=httpd state=restarted

playbook Yes, it is yaml Grammatically written , But you only need to know the following simple rules :

  • Document to  ---  start
  • Representative list , Or you could write it as [a, b]
  • It stands for the dictionary , Or you could write it as {a: b}
  • If the characters conflict, enclose the corresponding string in double quotation marks

Instructions

host: Definition playbook Execution host range of , And command mode ansible The matching rules are the same .

remote_user: Definition playbook The executing user , Execution tasks can also be defined at the task level , Such as :

tasks:
    - name: test connection
      ping:
      remote_user: yourname
      sudo: yes

Be careful : It can also be used. sudo Instructions to describe all or part of a task in order to sudo How to execute .

vars: Defining variables .

vars_files: Define variable file .

tasks: Define task list , It is executed by the module .

name: Definition playbook perhaps task The name of .

notify: If the task execution result is changed, the trigger is defined in han.

include: What can be included include task,handler and playbook, Can be in include When passing variables . Examples are as follows :

tasks:
  - include: wordpress.yml
    vars:
        remote_user: timmy
        some_list_variable:
          - alpha
          - beta
          - gamma

roles: Define the role corresponding to the host , A role is a set of configurations that are grouped by directory ,ansible Automatically complete file search , Go to the corresponding directory main.yml File to execute . The specific directory structure is as follows :

  • defaults/ The default variables are saved in this directory
  • files/ file
  • templates/ Templates
  • tasks/ Mission
  • handlers/ processor
  • vars/ Variable
  • meta/ Information about the role itself , Such as through dependencies Directive specifies dependencies
  • library/ Private module

Be careful : You can also give role Passing variables . Here's the main point ,role Is to make ansible The reusability of state management is an important concept , Most of the time you just need to be in your own playbook Quote someone else's role that will do , Everybody wrote role Can share with each other , Cross reference . The government also provided ansible-galaxy This command is used to install community shared role, For details, please refer to  Galaxy Official website .

pre_task and post_task: stay role List of tasks to be performed before and after being applied .

Variable

Variable in Playbook It's a very complicated , The complicated reason is that you don't know where it came from and where it went , Let's also analyze it from these two aspects .

Where are from

inventory

stay group and host Variables can be defined in , Examples are as follows :

[atlanta]
host1 http_port=80 maxRequestsPerChild=808
host2 http_port=303 maxRequestsPerChild=909
[southeast:vars]
some_server=foo.southeast.example.com
halon_system_timeout=30
self_destruct_countdown=60
escape_pods=2

vars and vars_files

stay playbook These two instructions can be used to define some initial variables at the beginning of , This can be seen from the playbook Of demo

include

By means of playbook Of include Instructions can be other task When , You can pass variables to a file , Examples are as follows :

tasks:
  - include: wordpress.yml user=timmy

roles

When applying roles to a host, you can pass variables , Then use these variables within the role , Examples are as follows :

- hosts: webservers
  roles:
    - common
    - { role: foo_app_instance, dir: '/opt/a',  port: 5000 }

facts

By default, each execution playbook Get device information before , All this information can be applied as variables to playbook in , To view these variables, you can execute :

ansible cloud -m setup

register

Define the output of a task as a variable , And then for other tasks , Examples are as follows :

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

Built-in variables

ansible Built in some variables to facilitate the host to call their own variables . These variables include :* hostvars Variables that allow you to access another host , Of course, the premise is ansible The variables of this host have been collected :

  • group_namesv Is the current host group list
  • groups It's all inventory Of group list
  • inventory_hostname Is in inventory Host name defined in
  • play_hosts It is current. playbook List of hosts in the scope
  • inventory_dir and inventory_file Definition inventory Directory and files for

Command line

Running playbook You can also pass some variables for playbook Use , Examples are as follows :

ansible-playbook release.yml --extra-vars "hosts=vipers user=starbuck"

You can also get it from json Read variables from the file , Examples are as follows :

ansible-playbook main.yml -e "@vars.json"

Where

All variables can be in playbook perhaps jinja2 Template through  { { varname }}  Use in . in addition , When variables and jinja2 It can provide various flexible condition judgment and variable processing when the pipelines are combined . See the following two examples for details . If the first task fails, the second task will be executed , It can be written like this :

tasks:
  - shell: /usr/bin/foo
    register: result
    ignore_errors: True
  - debug: msg="it failed"
    when: result|failed

To redo a list , It can be written like this :

{
   { list | uniq }}

Priority of variables

  • -e The maximum... Specified on the command line
  • inventory File defined variables take the second place , Actually inventory The file is also divided into global ,group Sum of levels hosts Level variable definitions
  • fact Variables take second place
  • Character's default Variables have the lowest priority

Conditions

when

Can be used for task,role and include, When we satisfy this condition task To be executed . as for when The logical expression following the instruction is also a standard logical expression , Examples are as follows :

tasks:
  - shell: echo "only on Red Hat 6, derivatives, and later"
    when: ansible_os_family == "RedHat" and ansible_lsb.major_release|int >= 6
  - shell: echo "This certainly is epic!"
    when: epic is defined

loop

Standard ergodic

use with_items You can traverse a list , Note that only one layer will be traversed here . Examples are as follows :

- name: add several users
  user: name={
   { item }} state=present groups=wheel
  with_items:
     - testuser1
     - testuser2

Nested traversal

use with_nested You can traverse a list , Note that this will traverse multiple layers , Until the innermost layer . Examples are as follows :

- name: give users access to multiple databases
  mysql_user: name={
   { item[0] }} priv={
   { item[1] }}.*:ALL append_privs=yes password=foo
  with_nested:
    - [ 'alice', 'bob', 'eve' ]
    - [ 'clientdb', 'employeedb', 'providerdb' ]

Ergodic dictionary

use with_dict You can traverse a dictionary , use key and value To express . Examples are as follows :

Variable file

---
users:
  alice:
    name: Alice Appleworth
    telephone: 123-456-7890
  bob:
    name: Bob Bananarama
    telephone: 987-654-3210

playbook file

tasks:
  - name: Print phone records
    debug: msg="User {
   { item.key }} is {
   { item.value.name }} ({
   { item.value.telephone }})"
    with_dict: users

File wildcard loop

use with_fileglob You can get a list of local files . Examples are as follows :

# copy each file over that matches the given pattern
    - copy: src={
   { item }} dest=/etc/fooapp/ owner=root mode=600
      with_fileglob:
        - /playbooks/files/fooapp/*

Aligned list

use with_together You can achieve something similar python Inside zip Function functions . Examples are as follows :

Variable file

---
alpha: [ 'a', 'b', 'c', 'd' ]
numbers:  [ 1, 2, 3, 4 ]
playbook file 

tasks:
    - debug: msg="{
   { item.0 }} and {
   { item.1 }}"
      with_together:
        - alpha
        - numbers

Child element loop

with_subelements This one is rather difficult to understand .

Number sequence loop

Can pass with_sequence To generate a sequence of numbers , Its parameters include :

  • start Start number
  • end End number
  • stride step
  • count Number
  • format The output string

Examples are as follows :

---
- hosts: all
  tasks:
    # create groups
    - group: name=evens state=present
    - group: name=odds state=present
    # create some test users
    - user: name={
   { item }} state=present groups=evens
      with_sequence: start=0 end=32 format=testuser%02x
    # create a series of directories with even numbers for some reason
    - file: dest=/var/stuff/{
   { item }} state=directory
      with_sequence: start=4 end=16 stride=2
    # a simpler way to use the sequence plugin
    # create 4 groups
    - group: name=group{
   { item }} state=present
      with_sequence: count=4

Random cycle

adopt with_random_choice Take a random element from a sequence . Examples are as follows :

- debug: msg={
   { item }}
  with_random_choice:
     - "go through the door"
     - "drink from the goblet"
     - "press the red button"
     - "do nothing"

until loop

This loop is completed by three instructions :

  • * until Is a conditional expression , If the conditions are met, the cycle ends
  • * retry Is the number of retries
  • * delay It's delay time

Examples are as follows :

- action: shell /usr/bin/foo
  register: result
  until: result.stdout.find("all systems go") != -1
  retries: 5
  delay: 10

Loop until the file is found

And with_items similar , It's just with_first_found Finding the first file in the list will terminate the loop . Examples are as follows :

- name: INTERFACES | Create Ansible header for /etc/network/interfaces
  template: src={
   { item }} dest=/etc/foo.conf
  with_first_found:
    - "{
   {ansible_virtualization_type}}_foo.conf"
    - "default_foo.conf"

Circle one task Output

with_lines Command followed by a command ,ansible Will traverse the output of the command . Examples are as follows :

- name: Example of looping over a command result
  shell: /usr/bin/frobnicate {
   { item }}
  with_lines: /usr/bin/frobnications_per_host --param {
   { inventory_hostname }}

Loop list with index

And with_items similar ,with_indexed_items Will put the list index and corresponding elements into a list . Examples are as follows :

- name: indexed loop demo
  debug: msg="at array position {
   { item.0 }} there is a value {
   { item.1 }}"
  with_indexed_items: some_list

Flatten the loop list

with_flattened I will flatten a list first , And then execute with_items. Examples are as follows :

- name: flattened loop demo
  yum: name={
   { item }} state=installed
  with_flattened:
  - ['nc','git', ['nmap', 'vim']]

coordination register Loop list

register After registering a variable , Can cooperate with with_items To traverse the variable results . Examples are as follows :

- shell: echo "{
   { item }}"
  with_items:
    - one
    - two
  register: echo
- name: Fail if return code is not 0
  fail:
    msg: "The command ({
   { item.cmd }}) did not have a 0 return code"
  when: item.rc != 0
  with_items: echo.results
原网站

版权声明
本文为[Technology d life]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206222134340964.html