Welcome to the Ansible User Guide!
This guide covers how to work with Ansible, including using the command line, working with inventory, and writing playbooks.
We’ve recorded a short video that introduces Ansible.
https://www.redhat.com/en/blog/system-administrators-guide-getting-started-ansible-fast (A system administrators guide to getting started with Ansible) 一篇入门指南
https://opensource.com/downloads/ansible-quickstart (A downloadable guide for getting started with Ansible)
These concepts are common to all uses of Ansible.
This page illustrates the basic process with a simple inventory and an ad-hoc command. Once you understand how Ansible works, you can read more details about ad-hoc commands, organize your infrastructure with inventory, and harness the full power of Ansible with playbooks.
Selecting machines from inventory use either IP addresses or FQDNs
192.0.2.50 aserver.example.org bserver.example.org
Your inventory can store much more than IPs and FQDNs. You can create aliases, set variable values for a single host with host vars, or set variable values for multiple hosts with group vars.
Ansible communicates with remote machines over the SSH protocol. By default, Ansible uses native OpenSSH and connects to remote machines using your current user name, just as SSH does.
Confirm that you can connect using SSH to all the nodes in your inventory using the same username. If necessary, add your public SSH key to the authorized_keys file on those systems.
Action: run your first Ansible commands
$ ansible all -m ping $ ansible all -a "/bin/echo hello"
If you need privilege escalation (sudo and similar) to run a command, pass the become flags:
# as bruce $ ansible all -m ping -u bruce # as bruce, sudoing to root (sudo is default method) $ ansible all -m ping -u bruce --become # as bruce, sudoing to batman $ ansible all -m ping -u bruce --become --become-user batman
Congratulations! You have contacted your nodes using Ansible. You used a basic inventory file and an ad-hoc command to direct Ansible to connect to specific remote nodes, copy a module file there and execute it, and return output. You have a fully working infrastructure.
The default location for inventory is a file called /etc/ansible/hosts. You can specify a different inventory file at the command line using the -i <path> option.
pull inventory from dynamic or cloud sources or different formats (YAML, ini, etc), as described in Working with dynamic inventory （即从CMDB、配管系统里通过API接口拿到）
The inventory file can be in one of many formats, depending on the inventory plugins you have. The most common formats are INI and YAML. A basic INI etc/ansible/hosts might look like this:
mail.example.com [webservers] foo.example.com bar.example.com [dbservers] one.example.com two.example.com three.example.com
Here’s that same basic inventory file in YAML format:
all: hosts: mail.example.com: children: webservers: hosts: foo.example.com: bar.example.com: dbservers: hosts: one.example.com: two.example.com: three.example.com:
There are two default groups: all and ungrouped. The all group contains every host. The ungrouped group contains all hosts that don’t have another group aside from all. Every host will always belong to at least 2 groups (all and ungrouped or all and some other group). Though all and ungrouped are always present, they can be implicit and not appear in group listings like group_names.
You can store variable values that relate to a specific host or group in inventory. To start with, you may add variables directly to the hosts and groups in your main inventory file. As you add more and more managed nodes to your Ansible inventory, however, you will likely want to store variables in separate host and group variable files.
Assigning a variable to one machine: host variables
You can easily assign a variable to a single host, then use it later in playbooks. In INI:
[atlanta] host1 http_port=80 maxRequestsPerChild=808 host2 http_port=303 maxRequestsPerChild=909 [targets] localhost ansible_connection=local other1.example.com ansible_connection=ssh ansible_user=myuser other2.example.com ansible_connection=ssh ansible_user=myotheruser badwolf.example.com:5309
Generally speaking, this is not the best way to define variables that describe your system policy. Setting variables in the main inventory file is only a shorthand. See Organizing host and group variables for guidelines on storing variable values in individual files in the ‘host_vars’ directory.
If all hosts in a group share a variable value, you can apply that variable to an entire group at once. In INI:
[atlanta] host1 host2 [atlanta:vars] ntp_server=ntp.atlanta.example.com proxy=proxy.atlanta.example.com
atlanta: hosts: host1: host2: vars: ntp_server: ntp.atlanta.example.com proxy: proxy.atlanta.example.com
Group variables are a convenient way to apply variables to multiple hosts at once. Before executing, however, Ansible always flattens variables, including inventory variables, to the host level. If a host is a member of multiple groups, Ansible reads variable values from all of those groups. If you assign different values to the same variable in different groups, Ansible chooses which value to use based on internal rules for merging.
[atlanta] host1 host2 [raleigh] host2 host3 [southeast:children] atlanta raleigh [southeast:vars] some_server=foo.southeast.example.com halon_system_timeout=30 self_destruct_countdown=60 escape_pods=2 [usa:children] southeast northeast southwest northwest In YAML: all: children: usa: children: southeast: children: atlanta: hosts: host1: host2: raleigh: hosts: host2: host3: vars: some_server: foo.southeast.example.com halon_system_timeout: 30 self_destruct_countdown: 60 escape_pods: 2 northeast: northwest: southwest:
Although you can store variables in the main inventory file, storing separate host and group variables files may help you organize your variable values more easily. Host and group variable files must use YAML syntax. Valid file extensions include ‘.yml’, ‘.yaml’, ‘.json’, or no file extension. See YAML Syntax if you are new to YAML.
Ansible loads host and group variable files by searching paths relative to the inventory file or the playbook file
Keeping your inventory file and variables in a git repo (or other version control) is an excellent way to track changes to your inventory and host variables.
/etc/ansible/hosts /etc/ansible/group_vars/raleigh # can optionally end in '.yml', '.yaml', or '.json' /etc/ansible/group_vars/webservers /etc/ansible/host_vars/foosball
You can target multiple inventory sources (directories, dynamic inventory scripts or files supported by inventory plugins) at the same time by giving multiple inventory parameters from the command line or by configuring ANSIBLE_INVENTORY. This can be useful when you want to target normally separate environments, like staging and production, at the same time for a specific action.
ansible-playbook get_logs.yml -i staging -i production inventory/ openstack.yml # configure inventory plugin to get hosts from Openstack cloud dynamic-inventory.py # add additional hosts with dynamic inventory script static-inventory # add static hosts and groups group_vars/ all.yml # assign variables to all hosts
ansible_host ansible_port ansible_user ansible_password ansible_become ansible_become_user ansible_shell_type ansible_python_interpreter
Examples from an Ansible-INI host file:
some_host ansible_port=2222 ansible_user=manager aws_host ansible_ssh_private_key_file=/home/example/.ssh/aws.pem freebsd_host ansible_python_interpreter=/usr/local/bin/python ruby_module_host ansible_ruby_interpreter=/usr/bin/ruby.1.9.3
- name: create jenkins container docker_container: docker_host: myserver.net:4243 name: my_jenkins image: jenkins - name: add container to inventory add_host: name: my_jenkins ansible_connection: docker ansible_docker_extra_args: "--tlsverify --tlscacert=/path/to/ca.pem --tlscert=/path/to/client-cert.pem --tlskey=/path/to/client-key.pem -H=tcp://myserver.net:4243" ansible_user: jenkins changed_when: false - name: create directory for ssh keys delegate_to: my_jenkins file: path: "/var/jenkins_home/.ssh/jupiter" state: directory
Example: One inventory per environment [dbservers] db01.test.example.com db02.test.example.com [appservers] app01.test.example.com app02.test.example.com app03.test.example.com Example: Group by function - hosts: dbservers tasks: - name: allow access from 10.0.0.1 iptables: chain: INPUT jump: ACCEPT source: 10.0.0.1
If you would like a GUI for handling dynamic inventory, the Red Hat Ansible Tower inventory database syncs with all your dynamic inventory sources, provides web and REST access to the results, and offers a graphical inventory editor. With a database record of all of your hosts, you can correlate past event history and see which hosts have had failures on their last playbook runs.
Using inventory directories and multiple inventory sources
If the location given to -i in Ansible is a directory (or as so configured in ansible.cfg), Ansible can use multiple inventory sources at the same time. When doing so, it is possible to mix both dynamic and statically managed inventory sources in the same ansible run. Instant hybrid cloud!
In an inventory directory, executable files will be treated as dynamic inventory sources and most other files as static sources. Files which end with any of the following will be ignored:
~, .orig, .bak, .ini, .cfg, .retry, .pyc, .pyo
Any group_vars and host_vars subdirectories in an inventory directory will be interpreted as expected, making inventory directories a powerful way to organize different sets of configurations. See Using multiple inventory sources for more information.
Patterns: targeting hosts and groups
Patterns are highly flexible - you can exclude or require subsets of hosts, use wildcards or regular expressions, and more. Ansible executes on all inventory hosts included in the pattern.
regular expressions 正则表达式
ansible <pattern> -m <module_name> -a "<module options>"" ansible webservers -m service -a "name=httpd state=restarted"
In a playbook the pattern is the content of the hosts: line for each play:
- name: <play_name> hosts: <pattern> - name: restart webservers hosts: webservers
Limitations of patterns
Patterns depend on inventory. If a host or group is not listed in your inventory, you cannot use a pattern to target it. If your pattern includes an IP address or hostname that does not appear in your inventory, you will see an error like this:
This works even if the host you target is not defined in your inventory. You can also limit the hosts you target on a particular run with the –limit flag:
ansible-playbook site.yml –limit datacenter2