Ansible知识汇总

#查询磁盘使用率超过60%

ansible all -m shell -a “df -h | awk ‘\$5+0 > 60 {print \$0}'”

#查询空闲内存比例<10%

ansible all -m shell -a “free | awk ‘NR==2 && (\$7/\$2)*100 < 10 {print \$0}'”

#查询swap使用率超过50%

ansible all -m shell -a “free | awk ‘NR==3 && (\$3/\$2)*100>50 {print \$0}'”

#查询磁盘使用率超过60%

df -h | awk ‘$5+0 > 60 {print $0}’

#查询空闲内存比例<10%

free | awk ‘NR==2 && ($7/$2)*100 < 10 {print $0}’

#查询swap使用率超过50%

free | awk ‘NR==3 && ($3/$2)*100>50 {print $0}’

file模块

# 创建目录/app/dir1

ansible 192.168.1.31 -m file -a ‘path=/app/dir1 state=directory’

# 创建文件/app/file1

ansible 192.168.1.31 -m file -a ‘path=/app/file1 state=touch’

# 建立软链接(src表示源文件,path表示目标文件)

ansible 192.168.1.31 -m file -a ‘src=/app/src1 path=/app/link1 state=link’

# 删除文件/app/file1

ansible 192.168.1.31 -m file -a ‘path=/app/file1 state=absent’

# 创建文件时同时设置权限等信息

ansible 192.168.1.31 -m file -a ‘path=/app/file2 state=directory mode=775 owner=root group=root’

copy模块

# 复制文件到远程主机并改名

ansible 192.168.1.31 -m copy -a ‘dest=/tmp/a.sh src=/root/ansible_test.sh’

# 复制文件到远程主机,并备份远程文件,安装时间信息备份文件(当更新文件内容后,重新copy时用到)

ansible 192.168.1.31 -m copy -a ‘dest=/tmp/a.sh src=/root/ansible_test.sh backup=yes’

# 直接在远程主机a.sh中添加内容

ansible 192.168.1.31 -m copy -a ‘dest=/tmp/a.sh content=”#!/bin/bash\n echo `uptime`”‘

# 复制文件到远程主机,并设置权限及属主与属组

ansible 192.168.1.31 -m copy -a ‘dest=/tmp/passwd src=/etc/passwd mode=700 owner=root group=root’

user模块

创建账户,账户名称alice,密码123456。

# ansible all -m user -a “name=alice password={{‘123456’ | password_hash(‘sha512’)}}”

配置alice账户可以提权执行所有命令    

# ansible all -m lineinfile -a “path=/etc/sudoers line=’alice  ALL=(ALL) NOPASSWD:ALL'”

#创建用户xikai

ansible dbservers -m user -a ‘name=”xikai” uid=9526 groups=wheel’

#修改密码

ansible dbservers -m user -a ‘name=”xikai” password=”123456″ shell=”/shell/nologin” ‘

#删除用户xikai

ansible dbservers -m user -a ‘name=”xikai” state=absent remove=yes’  

cron模块

# 创建计划任务

ansible dbservers -m cron -a ‘minute=”10″ hour=”10,22″ day=”10″  month=”*/2″ job=”/usr/bin/cp /var/log/messages /opt” name=”test crontab” ‘

常用的参数:

minute/hour/day/month/weekday: 分/时/日/月/周

job: 任务计划要执行的命令

name:任务计划的名称

#删除计划任务,假如该计划任务没有取名字,name=None即可

ansible webservers -m cron -a ‘ name=”test crontab” state=absent ‘

yum模块

#列出所有已安装的软件包

ansible 192.168.1.31 -m yum -a ‘list=installed’

#列出所有可更新的软件包

ansible 192.168.1.31 -m yum -a ‘list=updates’

#列出所有的yum仓库

ansible 192.168.1.31 -m yum -a ‘list=repos’

#只下载软件包并到指定目录下

ansible 192.168.1.31 -m yum -a ‘name=httpd download_only=yes download_dir=/tmp’

#安装软件包

ansible 192.168.1.31 -m yum -a ‘name=httpd state=installed’

#卸载软件包

