自动化_Ansible学习笔记

文章目录

      • Ansible 介绍
        • 配置文件
          • 主配置文件优先级
        • 常用命令
        • ansible-playbook
      • ad-hoc
      • inventory 主机清单
      • Playbook 剧本
        • YAML格式
      • ansible 模块
        • 介绍
        • 模块对应功能
        • Commands modules(命令模块)
          • command (命令)
          • shell (外壳)
        • 官方帮助文档 模块索引
        • playbook 开头示例
        • 系统类
          • setup (收集远程主机的一些基本信息)
          • group (组)
          • user (用户)
          • service (服务)
          • systemd (服务)
          • cron (计划任务)
          • hostname (修改主机名)
          • service (服务管理)
          • mount 挂载点
        • 文件类
          • synchronize(文件同步)
          • unarchive (解压缩)
          • script (脚本)
          • file (文件)
          • copy (复制到远程主机)
          • fetch (复制到ansible端)
          • find (查找)
          • replace (替换文件内容)
          • lineinfile (修改文件内容)
          • blockinfile (插入文本块)
          • template (根据模板生成文件)
        • 包管理
          • yum (软件包)
          • package (通用包管理)
          • pacman (ArchLinux)
          • yum_repository (yum仓库)
        • 网络安全类
          • Net Tools 网络工具
            • get_url (下载文件)
          • firewalld (防火墙)
        • Utilities (实用工具)
          • debug (调试信息)
          • fail (失败,停止后续)
        • Source Control modules(源代码控制模块)
          • git
      • playbook示例
        • lineinfile 替换文件内容
      • Ansible 常见问题
        • 指定客户端Python的位置

Ansible 介绍

  1. 官网
  2. galaxy
  3. 最新版模块索引
  4. 2.9版模块索引
  5. 安装
    curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
    yum -y install ansible
    
配置文件
  1. 配置文件
    文件 位置
    配置文件
    主配置文件 /etc/ansible/ansible.cfg
    主机清单 /etc/ansible/hosts
    存放角色目录 /etc/ansible/roles/
    执行文件
    主程序 /usr/bin/ansible
    功能查看 /usr/bin/ansible-doc
    上传下载优秀代码 /usr/bin/ansible-galaxy
    自动化任务 /usr/bin/ansible-playbook
    文件加密 /usr/bin/ansible-vault
    用户交互 /usr/bin/ansible-console
  2. 主配置文件介绍
    参数 解释
    inventory 主机清单文件
    library 库位置
    module_utils 模块位置
    remote_tmp 远程临时目录
    local_tmp 本地临时目录
    plugin_filters_cfg
    forks 并发操作主机数
    poll_interval 拉数据间隔
    sudo_user 以sudo身份执行命令
    remote_port 默认远程主机ssh端口
    host_key_checking 检查远程主机的host_key,建议取消即”False”
    private_key_file 私钥文件
    log_path 日志文件,建议允许,即取消注释
  3. 如果使用普通用户则sudo到root,vim /etc/ansible/ansible.cfg开启下列选项
    [privilege_escalation]  ##这一部分为提升权限的参数,如果使用普通用户需要开启。
    become=True
    become_method=sudo
    become_user=root
    become_ask_pass=False
    
  4. 主机清单文件inventory默认/etc/ansible/hosts
    用法 解释
    ansible_ssh_host 指定IP地址
    ansible_connection=ssh 指定通过ssh连接
    ansible_ssh_port=22 指定SSH端口
    ansible_ssh_user=osboxes 指定ssh用户
    ansible_ssh_pass=China123 指定ssh密码
    node[1:3] node1-3,共3台主机
    var=user 定义变量’var’的值为’user’
    [web:vars] 下面的变量为web组的变量
  5. inventory文件示例
    #表示一台主机
    test1 ansible_ssh_host=10.0.0.1 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass=password
    #表示一个主机组
    [test]
    10.0.0.1 ansible_connection=ssh ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass=password
    
