ansible others

1. Modify the file and copy it to the host

1.1 Common file modules
blockinfile Add a text block to an existing file
copy Copy files to managed host
fetch Copy files from managed host to control node
file Set file attributes
lineinfile Make sure a specific line is in a file
stat Retrieve file status information
synchronize A packager for the rsync command
file The module processes the file, and if it does not exist, it is created
cat file.yml
---
- name: Test
  hosts: webservers
  tasks:
    - name: Touch a file
      file:
        path: /root/file
        owner: student
        group: student
        mode: 0640
        state: touch

Modify file attributes

cat file.yml
---
- name: Test
  hosts: webservers
  tasks:
    - name: Touch a file
      file:
        path: /root/file
        owner: student
        group: student
        mode: 0640
        state: touch
    - name: Set SElinux
      file:
        path: /root/file
        setype: samba_share_t

Permanent change

cat file.yml
- name: Test
  hosts: webservers
  tasks:
    - name: Touch a file
      file:
        path: /root/file
        owner: student
        group: student
        mode: 0640
        state: touch
    - name: Set SElinux
      file:
        path: /root/file
        setype: samba_share_t
    - name: Set SElinux
      sefcontext:
        target: /root/file
        setype: samba_share_t
        state: present

Copy and edit files
on managed hosts Delete files from managed hosts

- name: Delete file
  file:
    dest: /root/file
    state: absent #absent 即删除

Check the file status on the managed host
Check the MD5 checksum of the file

- name: Verify the status
  stat:
    path: /root/file
    checksum_algorithm: md5
  register: result
-debug:
    msg: "The checksum is {{ result.stat.checksum }}"

Run (add the above code to file.yml at the end)

TASK [debug] *******************************************************************
ok: [servera.lab.example.com] => {
"msg": "The checksum is d41d8cd98f00b204e9800998ecf8427e"
}

Synchronize files between control node and managed host

- name: synchronize file
  synchronize:
    src: file
    dest: /root/file

Second, use jinja2 template to deploy custom files

