Ansible自动化运维2

目录

一 Playbook运维

1.1验证YAML语法

 1.2play的定义

1.3完整playbook

2.ansbible 变量

2.1主机变量

2.2facts变量

2.3.注册变量

2.4变量优先级

3.ansible任务控制

3.1循环

3.2tags属性

3.3handiers属性

二、jinja2模板

1.jinja逻辑控制

1.1一个基于facts的jinja2实例

三,ansible roles

实例1

2.新方式执行roes 

3.galaxy


一  Playbook运维

playbook是Ansible自定义的一门语言(类似于linux和shell的关系)

1.YAML特点

playbook遵循YAML语法

  • YAML 文件 #为注释符
  • YAML 文件.yml 或则.yam1结尾
  • YAML 文件--开始 以..结束 但是开始和结束的标志都是可选的

2.基本语法

  • 大小写密函
  • 使用缩进表示层级关系
  • 缩进是是使用tab 还是空格要统一,建议使用空格
  • 相同层级的元素必须左侧对其即可

3.字符串

列表定义:

以短横线+空格+ 具体的值

- red

#########################

字典定义:

key+冒号+空号+值 即key:value

name: huawei

######################

混合结构

class

   - name: huawei

     nmu:001

   -name:apple

    num:002 

1.1验证YAML语法

[root@master ~]# yum -y install python2-pip  ##安装pip
[root@master ~]# pip install pyyaml     ##下载解释包
[root@master ~]# python -c 'import yaml,sys;print yaml.load(sys.stdin)' < ceshi.yml 
 ##提前编写ceshi.yml文件写入配置 
['red', 'green']

 1.2play的定义

常用属性

  • name 每个play的名字
  • hosts 每个play色痕迹的被管理服务器 通ad hoc中的资产选择器
  • tasks 每个play中具体要完成的任务 以列表的形式表达
  • become属性 如果需要提权 则加上become 
  • become_user 若提权 提权到那个用户上
  • remote——user 指定来远程的用户 若不指定 则默认使用当前执行ansible playbook用户

1.3完整playbook

[root@master ~]# vi ceshi.yml 

---
- name: ceshi
  hosts: master
  remote_user: root
  tasks:
    - name: install nginx package
      yum: name=nginx state=present
    - name: start nginx server
      service:
        name: nginx
        enable: true
        state: started
...
~                                                                                           
~                                
[root@master ~]# ansible-playbook -i hosts ceshi.yml --syntax-check  ##检查完整性

playbook: ceshi.yml


[root@master ~]# python -c 'import yaml,sys;print yaml.load(sys.stdin)' < ceshi.yml
[{'tasks': [{'yum': 'name=nginx state=present', 'name': 'install nginx package'}, {'name': 'start nginx server', 'service': {'state': 'started', 'enable': True, 'name': 'nginx'}}], 'hosts': 'master', 'remote_user': 'root', 'name': 'ceshi'}]

[root@master ~]# ansible-playbook ceshi.yml 
###运行playbook

2.ansbible 变量

2.1主机变量

   

[root@master ~]# cat 01t 
[server]
192.168.1.105 user=lw port=3360

[root@master ~]# ansible 192.168.1.105 -i 01t -m debug -a "msg='{{user}} {{port}}'"
192.168.1.105 | SUCCESS => {
    "msg": "lw 3360"
}
##获取定义的变量


[root@master ~]# cat 01t 
[server]
192.168.1.105 user=lw port=3360
[server:var]
home="/home/lw"

[root@master ~]# ansible 192.168.1.105 -i 01t -m debug -a "var=home"

2.2facts变量

[root@master ~]# ansible all -i loaclhost, -c local -m setup
##手动收集变量