主配置文件优先级
优先级 位置 说明
1 ANSIBLE_CONFIG环境变量指定
2 ./ansible.cfg 推荐的,当前目录下的ansible.cfg
3 ~/.ansible.cfg 用户家目录下的.ansible.cfg
4 /etc/ansible/ansible.cfg
常用命令
  1. 主要命令选项
    选项 解释
    ansible
    语法 ansible <主机清单> [-m 模块名] [-a 参数]
    –version 显示版本
    -m 指定模块
    -v 详细模式
    –list 显示主机列表
    -k 密码验证
    -u 指定连接使用的用户
    -b 在远程上使用sudo
    -K sudo密码
    ansible-doc
    -a 显示所有模块的文档
    -l 显示可用模块
    -s 简洁帮助信息
ansible-playbook
  1. 剧本文件以ymlyaml为扩展名

  2. 使用方法

    ansible-playbook 命令选项 文件名
    
  3. 可以调用的变量

    #安装命令查看,可以调用的变量
    yum install -y facter
    facter -p
    
  4. ansible-playbook 命令选项

    选项 解释
    -C,–check 检查语法,模拟执行过程
    –syntax-check 检查语法
    –list-hosts 列出主机
    –list-tasks 列出所有任务
    –list-tags 列出标签
    –step 一次执行一步
    -t 仅执行指定的标签
    -e 直接传递变量
  5. 文件示例

    ---
    - hosts: 主机
      remote_user: 远程用户
        sudo_user: 使用的用户身份
      #任务列表
      tasks:
      - name: 名称
        #模块:
        yum: name=httpd state=latest 
        notify: 调用的Handlers
        when: 当满足条件时(使用jinja2语法格式)才运行此task
        ignore_errors: True(当此模块错误时忽略错误,继续执行其他)
        tags: test(打上标签,使用-t只运行指定标签的task)
      - name: start httpd
        service: name=httpd state=started
      #定义变量
     
      vars:
      - host: localhost
      #包含了模板语法的文本文件
      Templates:
      #由特定条件触发的任务
      Handlers:  
    - hosts: db
    
  6. playbook 示例

    示例 解释
    ansible_distribution == "CentOS" and ansible_distribution_major_version == "7" 当操作系统为CentOS7是才运行此task

ad-hoc

inventory 主机清单

Playbook 剧本

YAML格式
  1. 用三个-号开头,用于标记文档的开始,可以省略
  2. 注释符号为:#
  3. 一般情况字符串不需要用引号引起来,即使中间有空格
  4. 变量引用{ { 变量名 }}
  5. 布尔类型
    1. True,yes
    2. False,no
  6. 列表
    1. 使用”-“作为定界符,如
      - My Fair Lady
      - OK lahoma
      - The Pirates of Penzance
      
  7. 字典
    1.

ansible 模块