ansible 192.168.1.31 -m yum -a ‘name=httpd state=removed’

#安装包组,类似yum groupinstall ‘Development Tools’

ansible 192.168.1.31 -m yum -a ‘name=”@Development Tools” state=installed’

creates及removes

# creates  如果creates的文件不存在,则执行后面的操作

ansible 192.168.1.31 -a ‘creates=/tmp ls /etc/passwd’    #tmp文件存在,则不执行后面的ls命令

ansible 192.168.1.31 -a ‘creates=/tmp11 ls /etc/passwd’    # tmp11文件不存在,则执行后面的ls命令

# removes  和creates相反,如果removes的文件存在,才执行后面的操作

ansible 192.168.1.31 -a ‘removes=/tmp ls /etc/passwd’    #tmp文件存在,则执行后面的ls命令

ansible 192.168.1.31 -a ‘removes=/tmp11 ls /etc/passwd’  #tmp11文件不存在,则没有执行后面的ls命令

#可以使用 –limit 标识指定特定的目标主机:

ansible-playbook site.yml –limit datacenter2

#可以使用 –limit 从一个文件中读取主机列表, 使用时在文件名前加 @:

ansible-playbook site.yml –limit @retry_hosts.txt

示例:ansible限定多台主机执行命令:

(1)将多台主机IP放在某个文件中,比如retry.txt

cat retry.txt

16.5.32.19

16.5.32.20

16.5.32.39

16.5.32.40

(2)然后执行如下命令

ansible -i /cib/host all –limit @retry.txt -m shell -a “usr/bin/crontab –l”

ansible 对文件内容的操作

lineinfile模块

简介:该模块是操作文件中的每一行内容,它是按照行为单位的,和下面的replace模块并不冲突。

修改匹配行,如果不存在就会添加

tasks:

– name: Ensure SELinux is set to enforcing mode

  lineinfile:

    path: /etc/selinux/config

    regexp: ‘^SELINUX=’

    line: SELINUX=enforcing

把 SELINUX=这个开头的行直接替换成SELINUX=enforcing不管后面是什么,直接替换整行内容。

删除文件中的行

– name:  确保sudoers配置中没有wheel组。

  lineinfile:

    path: /etc/sudoers

    state: absent

    regexp: ‘^%wheel’

在匹配行前添加一行内容,并确保插入成功

– name: Ensure the default Apache port is 8080

  lineinfile:

    path: /etc/httpd/conf/httpd.conf

    regexp: ‘^Listen ‘                        //确保添加完成

    insertafter: ‘^#Listen ‘            //要在哪一行前面添加

line: Listen 8080                            //添加的内容

在匹配行后添加一行内容,并确保插入成功

– name: Ensure we have our own comment added to /etc/services

  lineinfile:

    path: /etc/services

    regexp: ‘^# port for http’                    //确保添加完成

    insertbefore: ‘^www.*80/tcp’                //要在哪一行后面添加

    line: ‘# port for http by default’    //添加的内容是什么

修改文件并更改权限

– name: Replace a localhost entry with our own

  lineinfile:

    path: /etc/hosts

    regexp: ‘^127\.0\.0\.1’

    line: 127.0.0.1 localhost

    owner: root

    group: root

    mode: ‘0644’

文件存在就添加一行内容,如果内容存在就不会添加(多次执行不会重复添加)

– name: add a line

  lineinfile:

    dest: /etc/hosts

line: ‘10.1.1.1 zhangshoufu.com’

#删除/etc/hosts文件中特定重复行:192.168.1.1 duplicate.com

ansible target_group -m lineinfile -a ‘dest=/etc/hosts state=absent line=”192.168.1.1 duplicate.com”‘

replace模块

介绍:replace模块可以根据我们指定的正则表达式替换匹配到的字符串,文件中所有被匹配到的字符串都会被替换,和lineinfile不同的地方是replace只会替换正则表达式匹配到的内容,而lineinfile是替换正则表达式匹配到行的内容。

常用参数

    path: 文件路径,我们要替换那个文件内的内容,必须

    regexp:正则表达式,必要参数

    replace: 替换成的内容

替换文件内容