Build a template to manage files more conveniently
{% EXPR%} #Expression or logic
{{EXPR}} #Finally output the expression or result to the user
{# COMMENT #} #Comment

2.1 Build jinja2 template

The jinja2 template is composed of multiple elements: data, variables, expressions
. The variables used in the template can be specified in the vars of the playbook
. All values in the template use variables, which will be replaced by the corresponding values ​​of the managed host in the future. For
example: / etc / ssh / sshd_config file
Port 22 ==> Port {{ssh_port}}
PermitRootLogin yes ==> {{root_allowed}}

2.2 Deploying jinja2 template
tasks:
  - name: template
    template:
      src: /root/j2-template.j2
      dest: /root/dest-config-file.txt

Use loop
jinja2 Use the for statement to provide loop:
# 1.
{% For user in users%}
{{user}} #user variable will traverse users
{% endfor%}
# 2.
{% For myhost in groups ['myhosts'] %} #List all hosts in the myhosts group
{{myhosts}}
{% endfor%} #Use
conditional sentences
{% if finished%} #Only if this condition is true, will the value of the result variable be put into the file
{{result }}
{% endif%}
Jinja2 loops and conditions can only be used in templates, not in playbooks

2.3 Variable filters

{{output | to_json}} #Output in json format
{{output | to_yaml}}
{{output | from_json}} #Parse json format string
{{output | from_yaml}}

3. Management of large projects

3.1 Use wildcards to match multiple hosts
- hosts: '*'
- hosts: '*.example.com'
- hosts: '172.25.254.*'
3.2 Matching hosts or host groups by list
- hosts: www1.example.com,www2.example.com,172.25.254.250
- hosts: webservers,westos

You can also use wildcards and lists together

- hosts: webservers,&westos #即属于webserver 组,也属于westos 组
- hosts: westos,!servera.lab.example.com#匹配westos 组中所有主机,但是servera.lab.example.com 除外
- all,!servera.lab.example.com #所有主机除了servera.lab.example.com

4. Management Dynamic List

4.1 Writing a dynamic inventory program

Convert list in INI format to JSON format

ansible-inventory -i inventory --list

Using forks to configure parallel
ansible in ansible The maximum number of simultaneous connections is controlled by the forks parameter in the ansible configuration file

grep forks /etc/ansible/ansible.cfg
#forks = 5 #默认是5
ansible-config dump | grep -i forks
DEFAULT_FORKS(default) = 5

You can use the -f or --forks parameter on the command line to specify the number of parallels

V. Management of rolling updates

If the update occurs on the load balancing server, it will restart after the update is completed, which may cause all back-end web servers to stop serving. You can use the serial keyword to run in batches

---
- name: Rolling update
  hosts: webservers
  serial: 2
  tasks:
    - name: Install apache
      yum:
        name: httpd
        state: latest
        notify: restart apache
  handlers:
    - name: restart apache
      service:
        name: httpd
        state: restarted

The serial parameter also has an advantage: if there is a problem during the update, then the problem in the first two is that the playbook will stop running, and the subsequent servers will not be executed, so the high availability of the service is also guaranteed

Six, include and import files

Large playbooks are more complicated to manage and can be managed in a modular way.
Two methods: include, import
Import playbook
example 1:

- name: configure webserver
   import_playbook: web.yml

Example 2:

- name: Play 1
  hosts: localhost
  tasks:
    - debug:
        msg: Play1
- name: Import Playbook
   import_playbook: play2.yml

Import and include a playbook of
tasks

cat tasks.yml
- name: Install apache
  yum:
    name: httpd
    state: latest
- name: Start Apache
  service:
    name: httpd
    state: started

Import task

---
- name: Install web
  hosts: webservers
  tasks:
    - import_tasks: tasks.yml

When importing, conditional statements such as when are applied to each task of the import; the loop cannot be applied to the imported
task.

---
- name: Install web
  hosts: webservers
  tasks:
    - include_tasks: tasks.yml

External play and tasks defined variables, improve reusability
a package installation tasks and configuration of the boot

---
- name: Install the {{ packages }}
  yum:
    name: "{{ packages }}"
    state: latest
- name: Start the {{ service }}
  service:
    name: "{{ service }}"
    enabled: true
    state: started

Can be used for import

tasks:
  - name: Import task
    import_tasks: task.yml
    vars:
      package: httpd
      service: httpd

Comprehensive experiment of managing large projects

cat ansible.cfg
[defaults]
inventory = ./inventory
cat inventory
servera.lab.example.com
serverb.lab.example.com
serverc.lab.example.com
ansible server*.lab.example.com --list-hosts

Same module: installation package

cat install_and_enabled.yml
---
- name: Install {{ packages }}
  yum:
    name: "{{ packages }}"
    state: latest
- name: Enable and start {{ service }}
  service:
    name: "{{ service }}"
    enabled: true
    state: started

Apache configuration

cat web_tasks.yml
---
- name: Install and start httpd
  import_tasks: install_and_enabled.yml
  vars:
    packages: httpd
    service: httpd
- name: Configure apache
  copy:
    src: files/example.conf
    dest: /etc/httpd/conf.d/example.conf
    owner: root
    group: root
    mode: 0644
  notify:
    - restart httpd

firewall configuration

cat firewall_tasks.yml
---
- name: Install and start firewalld
  import_tasks: install_and_enabled.yml
  vars:
    packages: firewalld
    service: firewalld
- name: Firewall permit apache
  firewalld:
    service: http
    immediate: true
    permanent: true
    state: enabled

主playbook

cat playbook.yml
---
- name: Install and Configure web service
  hosts: server*.lab.example.com
  serial: 2
  tasks:
    - name: Import web_tasks.yml
      import_tasks: tasks/web_tasks.yml
    - name: Import the firewall_tasks.yml
      import_tasks: tasks/firewall_tasks.yml
  handlers:
    - name: restart httpd
      service:
        name: httpd
        state: restarted
Published 35 original articles · praised 0 · visits 928

Guess you like

Origin blog.csdn.net/weixin_43834060/article/details/105615327