介绍
  1. [2.9版模块索引](https://docs.ansible.com/ansible/2.9/modules
模块对应功能
  1. 功能对应表
    模块|功能
    -|-|-
    parted|硬盘分区|
    filesystem|分区格式化
    copy|复制文件
    mount|挂载点
    file|文件软链接
    script|在远程主机上运行shell脚本
Commands modules(命令模块)
command (命令)
  1. 参数
    参数 解释
    <free_form> 指定远程命令,直接使用命令,不含free_form
    chdir 执行命令前进入的目录
    creates 当指定的文件存在时,就不执行命令
    removes 当指定文件不存在时,就不执行命令
  2. 示例
    - name: test
      hosts: temp2
      gather_facts: no
      become: yes
    
      tasks:
        - name: cat hosts
          command: cat /etc/hosts
          register: hosts_value
        - debug: var=hosts_value.stdout_lines
    
shell (外壳)
  1. 官方文档
  2. 参数
    参数 解释
    free_form 指定命令
    chdir 指定执行命令前先进入的目录
    creates 指定文件存在,就不执行命令
    removes 指定文件不存在,就不执行命令
    executable /bin/sh(默认),指定使用的shell
  3. 示例
    - name: Change the working directory to somedir/ before executing the command.
      shell: somescript.sh >> somelog.txt
      args:
        chdir: somedir/
    
官方帮助文档 模块索引

模块索引

playbook 开头示例
- name: test
  hosts: temp2
  gather_facts: no
  become: yes
系统类
setup (收集远程主机的一些基本信息)
1. 选项 解释
filter 过滤
变量 解释
ansible_devices 仅显示磁盘设备信息。
ansible_default_ipv4.interface 默认IPv4接口
ansible_default_ipv4.address 默认IPv4地址
ansible_default_ipv4.gateway 默认IPv4网关
ansible_interfaces 所有接口
ansible_distribution 显示是什么系统,例:centos,suse等。
ansible_distribution_major_version 显示是系统主版本。
ansible_distribution_version 仅显示系统版本。
ansible_machine 显示系统类型,例:32位,还是64位。
ansible_eth0 仅显示eth0的信息。
ansible_hostname 仅显示主机名。
ansible_kernel 仅显示内核版本。
ansible_lvm 显示lvm相关信息。
ansible_memtotal_mb 显示系统总内存。
ansible_memfree_mb 显示可用系统内存。
ansible_memory_mb 详细显示内存情况。
ansible_swaptotal_mb 显示总的swap内存。
ansible_swapfree_mb 显示swap内存的可用内存。
ansible_mounts 显示系统磁盘挂载情况。
ansible_processor 显示cpu个数(具体显示每个cpu的型号)。
ansible_processor_vcpus 显示cpu个数(只显示总的个数)。
ansible_pkg_mgr 安装包管理器,如:yum,apt
group (组)
  1. 参数
    参数 解释
    <name> 指定要操作的组名称
    state present(默认);absent:删除
  2. 示例
      tasks:
        - name: Ensure group "somegroup" exists
          group:
            name: somegroup
            state: present
            gid: 2000
    
user (用户)
  1. 官方说明
  2. 参数
    参数 解释
    <name> 指定用户
    group 指定基本组
    gourps 指定附加组
    append 追加附加组,而不覆盖附加组
    shell 指定用户默认shell
    uid 指定UID
    expires 指定过期时间,值为unix时间戳获取命令:date -d 2018-12-31 +%s
    comment 注释
    state present(默认):存在;absent:删除
    remove 是否删除家目录
    password 指定加密后的密码.加密命令:import crypt; crypt.crypt(‘明文密码’)
    update_password always(默认):如果 password 参数设置的值与用户当前的加密过的密码字符串不一致,则直接更新用户的密码.on_create:如果 password参数设置的值与用户当前的加密过的密码字符串不一致,则不会更新用户的密码字符串,保持之前的密码设定。如果是新创建的用户,即使此参数设置为 on_create,也会将用户的密码设置为 password 参数对应的值。
    generate_ssh_key no(默认):生成 ssh 密钥对,如果已有则不操作
    ssh_key_file 自定义生成 ssh 私钥的路径和名称
    ssh_key_comment 注释信息,默认的注释信息为”ansible-generated on 远程主机的主机名”
    ssh_key_passphrase 在创建证书时,使用此参数设置私钥的密码
    ssh_key_type 设置密钥对的类型。默认密钥类型为 rsa
  3. 示例
    ---
    - name: Added a consultant whose account you want to expire
      user:
        name: tftp
        group: ftp
        state: present
        remove: yes
        shell: /usr/sbin/nologin
        uid: 1800
        comment: FTP user
        password: $1$hLGoLIZR$vmyUeES3TTHNgGgawgIw7/
    
  4. 安装passlib后可使用明文密码
  5. 安装passlib
    pip install passlib
    
  6. 示例
    - name: Added a consultant whose account you want to expire
      user:
        name: user1
        #group: user1
        state: present
        remove: yes
        shell: /usr/bin/bash
        uid: 1800
        comment: user
        password: "{{'password' | password_hash('sha512')}}"
    
service (服务)
  1. 参数
    参数 解释
    <name> 服务名
    state started:启动;stopped:停止;restarted:重启;reloaded:刷新
    enabled 是否开机自启
  2. 示例
    - name:      redhat | Ensuring DNSMasq Service is Enabled and Started
      service:
        name:    dnsmasq
        state:   started
        enabled: true
      become:    true
    
systemd (服务)
  1. 官方文档
  2. 参数
    参数 选项 默认 解释
    daemon_reexec 可选 no 重排序列
    daemon_reload 可选 no 重载配置
    enabled 可选 开机自启
    name 必选 服务名称
    state 可选 服务状态:reloaded,restarted,started,stopped)
  3. 示例
    - name: httpd
      systemd:
        name: httpd
        state: restarted
        daemon_reload: yes
        enabled: yes
    
    - name: restart service cron on centos, in all cases, also issue daemon-reload to pick up config changes
      systemd:
        state: restarted
        daemon_reload: yes
        name: crond
    