tasks:

– name: ‘替换zsf 字符串为zhangshoufu’

  replace:

    path: /tmp/test.txt

    regexp: ‘zsf’

    replace: ‘zhangshoufu’

注释 Apache 配置文件/etc/apache2/sites-available/default.conf中NameVirtualHost [*]行之后的所有内容:

– name: Replace after the expression till the end of the file (requires Ansible >= 2.4)

  replace:

    path: /etc/apache2/sites-available/default.conf

    after: ‘NameVirtualHost [*]’

    regexp: ‘^(.+)$’

    replace: ‘# \1’

注释 Apache 配置文件/etc/apache2/sites-available/default.conf中# live site config行之前的所有内容:

– name: Replace before the expression till the begin of the file (requires Ansible >= 2.4)

  replace:

    path: /etc/apache2/sites-available/default.conf

    before: ‘# live site config’

    regexp: ‘^(.+)$’

    replace: ‘# \1’

注释 Apache 配置文件/etc/apache2/sites-available/default.conf中<VirtualHost [*]>行和</VirtualHost>行之间的内容:

# Prior to Ansible 2.7.10, using before and after in combination did the opposite of what was intended.

# see https://github.com/ansible/ansible/issues/31354 for details.

– name: Replace between the expressions (requires Ansible >= 2.4)

  replace:

    path: /etc/apache2/sites-available/default.conf

    after: ‘<VirtualHost [*]>’

    before: ‘</VirtualHost>’

    regexp: ‘^(.+)$’

    replace: ‘# \1’

删除jdoe用户 SSH 的known_hosts文件中的old.host.name及之后的空行,同时修改文件属性和权限:

– name: Supports common file attributes

  replace:

    path: /home/jdoe/.ssh/known_hosts

    regexp: ‘^old\.host\.name[^\n]*\n’

    owner: jdoe

    group: jdoe

    mode: ‘0644’

修改/etc/apache/ports文件并校验:

– name: Supports a validate command

  replace:

    path: /etc/apache/ports

    regexp: ‘^(NameVirtualHost|Listen)\s+80\s*$’

    replace: ‘\1 127.0.0.1:8080’

    validate: ‘/usr/sbin/apache2ctl -f %s -t’

在 Ansible 中,你可以使用以下几种方法来验证 YAML 文件而不真正执行任务:

1. 语法检查模式 (–syntax-check)

# 检查 playbook 语法

ansible-playbook playbook.yml –syntax-check

# 检查 inventory 文件语法

ansible-inventory -i inventory.yml –list –yaml

2. 空运行模式 (-C 或 –check)

# 模拟执行,显示会做什么但不实际执行

ansible-playbook playbook.yml –check

# 配合详细模式查看详细信息

ansible-playbook playbook.yml –check -v

ansible-playbook playbook.yml –check -vvv  # 更详细

3. 差异模式 (-D 或 –diff)

# 显示文件变化(如果有文件操作)

ansible-playbook playbook.yml –check –diff

4. 验证 Playbook 结构

# 使用 ansible-lint(需要安装)

ansible-lint playbook.yml

# 安装 ansible-lint

pip install ansible-lint

5. 组合使用多个选项

# 完整验证:语法检查 + 空运行 + 差异显示

ansible-playbook playbook.yml \

  –syntax-check \

  –check \

  –diff \

  -v

# 只验证,不连接远程主机

ansible-playbook playbook.yml \

  –check \

  –list-hosts \

  –list-tasks

6. 验证特定部分

# 列出所有任务

ansible-playbook playbook.yml –list-tasks

# 列出所有主机

ansible-playbook playbook.yml –list-hosts

# 列出所有 tags

ansible-playbook playbook.yml –list-tags

最佳实践建议(按顺序验证:)

# 1. 语法检查

ansible-playbook playbook.yml –syntax-check

(或:测试playbook语法是否正确ansible-playbook -C playbook.yml)

# 2. 结构检查

ansible-playbook playbook.yml –list-tasks –list-hosts

# 3. 模拟执行

ansible-playbook playbook.yml –check –diff

# 4. 代码质量检查

ansible-lint playbook.yml