任务中心之Ansible进阶篇

327次阅读  |  发布于3年以前
  • 在 [任务中心之Ansible基础篇] 已经介绍了Ansible的技术架构以及功能和基本配置、使用方法,如果看完的同学,想必对Ansible的基础已经入门了,现在可以阅读本篇文章由浅入深的来学习Ansible的高级功能 ansible-playbook
  • 如果有想基于AnsibleAPI二次开发任务中心的同学,ansible-playbook 是非常关键的功能,请大家一定要耐心的看完本文。
  • 敬请期待下一篇如何基于AnsibleAPI二次开发 任务中心之AnsibleAPI篇

ansible-playbook

playbook & yml 说明

playbook 核心元素

ansible-playbook 命令

ansible-playbook setup

# ansible k3s-cluster -m setup
ubuntu20-bj03 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "10.0.16.4"
        ],
        "ansible_all_ipv6_addresses": [
            "fe80::5054:ff:fed6:42a8"
        ],
        "ansible_apparmor": {
            "status": "enabled"
        },
        "ansible_architecture": "x86_64",
        "ansible_bios_date": "04/01/2014",
        "ansible_bios_vendor": "SeaBIOS",
        "ansible_bios_version": "seabios-1.9.1-qemu-project.org",
        "ansible_board_asset_tag": "NA",
        "ansible_board_name": "NA",
        "ansible_board_serial": "NA",
        "ansible_board_vendor": "NA",
        "ansible_board_version": "NA",
        "ansible_chassis_asset_tag": "NA",
        "ansible_chassis_serial": "NA",
        "ansible_chassis_vendor": "Smdbmds",
        "ansible_chassis_version": "3.0",

        # 多余的冗余信息就不放了,自己可以执行验证下。
        # setup获得变量信息,都可以用于继承给playbook调用。
}

denis_test.fact

[general]
package = vsftpd
service = vsftpd
state = starte

setup_facts.yaml

---
- name: Install Remote Facts
  hosts: k3s-cluster
  vars: 
    remote_dir: /etc/ansible/facts.d
    facts_file: denis_test.fact
  tasks:
    - name: Create Directory
      file:
        state: directory
        recurse: yes
        path: "{{ remote_dir }}"
    - name: Install the new facts
      copy:
        src: "{{ facts_file }}"
        dest: "{{ remote_dir }}"

执行测试