cron (计划任务)
  1. 参数
    参数 解释
    minute 分钟,默认*
    hour 小时,默认*
    day 天,默认*
    month 月,默认*
    weekday 周,默认*
    special_time @+值.reboot(重启后)、yearly(每年)、annually(每年,与yearly相同)、monthly(每月)、weekly(每周)、daily(每天)、hourly(每时)
    注意 以上全为默认时表示每秒执行一次
    user 用户,默认root
    job 执行的脚本或命令
    name 指定名称
    state 对name操作,absent表示删除
    disabled 是否禁用
    backup 是否备份
hostname (修改主机名)
  1. 官方说明
  2. 参数
    参数 解释
    name 定义主机名
    use 策略,如果未指定使用自动;generic,debian,sles,redhat,alpine,systemd,openrc,openbsd,solaris,freebsd
  3. 示例
    - hostname:
        name: web01
    
service (服务管理)
  1. 官方文档
  2. 参数
    参数 解释
    name 必选,服务名称
    enabled 可选,
    state 可选,reloaded,restarted,started,stopped
mount 挂载点
  1. 官方文档
  2. 参数
    参数 取值 解释
    backup 布尔,默认:no 创建一个包含时间戳信息的备份文件
    boot 布尔,默认:yes 确定文件系统是否应在引导时挂载,仅适用于 Solaris 系统
    fstab 字符串
    fstype 字符串 文件系统类型
    opts 字符串 挂载选项
    path 路径 挂载点的路径
    src 路径 要安装在path上的设备
    state 字符串,absent/mounted/present/unmounted/remounted
  3. 解释
    1. state
      1. mounted 在/etc/fstab中加入,并挂载,如果挂载点不存在就创建
      2. present 在/etc/fstab中加入,不触发挂载
      3. absent 在/etc/fstab中删除,解除挂载
      4. unmounted 不修改/etc/fstab,仅仅卸载
  4. 示例
    # Before 2.3, option 'name' was used instead of 'path'
    - name: Mount DVD read-only
    mount:
       path: /mnt/dvd
       src: /dev/sr0
       fstype: iso9660
       opts: ro,noauto
       state: present
    
    - name: Mount up device by label
    mount:
       path: /srv/disk
       src: LABEL=SOME_LABEL
       fstype: ext4
       state: present
    
    - name: Mount up device by UUID
    mount:
       path: /home
       src: UUID=b3e48f45-f933-4c8e-a700-22a159ec9077
       fstype: xfs
       opts: noatime
       state: present
    
    - name: Unmount a mounted volume
    mount:
       path: /tmp/mnt-pnt
       state: unmounted
    
    - name: Mount and bind a volume
    mount:
       path: /system/new_volume/boot
       src: /boot
       opts: bind
       state: mounted
       fstype: none
    
文件类
  1. 官方文档
synchronize(文件同步)
  1. 官方文档

  2. 参数

    参数 解释
    src 必选,源文件,可以是绝对或相对路径
    dest 必选,目标文件,可以是绝对或相对路径
    delete 可选,删除源是不存在的文件
    mode 可选,默认是push,push模式本地是源,pull模式远程是源
  3. 示例

    - name: sync files
      synchronize:
        src: /usr/local/src
        dest: /usr/local/src
        delete: yes
        mode: push
    
