Ansible 常见用法

弄了近一个月的Ansible脚本部署工作,做了一些整理,列出了我常用的一些指令,与模块用法。Ansible 是个好东西,就是相关资料不多,列出这些基本模块用法可以覆盖大部分工作了。

安装

推荐包管理器(yum)

yum install -y ansible

# 在被控节点需要安装,(文件传输)
yum install -y libselinux-python

指令

Ad-Hoc

# 在所有主机上Do shell
ansible -i hosts all -m shell -a "systemctl restart docker"
# 信息采集+条件过滤
ansible nodes -m setup -a "filter=ansible_local"
# 限制主机执行+外部参数
ansible nodes -l 192.168.1.211 -m setup -a "filter=ansible_local" --extra-vars "ansible_sshpass=666"

常用模块

文件操作

# copy
- name: Write docker daemon.conf file
  copy: src=daemon.json dest=/etc/docker/daemon.json mode=0440

# file
- name: Create config file directory
  file: path={{ flannel_config_dir }} state=directory

- name: Verify docker config files exists
  file: path={{ docker_config_dir }}/{{ item }} state=touch

- name: Clean up the flannel config file
  file: path=/tmp/flannel-config.json state=absent
  # 以下两个常组合使用
  run_once: true
  delegate_to: "{{ groups['etcd'][0] }}"

# template
- name: replace repo
  template:
    src: offline.repo.j2
    dest: /etc/yum.repos.d/offline.repo

# lineinfile 用于配置文件修改
- name: Install http_proxy into docker(-network)
  lineinfile: dest={{ docker_config_net }} regexp="^{{ docker_env_export }}http_proxy=" line="{{docker_env_export}}http_proxy={{ http_proxy }}"
  when: http_proxy is defined
  notify:
    - restart docker
  tags: configure

命令

# shell
- name: Create CA cert
  shell: "cfssl gencert -initca ca-csr.json | cfssljson -bare ca -"
  args:
    chdir: "{{ etcd_cert_tempdir }}/"
    # 当下面路径存在时不执行shell
    creates: "{{ etcd_ca_file }}"
  when: inventory_hostname == groups['masters'][0]

# command
- name: reload systemd
  command: systemctl --system daemon-reload

# script
- name: Detect docker version
  script: detect-docker-version.sh
  register: docker_version

System

# debug
- name: Detected version
  debug:
    msg: "{{ docker_version.stdout | regex_replace('(\\r\\n)','') }}"

# service
- name: stop docker
  service: name=docker state=stopped
    
# yum_repository
- name: Setup base repo
  yum_repository:
    name: offline
    description: offline
    baseurl: http://{{ offline_yum_repo }}/base
    enabled: yes
    gpgcheck: no
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • ansible 系统架构 ansible简介ansible是新出现的自动化运维工具,ansible是一个配置管理和...
    运维阿文阅读 9,722评论 1 52
  • 本文主要内容均收集于网络上的博文资料,仅以此文作为学习总结。BTW,目前Ansible对python3的支持还不是...
    qiuyi943阅读 18,370评论 1 15
  • 第3章 Ansible Ad-Hoc命令集 在前面章节中,为大家介绍了掌握Ansible所必须了解的基础,如变量命...
    stanleylst阅读 640评论 0 0
  • 蛇嘴中含着的猩气,与这不知名的红色的清香,显然后者更讨人喜爱。 男人和女人,心里略作对比,思虑到,吃了吧,这困扰我...
    雨拾青阶阅读 1,276评论 0 0
  • 很喜欢清晨漫步湖对面的广场,观水中几条金黄的小鱼自由自在的游来游去,摆动尾巴,瞬间消失在远处的水面。在霜降时节,观...
    心之山水阅读 486评论 0 0