跳到主要内容

Ansible 参考

常用目录结构

production                # 正式环境仓库
staging # 预发环境仓库

group_vars/
all.yml # 全局变量
group1.yml # 分组变量
group2.yml
host_vars/
hostname1.yml # 主机变量
hostname2.yml

library/ # 自定义模块
module_utils/ # 用于支持模块的模块工具
filter_plugins/ # 自定义过滤插件

site.yml # 主 playbook
webservers.yml # playbook for webserver tier
dbservers.yml # playbook for dbserver tier

roles/
common/ # 角色结构
tasks/ #
main.yml # <-- tasks file can include smaller files if warranted
handlers/ #
main.yml # <-- handlers file
templates/ # <-- files for use with the template resource
ntp.conf.j2 # <------- templates end in .j2
files/ #
bar.txt # <-- files for use with the copy resource
foo.sh # <-- script files for use with the script resource
vars/ #
main.yml # <-- variables associated with this role
defaults/ #
main.yml # <-- default lower priority variables for this role
meta/ #
main.yml # <-- role dependencies
library/ # roles can also include custom modules
module_utils/ # roles can also include custom module_utils
lookup_plugins/ # or other types of plugins, like lookup in this case

webtier/ # same kind of structure as "common" was above, done for the webtier role
monitoring/ # ""
fooapp/ # ""

独立仓库目录结构

如果仓库区别较大,可采用

inventories/
production/
hosts # production 仓库主机定义
group_vars/
all.yml # production 全局变量
group1.yml # 分组变量
group2.yml
host_vars/
hostname1.yml # 主机变量
hostname2.yml

staging/
hosts # staging 仓库主机定义
group_vars/
group1.yml # here we assign variables to particular groups
group2.yml
host_vars/
stagehost1.yml # here we assign variables to particular systems
stagehost2.yml

library/
module_utils/
filter_plugins/

site.yml
webservers.yml
dbservers.yml

roles/
common/
webtier/
monitoring/
fooapp/

Generate ansible directories

mkdir gourp_vars host_vars
for ROLE in "apache" "web";do mkdir -p roles/${ROLE}/{files,handlers,tasks}; done

变量加载顺序

  • role defaults
  • inventory vars
  • inventory group_vars
  • inventory host_vars
  • playbook group_vars
  • playbook host_vars
  • host facts
  • registered vars
  • set_facts
  • play vars
  • play vars_prompt
  • play vars_files
  • role and include vars
  • block vars (only for tasks in block)
  • task vars (only for the task)
  • extra vars (always win precedence)

Name Default Description

Inventory VarsDescription
ansible_ssh_hostname of host Hostname or IP address to SSH to
ansible_ssh_port22 Port to SSH to
ansible_ssh_userroot User to SSH as
ansible_ssh_passnone Password to use for SSH authentication
ansible_connectionsmart How Ansible will connect to host (see below)
ansible_ssh_private_key_filenone SSH private key to use for SSH authentication
ansible_shell_typesh Shell to use for commands (see below)
ansible_python_interpreter/usr/bin/python Python interpreter on host (see below)
ansible_*_interpreternone Like ansible_python_interpreter for other languages (see below)

在新版本中,变量中的 ssh 已经去掉了

Behavioral inventory parameteransible.cfg option
ansible_ssh_portremote_port
ansible_ssh_userremote_user
ansible_ssh_private_key_fileprivate_key_file
ansible_shell_typeexecutable (see the following paragraph)

ansible-vault 命令

CommandDescription
ansible-vault encrypt file.ymlEncrypt the plaintext file.yml file
ansible-vault decrypt file.ymlDecrypt the encrypted file.yml file
ansible-vault view file.ymlPrint the contents of the encrypted file.yml file
ansible-vault create file.ymlCreate a new encrypted file.yml file
ansible-vault edit file.ymlEdit an encrypted file.yml file
ansible-vault rekey file.ymlChange the password on an encrypted file.yml file

SSH 多播选项

OptionValue
ControlMasterauto
ControlPath$HOME/.ansible/cp/ansible-ssh-%h-%p-%r
ControlPersist60s

AnsibleModule 参数属性

OptionDescription
requiredIf True, argument is required
defaultDefault value if argument is not required
choicesA list of possible values for the argument
aliasesOther names you can use as an alias for this argument
typeArgument type. Allowed values: 'str', 'list', 'dict', 'bool', 'int', 'float'

AnsibleModule 初始化参数

Parameter DefaultDescription
argument_spec (none)Dictionary that contains information about arguments
bypass_checksFalse If true, don’t check any of the parameter constrains
no_logFalse If true, don’t log the behavior of this module
check_invalid_argumentsTrue If true, return error if user passed an unknown argument
mutually_exclusiveNone List of mutually exclusive arguments
required_togetherNone List of arguments that must appear together
required_one_ofNone List of arguments where at least one must be present
add_file_common_argsFalse Supports the arguments of the file module
supports_check_modeFalse If true, indicates module supports check mode

调用外部命令

在 Ansible 模块中使用 run_command 调用外部命令

ArgumentTypeDefaultDescription
args (default)string or list of strings(none) The command to be executed (see the following section)
check_rcBooleanFalseIf true, will call fail_json if command returns a non-zero value.
close_fdsBooleanTruePasses as close_fds argument to subprocess.Popen
executablestring (path to program)NonePasses as executable argument to subprocess.Popen
datastringNoneSend to stdin if child process
binary_dataBooleanFalseIf false and data is present, Ansible will send a newline to stdin after sending data
path_prefixstring (list of paths)NoneColon-delimited list of paths to prepend to PATH environment variable
cwdstring (directory path)NoneIf specified, Ansible will change to this directory before executing
use_unsafe_shellBooleanFalseSee the following section

Documentation markup

TypeSyntax with exampleWhen to use
URLU(http://www.example.com)URLs
ModuleM(apt)Module names
ItalicsI(port)Parameter names
Constant-widthC(/bin/bash)File and option names

functions

fnargs
defaultdef,when_empty_or_false=false
ternarytrue,false,null
mandatory
type_debug
human_readableisbites,unit
human_to_bytesisbits
# omit 可选
mode: "{{ item.mode | default(omit) }}"
# 如果要 chain 则使用 None
mode: "{{ foo | default(None) | some_filter or omit }}"
# 必须要的变量
required: "{{ variable | mandatory }}"

Tests

testargs/meaning
is truthyconvert_bool=True
is falsyconvert_bool=True
is version(str,operator,strict='False',version_type='semver')
is superset
is subset
is allall true
is anyany true
is failedtest result
is changed
is succeeded
is success
is skipped

检测控制器上文件存在情况

  • is directory,file,link,exists,same_file(path),mount,abs
vars:
lacp_groups:
- master: lacp0
network: 10.65.100.0/24
gateway: 10.65.100.1
dns4:
- 10.65.100.10
- 10.65.100.11
interfaces:
- em1
- em2

- master: lacp1
network: 10.65.120.0/24
gateway: 10.65.120.1
dns4:
- 10.65.100.10
- 10.65.100.11
interfaces:
- em3
- em4

# Test list contains value
tasks:
- debug:
msg: "{{ (lacp_groups|selectattr('interfaces', 'contains', 'em1')|first).master }}"