[root@master ~]# ansible all -i loaclhost, -c local -m setup -a "filter=*ansible_processor"
loaclhost | SUCCESS => {
    "ansible_facts": {
        "ansible_processor_vcpus": 4, 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}
##获取主机cpu信息

关闭facts变量  可以使playbook执行更快
gather_facts: no  ##添加这行代码 

2.3.注册变量

[root@master ~]# cat ceshi.yml 
---
- name: ceshi
  hosts: master
  remote_user: root
  tasks:
    - name: install nginx package
      yum: name=nginx state=present
      register: install_result ##定义变量
    - name: print
      debug: var=install_result
...

[root@master ~]# ansible-playbook -i hosts ceshi.yml 

PLAY [ceshi] ***********************************************************************************

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

TASK [install nginx package] *******************************************************************
ok: [192.168.1.105]

TASK [print] ***********************************************************************************
ok: [192.168.1.105] => {
    "install_result": {
        "changed": false, 
        "failed": false, 
        "msg": "", 
        "rc": 0, 
        "results": [     ##nginx已经安装了
            "1:nginx-1.20.1-9.el7.x86_64 providing nginx is already installed"
        ]
    }
}

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

2.4变量优先级

  • 优先级最高的是全局变量 其次是自己变量

3.ansible任务控制

[root@master ~]# cat ceshi.yml  ##编辑yml文件
---
- name: ceshi
  hosts: master
  gather_facts: no
  remote_user: root
  tasks:
    - name: install nginx package
      yum: name=nginx state=present
      register: install_result
  ##  - name: update ngxin
  ##    copy: src=nginx.conf dest=/etc/nginx/
    - name: check nginx
      shell: /usr/sbin/nginx -t
      register: nginxsyntax
    - name: print nginxsyntx
      debug: var=nginxsyntax      
    - name: start nginx
      service: name=nginx state=started
      when: nginxsyntax.rc == 0  ##当变量值为0 启动  when关键字 
...

[root@master ~]# ansible-playbook -i hosts ceshi.yml 

PLAY [ceshi] ***********************************************************************************

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

TASK [install nginx package] *******************************************************************
ok: [192.168.1.105]

TASK [check nginx] *****************************************************************************
changed: [192.168.1.105]

TASK [print nginxsyntx] ************************************************************************
ok: [192.168.1.105] => {
    "nginxsyntax": {
        "changed": true, 
        "cmd": "/usr/sbin/nginx -t", 
        "delta": "0:00:00.006268", 
        "end": "2022-09-18 23:23:44.675290", 
        "failed": false, 
        "rc": 0,   ##代表是否成功
        "start": "2022-09-18 23:23:44.669022", 
        "stderr": "nginx: the configuration file /etc/nginx/nginx.conf syntax is ok\nnginx: configuration file /etc/nginx/nginx.conf test is successful", 
        "stderr_lines": [
            "nginx: the configuration file /etc/nginx/nginx.conf syntax is ok", 
            "nginx: configuration file /etc/nginx/nginx.conf test is successful"
        ], 
        "stdout": "", 
        "stdout_lines": []
    }
}

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

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

3.1循环

在playbook中是使用with_items循环遍历这个变量来达到创建用户的目的

[root@master ~]# ansible-playbook -i hosts ceshi01.yml 

PLAY [variable playbook example] ***************************************************************

TASK [create user] *****************************************************************************
ok: [192.168.1.105] => (item=tom)
ok: [192.168.1.105] => (item=lihua)
ok: [192.168.1.105] => (item=hauwei)

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

[root@master ~]# cat ceshi01.yml 
---

 - name: variable playbook example
   hosts: master
   gather_facts: no
   vars:  
      createuser:    ##定义列表
         - tom
         - lihua
         - hauwei
   tasks:
        - name: create user
          user: name={{ item }} state=present  ##将变量每一个带入
          with_items: "{{ createuser}}"        ##调用列表:

新版本循环loop 就是将with_items换成loop

3.2tags属性

执行时一定要指定tags 执行task任务打上tag标记为updateconfig任务 即只会执行打上标签的任务

3.3handiers属性

当task文件配置发生改变时,则触发条件执行task任务

二、jinja2模板

  • jiaja2文件以.j2为后缀,也可以不写后缀
  • 三种界定符号: 注释{##}

                         变量引用:{{  }}

                         逻辑表达{% %}

1.jinja逻辑控制

条件表达

{% if %}

...

...

{% endif %}

##example:

{% if idc is defied%}

{{ idc} }

{{ else' if }}

{% endif %}

1.1一个基于facts的jinja2实例

[root@master ~]# cat config.j2 
{# ceshi1 #}
wlecome host  {{ ansible_hostname}},os is{{ansible_os_family}}
today is {{ ansible_date_time.date }}
coucore numbers {{ ansible_processor_vcpus }}
[root@master ~]# cat usejinja2.yml 
---
- name: a template example
  hosts: master
  remote_user: root
  tasks:
    - name: update jinja2 config
      template: src=config.j2 dest=/tmp/config.conf

...


[root@master ~]# cat /tmp/config.conf 
wlecome host  master,os isRedHat
today is 2022-09-20
coucore numbers 4


[root@master ~]# ansible-playbook -i hosts usejinja2.yml 
##调用命令

三,ansible roles

表面看是哟个目录,目录的名字就是role的名字

使用时,每个目录必须包含一个main.yml的文件 这个文件应该包含如下目录对应的内容

  • task 包含就角色执行的任务主要列表
  • handlers 处理程序
  • defults 角色的默认变量
  • vars 角色的其他变量
  • files 通过角色部署的文件
  • templates 包含通过此角色部署的模板
  • meta 角色定义的一些元数据

实例1

1.执行roes文件

[root@master nginx]# for i in `ls`; do touch $i/main.yml; done
[root@master nginx]# tree ##在创建这些文件夹和文件
.
├── files
│?? └── main.yml
├── handles
│?? └── main.yml
├── tasks
│?? └── main.yml
├── templates
│?? └── main.yml
└── vars
[root@master ~]# cat nginx/tasks/main.yml 
---
    - name: install nginx package
      yum: name=nginx state=present
      register: install_result
    - name: check nginx
      shell: /usr/sbin/nginx -t
      register: nginxsyntax
    - name: print nginxsyntx
      debug: var=nginxsyntax
    - name: start nginx
      service: name=nginx state=started
      when: nginxsyntax.rc == 0
...

[root@master ~]# cat nginx/handles/main.yml 
---
- name: reload nginx serber
  service: name=nginx state=started
  when:
    - nginxsyntax.rc == 0 
      nginxrunning.stat.exists true
[root@master ~]# cat nginx/vars/main.yml 
---
createuser:
     - tomcat
     - www
     - mysql
[root@master ~]# ls       ##需要创建文件nginx_test.yml
01t   anaconda-ks.cfg  ceshi.yml  nginx                               sudoers
1.sh  a.sh             config.j2  nginx_test.yml                      usejinja2.yml
2.sh  ceshi01.yml      hosts      openpbs-server-20.0.0-0.x86_64.rpm


[root@master ~]# cat nginx_test.yml ##role不能被调用 同样也需要创建yml文件 进行调用
---
- name: a playbook uesd role
  hosts: master
  roles:
    - nginx

[root@master ~]# ansible-playbook -i hosts nginx_test.yml 

PLAY [a playbook uesd role] ********************************************************************

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

TASK [install nginx package] *******************************************************************
ok: [192.168.1.105]

TASK [check nginx] *****************************************************************************
changed: [192.168.1.105]

TASK [print nginxsyntx] ************************************************************************
ok: [192.168.1.105] => {
    "nginxsyntax": {
        "changed": true, 
        "cmd": "/usr/sbin/nginx -t", 
        "delta": "0:00:00.017429", 
        "end": "2022-09-21 20:54:06.667458", 
        "failed": false, 
        "rc": 0, 
        "start": "2022-09-21 20:54:06.650029", 
        "stderr": "nginx: the configuration file /etc/nginx/nginx.conf syntax is ok\nnginx: configuration file /etc/nginx/nginx.conf test is successful", 
        "stderr_lines": [
            "nginx: the configuration file /etc/nginx/nginx.conf syntax is ok", 
            "nginx: configuration file /etc/nginx/nginx.conf test is successful"
        ], 
        "stdout": "", 
        "stdout_lines": []
    }
}

TASK [start nginx] *****************************************************************************
changed: [192.168.1.105]

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

2.新方式执行roes 

在playbook定import-role属性

[root@master ~]# mkdir master
[root@master ~]# mv nginx
nginx/          nginx_test.yml  
[root@master ~]# mv nginx master/
[root@master ~]# mv nginx_test.yml  master/
[root@master ~]# ls master/
nginx  nginx_test.yml


[root@master ~]# cat master/newnginx_test.yml 
- name: new playbook use role
  hosts: master
  tasks:
    - debug:
        msg: "before we run our role"
    - import_role:
        name: nginx
    - debug:
        msg: "new use role"

[root@master ~]# ansible-playbook -i hosts master/newnginx_test.yml 

PLAY [new playbook use role] *******************************************************************

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

TASK [debug] ***********************************************************************************
ok: [192.168.1.105] => {
    "msg": "before we run our role"
}

TASK [install nginx package] *******************************************************************
ok: [192.168.1.105]

TASK [check nginx] *****************************************************************************
changed: [192.168.1.105]

TASK [print nginxsyntx] ************************************************************************
ok: [192.168.1.105] => {
    "nginxsyntax": {
        "changed": true, 
        "cmd": "/usr/sbin/nginx -t", 
        "delta": "0:00:00.005298", 
        "end": "2022-09-21 21:12:03.357452", 
        "failed": false, 
        "rc": 0, 
        "start": "2022-09-21 21:12:03.352154", 
        "stderr": "nginx: the configuration file /etc/nginx/nginx.conf syntax is ok\nnginx: configuration file /etc/nginx/nginx.conf test is successful", 
        "stderr_lines": [
            "nginx: the configuration file /etc/nginx/nginx.conf syntax is ok", 
            "nginx: configuration file /etc/nginx/nginx.conf test is successful"
        ], 
        "stdout": "", 
        "stdout_lines": []
    }
}

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

TASK [debug] ***********************************************************************************
ok: [192.168.1.105] => {
    "msg": "new use role"
}

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

3.galaxy

[root@master ~]# ansible-galaxy init huaweitestrole ##创建一个role
- Role huaweitestrole was created successfully
[root@master ~]# ls
01t   anaconda-ks.cfg  ceshi.yml  huaweitestrole                      sudoers
1.sh  a.sh             config.j2  master                              usejinja2.yml
2.sh  ceshi01.yml      hosts      openpbs-server-20.0.0-0.x86_64.rpm
[root@master ~]# tree huaweitestrole/
huaweitestrole/
├── defaults
│   └── main.yml
├── files
├── handlers
│   └── main.yml
├── meta
│   └── main.yml
├── README.md
├── tasks
│   └── main.yml
├── templates
├── tests
│   ├── inventory
│   └── test.yml
└── vars
    └── main.yml

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值