# ansible-playbook setup_facts.yaml
# ansible test -m setup        
ubuntu20-bj03 | SUCCESS => {
    "ansible_facts": {

        # -----分隔符-----

        "ansible_local": {
            "custom": {
                "general": {
                    "package": "vsftpd",
                    "service": "vsftpd",
                    "state": "started"
                }
            }
        },

        # -----分隔符-----

}

调用测试

deniss_test.yaml


- name: Install Apache and starts the service
  hosts: k3s-cluster
  tasks:
    - name: Install Package
      yum: 
        name: "{{ ansible_facts.ansible_local.custom.general.package }}"
        state: latest
    - name: Start Service
      service: 
        name: "{{ ansible_facts.ansible_local.custom.general.service }}"
        state: "{{ ansible_facts.ansible_local.custom.general.state }}"

ansible-playbook set_fact

deniss_fact_demo.yaml

- name: set_fact demo
  hosts: k3s-cluster
  tasks:
    - name: Calculate InnoDB buffer pool size
      set_fact: innodb_buffer_pool_size_mb="{{ ansible_memtotal_mb / 2 |int }}"      
    - debug: var=innodb_buffer_pool_size_mb

执行测试

# ansible-playbook deniss_fact_demo.yaml 
PLAY [set_fact demo] *****************************************************************************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************************************************
ok: [ubuntu20-bj03]

TASK [Calculate InnoDB buffer pool size] ************************************************************************************************************************************
ok: [ubuntu20-bj03]

TASK [debug] ****************************************************************************************************************************************************************
ok: [ubuntu20-bj03] => {
    "innodb_buffer_pool_size_mb": "2911.2"
}

PLAY RECAP ******************************************************************************************************************************************************************
ubuntu20-bj03                : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
- hosts: k3s-cluster
  name: test demo 
  gather_facts: False
  tasks:
    - name: wait for ssh to be running
      local_action: wait_for port=22 host="{{ inventory_hostname }}" search_regex=OpenSSH
    - name: gather facts
      setup:
[defaults]
gathering = smart
# 缓存时间
fact_caching_timeout = 86400    
fact_caching = {jsonfile/redis/memcached}
# 指定ansible包含fact的json文件位置,如果目录不存在,会自动创建
# local
fact_caching_connection = /tmp/ansible_fact_cache
# redis
fact_caching_connection = 127.0.0.1:6379:admin
# memcached
fact_caching_connection = ['127.0.0.1:11211']
# playbook 配置
- hosts: k3s-cluster
  gather_facts: no
# ansible.cfg 配置  
[defaults]
gathering = explicit

ansible-playbook 变量

[appserver]
# 定义变量 node_id
10.0.8.2 node_id=17

# 对主机组 定义统一变量 domain_name
[k3s-cluster:vars]
domain_name=deniss.wang
---
- hosts: k3s-cluster
  become: yes
  become_user: root

  tasks:
    - name: set hostname
      hostname: name={{ node_id }}.{{ domain_name }}
---
- hosts: k3s-cluster
  remote_user: root

  # 定义变量
  vars:
    - pkg_name: httpd
    - env_name: prod

  tasks:
    - name: {{ env_name }} install {{ pkg_name }}
      yum: name={{ pkg_name }}
---
pkg_name: httpd
file_name: deniss.wang
---
- hosts: k3s-cluster
  remote_user: root

  # 配置模板文件
  vars_files:
    # 指定文件的路径
    - vars.yaml

  tasks:
    - name: install {{ pkg_name }}
      yum: name={{ pkg_name }}
    - name: create {{ file_name }} file
      file: name=/tmp/{{ file_name }}.txt state=touch
# ansible-playbook install.yaml
PLAY [k3s-cluster] *******************************************************************************************************

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

TASK [install httpd] *********************************************************************************************
changed: [10.0.8.2]

TASK [create deniss.wang file] **************************************************************************************
changed: [10.0.8.2]

PLAY RECAP *******************************************************************************************************
10.0.8.2                  : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

ansible-playbook template

# tree nginx/
|-- nginx.yaml
|-- templates   
    |-- nginx.conf.j2

“算术运算

user nginx;
# 这里使用 环境变量 vcpus * 2,会根据操作系统CPU自动生成。
worker_processes {{ ansible_processor_vcpus * 2 }};
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 10240;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
}
---
- hosts: k3s-cluster
  become: yes
  become_user: root

  tasks:
    - name: install nginx
      yum: name=nginx
    - name: nginx template conf
      # 如果yaml与templates在同一目录, src直接写.j2文件
      template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
      notify:
        - restart nginx
    - name: start nginx
      service: name=nginx state=started enabled=yes

  handlers:
    - name: restart nginx
      service: name=nginx state=restarted

“when 条件语句

# tree nginx
|-- nginx.yaml
|-- templates   
    |-- nginx.conf.centos7.j2   
    |-- nginx.conf.centos8.j2
