自动化_Ansible学习笔记

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
    
主配置文件优先级
优先级位置说明
1ANSIBLE_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
    -Ksudo密码
    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>指定要操作的组名称
    statepresent(默认);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注释
    statepresent(默认):存在;absent:删除
    remove是否删除家目录
    password指定加密后的密码.加密命令:import crypt; crypt.crypt(‘明文密码’)
    update_passwordalways(默认):如果 password 参数设置的值与用户当前的加密过的密码字符串不一致,则直接更新用户的密码.on_create:如果 password参数设置的值与用户当前的加密过的密码字符串不一致,则不会更新用户的密码字符串,保持之前的密码设定。如果是新创建的用户,即使此参数设置为 on_create,也会将用户的密码设置为 password 参数对应的值。
    generate_ssh_keyno(默认):生成 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>服务名
    statestarted:启动;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>指定文件
    statedirectory:目录;touch:文件;link:软连接;hard:硬连接;absent:删除
    src指定软硬链接源
    forceyes:强制创建连接
    owner指定属主
    group指定属组
    mode权限,如775.suid:4700
    recurseyes:递规目录
  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远程主机文件
    destansible端文件
find (查找)
  1. 参数
    参数解释
    <paths/path/name>指定在哪个目录中查找文件,可以指定多个路径,路径间用逗号隔开
    recurseno(默认),不递规目录;yes:递规
    hiddenno(默认),不含隐藏文件;yes:含隐藏文件
    file_typefile(默认)文件;directory:目录;link:软连接;any:所有
    patterns指定文件名称,支持通配符,正则需要下面参数
    use_regex使patterns 参数支持正则表达式
    contains根据文章内容查找文件,此参数的值为一个正则表达式
    age根据时间范围查找文件,默认以文件的 mtime 为准与指定的时间进行对比.3d:3天前;-3d:3天内.可以使用的单位有秒(s)、分(m)、时(h)、天(d)、星期(w)。
    age_stampmtime(默认),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指定正则表达式,如果不止一行能够匹配正则,那么只有最后一个匹配正则的行才会被替换,但是如果指定的表达式没有匹配到任何一行,则插入到末尾
    stateabsent:删除;present:默认
    backrefs=yes时:line参数中就能对regexp参数中的分组进行后向引用,当正则没有匹配到任何的行时,则不会对文件进行任何操作
    insertafterEOF(默认):插入到末尾;值设置为正则表达式,表示将文本插入到匹配到正则的行之后,,如果正则没有匹配到任何行,则插入到文件末尾,当使用backrefs参数时,此参数会被忽略
    insertbeforeBOF(默认):插入到开头;值设置为正则表达式,表示将文本插入到匹配到正则的行之前,如果正则没有匹配到任何行,则插入到文件末尾,当使用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
    statepresent(默认):更新;absent:表示从文件中删除对应标记的段落
    insertafterEOF(默认):在末尾插入;使用正则表达式(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>需要管理的软件包
    statepresent(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是否启用,默认启用
    gpgcheckgpg验证,默认为no即不验证
    gpgcakey指定gpg验证的公钥
    statepresent(默认),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'
    
  • 13
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Ansible 是一种自动化运维工具,可以用于管理和配置多个计算机系统。它使用 Python 编写,并且提供了一个简单易用的 DSL(Domain Specific Language)来描述系统配置和部署任务。使用 Ansible,可以通过编写 Playbooks 来定义系统配置和任务,然后通过 SSH 协议远程执行这些任务。 在 Python 中使用 Ansible,可以使用 Ansible 的 Python API 来编写自动化脚本。这个 API 提供了一系列的模块和方法,可以用于远程执行命令、复制文件、安装软件等操作。你可以通过在 Python 脚本中导入 Ansible 的相关模块,然后调用相应的方法来完成自动化运维任务。 以下是一个简单的示例代码,演示了如何使用 Ansible 的 Python API 来执行远程命令: ```python from ansible import context from ansible.playbook import Playbook from ansible.executor.playbook_executor import PlaybookExecutor # 设置 Ansible 的上下文 context.CLIARGS = { 'listtags': False, 'listtasks': False, 'listhosts': False, 'syntax': False, 'connection': 'ssh', 'module_path': None, 'forks': 100, 'remote_user': 'root', 'private_key_file': None, 'ssh_common_args': None, 'ssh_extra_args': None, 'sftp_extra_args': None, 'scp_extra_args': None, 'become': None, 'become_method': None, 'become_user': None, 'verbosity': None, 'check': False, 'start_at_task': None, } # 定义 Playbook 的路径和主机列表 playbook_path = '/path/to/playbook.yaml' host_list = '/path/to/hosts' # 创建 Playbook 对象和执行器 playbook = Playbook.load(playbook_path) executor = PlaybookExecutor( playbooks=[playbook], inventory=host_list, variable_manager=playbook._variable_manager, loader=playbook._loader, ) # 执行 Playbook executor.run() ``` 上面的代码中,我们首先设置了 Ansible 的上下文,然后定义了 Playbook 的路径和主机列表。接着创建了 Playbook 对象和执行器,并最终执行了 Playbook。 需要注意的是,上述示例代码中的相关路径和参数需要根据实际情况进行修改。另外,为了运行该示例代码,你需要安装 ansible-python 包。可以使用 pip 命令进行安装: ``` pip install ansible ``` 希望这个示例能帮助到你开始使用 Ansible 进行自动化运维的 Python 编程。如果有更多问题,请随时提问!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liujinbao8000

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值