unarchive (解压缩)
  1. 官方文档
  2. 参数
    参数 解释
    src 必选,可以是本地路径,也可以是远程路径,如果是远程路径需要设置’copy=no’
    dest 必选,远程主机的目标路径
    copy 可选,yes:本地解压后传到远程主机;no:在远程主机上操作
    mode 可选,解压后的文件权限如0644
    remote_src boolean 可选,yes表示文件在远程主机上
  3. 示例
    - name: Unarchive a file that is already on the remote machine
      unarchive:
        src: "{{ aria2_dest }}"
        dest: /usr/local/src
        remote_src: yes
    
    - name: Unarchive a file that needs to be downloaded (added in 2.0)
      unarchive:
        src: https://example.com/example.zip
        dest: /usr/local/bin
        remote_src: yes
    
script (脚本)
  1. 参数
    参数 解释
    free_form 指定ansible端脚本
    chdir 执行脚本前,先进入的远程目录
    creates 指定文件存在就不执行脚本
    removes 指定文件不存在就不执行脚本
file (文件)
  1. 官方文档
  2. 参数
    参数 解释
    <path/dest/name> 指定文件
    state directory:目录;touch:文件;link:软连接;hard:硬连接;absent:删除
    src 指定软硬链接源
    force yes:强制创建连接
    owner 指定属主
    group 指定属组
    mode 权限,如775.suid:4700
    recurse yes:递规目录
  3. 示例
    - name: soft_link
      tags: link
      file:
        name: /usr/bin/aria2c
        state: link
        src: /home/program/aria2/bin/aria2c
    
    - name: Create a directory if it does not exist
      file:
        path: /etc/some_directory
        state: directory
        mode: '0755'
    
copy (复制到远程主机)
  1. 官方文档_2.9版
  2. 官方文档_最新版
  3. 目录如果不存在会报错
  4. 源目录中最后使用/表示复制目录和目录下的文件
  5. 参数
    参数 解释
    src 指定ansible端文件
    dest 远程主机端文件
    content 文件内容,与src参数冲突
    force 强制覆盖
    backup 文件内容不同时是否备份
    owner 属主
    group 属组
    mode 权限.如:0644,u+x
  6. 示例
    - name: Copy file with owner and permissions
    ansible.builtin.copy:
       src: /srv/myfiles/foo.conf
       dest: /etc/foo.conf
       owner: foo
       group: foo
       mode: '0644'
    
    - name: Copy file with owner and permission, using symbolic representation
    ansible.builtin.copy:
       src: /srv/myfiles/foo.conf
       dest: /etc/foo.conf
       owner: foo
       group: foo
       mode: u=rw,g=r,o=r
    
    - name: Another symbolic mode example, adding some permissions and removing others
    ansible.builtin.copy:
       src: /srv/myfiles/foo.conf
       dest: /etc/foo.conf
       owner: foo
       group: foo
       mode: u+rw,g-wx,o-rwx
    
    - name: Copy a new "ntp.conf" file into place, backing up the original if it differs from the copied version
    ansible.builtin.copy:
       src: /mine/ntp.conf
       dest: /etc/ntp.conf
       owner: root
       group: root
       mode: '0644'
       backup: yes
    
    - name: Copy a new "sudoers" file into place, after passing validation with visudo
    ansible.builtin.copy:
       src: /mine/sudoers
       dest: /etc/sudoers
       validate: /usr/sbin/visudo -csf %s
    
    - name: Copy a "sudoers" file on the remote machine for editing
    ansible.builtin.copy:
       src: /etc/sudoers
       dest: /etc/sudoers.edit
       remote_src: yes
       validate: /usr/sbin/visudo -csf %s
    
    - name: Copy using inline content
    ansible.builtin.copy:
       content: '# This file was moved to /etc/other.conf'
       dest: /etc/mine.conf
    
    - name: If follow=yes, /path/to/file will be overwritten by contents of foo.conf
    ansible.builtin.copy:
       src: /etc/foo.conf
       dest: /path/to/link  # link to /path/to/file
       follow: yes
    
    - name: If follow=no, /path/to/link will become a file and be overwritten by contents of foo.conf
    ansible.builtin.copy:
       src: /etc/foo.conf
       dest: /path/to/link  # link to /path/to/file
       follow: no
    