---
- hosts: k3s-cluster
  become: yes
  become_user: root

  tasks:
    - name: install nginx
      yum: name=nginx
    - name: template centos 7 conf
      # 如果 yaml 与 templates 在同一目录, src 直接写.j2 文件。
      template: src=nginx.conf.centos7.j2 dest=/etc/nginx/nginx.conf
      # 使用 when 语句进行判断 如果变量为 "7" 执行以下操作
      when: ansible_distribution_major_version == "7"
      notify:
        - restart nginx
    - name: template centos 8 conf
      # 同上
      template: src=nginx.conf.centos8.j2 dest=/etc/nginx/nginx.conf
      # 使用 when 语句进行判断 如果变量为 'Ubuntu' 且版本为20 执行以下操作
   when: (ansible_distribution == "Ubuntu" and ansible_distribution_major_version == "20"
      notify:
        - restart nginx
    - name: start nginx
      service: name=nginx state=started enabled=yes

  handlers:
    - name: restart nginx
      service: name=nginx state=restarted
# ansible-playbook nginx.yml

PLAY [k3s-cluster] *******************************************************************************************

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

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

TASK [template centos 7 conf] ************************************************************************
changed: [10.0.8.2]

TASK [template centos 8 conf] ************************************************************************
skipping: [10.0.8.2]

TASK [start nginx] ***********************************************************************************
ok: [10.0.8.2]

RUNNING HANDLER [restart nginx] **********************************************************************
changed: [10.0.3.13]

PLAY RECAP *******************************************************************************************
10.0.8.2      : ok=5    changed=2    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0

“迭代变量 with_tiems

---
- hosts: k3s-cluster
  become: yes
  become_user: root

  tasks:
    - name: create multi files
      # {{ item }} 为内置特殊变量, 代表 with_items 列表中的内容
      file: name=/tmp/{{ item }} state=touch
      with_items:
        - file_one
        - file_two
        - file_three
        - file_four
    - name: install multi software
      yum: name={{ item }}
      with_items:
        - vsftpd
        - net-tools
        - iftop

“代嵌套子变量 (字典)

---
- hosts: k3s-cluster
  become: yes
  become_user: root

  tasks:
    - name: create some files
      # {{ item }} 为特殊变量, 代表 with_itmes 列表中的内容
      file: name=/tmp/{{ item }} state=touch
      with_items:
        - file_one
        - file_two
        - file_three
        - file_four

    - name: create multi group
      group: name={{ item }}
      with_items:
        - jinja2_file1
        - jinja2_file2
        - jinja2_file3
        - jinja2_file4

    - name: create multi user
      # 使用 item.key值 进行引用
      user: name={{ item.name }} group={{ item.group }}
      # 使用 字典 定义 嵌套的子 变量
      with_items:
        - { name: 'file_one', group: 'jinja2_file1' }
        - { name: 'file_two', group: 'jinja2_file2' }
        - { name: 'file_three', group: 'jinja2_file3' }
        - { name: 'file_four', group: 'jinja2_file4' }

    - name: permission multi files
      file: name=/tmp/{{ item.name }} owner={{ item.name }} group={{ item.group }}
      with_items:
        - { file: 'file_one', name: 'file_one', group: 'jinja2_file1' }
        - { file: 'file_two', name: 'file_two', group: 'jinja2_file2' }
        - { file: 'file_three', name: 'file_three', group: 'jinja2_file3' }
        - { file: 'file_four', name: 'file_four', group: 'jinja2_file4' }

# ansible-playbook file.yml

PLAY [k3s-cluster] *****************************************************************************************

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

TASK [create multi files] ***************************************************************************
changed: [10.0.8.2] => (item=file_one)
changed: [10.0.8.2] => (item=file_two)
changed: [10.0.8.2] => (item=file_three)
changed: [10.0.8.2] => (item=file_four)

TASK [create multi group] ***************************************************************************
changed: [10.0.8.2] => (item=jinja2_file1)
changed: [10.0.8.2] => (item=jinja2_file2)
changed: [10.0.8.2] => (item=jinja2_file3)
changed: [10.0.8.2] => (item=jinja2_file4)

TASK [create multi user] ****************************************************************************
changed: [10.0.8.2] => (item={u'group': u'jinja2_file1', u'name': u'file_one'})
changed: [10.0.8.2] => (item={u'group': u'jinja2_file2', u'name': u'file_two'})
changed: [10.0.8.2] => (item={u'group': u'jinja2_file3', u'name': u'file_three'})
changed: [10.0.8.2] => (item={u'group': u'jinja2_file4', u'name': u'file_four'})

TASK [permission multi files] ***********************************************************************
changed: [10.0.8.2] => (item={u'group': u'jinja2_file1', u'name': u'file_one', u'file': u'file1'})
changed: [10.0.8.2] => (item={u'group': u'jinja2_file2', u'name': u'file_two', u'file': u'file2'})
changed: [10.0.8.2] => (item={u'group': u'jinja2_file3', u'name': u'file_three', u'file': u'file3'})
changed: [10.0.8.2] => (item={u'group': u'jinja2_file4', u'name': u'file_four', u'file': u'file4'})

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

“流程控制、循环 for 与 if

---
- hosts: k3s-cluster
  become: yes
  become_user: root

  vars:
    # 列表
    listen_port:
      - 80
      - 81
      - 82
    # 字典
    service:
      - name: web1
        domain: deniss.wang
        port: 9090
        user: nginx
        path: /var/www/html 
      - name: web2
        domain: deniss.wang
        port: 9091
        user: nginx
        path: /var/www/html
      - name: web3
        domain: deniss.wang
        port: 9092
        user: nginx
        path: /var/www/html

  tasks:
    - name: copy template conf
      template: src=for.conf.j2 dest=/tmp/for.conf
{% for port in listen_port %}

server {
   listen {{ port }}
}

{% endfor %}
# cat /root/for.conf

server {
   listen 80
}


server {
   listen 81
}


server {
   listen 82
}
---
- hosts: k3s-cluster
  become: yes
  become_user: root

  vars:
    # 字典的形式
    service:
      - name: web1
        domain: deniss.wang
        port: 9090
        user: nginx
        path: /var/www/html
      - name: web2
        domain: deniss.wang
        port: 9091
        user: nginx
        path: /var/www/html
      - name: web3
        domain: deniss.wang
        port: 9092
        user: nginx
        path: /var/www/html

  tasks:
    - name: copy template conf
      template: src=nginx.conf.j2 dest=/tmp/nginx.conf
{% for s in service %}
user {{ s.user }};
worker_processes {{ ansible_processor_vcpus * 2 }};
pid /run/nginx.pid;
    server {
        listen       {{ s.port }} default_server;
        listen       [::]:{{ s.port }} default_server;
        server_name  {{ s.name }}.{{ s.domain }};
        root         {{ s.path }};
    }

{% endfor %}
---
- hosts: k3s-cluster
  become: yes
  become_user: root

  vars:
    # 字典
    service:
      - name: web1
        domain: deniss.wang
        port: 90
        path: /var/www/html

      - name: web2
        domain: deniss.wang
        port: 91
        path: /var/www/html

      - name: web3
        domain: deniss.wang
        port: 92
        user: nginx
        path: /var/www/html

  tasks:
    - name: copy template conf
      template: src=nginx2.conf.j2 dest=/tmp/nginx2.conf
{% for s in service %}

{% if s.user is defined %}
user {{ s.user }};
{% else %}
user root;
{% endif %}
worker_processes {{ ansible_processor_vcpus * 2 }};
pid /run/nginx.pid;
    server {
        listen       {{ s.port }} default_server;
        server_name  {{ s.name }}.{{ s.domain }};
        root         {{ s.path }};
    }

{% endfor %}
# cat  nginx2.conf
user root;
worker_processes 4;
pid /run/nginx.pid;
    server {
        listen       90 default_server;
        server_name  web1.deniss.wang;
        root         /var/www/html;
    }


user root;
worker_processes 4;
pid /run/nginx.pid;
    server {
        listen       91 default_server;
        server_name  web2.deniss.wang;
        root         /var/www/html;
    }


user nginx;
worker_processes 4;
pid /run/nginx.pid;
    server {
        listen       92 default_server;
        server_name  web3.deniss.wang;
        root         /var/www/html;
    }

tasks 示范

Demo

---
# 指定主机组
- hosts: k3s-cluster
  # 开启提权,指定用户
  become: yes
  become_user: root

  # 任务
  tasks:
    # 任务的名称
    - name: ping server
      ping:
    - name: echo hostname
      # shell 为模块名, 后面等同于 -a '' 参数
      shell: hostname
    - name: touch file
      file: name=/tmp/file.txt state=touch
    - name: echo file
      shell: ls -l /tmp/file.txt
    - name: write file
      shell: echo "hello world" > /tmp/file.txt
    - name: copy module write file
      copy: content="hello deniss\n" dest=/tmp/deniss.txt
    - name: display file content
      shell: cat /tmp/file.txt
      register: display_content1
    - name: show
      debug: var=display_content1.stdout verbosity=0
    - name: display copy module file content
      shell: cat /tmp/deniss.txt
      register: display_content2
    - name: show
      debug: var=display_content2.stdout verbosity=0
# ansible-playbook hello.yaml
PLAY [k3s-cluster] *******************************************************************************************************************************************************************

TASK [Gathering Facts] ***************************************************************************************************************************************************************
ok: [ubuntu20-bj03]

TASK [ping server] *******************************************************************************************************************************************************************
ok: [ubuntu20-bj03]

TASK [echo hostname] *****************************************************************************************************************************************************************
changed: [ubuntu20-bj03]

TASK [touch file] ********************************************************************************************************************************************************************
changed: [ubuntu20-bj03]

TASK [echo file] *********************************************************************************************************************************************************************
changed: [ubuntu20-bj03]

TASK [write file] ********************************************************************************************************************************************************************
changed: [ubuntu20-bj03]

TASK [copy module write file] ********************************************************************************************************************************************************
ok: [ubuntu20-bj03]

TASK [display file content] **********************************************************************************************************************************************************
changed: [ubuntu20-bj03]

TASK [show] **************************************************************************************************************************************************************************
ok: [ubuntu20-bj03] => {
    "display_content1.stdout": "hello world"
}

TASK [display copy module file content] **********************************************************************************************************************************************
changed: [ubuntu20-bj03]

TASK [show] **************************************************************************************************************************************************************************
ok: [ubuntu20-bj03] => {
    "display_content2.stdout": "hello deniss"
}

PLAY RECAP ***************************************************************************************************************************************************************************
ubuntu20-bj03              : ok=11   changed=6    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

handles 示范

---
# 指定主机组
- hosts: k3s-cluster
  # 开启提权,指定用户
  become: yes
  become_user: root

  tasks:
    - name: copy httpd.conf
      copy: src=~/ansible/httpd.conf dest=/etc/httpd/conf/httpd.conf backup=yes
      # 关联多个触发器的写法
      notify:
        - restart httpd
        - check status httpd
        - check network port

Demo

Centos

---
# 指定主机组
- hosts: k3s-cluster
  # 开启提权,指定用户
  become: yes
  become_user: root

  tasks:
    - name: install httpd
      yum: name=httpd
    - name: copy httpd.conf
      copy: src=/opt/ansible/conf/httpd.conf dest=/etc/httpd/conf/httpd.conf backup=yes
      # 此任务 如果有变动会触发如下定义名称的触发器
      notify: restart httpd
    - name: start httpd
      service: name=httpd state=started enabled=yes

  # 触发器, 需要配置 notify 触发
  handlers:
    - name: restart httpd
      service: name=httpd state=restarted

Ubuntu

---
# 指定主机组
- hosts: k3s-cluster
  # 开启提权,指定用户
  become: yes
  become_user: root

  tasks:
    - name: Update apt-get repo and cache
      apt: update_cache=yes force_apt_get=yes cache_valid_time=3600
    - name: Install Vsftpd
      apt:
        name: vsftpd
    - name: copy vsftpd.conf
      copy: src=/opt/ansible/conf/vsftpd.conf dest=/etc/vsftpd.conf backup=yes
      notify: restart vsftpd
    - name: start vsftpd
      service: name=vsftpd state=started enabled=yes
  # 配置 notify 触发,修改配置文件的时候生效。
  handlers:
    - name: restart vsftpd
      service: name=vsftpd state=restarted
# ansible-playbook install_vsftpd.yaml
PLAY [k3s-cluster] *******************************************************************************************************************************************************************

TASK [Gathering Facts] ***************************************************************************************************************************************************************
ok: [ubuntu20-bj03]

TASK [Update apt-get repo and cache] *************************************************************************************************************************************************
ok: [ubuntu20-bj03]

TASK [Install Vsftpd] ****************************************************************************************************************************************************************
ok: [ubuntu20-bj03]

TASK [copy vsftpd.conf] **************************************************************************************************************************************************************
ok: [ubuntu20-bj03]

TASK [start vsftpd] ******************************************************************************************************************************************************************
ok: [ubuntu20-bj03]

PLAY RECAP ***************************************************************************************************************************************************************************
ubuntu20-bj03              : ok=5    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
# ansible-playbook install_pkg.yaml
PLAY [k3s-cluster] *******************************************************************************************************************************************************************

TASK [Gathering Facts] ***************************************************************************************************************************************************************
ok: [ubuntu20-bj03]

TASK [Update apt-get repo and cache] *************************************************************************************************************************************************
ok: [ubuntu20-bj03]

TASK [Install Vsftpd] ****************************************************************************************************************************************************************
ok: [ubuntu20-bj03]

TASK [copy vsftpd.conf] **************************************************************************************************************************************************************
changed: [ubuntu20-bj03]

TASK [start vsftpd] ******************************************************************************************************************************************************************
ok: [ubuntu20-bj03]

RUNNING HANDLER [restart vsftpd] *****************************************************************************************************************************************************
changed: [ubuntu20-bj03]

PLAY RECAP ***************************************************************************************************************************************************************************
ubuntu20-bj03              : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Tags示范

---
# 指定主机组
- hosts: k3s-cluster
  # 开启提权,指定用户
  become: yes
  become_user: root

  tasks:
    - name: Update apt-get repo and cache
      apt: update_cache=yes force_apt_get=yes cache_valid_time=3600
    - name: Install Vsftpd
      apt:
        name: vsftpd
    - name: copy vsftpd.conf
      copy: src=conf/vsftpd.conf dest=/etc/vsftpd.conf backup=yes
      notify: restart vsftpd
      # 定义标签
      tags: cpconf      
    - name: start vsftpd
      service: name=vsftpd state=started enabled=yes
      # 定义标签
      tags: upvsftpd      
  # 配置 notify 触发,修改配置文件的时候生效。
  handlers:
    - name: restart vsftpd
      service: name=vsftpd state=restarted      
# ansible-playbook -t upvsftpd  install_vsftpd.yaml
PLAY [k3s-cluster] *******************************************************************************************************************************************************************

TASK [Gathering Facts] ***************************************************************************************************************************************************************
ok: [ubuntu20-bj03]

TASK [start vsftpd] ******************************************************************************************************************************************************************
ok: [ubuntu20-bj03]

PLAY RECAP ***************************************************************************************************************************************************************************
ubuntu20-bj03              : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

# ansible-playbook -t cpconf  install_vsftpd.yaml
PLAY [k3s-cluster] *******************************************************************************************************************************************************************

TASK [Gathering Facts] ***************************************************************************************************************************************************************
ok: [ubuntu20-bj03]

TASK [copy vsftpd.conf] **************************************************************************************************************************************************************
changed: [ubuntu20-bj03]

RUNNING HANDLER [restart vsftpd] *****************************************************************************************************************************************************
changed: [ubuntu20-bj03]

PLAY RECAP ***************************************************************************************************************************************************************************
ubuntu20-bj03              : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

ansible-vault

ansible-console

# ansible-consoleWelcome to the ansible console.Type help or ? to list commands.deniss.wang@all (10)[f:5]$

ansible Roles

# tree .

|-- nginx
    |-- defaults
    |-- files
    |-- handlers
    |-- meta
    |-- tasks
    |-- templates
    |-- vars
# tree  roles/
roles/
|-- nginx
    |-- defaults
    |-- files
    |-- handlers
    |-- meta
    |-- tasks
    |   |-- group.yaml
    |   |-- main.yaml
    |   |-- restart.yaml
    |   |-- start.yaml
    |   |-- template.yaml
    |   |-- user.yaml
    |   |-- yum.yaml
    |-- templates
    |   |-- nginx.conf.j2
    |-- vars
---
- hosts: k3s-cluster
  become: yes
  become_user: root

  # 选择 调用的 roles 属性
  roles:
      # 调用定义好的role,存放在roles目录中。
    - role: nginx
- include: group.yml
- include: user.yml
- include: yum.yml
- include: template.yml
- include: start.yml
- name: create group
  group: name=nginx gid=80
PLAY [k3s-cluster] ****************************************************************************************

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

TASK [nginx : create group] ***********************************************************************
changed: [10.0.8.2]

TASK [nginx : create user] ************************************************************************
changed: [10.0.8.2]

TASK [nginx : install package] ********************************************************************
changed: [10.0.8.2]

TASK [nginx : copy conf] **************************************************************************
changed: [10.0.8.2]

TASK [nginx : start service] **********************************************************************
changed: [10.0.8.2]

PLAY RECAP ****************************************************************************************
10.0.8.2   : ok=6    changed=5    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

“roles tags 标签

- hosts: k3s-cluster
  become: yes
  become_user: root


  # 选择 roles 属性
  roles:
    # 配置相应的 tags 用 { } 引用
    - { role: nginx, tags: ['web', 'nginx'] }
    - { role: mysql, tags: ['db', 'mysql'] }
    - { role: redis, tags: ['db', 'redis'] }
    - { role: golang, tags: ['web', 'golang'] }
    - { role: vue, tags: ['web', 'vue'] }   
    - { role: app_demo, tags: "app_demo" }
# ansible-playbook -t web playbook.yml

“roles when 语句

---
- hosts: all
  become: yes
  become_user: root

  # 选择 roles 属性
  roles:
    # 配置相应的 tags 用 { } 引用
    - { role: nginx, tags: ['web', 'nginx'] }
    - { role: mysql, tags: ['db', 'mysql'] }
    - { role: redis, tags: ['db', 'redis'] }
    # 只针对操作系统为 Centos7 的执行
    - { role: golang, tags: ['web', 'golang'], when: ansible_distribution_major_version == "7" }
    # 只针对操作系统为 Ubuntu20 的执行
    - { role: vue, tags: ['web', 'vue'], when: (ansible_distribution == "Ubuntu" and ansible_distribution_major_version == "20")}
    - { role: app, tags: "app" }

extra-vars

# 以变量方式传参
ansible-playbook deploy.yaml --extra-vars "hosts=k3s-cluster user=ubuntu" 
# 以json格式传参
ansible-playbook deploy.yaml --extra-vars "{'app_name':'nginx', 'pkg_name':'vsftpd'}"
# 以json文件方式传参
ansible-playbook deploy.yml --extra-vars "@test_vars.json"

附上2个Demo

Ubuntu 安装软件,传入参数即可安装软件。

---
# 定义集群,并设置提权root,
- hosts: all
  become: yes
  become_user: root

  vars:
    # 传入参数
    - DEPLOY_USER: ubuntu
    - APP_NAME: '{{ app_name }}'

  tasks:
    - name: 更新 apt-get 仓库以及缓存
      apt: update_cache=yes force_apt_get=yes cache_valid_time=3600
    - name: 安装 {{ APP_NAME }} 程序
      apt:
        name: "{{ APP_NAME }}"
    # - name: "复制 {{ APP_NAME }} 配置文件"
    #   copy: src=./conf/vsftpd.conf dest=/etc/{{ APP_NAME }}.conf backup=yes
    #   notify: restart {{ APP_NAME }} # 此处必须与handlers一致
    #   # 定义标签
    #   tags: copyconf
    - name: "启动 {{ APP_NAME }} 服务"
      service: name={{ APP_NAME }} state=started enabled=yes
      # 定义标签
      tags: startvsftpd

  # 配置 notify 触发,修改配置文件的时候生效。
  handlers:
    - name: restart {{ APP_NAME }}
      service: name={{ APP_NAME }} state=restarted

发布流程,Demo中的具体实现逻辑,需要根据自己的环境来定义,此处仅做参考,如果你有什么好的建议和意见,可以扫描下面的二维码,加我微信,一起交流。

---
- hosts: all
  gather_facts: no

  vars:
    # OSS参数
    - OSS_URL: 'https://repo.opendevops.cn'
    - OSS_PATH: 'codo/codo-api/cclib/production'
    - OSS_FILE: 'xxxxx_20211020181130_dispatch-service-0.0.7.jar'
    - OSS_FILE_KEY: '?xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    # 部署参数
    - DEPLOY_USER: '{{ deploy_user }}' # "ubuntu"
    - APP_NAME: '{{ app_name }}' # "tomcat"
    - APP_DIR:  '{{ app_dir }}' # "/tmp"
    - DING_URL: '{{ ding_url }}'
    - DING_TOKEN: '{{ ding_token }}'

  tasks:

    - name: "验证 {{ inventory_hostname }} SSH 端口"
      local_action: wait_for port=22 host="{{ inventory_hostname }}" search_regex=OpenSSH
    - name: gather facts
      setup:    

    - name: "钉钉 {{ ding_url }} {{ ding_token }}"
      shell: "echo {{ ding_url }}"   
      register: print_ding_url

    - name: "获取当前发布主机IP"
      shell: "curl http://ip.me"   
      register: get_ip_addr
    - name: "获取当前发布主机IP SDTOUT"  
      debug: var=get_ip_addr.stdout

    - name: "获取当前发布主机名称"
      shell: "hostname"
      register: get_hostname
    - name: "获取当前发布主机名称 SDTOUT"
      debug: var=get_hostname

    # 发布的一些动作
    - name: "发布主机: {{ get_hostname.stdout }} 验证 {{ APP_NAME }} 目录"
      file:
        path: "{{ APP_DIR }}/{{ APP_NAME }}"
        state: directory
        mode: '0755'   
      register: create_dir
    - name: "发布主机: {{ get_hostname.stdout }} 验证 {{ APP_NAME }} 目录 STDOUT"
      debug: var=create_dir

    - name: "发布主机: {{ get_hostname.stdout }} APP {{ APP_NAME }} 程序包下载"            
      shell: "wget {{ OSS_URL }}/{{ OSS_PATH }}/{{ OSS_FILE }}'{{ OSS_FILE_KEY }}' -O {{ APP_DIR }}/{{ APP_NAME }}/{{ OSS_FILE }}"
      args:
        chdir: /opt/
        creates: /opt/{{ OSS_URL }}/{{ OSS_FILE }}
      register: download_file
      #notify: restart {{ APP_NAME }}
    - name: "发布主机: {{ get_hostname.stdout }} APP {{ APP_NAME }} 程序包下载 CMD"
      debug: var=download_file.cmd

    - name: "发布主机: {{ get_hostname.stdout }} APP {{ APP_NAME }} 改名"
      shell: "new_file_name=`ls {{ APP_DIR }}/{{ APP_NAME }}/{{ OSS_FILE }} |awk -F'_' '{print $3}'` && echo ${new_file_name} && mv {{ APP_DIR }}/{{ APP_NAME }}/{{ OSS_FILE }} {{ APP_DIR }}/{{ APP_NAME }}/${new_file_name}"
      args:
        chdir: /opt/
        creates: /opt/{{ OSS_URL }}/{{ OSS_FILE }}
      register: move_file
    - name: "发布主机: {{ get_hostname.stdout }} APP {{ APP_NAME }} 改名 STDOUT"
      debug: var=move_file.stdout

    - name: "发布主机: {{ get_hostname.stdout }} APP {{ APP_NAME }} 权限修改"
      file:
        path: "{{ APP_DIR }}/{{ APP_NAME }}"
        state: directory
        owner: "{{ DEPLOY_USER }}"
        group: "{{ DEPLOY_USER }}"
        recurse: yes
      register: changed_permissions
    - name: "APP {{ APP_NAME }} 权限修改 STDOUT"
      debug: var=changed_permissions

    - name: "发布主机: {{ get_hostname.stdout }} APP {{ APP_NAME }} 服务重启"      
      shell: "echo {{ OSS_URL }}/{{ OSS_PATH }}/{{ OSS_FILE }} -O {{ APP_DIR }}/{{ APP_NAME }}/{{ OSS_FILE }}"
      register: restart_service
      notify: restart {{ APP_NAME }}
    - name: "发布主机: {{ get_hostname.stdout }} APP {{ APP_NAME }} 服务重启 SDTOUT"
      debug: var=restart_service.cmd

    # 发布完成后的验证
    - name: "发布主机: {{ get_hostname.stdout }} 验证 {{ APP_NAME }} 进程状态"      
      shell: "echo {{ OSS_URL }}/{{ OSS_PATH }}/{{ OSS_FILE }} -O {{ APP_DIR }}/{{ APP_NAME }}/{{ OSS_FILE }}"
      args:
        chdir: /opt/
        creates: /opt/{{ OSS_URL }}/{{ OSS_FILE }}
      register: process_status
    - name: "发布主机: {{ get_hostname.stdout }} 验证 {{ APP_NAME }} 进程状态 STDOUT"
      debug: var=process_status.stdout      

    - name: "发布主机: {{ get_hostname.stdout }} 验证 {{ APP_NAME }} 服务状态"      
      shell: "echo {{ OSS_URL }}/{{ OSS_PATH }}/{{ OSS_FILE }} -O {{ APP_DIR }}/{{ APP_NAME }}/{{ OSS_FILE }}"
      args:
        chdir: /opt/
        creates: /opt/{{ OSS_URL }}/{{ OSS_FILE }}
      register: service_status
    - name: "发布主机: {{ get_hostname.stdout }} 验证 {{ APP_NAME }} 服务状态 STDOUT"
      debug: var=service_status.stdout  

    - name: "发布主机: {{ get_hostname.stdout }} 验证 {{ APP_NAME }} 接口状态"      
      shell: "curl -s -L %{http_code} {{ OSS_URL }}  | grep \"Welcome!\" |awk '{print $1}'"
      args:
        chdir: /opt/
        creates: /opt/{{ OSS_URL }}/{{ OSS_FILE }}
      register: interface_status
    - name: "发布主机: {{ get_hostname.stdout }} 验证 {{ APP_NAME }} 接口状态 STDOUT"
      debug: var=interface_status.stdout

  # 重启服务
  handlers:
    - name: restart {{ APP_NAME }}
      service: name={{ APP_NAME }} state=restarted

执行参数

# 变量
ansible-playbook -C deploy.yaml -e "ding_url=ding.opendevops.cn app_name=tomcat app_dir=/tmp/deniss deploy_user=ubuntu, ding_token=qwerty&^%FDSFBSNFXZ&^%%"
# json
ansible-playbook -C deploy.yaml --extra-vars "{'app_name':'tomcat', 'deploy_user':'ubuntu', 'app_dir':'/tmp/deniss', 'ding_url':'ding.opendevops.cn', 'ding_token':'qwerty&^%FDSFBSNFXZ&^%%'}"

至此,Ansible的基础篇与进阶篇已经完结,如果你认真的阅读学习并动手实践,你一定可以写出高效的Ansible-PlayBook脚本!敬请期待下一篇如何基于AnsibleAPI二次开发 任务中心之AnsibleAPI篇

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8