Ansible篇-ansible-playbook模块使用详解

1 引言

本篇笔记的目的是总结Ansible模块的使用方法,会不定时更新。
下面是官方的链接:
https://docs.ansible.com/ansible/latest/modules/modules_by_category.html

2 yum

用于软件安装、升级和卸载
https://docs.ansible.com/ansible/latest/modules/yum_repository_module.html#yum-repository-module

#常用:
disable_gpg_check     安装之前是否检查gpg_key,yes做检查,no不做检查
enablerepo                  指定repo源,多个repo则用逗号隔开
name                           软件名称,支持带版本(如name-1.0),支持软件组安装
skip_broken                 跳过异常软件节点
state                            包括:installed (present)、 latest 、removed(absent)
update_cache             更新缓存,只有state=present/latest时生效
  • 例 1
- name: ensure a list of packages installed
yum:
name: "{{ packages }}"
vars:
packages:
- httpd
- httpd-tools

- name: install the latest version of Apache from the testing repo
yum:
name: httpd
enablerepo: testing
state: present

- name: install one specific version of Apache
yum:
name: httpd-2.2.29-1.4.amzn1
state: present

- name: upgrade all packages
yum:
name: '*'
state: latest

- name: upgrade all packages, excluding kernel & foo related packages
yum:
name: '*'
state: latest
exclude: kernel*,foo*

- name: install the nginx rpm from a remote repo
yum:
name: http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm
state: present

- name: install nginx rpm from a local file
yum:
name: /usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm
state: present
  • 例 2
- name: install the 'Development tools' package group
yum:
name: "@Development tools"
state: present

- name: install the 'Gnome desktop' environment group
yum:
name: "@^gnome-desktop-environment"
state: present
  • 例 3
- name: List ansible packages and register result to print with debug later.
yum:
list: ansible
register: result

- name: Install package with multiple repos enabled
yum:
name: sos
enablerepo: "epel,ol7_latest"

- name: Install package with multiple repos disabled
yum:
name: sos
disablerepo: "epel,ol7_latest"

- name: Install a list of packages
yum:
name:
- nginx
- postgresql
- postgresql-server
state: present

- name: Download the nginx package but do not install it
yum:
name:
- nginx
state: latest
download_only: true

3 command

https://docs.ansible.com/ansible/latest/modules/command_module.html#command-module

chdir			在执行命令前,进入到指定目录中
creates		判断指定文件是否存在,如果存在,不执行后面的操作
removes		判断指定文件是否存在,如果存在,执行后面的操作
free_form		必须要输入一个合理的命令
cmd				指定将要执行的命令
argv				把传入的命令作为列表而不是字符串
warn			启动(yes)或者禁用(no)任务的警告
  • 例子
- name: return motd to registered var
  command: cat /etc/motd
  register: mymotd

- name: Run command if /path/to/database does not exist (without 'args' keyword).
  command: /usr/bin/make_database.sh db_user db_name creates=/path/to/database

# 'args' is a task keyword, passed at the same level as the module
- name: Run command if /path/to/database does not exist (with 'args' keyword).
  command: /usr/bin/make_database.sh db_user db_name
  args:
    creates: /path/to/database

# 'cmd' is module parameter
- name: Run command if /path/to/database does not exist (with 'cmd' parameter).
  command:
    cmd: /usr/bin/make_database.sh db_user db_name
    creates: /path/to/database

- name: Change the working directory to somedir/ and run the command as db_owner if /path/to/database does not exist.
  command: /usr/bin/make_database.sh db_user db_name
  become: yes
  become_user: db_owner
  args:
    chdir: somedir/
    creates: /path/to/database

# 'argv' is a parameter, indented one level from the module
- name: Use 'argv' to send a command as a list - leave 'command' empty
  command:
    argv:
      - /usr/bin/make_database.sh
      - Username with whitespace
      - dbname with whitespace

- name: safely use templated variable to run command. Always use the quote filter to avoid injection issues.
  command: cat {{ myfile|quote }}
  register: myoutput

4 shell

https://docs.ansible.com/ansible/latest/modules/shell_module.html#shell-module
类似command模块升级版,是万能模块!
参数和command模块一样!

  • 例子
- name: Execute the command in remote shell; stdout goes to the specified file on the remote.
  shell: somescript.sh >> somelog.txt

- name: Change the working directory to somedir/ before executing the command.
  shell: somescript.sh >> somelog.txt
  args:
    chdir: somedir/