fetch (复制到ansible端)
  1. 官方文档_2,9版
  2. 官方文档_最新版
  3. 参数
    参数 解释
    src 远程主机文件
    dest ansible端文件
find (查找)
  1. 参数
    参数 解释
    <paths/path/name> 指定在哪个目录中查找文件,可以指定多个路径,路径间用逗号隔开
    recurse no(默认),不递规目录;yes:递规
    hidden no(默认),不含隐藏文件;yes:含隐藏文件
    file_type file(默认)文件;directory:目录;link:软连接;any:所有
    patterns 指定文件名称,支持通配符,正则需要下面参数
    use_regex 使patterns 参数支持正则表达式
    contains 根据文章内容查找文件,此参数的值为一个正则表达式
    age 根据时间范围查找文件,默认以文件的 mtime 为准与指定的时间进行对比.3d:3天前;-3d:3天内.可以使用的单位有秒(s)、分(m)、时(h)、天(d)、星期(w)。
    age_stamp mtime(默认),atime、ctime
    size 文件大小,3m:大于3M;-50k:小于50K;可以使用的单位有 t、g、m、k、b
    get_checksum 同时返回对应文件的 sha1校验码
replace (替换文件内容)
  1. 参数
    参数 解释
    <path> 指定要操作的文件
    regexp 指定python 正则表达式,文件中与正则匹配的字符串将会被替换。
    replace 指定最终要替换成的字符串
    backup 是否备份
lineinfile (修改文件内容)
  1. 官方文档
  2. 可以借助lineinfile模块,确保”某一行文本”存在于指定的文件中,或者确保从文件中删除指定的”文本” (即确保指定的文本不存在于文件中) ,还可以根据正则表达式,替换”某一行文本”。
  3. 参数
    参数 解释
    指定要操作的文件
    line 指定文本内容
    regexp 指定正则表达式,如果不止一行能够匹配正则,那么只有最后一个匹配正则的行才会被替换,但是如果指定的表达式没有匹配到任何一行,则插入到末尾
    state absent:删除;present:默认
    backrefs =yes时:line参数中就能对regexp参数中的分组进行后向引用,当正则没有匹配到任何的行时,则不会对文件进行任何操作
    insertafter EOF(默认):插入到末尾;值设置为正则表达式,表示将文本插入到匹配到正则的行之后,,如果正则没有匹配到任何行,则插入到文件末尾,当使用backrefs参数时,此参数会被忽略
    insertbefore BOF(默认):插入到开头;值设置为正则表达式,表示将文本插入到匹配到正则的行之前,如果正则没有匹配到任何行,则插入到文件末尾,当使用backrefs参数时,此参数会被忽略。
    backup 是否在修改文件之前对文件进行备份
    create 当要操作的文件并不存在时,是否创建对应的文件
  4. 示例
    - name: Configure Apache.
      lineinfile:
        dest: "{{ apache_server_root }}/conf/{{ apache_daemon }}.conf"
        regexp: "{{ item.regexp }}"
        line: "{{ item.line }}"
        state: present
      with_items: "{{ apache_ports_configuration_items }}"
      notify: restart apache
    
