收藏文章 楼主

ansible 使用 playbook.yml 文件运行

版块:ansible.playbook.yml   类型:普通   作者:小绿叶技术博客   查看:2735   回复:0   获赞:0   时间:2021-04-09 09:11:39

 a

# yaml 语法

yaml是”YAML Ain't a Markup Language”的缩写 ; 表达资料序列的编程语言


#-------- playbook.yml 配置文件规范 ---------#


1. 首行顶格写: ---

2. 注释符号:#

3. 缩进必须统一,tab 和空格不能混合使用

4. 缩进级别对齐,例如:name 多个名称对齐

5. yml 区分大小写

6. k/v 可以换行:  同行  冒号 : 分隔; 换行 - 

7. 代码块: 一个 name  只能包含一个 task 任务

8. 两个空格为一个tab


yum install -y vim  # 安装vim

echo "autocmd filetype yaml setlocal ai ts=2 sw=2 et" >> .vimrc

# 设置vim 编辑中 tab 为2个空格



# yml 编写执行 ansible playbook

#------ playbook 组成主要元素 -------#

hosts: # 选择目标:主机ip 或 分组

remote_user: # 指定目标主机的用户,如:root

 

# 案例:

---

- hosts: eisc

         # 指定被执行的组,也可以指定IP

  remote_user: root

  become: yes

            # 切换用户

  tasks:

             # 任务列表

    - name: ping test

                # name 任务名称

      shell: |

        # 使用shell模块,多个命令需要加符号:  |

        ping -c 3 eisc.cn

        df -hl

      remote_user: root

        # 每个tasks任务也可以指定运行用户为 aaa

      register: out

        # 消息结果输出变量:out

    - debug:

            # 打印

          msg: "DBLOAD hostres {{out.stdout_lines}} ENDLOAD"

            # 消息模块


ansible-playbook ping.yml -k # 执行playbook ; -k 输入aaa的密码

# 注意: 对于缩进要求十分严格,连注释行都要根据内容进行缩进


ansible-playbook ping.yml -e  "key1=value1,key2=value2"

# 在执行命令的后面:-e 跟上变量参数 

 -i(--inventory=PATH):指定inventory文件,默认文件是/etc/ansible/hosts

#  -v(--verbose):显示详细的输出,也可使用-vvvv显示精确到每分钟的输出

#  -f(--forks=NUM):指定并发执行的任务数,默认为5,可根据服务器的性能进行调节

# -C(--check):检测模式,playbook中定义的所有任务将在每台远程主机上进行检测,但不执行。

# play中只要执行命令的返回值不为0,就会报错,tasks停止,可以添加下面

# ignore_errors: True #忽略错误,强制返回成功


# playbook常用命令

ansible-playbook    # 查看帮助

ansible-playbook a.yml --syntax-check

# 检查yaml文件的语法是否正确

ansible-playbook a.yml --list-task # 检查tasks任务

ansible-playbook a.yml --list-hosts 

# 检查生效的主机

ansible-playbook a.yml --start-at-task='Copy Nginx.conf'    

# 指定从某个task开始运行

ansible-playbook --syntax-check -e "hosts=c7" xx.yml -s -k  

# 语法检查


参数:

-k(–ask-pass) 用来交互输入ssh密码

-K(-ask-become-pass) 用来交互输入sudo密码

-u 指定用户


ansible_become_pass: "{{gdr_passwd}}"  # 定义变量,用来表示要切换用户的密码


# 交互内容

vars_prompt:

                - name: bmp_pass

                  prompt: "what is your sudo bmp passwd?"

                  private: yes

                  vars:

                  ansible_become_pass: "{{bmp_pass}}"


#------- 排除某些主机 ---------#

ansible-playbook -i hostslist ***.yml --limit 192.168.0.1  

# 排除单个主机


ansible-playbook -i hostslist ***.yml --limit @failed.txt 

# 排除多个主


#--------- 远程主机 sudo 切换用 ------#

---

- hosts: abc

    remote_user: root           

    become: yes                #2.6版本以后的参数,之前是sudo,意思为切换用户运行

    become_user: mysql          #指定sudo用户为mysql


ansible-playbook ping.yml -K

# 执行playbook