# You can also use the 'args' form to provide the options.
- name: This command will change the working directory to somedir/ and will only run when somedir/somelog.txt doesn't exist.
  shell: somescript.sh >> somelog.txt
  args:
    chdir: somedir/
    creates: somelog.txt

# You can also use the 'cmd' parameter instead of free form format.
- name: This command will change the working directory to somedir/.
  shell:
    cmd: ls -l | grep log
    chdir: somedir/

- name: Run a command that uses non-posix shell-isms (in this example /bin/sh doesn't handle redirection and wildcards together but bash does)
  shell: cat < /tmp/*txt
  args:
    executable: /bin/bash

- name: Run a command using a templated variable (always use quote filter to avoid injection)
  shell: cat {{ myfile|quote }}

# You can use shell to run other executables to perform actions inline
- name: Run expect to wait for a successful PXE boot via out-of-band CIMC
  shell: |
    set timeout 300
    spawn ssh admin@{{ cimc_host }}

    expect "password:"
    send "{{ cimc_password }}\n"

    expect "\n{{ cimc_name }}"
    send "connect host\n"

    expect "pxeboot.n12"
    send "\n"

    exit 0
  args:
    executable: /usr/bin/expect
  delegate_to: localhost

# Disabling warnings
- name: Using curl to connect to a host via SOCKS proxy (unsupported in uri). Ordinarily this would throw a warning.
  shell: curl --socks5 localhost:9000 http://www.ansible.com
  args:
    warn: no

5 copy

https://docs.ansible.com/ansible/latest/modules/copy_module.html#copy-module
主要用于将管理机上的数据信息传送给多台主机

src				指定将本地管理主机的什么数据信息进行远程复制
dest				必须使用这个参数。将数据复制到远程节点的路径信息。
backup		默认数据复制到远程主机,会覆盖原有文件,=yes 则将源文件进行备份
content		在文件中添加信息
group			文件数据复制到远程主机,设置文件属组用户信息
owner			文件数据复制到远程主机,设置文件属主用户信息
mode			文件数据复制到远程主机,设置数据的权限,如0644,必须加上黏贴位的权限值。
remote_src	如果设置为yes,表示将远程主机上的数据进行移动操作如果设置为no, 表示将管理主机上的数据进行分发操作
  • 例子
- name: Copy file with owner and permissions
  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
  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
  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
  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
  copy:
    src: /mine/sudoers
    dest: /etc/sudoers
    validate: /usr/sbin/visudo -csf %s

- name: Copy a "sudoers" file on the remote machine for editing
  copy:
    src: /etc/sudoers
    dest: /etc/sudoers.edit
    remote_src: yes
    validate: /usr/sbin/visudo -csf %s

- name: Copy using inline content
  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
  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
  copy:
    src: /etc/foo.conf
    dest: /path/to/link  # link to /path/to/file
    follow: no

6 file

实现创建/删除文件信息 对数据权限进行修改
https://docs.ansible.com/ansible/latest/modules/file_module.html#file-module

dest/path/name	将数据复制到远程节点的路径信息
src						指定将本地管理主机的什么数据信息进行远程复制
group					文件数据复制到远程主机,设置文件属组用户信息
owner					文件数据复制到远程主机,设置文件属主用户信息	
mode					文件数据复制到远程主机,设置数据的权限,如0644,须添加黏贴位值
state					absent将数据进行删除,directory创建一个空目录信息,file查看指定目录信息是否存在,touch创建一个空文件信息,hard/link创建链接文件

  • 例子
- name: Change file ownership, group and permissions
  file:
    path: /etc/foo.conf
    owner: foo
    group: foo
    mode: '0644'

- name: Give insecure permissions to an existing file
  file:
    path: /work
    owner: root
    group: root
    mode: '1777'

- name: Create a symbolic link
  file:
    src: /file/to/link/to
    dest: /path/to/symlink
    owner: foo
    group: foo
    state: link

- name: Create two hard links
  file:
    src: '/tmp/{{ item.src }}'
    dest: '{{ item.dest }}'
    state: hard
  loop:
    - { src: x, dest: y }
    - { src: z, dest: k }

- name: Touch a file, using symbolic modes to set the permissions (equivalent to 0644)
  file:
    path: /etc/foo.conf
    state: touch
    mode: u=rw,g=r,o=r

- name: Touch the same file, but add/remove some permissions
  file:
    path: /etc/foo.conf
    state: touch
    mode: u+rw,g-wx,o-rwx

- name: Touch again the same file, but dont change times this makes the task idempotent
  file:
    path: /etc/foo.conf
    state: touch
    mode: u+rw,g-wx,o-rwx
    modification_time: preserve
    access_time: preserve

- name: Create a directory if it does not exist
  file:
    path: /etc/some_directory
    state: directory
    mode: '0755'

- name: Update modification and access time of given file
  file:
    path: /etc/some_file
    state: file
    modification_time: now
    access_time: now

- name: Set access time based on seconds from epoch value
  file:
    path: /etc/another_file
    state: file
    access_time: '{{ "%Y%m%d%H%M.%S" | strftime(stat_var.stat.atime) }}'

- name: Recursively change ownership of a directory
  file:
    path: /etc/foo
    state: directory
    recurse: yes
    owner: foo
    group: foo

- name: Remove file (delete file)
  file:
    path: /etc/foo.txt
    state: absent

- name: Recursively remove directory
  file:
    path: /etc/foo
    state: absent

7 service

用于管理服务运行状态
https://docs.ansible.com/ansible/latest/modules/service_module.html#service-module

enabled		no/yes,设置服务是否开机自启动 如果参数不指定,原有服务开机自启动状态进行保留
name			设置要启动/停止服务名称
state			reloaded平滑重启,restarted重启,started启动,stopped停止
  • 例子
- name: Start service httpd, if not started
  service:
    name: httpd
    state: started

- name: Stop service httpd, if started
  service:
    name: httpd
    state: stopped

- name: Restart service httpd, in all cases
  service:
    name: httpd
    state: restarted

- name: Reload service httpd, in all cases
  service:
    name: httpd
    state: reloaded

- name: Enable service httpd, and not touch the state
  service:
    name: httpd
    enabled: yes

- name: Start service foo, based on running process /usr/bin/foo
  service:
    name: foo
    pattern: /usr/bin/foo
    state: started

- name: Restart network service for interface eth0
  service:
    name: network
    state: restarted
    args: eth0

8 fetch

抓取文件到管理机上
https://docs.ansible.com/ansible/latest/modules/fetch_module.html#fetch-module

src		是必选参数,要获取的远程系统上的文件,必须是文件,而不是目录
dest		用于保存文件的目录
  • 例子
- name: Store file into /tmp/fetched/host.example.com/tmp/somefile
  fetch:
    src: /tmp/somefile
    dest: /tmp/fetched

- name: Specifying a path directly
  fetch:
    src: /tmp/somefile
    dest: /tmp/prefix-{{ inventory_hostname }}
    flat: yes

- name: Specifying a destination path
  fetch:
    src: /tmp/uniquefile
    dest: /tmp/special/
    flat: yes

- name: Storing in a path relative to the playbook
  fetch:
    src: /tmp/uniquefile
    dest: special/prefix-{{ inventory_hostname }}
    flat: yes

9 cron

定时任务模块
https://docs.ansible.com/ansible/latest/modules/cron_module.html#cron-module

minute/hour/day/month/weekday	和设置时间信息相关参数
job			和设置定时任务相关参数
name		设置定时任务注释信息
state		absent删除指定定时任务
disabled	yes将指定定时任务进行注释,no取消注释
  • 例子
- name: Ensure a job that runs at 2 and 5 exists. Creates an entry like "0 5,2 * * ls -alh > /dev/null"
  cron:
    name: "check dirs"
    minute: "0"
    hour: "5,2"
    job: "ls -alh > /dev/null"

- name: 'Ensure an old job is no longer present. Removes any job that is prefixed by "#Ansible: an old job" from the crontab'
  cron:
    name: "an old job"
    state: absent

- name: Creates an entry like "@reboot /some/job.sh"
  cron:
    name: "a job for reboot"
    special_time: reboot
    job: "/some/job.sh"

- name: Creates an entry like "PATH=/opt/bin" on top of crontab
  cron:
    name: PATH
    env: yes
    job: /opt/bin

- name: Creates an entry like "APP_HOME=/srv/app" and insert it after PATH declaration
  cron:
    name: APP_HOME
    env: yes
    job: /srv/app
    insertafter: PATH

- name: Creates a cron file under /etc/cron.d
  cron:
    name: yum autoupdate
    weekday: "2"
    minute: "0"
    hour: "12"
    user: root
    job: "YUMINTERACTIVE=0 /usr/sbin/yum-autoupdate"
    cron_file: ansible_yum-autoupdate

- name: Removes a cron file from under /etc/cron.d
  cron:
    name: "yum autoupdate"
    cron_file: ansible_yum-autoupdate
    state: absent

- name: Removes "APP_HOME" environment variable from crontab
  cron:
    name: APP_HOME
    env: yes
    state: absent

10 template

11 debug

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章