ansible使用5-Variables
变量命名
支持数字、字母、下划线
有效:foo_port, foo5
无效:foo-port, foo port, foo.port, 12
playbook定义
- hosts: webservers
vars:
http_port: 80
jinja2模板使用变量
My amp goes to {{ max_amp_value }}
template: src=foo.cfg.j2 dest={{ remote_install_path }}/foo.cfg
Jinja2 Filters
格式化数据
{{ some_variable | to_nice_json }}
{{ some_variable | to_nice_yaml }}
使用条件表达式
tasks:
- shell: /usr/bin/foo
register: result
ignore_errors: True
- debug: msg="it failed"
when: result|failed
# in most cases you'll want a handler, but if you want to do something right now, this is nice
- debug: msg="it changed"
when: result|changed
- debug: msg="it succeeded"
when: result|success
- debug: msg="it was skipped"
when: result|skipped
强制变量定义
{{ variable | mandatory }}
变量默认值
{{ some_variable | default(5) }}
变量省略值
- name: touch files with an optional mode
file: dest={{item.path}} state=touch mode={{item.mode|default(omit)}}
with_items:
- path: /tmp/foo
- path: /tmp/bar
- path: /tmp/baz
mode: "0444"
列表
# 最小值
{{ list1 | min }}
# 最大值
{{ [3, 4, 2] | max }}
# 唯一值
{{ list1 | unique }}
# 并集
{{ list1 | union(list2) }}
# 交集
{{ list1 | intersect(list2) }}
# 补集(存在list1,不存在list2)
{{ list1 | difference(list2) }}
# 对称差集 (不同时存在每个列表)
{{ list1 | symmetric_difference(list2) }}
版本比较
{{ ansible_distribution_version | version_compare('12.04', '>=') }}
# <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne
# 版本分析strict=True,默认值false
随机数
{{ ['a','b','c']|random }} => 'c'
{{ 59 |random}} * * * * root /script/from/cron
{{ 100 |random(step=10) }} => 70
{{ 100 |random(1, 10) }} => 31
{{ 100 |random(start=1, step=10) }} => 51
洗牌(shuffle)
{{ ['a','b','c']|shuffle }} => ['c','a','b']
{{ ['a','b','c']|shuffle }} => ['b','c','a']
其他
# 列表转字符串
{{ list | join(" ") }}
# 文件全路径
{{ path | basename }}
# 目录全路径
{{ path | dirname }}
# 用户目录(~)全路径
{{ path | expanduser }}
# link的路径
{{ path | readlink }}
# Base64加解密
{{ encoded | b64decode }}
{{ decoded | b64encode }}
# 文件的sha1sum
{{ filename | sha1 }}
bool
- debug: msg=test
when: some_string_value | bool
正则
vars:
url: "http://example.com/users/foo/resources/bar"
tasks:
- shell: "msg='matched pattern 1'"
when: url | match("http://example.com/users/.*/resources/.*")
- debug: "msg='matched pattern 2'"
when: url | search("/users/.*/resources/.*")
# convert "ansible" to "able"
{{ 'ansible' | regex_replace('^a.*i(.*)$', 'a\\1') }}
# convert "foobar" to "bar"
{{ 'foobar' | regex_replace('^f.*o(.*)$', '\\1') }}
- hosts: app_servers
vars:
app_path: "{{ base_path }}/22"
Facts
'''bash
ansible hostname -m setup
{{ ansible_devices.sda.model }}
{{ ansible_hostname }}
'''
Turning Off Facts
- hosts: whatever
gather_facts: no
本地facts(自定义facts)
# /etc/ansible/facts.d/preferences.fact
[general]
asdf=1
bar=2
# 命令
ansible <hostname> -m setup -a "filter=ansible_local"
# API
"ansible_local": {
"preferences": {
"general": {
"asdf" : "1",
"bar" : "2"
}
}
}
# 引用
{{ ansible_local.preferences.general.asdf }}
# 部署
- hosts: webservers
tasks:
- name: create directory for ansible custom facts
file: state=directory recurse=yes path=/etc/ansible/facts.d
- name: install custom impi fact
copy: src=ipmi.fact dest=/etc/ansible/facts.d
- name: re-read facts after adding custom fact
setup: filter=ansible_local
Fact Caching
{{ hostvars['asdf.example.com']['ansible_os_family'] }}
# /etc/ansible/ansible.cfg
[defaults]
fact_caching = redis
fact_caching_timeout = 86400
# seconds
yum install redis
service redis start
pip install redis
Registered Variables
- hosts: web_servers
tasks:
- shell: /usr/bin/foo
register: foo_result
ignore_errors: True
- shell: /usr/bin/bar
when: foo_result.rc == 5
Accessing Complex Variable Data
{{ ansible_eth0["ipv4"]["address"] }}
{{ ansible_eth0.ipv4.address }}
{{ foo[0] }}
Magic Variables, and How To Access Information About Other Hosts
{{ hostvars['test.example.com']['ansible_distribution'] }}
{% if 'webserver' in group_names %}
# some part of a configuration file that only applies to webservers
{% endif %}
{% for host in groups['app_servers'] %}
# something that applies to all app servers.
{% endfor %}
# example
{% for host in groups['app_servers'] %}
{{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}
Variable File Separation
---
- hosts: all
remote_user: root
vars:
favcolor: blue
vars_files:
- /vars/external_vars.yml
tasks:
- name: this is just a placeholder
command: /bin/echo foo
---
# in the above example, this would be vars/external_vars.yml
somevar: somevalue
password: magic
Passing Variables On The Command Line
ansible-playbook release.yml --extra-vars "version=1.23.45 other_variable=foo"
#example
---
- hosts: '{{ hosts }}'
remote_user: '{{ user }}'
tasks:
- ...
ansible-playbook release.yml --extra-vars "hosts=vipers user=starbuck"
or
--extra-vars '{"pacman":"mrs","ghosts":["inky","pinky","clyde","sue"]}'
or
--extra-vars "@some_file.json"
Variable Precedence: Where Should I Put A Variable?
#组变量默认值在group_vars/all
---
# file: /etc/ansible/group_vars/all
# this is the site wide default
ntp_server: default-time.example.com
# 组变量,覆盖组默认变量
---
# file: /etc/ansible/group_vars/boston
ntp_server: boston-time.example.com
# 主机变量,覆盖组变量
---
# file: /etc/ansible/host_vars/xyz.boston.example.com
ntp_server: override.example.com
role variable precedence
---
# file: roles/x/defaults/main.yml
# if not overridden in inventory or as a parameter, this is the value that will be used
http_port: 80
# 不能覆盖默认值
---
# file: roles/x/vars/main.yml
# this will absolutely be used in this role
http_port: 80
# 使用这种方式覆盖默认值
roles:
- { name: apache, http_port: 8080 }
roles:
- { role: app_user, name: Ian }
- { role: app_user, name: Terry }
- { role: app_user, name: Graham }
- { role: app_user, name: John }
# roles/common/vars/main.yml
roles:
- { role: common_settings }
- { role: something, foo: 12 }
- { role: something_else }
ansible使用5-Variables的更多相关文章
- ansible 配置文件设置
目录 ansible 配置文件设置 一.ansible configuration settings 二.ansible 配置文件查找顺序(从上到下,依次查找) 三.附录ansible配置参数 ans ...
- Ansible@一个高效的配置管理工具--Ansible configure management--翻译(三)
未经书面许可.请勿转载 一张图简单概括 Simple Playbooks Ansible is useful as a command-line tool for making small chang ...
- Ansible--Ansible之Playbook
Ansible之Playbook Playbook介绍 playbook参考文档 Playbook与ad-hoc相比,是一种完全不同的运用ansible的方式,类似与saltstack的state状态 ...
- Ansible Playbook Variables
虽然自动化存在使得更容易使事情重复,但所有的系统可能不完全一样. 在某些系统上,您可能需要设置一些与其他操作略有不同的行为或配置. 此外,一些观察到的远程系统的行为或状态可能需要影响如何配置这些系统. ...
- useful Ansible commands
This article includes some useful Ansible commands. I will try to write blogs by English. You may wa ...
- Ansible学习笔记
一.Ansible简介 Ansible是一种agentless(基于ssh),可实现批量配置.命令执行和控制,基于Python实现的自动化运维工具. 其特性有: ①模块化:通过调用相关模块,完成指定任 ...
- ansible模块debug
示例: # Example that prints the loopback address and gateway for each host - debug: msg="System { ...
- ansible的使用技巧
#查看ansible的帮助 $ ansible -h #ansible 指定不通的模块执行 $ ansible -i /etc/ansible/hosts docker -u root -m c ...
- Ansible之playbook
简介 playbook是一个非常简单的配置管理和多主机部署系统.可作为一个适合部署复杂应用程序的基础.playbook可以定制配置,可以按指定的操作步骤有序执行,支持同步和异步方式.playbook是 ...
- ansible的playbook组件
playbook的核心元素: tasks: 任务 variables: 变量 templates: 模板 handlers: 处理器 roles: 角色 组织格式:YAML(被称为另外一种标记语言) ...
随机推荐
- 命令行编译运行Java程序
- react 中文文档案例四 (登陆登出按钮)
import React from 'react'; import ReactDOM from 'react-dom'; class LoginControl extends React.Compon ...
- 4 Values whose Sum is 0(枚举+二分)
The SUM problem can be formulated as follows: given four lists A, B, C, D of integer values, compute ...
- 用异或运算交换两个整数实现swap函数功能
对于异或运算有这如下说明: 1^1=0 0^0=0 1^0=1 0^1=1 简单理解就是当两个书相同时结果为0,而两个数不同时异或的结果为1 可用于两个整数的交换,而不用去引入一个中间变量 #incl ...
- hau1021 Fibonacci Again(递归)
Fibonacci Again Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)T ...
- Go语言基础之10--面向对象编程2之方法
一.方法的定义 之前我们学习了结构体(struct),其仅仅是对数据的封装,并没有行为方法,还不是一个完全的面向对象的思路,所以现在我们来学习在结构体的基础上如何去定义一个方法.结构体(类)+方法=完 ...
- asp.net搭建项目架构
项目的架构决定这个项目的好坏. 今天我说说传统三层架构的搭建 第一步 创建一个解决方案 例如 TaskSystem 接着这个解决方案下创建六个项目分别: TaskSystem.DAL TaskSyst ...
- centos7安装与卸载软件
安装 yum install 服务名 查看服务名 rpm -qa |grep -i aerospike 或者 yum list installed | grep aerospike 卸载 yum re ...
- kubernetes命令补全
# yum install -y bash-completion # locate bash_completion /usr/share/bash-completion/bash_completion ...
- appium手机自动化环境搭建
在robotframework环境安装完成的基础上进行如下安装,如果没有安装rfs环境,请先参考robotframework安装文章:Robot Framework的环境搭建 文件下载地址:链接:ht ...