Ansible Cheatsheet

Summary based on Ansible Tutorial

Basic

  • default inventory file:

/etc/ansible/hosts

  • ping server (test connection)

ansible -m ping localhost
ansible -m ping test-ansible
ansible -m ping all
ansible test-ansible -m ping -s -k -u vagrant

  • m ping: Use the "ping" module, which simply runs the ping command and returns the results
  • s: Use "sudo" to run the commands
  • k: Ask for a password rather than use key-based authentication
  • u vagrant: Log into servers using user vagrant

Module

  • Ansible modules ensure indempotence - we can run the same Tasks over and over without affecting the final result.

ansible all -s -m shell -a 'apt-get install nginx'

  • For installing software on Debian/Ubuntu servers, the "apt" module will run the same command, but ensure idempotence.

ansible all -s -m apt -a 'pkg=nginx state=installed update_cache=true'


Playbook

Sample playbook:

---
- hosts: local
  vars:
   - docroot: /var/www/serversforhackers.com/public
  tasks:
   - name: Add Nginx Repository
     apt_repository: repo='ppa:nginx/stable' state=present
     register: ppastable

   - name: Install Nginx
     apt: pkg=nginx state=installed update_cache=true
     when: ppastable|success
     register: nginxinstalled
     notify:
      - Start Nginx

   - name: Create Web Root
     when: nginxinstalled|success
     file: dest={{ '{{' }} docroot {{ '}}' }} mode=775 state=directory owner=www-data group=www-data
     notify:
      - Reload Nginx

  handlers:
   - name: Start Nginx
     service: name=nginx state=started

    - name: Reload Nginx
      service: name=nginx state=reloaded
  • Ansible debug
# 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

- 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
  • Task
  • Register
  • Handler
  • Variable
  • Hosts

We can run the playbook like this:

ansible-playbook -s nginx.yml

Or, as I ran on my Vagrant machine:

ansible-playbook -s -k -u vagrant nginx.yml


Ansible and AWS integration

https://www.ansible.com/aws
http://docs.ansible.com/ansible/guide_aws.html

Ansible server communication setting

  • Ansible use ssh to communicate with server. Before trying Ansible ping, we should first make sure we can ssh into server.
  • For AWS, that means setup configure file in .ssh/config, .aws/credentials, .aws/config, and have correct .pem key.
  • Inventory file (default to be /etc/ansible/hosts)
[test-ansible]
test-ansible-1
test-ansible-2
test-ansible-3

[local]
127.0.0.1
  • Test ansible can connect to inventory server:

ansible -m ping test-ansible
ansible all -m ping # ping all machine on default inventory


Ansible Galaxy and Role

https://galaxy.ansible.com/intro#download
http://docs.ansible.com/ansible/galaxy.html#list-installed-roles (better)

目录名同角色名
目录结构固定:
files静态文件
templates jinjia2模板文件
tasks 至少有main.yml文件,定义各tasks
handlers至少有main.yml文件,定义各handlers
vars至少有main.yml文件,定义变量
meta定义依赖关系等信息

Download Roles

$ ansible-galaxy install username.rolename

Download multiple Roles

$ ansible-galaxy install -r install_roles.yml

You can specify a particular directory where you want the downloaded roles to be placed:

$ ansible-galaxy install username.role -p ~/Code/ansible_roles/

List installed Roles

ansible-galaxy list

Search for Roles

ansible-galaxy search elasticsearch --author geerlingguy

# install_roles.yml

# from galaxy
- src: yatesr.timezone

# from github
- src: https://github.com/bennojoy/nginx

# from github installing to a relative path
- src: https://github.com/bennojoy/nginx
  path: vagrant/roles/

# from github, overriding the name and specifying a specific tag
- src: https://github.com/bennojoy/nginx
  version: master
  name: nginx_role

Create a Role

$ ansible-galaxy init role_name

This creates the directory structure needed for organizing your code:

README.md
.travis.yml
defaults/
    main.yml
files/
handlers/
    main.yml
meta/
    main.yml
templates/
tests/
    inventory
    test.yml
vars/
    main.yml

Components for Ansible Role

ReadMe file

# README.md
# Ansible Role: Acme 2.x

An Ansible role that installs Acme 2.x on Centos 7.x

## Requirements
If you are using SSL/TLS, you will need to provide your own certificate and key files. You can generate a self-signed certificate with a command like `openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout example.key -out example.crt`.

## Role Variables
Available variables are listed below, along with default values:

    acme_listen_port: 80
    acme_listen_port_ssl: 443

## Dependencies
- username.iptables - configure the firewall and block all ports except those needed for the web server and ssh access.
- username.common - perform common server configuration

## Example Playbook

    - hosts: webservers
      roles:
        - { role: username.acme }

## License

MIT

Variable

  • Q: where to put these ??

为了方便让playbooks配置使用。

[Hvariables]

host1 http_port=80
host2 http_port=8080

定义组变量:

组变量作用于组的所有成员

[Gvariable]
host1
host2
[Gvariable:vars]
ftp_server = ftp.fuchao.com
web_server = www.fuchao.com

Inventory

The “inventory” is a configuration file where you define the host information. In the above /etc/ansible/hosts example, we declared two servers under test-hosts.

[webservers]
www[01:50].example.com
[databases]
db-[a:f].example.com
  • 主机变量
    可以在inventory中定义主机时为其添加主机变量以便于在playbook中使用。例如
[webservers]
www1.magedu.com http_port=80 maxRequestsPerChild=808
www2.magedu.com http_port=303 maxRequestsPerChild=909
  • 组变量
    组变量是指赋予给指定组内所有主机上的在playbook中可用的变量。例如
[webservers]
www1.magedu.com
www2.magedu.com
 
[webservers:vars]
ntp_server=ntp.magedu.com
nfs_server=nfs.magedu.com
  • 组嵌套
    inventory中组还可以包含其它的组并且也可以向组中的主机指定变量。不过这些变量只能在ansible-playbook中使用而ansible不支持。例如
[apache]
httpd1.magedu.com
httpd2.magedu.com
 
[nginx]
ngx1.magedu.com
ngx2.magedu.com
 
[webservers:children]
apache
nginx
 
[webservers:vars]
ntp_server=ntp.magedu.com
  • ansible parameters
    ansible_ssh_host # 要连接的主机名
    ansible_ssh_port # 端口号默认是22
    ansible_ssh_user # ssh连接时默认使用的用户名
    ansible_ssh_pass # ssh连接时的密码
    ansible_sudo_pass # 使用sudo连接用户是的密码
    ansible_ssh_private_key_file # 秘钥文件如果不想使用ssh-agent管理时可以使用此选项
    ansible_shell_type # shell的类型默认sh
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容