Inventory
[web]web1 ansible_host=203.0.113.10web2 ansible_host=203.0.113.11
[db]db1 ansible_host=10.0.1.20 ansible_user=admin
[all:vars]ansible_user=deployansible-inventory -i inventory.ini --graph # groups and hostsansible-inventory -i inventory.ini --host web1 # one host's variablesansible all -i inventory.ini --list-hostsAd-hoc commands
ansible all -i inventory.ini -m ping # can Ansible log in?ansible web -i inventory.ini -a 'uptime' # run a commandansible web -i inventory.ini -m shell -a 'df -h / | tail -1'ansible db -i inventory.ini -b -m apt -a 'name=htop state=present' # -b = sudoansible web -i inventory.ini -b -m service -a 'name=nginx state=restarted'ansible web1 -i inventory.ini -m setup -a 'filter=ansible_distribution*' # factsRun playbooks
ansible-playbook -i inventory.ini site.ymlansible-playbook site.yml --syntax-checkansible-playbook site.yml --check --diff # dry run, show changesansible-playbook site.yml --limit web1 # only some hostsansible-playbook site.yml --tags nginx # only tagged tasksansible-playbook site.yml --list-tasksansible-playbook site.yml --start-at-task 'Install nginx'ansible-playbook site.yml -e 'version=1.4.2' # extra variablesansible-playbook site.yml -K # ask for the sudo passwordansible-playbook site.yml -vvv # debug connection problemsA playbook
- name: Web servers hosts: web become: true vars: site_root: /var/www/app tasks: - name: Install nginx ansible.builtin.apt: name: nginx state: present update_cache: true
- name: Deploy the site config ansible.builtin.template: src: app.conf.j2 dest: /etc/nginx/conf.d/app.conf notify: Reload nginx
handlers: - name: Reload nginx ansible.builtin.service: name: nginx state: reloadedSecrets with Vault
ansible-vault create secrets.ymlansible-vault edit secrets.ymlansible-vault encrypt_string 'the-value' --name 'db_password'ansible-playbook site.yml --ask-vault-passansible-playbook site.yml --vault-password-file ~/.vault_passCollections and docs
ansible-galaxy collection install community.dockeransible-galaxy collection install -r requirements.ymlansible-galaxy collection listansible-doc ansible.builtin.copy # a module's options and examplesansible-doc -l | grep docker # find a moduleansible-config dump --only-changed # settings that aren't defaultIf ansible-doc -l stops with Unexpected Exception, this is probably a bug (we saw it on ansible-core 2.21 with collections installed), list one collection at a time: ansible-doc -l community.docker, ansible-doc -l ansible.builtin.
Common errors
UNREACHABLE! … Failed to connect to the host via sshMissing sudo passwordyou must install the sshpass programcouldn't resolve module/actionmapping values are not allowed in this context