blockinfile (插入文本块)
  1. 官方文档
  2. blockinfile 模块可以帮助我们在指定的文件中插入”一段文本”,这段文本是被标记过的,也就是,我们在这段文本上做了记号,以便在以后的操作中可以通过”标记”找到这段文本,然后修改或者删除它
  3. 参数
    参数 解释
    <path> 指定要操作的文件
    block/content 指定我们想要操作的那”一段文本”
    marker 指定标记.ANSIBLE MANAGED BLOCK(默认);#{mark}test:表示# BEGIN test和# END test
    state present(默认):更新;absent:表示从文件中删除对应标记的段落
    insertafter EOF(默认):在末尾插入;使用正则表达式(python正则),表示将文本插入在符合正则表达式的行的前面;如果有多行文本都能够匹配对应的正则表达式,则以最后一个满足正则的行为准
    backup 是否备份
    create 文件不存在时是否创建
  4. 实例
    1. 在文件末尾添加
    - name: modify source for China
      blockinfile:
        path: /etc/pacman.d/mirrorlist
        block: |
          #清华大学源
          Server = https://mirrors.tuna.tsinghua.edu.cn/archlinux/$repo/os/$arch
    
    1. 在文件开头添加 增加如下
    - name: modify source for China
      blockinfile:
        path: /etc/pacman.d/mirrorlist
        insertbefore: BOF
        block: |
          #清华大学源
          Server = https://mirrors.tuna.tsinghua.edu.cn/archlinux/$repo/os/$arch
    
template (根据模板生成文件)
  1. 官方文档

  2. 参数

    参数 解释
    src 必选,源路径
    dest 必选,目标路径
  3. 示例

    - name: Add apache vhosts configuration.
      template:
        src: "{{ apache_vhosts_template }}"
        dest: "{{ apache_conf_path }}/{{ apache_vhosts_filename }}"
        owner: root
        group: root
        mode: 0644
      notify: restart apache
      when: apache_create_vhosts | bool
    
包管理
yum (软件包)
  1. 官方说明
  2. 参数
    参数 解释
    <name> 需要管理的软件包
    state present(installed):如果装了就不装,如果没装就安装;latest:安装最新版;absent(removed):删除
    disable_gpg_check 禁用公钥gpg验证,默认值是no,即验证
    enablerepo 指定临时启用的软件源
    disablerepo 指定临时禁用的软件源
  3. 示例
      tasks:
        - name: install git 
          yum:
            name: git
            state: present
    
  4. 安装多个软件示例
      tasks:
        - name: install git httpd
          yum:
            name: "git,httpd,fping"
            state: present
    
  5. 安装多个软件示例2
      tasks:
        - name: ensure a list of packages installed
          yum:
            name: "{{ packages }}"
          vars:
            packages:
            - httpd
            - httpd-tools
    
package (通用包管理)
  1. 官方说明
  2. 参数
    参数 解释
    name 必选,软件包名称
    state 必选,状态,present,absent,latest
    use 可选,默认:auto
  3. 示例
    - name: ensure a list of packages installed
      package:
        name: "{{ packages }}"
        state: present
      vars:
        packages:
        - httpd
        - httpd-tools
    
    - name: install the latest version of Apache and MariaDB
      package:
        name:
          - httpd
          - mariadb-server
        state: latest  
    
pacman (ArchLinux)
  1. 官方说明
  2. 参数
    参数 解释
    name 软件包名称
    state 状态,present,absent,latest
    upgrade 是否升级
  3. 示例
    1. pacman -Syu
    - name: Run the equivalent of "pacman -Syu" as a separate step
      pacman:
        update_cache: yes
        upgrade: yes
    
    1. 安装软件包
    - name: install Archlinux packages
      pacman:
        name:
          - sudo
          - archlinuxcn-keyring
          - xorg-server 
    
yum_repository (yum仓库)
  1. 参数
    参数 解释
    <name> 仓库ID
    baseurl 仓库的 baseurl
    description 注释
    file 配置文件名称即.repo的前缀,默认为仓库ID
    enabled 是否启用,默认启用
    gpgcheck gpg验证,默认为no即不验证
    gpgcakey 指定gpg验证的公钥
    state present(默认),absent表示删除