ansible-playbook update-stg.yml -f 10 -s -k   #

# 启用10个并行进程数执行


#-------- 启用并行进程数执行 --------#

ansible-playbook update-stg.yml -f 10 -s -k   

# 启用10个并行进程数执行



#----- 启用换行编写 -------#

ansible c6 -m shell -a “ls /opt/backup/” -s -k



# ansible_playbook的变量定义与调用


# 作用:不同主机可以调用同样的变量


#------- 变量定义与调用 -------#

### 在 /etc/ansible/hosts 文件中定义变量


echo "

[apache]

192.168.1.36 webdir=/opt/test     #定义单个主机的变量


[apache:vars]      #定义整个组的统一变量

webdir=/web/test


[nginx] 192.168.1.3[1:2]

[nginx:vars]

webdir=/opt/web


" >> /etc/ansible/hosts


# eisc.yml 文件调用变量

echo "

---

- hosts: all

remote_user: root

tasks:

- name: create webdir

file: name={{ webdir }} state=directory   #引用变量

 " >> eisc.yml



### 在 playbook中定义和调用变量

echo "

- hosts: webservers

remote_user: root

vars:  #开始声明变量

- package: httpd  #变量名与变量值

 - service: httpd

tasks:

- name: install apache

yum: name={{ package }} state=latest  #要引用的变量用"{{ }}"囊括

 - name: install configure file for httpd

copy: src=/root/conf/httpd.conf dest=/etc/httpd/conf/httpd.conf

- name: start httpd service

service: enabled=true name={{ service }} state=started

" >> eisc.yml


#### 使用ansible-playbook -e选项定义变量,

- hosts: all

 remote_user: root

 tasks:

 - name: install httpd

yum: name={{ package }}  #配置文件需要引用package变量


ansible-playbook -e 'package=httpd' app.yml  #通过-e定义变量,在app.yml文件全局生效

# 命令行变量优先级高于配置文件中的变量


#### 调用setup模块获取变量

ansible webserver -m setup



---

- hosts: webservers

remote_user: root

tasks:

 - name: copy file

 copy: content='{{ ansible_all_ipv4_addresses }}'        dest=/tmp/vars.anss }}' dest=/tmp/vars.ans


# {{ansible_devices.sda.partitions.sda.size}}    # sda 硬盘点分区,硬盘.大小





#-------------- 使用独立yml 文件定义变量 ---------------#

# 为了方便管理将所有的变量统一放在一个独立的变量YAML文件中,laybook文件直接引用文件调用变量即可


echo "

run1: "df -hl"

run2: "nginx"

run3: "iftop"


" >> bianl.yml


echo "

---

- hosts: eisc

  remote_user: root

  vars_files:

    - /root/bianl.yml

         # 引用变量文件

  tasks:

    - name: shell

      shell: |

        {{ run1  }}

      register: out

                # 调用文件中的变量 :run1   用符号 {{  }}

    - debug:

        msg: "DBLOAD hostres {{out.stdout_lines}} ENDLOAD"

" >> run.yml


# ansible-playbook 条件语句-内部变量使用


echo "

- hosts: u12

   gather_facts: False

tasks:

- name: debug loops

debug: msg="name -------> {{ item  }}"

 with_items:

    - one

    - two

" >>  


#------ 嵌套循环 --------#

- hosts: u12

  gather_facts: False

  tasks:

  - name: debug loops

   debug: msg="name --> {{ item[0] }} value ---> {{ item[1] }}"

   with_nested:

    - [1]

      - ['a','b','c']



#----- 散列 ----#


- hosts: u12

  gather_facts: False

  vars:

  users: 

   yq:

  name: yq

   shell: bash

    ljf:

    name: ljf

   shell: bash

  tasks:

  - name: test for sanlie loop

 debug: msg="name --> {{ item.key }} value --> {{ item.value.name }} shell ---> {{ item.value.shell }}"

  with_dict:  users


#------ 文件匹配 loops -------#

