[Ansible学习一] Ansible Galaxy使用小记

ansible也有类似rubygems.org 的网站, 让ansible用户分享ansible功能模块
网址 https://galaxy.ansible.com/

安装模块

直接使用ansible-galaxy 安装一些模块

$ ansible-galaxy install username.rolename

当然也支持 批量安装, Ansible 提供了两种方式配置依赖模块,可以批量安装模块

方式1 使用 roles.txt

# roles.txt
user1.role1,v1.0.0
user2.role2,v0.5
user2.role3

配置规则格式是 username.rolename[,version] 的形式

$ ansible-galaxy install -r roles.txt

方式1 不能指定安装路径,也不能指定安装名字

ansible提供了更高级的配置yml的格式

方式2 使用yml格式的配置文件

创建 install_roles.yml 配置文件

# 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

# from a webserver, where the role is packaged in a tar.gz
- src: https://some.webserver.example.com/files/master.tar.gz
  name: http-role

# from bitbucket, if bitbucket happens to be operational right now :)
- src: git+http://bitbucket.org/willthames/git-ansible-galaxy
  version: v1.4

# from bitbucket, alternative syntax and caveats
- src: http://bitbucket.org/willthames/hg-ansible-galaxy
  scm: hg

安装配置好的role模块

$ ansible-galaxy install -r install_roles.yml

可以在项目里创建ansible.cfg配置文件,配置role模块下载位置

ansible.cfg

[defaults]
hostfile = inventory
roles_path = roles

创建模块

比如创建一个acme模块,

$ ansible-galaxy init acme --force

文件结构

  .
  ├── README.md
  ├── defaults
  │   └── main.yml
  ├── files
  ├── handlers
  │   └── main.yml
  ├── meta
  │   └── main.yml
  ├── tasks
  │   └── main.yml
  ├── templates
  ├── tests
  │   ├── inventory
  │   └── test.yml
  └── vars
      └── main.yml

Meta Data - meta/main.yml

meta/main.yml 用来配置模块一些元信息,比如支持的平台,Ansible最小依赖版本,
这个模块的标签,依赖,作者的信息等等。

ansible-galaxy init 创建项目生成的模板如下

---
galaxy_info:
 author: John Doe
 description: Quick and easy acme web installer.
 company: Acme
 license: MIT
 min_ansible_version: 1.9
 platforms:
 - name: EL
   versions:
   - all
 galaxy_tags:
   - acme
   - installer
   - web
dependencies:
 - { role: username.common, some_parameter: 3 }
 - { role: username.iptables, open_port: 80 }

dependencies 用于配置依赖的其它模块

比如

dependencies:
  - { role: stouts.elasticsearch }

也可以传参数

dependencies:
  - { role: stouts.elasticsearch, elasticsearch_home: "{{ install_path_variable }}", elasticsearch_http_port: 8900 }

task/main.yml

是这个role的入口文件,命令从main.yml开始执行

files

files 目录是放一些文件用的,比如可以用copy命令,把files目录下的文件复制到服务器上

- name: copy source.list.{{ansible_distribution_release}} file
  copy: src=sources.list.{{ansible_distribution_release}} dest=/etc/apt/sources.list backup=yes

templates

用于jinjia2模板文件

defaults/main.yml

默认的配置变量写在defaults/main.yml里

handlers/main.yml

一般用来重启服务,比如


---
# this might be in a file like handlers/handlers.yml
- name: restart apache
 service: name=apache state=restarted
  

lidashuang
6.7k 声望165 粉丝

$ Ruby/Elixir/Golang