网络安全类
Net Tools 网络工具
get_url (下载文件)
  1. 官方文档

  2. 参数

    参数 解释
    dest path 必选,将文件下载到的绝对路径,如果dest是目录,则将使用服务器提供的文件名
    url string 必选,`HTTP, HTTPS, or FTP URL in the form (http
    backup boolean 可选,创建备份文件
    checksum string 可选,校验
    force boolean 可选,强制覆盖
    group string 可选,属组
    owner string 可选,属主
    mode string 可选,权限码如0644
  3. 示例

    - name: Download file with check (md5)
      get_url:
        url: http://example.com/path/file.conf
        dest: /etc/foo.conf
        checksum: md5:66dffb5228a211e61d6d7ef4a86f5758
    
firewalld (防火墙)
  1. 官方文档
  2. 参数
    参数 解释
    state 必选,absent,disabled,enabled,present
    interface 可选,从一个zone中增加或删除的接口
    immediate 可选,默认no,如果设置为永久,应立即应用此配置
    masquerade 可选,允许或禁用从一个zones中
    permanent 可选,no,yes.
    port 可选
    rich_rule 可选,富规则
    service 可选,
    source 可选,
    timeout 可选,
    zone 可选,
  3. 示例
    - firewalld:
        port: 161-162/udp
        permanent: yes
        state: enabled
    
Utilities (实用工具)
debug (调试信息)
  1. 官方2.9文档
  2. 参数
    参数 解释
    msg string 可选,显示定义的信息
    var string
    verbosity int
  3. 示例
    # Example that prints the loopback address and gateway for each host
    - debug:
       msg: System {{ inventory_hostname }} has uuid {{ ansible_product_uuid }}
    
    - debug:
       msg: System {{ inventory_hostname }} has gateway {{ ansible_default_ipv4.gateway }}
    when: ansible_default_ipv4.gateway is defined
    
    # Example that prints return information from the previous task
    - shell: /usr/bin/uptime
    register: result
    
    - debug:
       var: result
       verbosity: 2
    
    - name: Display all variables/facts known for a host
       debug:
       var: hostvars[inventory_hostname]
       verbosity: 4
    
    # Example that prints two lines of messages, but only if there is an environment value set
    - debug:
       msg:
       - "Provisioning based on YOUR_KEY which is: {{ lookup('env', 'YOUR_KEY') }}"
       - "These servers were built using the password of '{{ password_used }}'. Please retain this for later use."
    
fail (失败,停止后续)
  1. 官方文档
  2. 参数
    参数 解释
    msg string 可选,显示定义的信息
  3. 示例
    - name: "fail if Operating System is not CentOS-7.x"
      fail: msg="Operating System {{ ansible_distribution }}-{{ ansible_distribution_version }} not supported"
      when: (ansible_distribution != "CentOS" and ansible_distribution != "RedHat") or ansible_distribution_major_version != "7"
    
Source Control modules(源代码控制模块)
git
  1. 官方文档
  2. 参数
    参数 解释
    dest 必选,目的路径
    repo 必选,源地址
  3. 示例
    # Example read-write git checkout from github
    - git:
        repo: git@github.com:mylogin/hello.git
        dest: /home/mylogin/hello
    

playbook示例

lineinfile 替换文件内容
---
- hosts: temp
  remote_user: root
  sudo_user: root
  tasks:
    - name:
      lineinfile:
        dest: "/etc/pam.d/vsftpd"
        regexp: 'pam_shells.so'
        line: '#auth       required     pam_shells.so'
        backup: yes

Ansible 常见问题

指定客户端Python的位置
  1. 全局设置:修改 ansible.cfg
    interpreter_python = /usr/bin/python3  <<< 在 [defaults] 部分添加选项,指定 Python 解释器
    
  2. 针对设备(组)单独设置:修改 hosts 文件
    ansible_python_interpreter=/usr/bin/python3  <<< 在 [xxx:vars] 部分添加属性,指定 Python 解释器
    
  3. 手工指定:-e 选项
    ansible ASA -m ping -o -e 'ansible_python_interpreter=/usr/bin/python3'
    

版权声明:本文为博主作者:liujinbao8000原创文章,版权归属原作者,如果侵权,请联系我们删除!

原文链接:https://blog.csdn.net/liujinbao8000/article/details/137814399

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
社会演员多的头像社会演员多普通用户
上一篇 2024年4月22日
下一篇 2024年4月22日

相关推荐