- hosts: u12

 gather_facts: False

 tasks:

  - name: debug file loop

   debug: msg="files ---> {{ item }}"

   with_fileglob:

     - /tmp/playb/*.yaml


#---- 随机选择loops ----#


- hosts: u12

  gather_facts: False

 tasks:

 - name: debug loops

     debug: msg="name -->> {{ item }}"

    with_random_choice:

     - "a1"

     - "a2"

    - "a3"

      - "a4"


#---- 条件判断 ----#

- hosts: u12

  tasks:

  - name: debug loop

   shell: hostname

 register: pwd

    until: pwd.stdout.startswith("LeoTestMachine")  # stdout与stdout_lines是不一样的,这个要注意哦

   retries: 3   # 重复3次

    delay: 2  # 间隔2秒



#------- 文件优先匹配 -------#

gather_facts: True

tasks:

 - name: debug codes

 debug: msg="files --->{{ item }}"

  with_first_found:

    - "{{ ansible_distribution }}.yaml"

    - "default.yaml"



#------- register loops -----#

- hosts: u12

 gather_facts: True

 tasks:  

  - name: debug loops

  shell: "{{ item }}"

  with_items:

   - hostname

   - uname

    register: ret

    - name: display loops

  debug: msg="{% for i in ret.results  %}--->{{ i.stdout  }}{% endfor  %}"


# 案例

#------ 批量创建用户. 组 ------#


---

        - hosts: SUSE_ALL

          remote_user: sysomc

become: yes

become_user: root

          tasks:

                - name: create group

                  group: name={{item}}

                  with_items:

                        - seeiot

                        - bmpiot

                        - rbiot


                - name: create user

                  user: name={{item.name}} group={{item.group}} password={{'123456'|password_hash('sha512')}}

                  with_items:

                        - {name: "see",group: "seeiot"}

                        - {name: "bmp",group: "bmpiot"}

                        - {name: "rbi",group: "rbiot"}


#----------- 批量删除用户、组及家目录 -------------#

---

        - hosts: SUSE_ALL

          remote_user: sysomc

become: yes

become_user: root

          tasks:

                - name: delete user

                  user: name={{item.name}} group={{item.group}} password={{'123456'|password_hash('sha512')}} state=absent remove=yes

                  with_items:

                        - {name: "see",group: "seeiot"}

                        - {name: "bmp",group: "bmpiot"}

                        - {name: "rbi",group: "rbiot"}

                - name: delete user_dir

                  file: path={{item}} state=absent

                  with_items:

                        - /home/see

                        - /home/bmp

                        - /home/rbi

- name: delete group

                   group: name={{item}} state=absent

                   with_items:

                         - seeiot

                         - bmpiot

                         - rbiot


#------- ansible限制并行执行play的主机数量 --------#


---

        - hosts: SUSE_ALL

          remote_user: sysomc

become: yes

become_user: root

serial: 1

tasks:

- name: enable alerts

      nagios: action=enable_alerts service=web host="{{ inventory_hostname }}"

      delegate_to: 192.168.146.51


#--------- 停止应用的进程或用于检查应用启停状态 ---------#


      - hosts: SUSE_ALL

remote_user: sysmomc

  become: yes

  become_user: see

  vars_files:

./password/passwd.yml

vars:

ansible_become_pass: “{{see_passwd}}”

tasks:

- name: 执行停止应用进程的shell脚本

shell:

~/stop.sh

    ignore_errors: yes   ##忽略报错


echo "

#!/bin/bash

LANG=zh_CN.utf8

export LANG

RunFlag='omc_collect_client';

for pid in `ps -ef | grep "${RunFlag}" | grep -v "grep" | awk ' { print $2 } '`

do

kill -9 $pid;

echo $pid;

done


" >> stop.sh


### 使用run_once: true来指定该task只能在某一台机器上执行一次. 可以和delegate_to 结合使用:

机器上执行)

---

        - hosts: SUSE_ALL

          remote_user: sysomc

become: yes

become_user: root

tasks:

- name: 查询进程

      shell: 

ps -ef|grep see

run_once: true

      delegate_to: 192.168.146.51









#

提供企业建站服务,免费网防系统,提交信息登录 http://yundun.ddoss.cn 邮箱: proposal@ddoss.cn 
回复列表
默认   热门   正序   倒序

回复:ansible 使用 playbook.yml 文件运行

头像

用户名:

粉丝数:

签名:

资料 关注 好友 消息