Ansible automation: playbooks, roles and deployments
Ansible is an agentless automation tool for configuration management, application deployment and orchestration. A control node connects to managed hosts over SSH (or WinRM or SSH for Windows), pushes small modules, runs them, and removes them again; nothing needs to be installed on the targets except Python on Linux hosts and PowerShell on Windows hosts. You describe the desired state in YAML playbooks, and Ansible changes only what differs. This page builds an OrdersPortal deployment from an inventory to a GitLab pipeline.
Samples were run with ansible-core 2.22.0 (from the Ansible 15.0.0 community package, which bundles collections such as ansible.posix and ansible.windows) on Python 3.13. The local playbook was executed against localhost; the Linux and Windows deployment playbooks were checked with ansible-playbook --syntax-check and ansible-lint 26.11 (production profile, no findings) but not run against real hosts. ansible-core 2.22 requires Python 3.13 or later on the control node.
Topics on this page
Section titled “Topics on this page”| Topic | What it answers |
|---|---|
| How Ansible works | Control node, managed nodes, modules and collections. |
| Inventory | Hosts, groups, host and group variables, one inventory per environment. |
| Playbooks and idempotency | Plays, tasks, handlers, check mode and diff, with a runnable sample. |
| Roles and project layout | Structuring reusable automation. |
| Linux deployment | Privilege escalation, rolling releases and a web server role. |
| Windows deployment | WinRM and SSH connections and Windows modules. |
| Secrets with Ansible Vault | Encrypting variables and supplying the password. |
| GitLab CI integration | Linting, dry runs on merge requests and deployments from pipelines. |
How Ansible works
Section titled “How Ansible works”The control node is any Linux or macOS machine (or a container in CI) with Ansible installed. Managed nodes are the servers, network devices or cloud APIs you automate. For each task, Ansible connects to the host, transfers the module, runs it, collects JSON output and cleans up. Because there is no agent, there is nothing to keep patched on the targets, and a new server is manageable as soon as SSH works.
Modules are the units of work: ansible.builtin.apt, ansible.builtin.template, ansible.builtin.systemd_service, ansible.windows.win_feature. Most are idempotent: they check the current state and act only when it differs from the requested state, then report ok or changed. Modules ship in collections with fully qualified collection names (FQCNs) such as ansible.posix.synchronize; use the FQCN so it is always clear which module runs. The ansible community package includes many collections; with only ansible-core, install the ones you need from Ansible Galaxy with a requirements.yml file.
Ansible fits configuration that lives inside machines: packages, files, services, users, application deployments. For creating the machines, networks and cloud resources themselves, a declarative provisioning tool such as Terraform keeps state of what exists; the two are often used together.
Pitfalls:
shellandcommandfor everything. They always reportchangedand do not know the current state. Use a module where one exists, or addcreates,removesorchanged_when.- Short module names.
copymight resolve to a different collection’s module; use FQCNs.
Inventory
Section titled “Inventory”The inventory lists the hosts Ansible manages and groups them. It can be a static INI or YAML file, or a dynamic inventory plugin that queries a cloud provider. Keep one inventory per environment, so a staging run can never touch production hosts.
all: children: web: hosts: web01.staging.example.test: web02.staging.example.test: windows: hosts: win01.staging.example.test: vars: ansible_connection: winrm ansible_port: 5986 ansible_winrm_transport: ntlm ansible_winrm_server_cert_validation: validateVariables for a group live in group_vars/<group>.yml next to the inventory, and per-host overrides in host_vars/<host>.yml:
ordersportal_version: "2.4.1"ordersportal_port: 8080ordersportal_api_url: "https://api.staging.example.test"ansible-inventory --graph shows how Ansible understood the file:
ansible-inventory -i inventories/staging --graph@all: |--@ungrouped: |--@web: | |--web01.staging.example.test | |--web02.staging.example.test |--@windows: | |--win01.staging.example.testPitfalls:
- Passwords in inventory files. Put credentials in Vault-encrypted variables or let the CI system provide them.
- One inventory with
envvariables. A forgotten--limitthen deploys everywhere. Separate inventories per environment are safer.
Playbooks and idempotency
Section titled “Playbooks and idempotency”A playbook is a list of plays; each play maps a group of hosts to a list of tasks run in order. Handlers are tasks that run once at the end of the play, and only if a task that notified them reported changed, which is how “restart the service only if its configuration changed” works. Variables are referenced with Jinja2 expressions such as {{ ordersportal_version }}.
This playbook renders an OrdersPortal settings file on the control node itself, so it runs anywhere Ansible is installed:
- name: Render OrdersPortal settings on this machine hosts: localhost connection: local gather_facts: false vars: ordersportal_version: "2.4.1" ordersportal_api_url: "https://api.staging.example.test" ordersportal_dir: "{{ playbook_dir }}/out" tasks: - name: Create the settings directory ansible.builtin.file: path: "{{ ordersportal_dir }}" state: directory mode: "0755"
- name: Render the settings file ansible.builtin.template: src: ordersportal.env.j2 dest: "{{ ordersportal_dir }}/ordersportal.env" mode: "0644" notify: Restart OrdersPortal
handlers: - name: Restart OrdersPortal ansible.builtin.debug: msg: "Settings changed: OrdersPortal {{ ordersportal_version }} would restart here"ORDERSPORTAL_VERSION={{ ordersportal_version }}ORDERSPORTAL_API_URL={{ ordersportal_api_url }}The first run creates both files and fires the handler:
TASK [Create the settings directory] *******************************************changed: [localhost]TASK [Render the settings file] ************************************************changed: [localhost]RUNNING HANDLER [Restart OrdersPortal] *****************************************ok: [localhost] => { "msg": "Settings changed: OrdersPortal 2.4.1 would restart here"}PLAY RECAP *********************************************************************localhost : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0The second run changes nothing and the handler does not fire (ok=2 changed=0). That is idempotency, and it is what makes Ansible safe to run repeatedly.
Check mode (--check) predicts changes without making them, and --diff shows the content difference. Overriding the version with an extra variable shows exactly what a release would change:
ansible-playbook render-config.yml -e ordersportal_version=2.5.0 --check --diffTASK [Render the settings file] ************************************************-ORDERSPORTAL_VERSION=2.4.1+ORDERSPORTAL_VERSION=2.5.0 ORDERSPORTAL_API_URL=https://api.staging.example.testchanged: [localhost]PLAY RECAP *********************************************************************localhost : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0Pitfalls:
- Tasks that do not support check mode.
commandandshelltasks are skipped in check mode, so the prediction is incomplete. Note which tasks those are. - Restarting services in tasks instead of handlers. Every run then restarts the application, even when nothing changed.
Roles and project layout
Section titled “Roles and project layout”A role packages tasks, handlers, templates, files, defaults and variables for one responsibility (a web server, an application, a database client) in a standard directory layout, so plays become short lists of roles:
deploy/ ansible.cfg inventories/ staging/hosts.yml staging/group_vars/web.yml production/hosts.yml roles/ ordersportal/ defaults/main.yml # lowest-precedence, overridable defaults tasks/main.yml handlers/main.yml templates/ordersportal.conf.j2 deploy-web.yml deploy-windows.yml requirements.yml # collections to installPrefix role variables with the role name (ordersportal_port), which ansible-lint enforces, so variables from different roles cannot collide. Put defaults in defaults/main.yml, where inventory variables can override them. Share roles across repositories as collections, pinned by version in requirements.yml.
Pitfalls:
- Roles that do everything. A role that installs nginx, deploys the app and configures monitoring cannot be reused. One responsibility per role.
- Variables in
vars/main.ymlthat users need to change.vars/has high precedence and is hard to override; usedefaults/.
Linux deployment
Section titled “Linux deployment”On Linux, Ansible connects over SSH with key-based authentication and uses privilege escalation (become: true, sudo by default) for tasks that need root. The OrdersPortal role installs nginx, deploys a release into a versioned directory, switches a current symlink and reloads nginx only when something changed:
- name: Install nginx ansible.builtin.apt: name: nginx state: present update_cache: true cache_valid_time: 3600
- name: Create the release directory ansible.builtin.file: path: "{{ ordersportal_root }}/releases/{{ ordersportal_version }}" state: directory owner: www-data group: www-data mode: "0755"
- name: Copy the built site ansible.posix.synchronize: src: "{{ playbook_dir }}/dist/" dest: "{{ ordersportal_root }}/releases/{{ ordersportal_version }}/" delete: true
- name: Point the current symlink at the new release ansible.builtin.file: src: "{{ ordersportal_root }}/releases/{{ ordersportal_version }}" dest: "{{ ordersportal_root }}/current" state: link notify: Reload nginx
- name: Render the nginx site ansible.builtin.template: src: ordersportal.conf.j2 dest: /etc/nginx/conf.d/ordersportal.conf mode: "0644" validate: nginx -t -c /etc/nginx/nginx.conf notify: Reload nginx
- name: Keep nginx enabled and running ansible.builtin.systemd_service: name: nginx state: started enabled: true- name: Deploy OrdersPortal to the Linux web servers hosts: web become: true serial: 1 roles: - ordersportalserial: 1 deploys one host at a time, so a failure stops the rollout with the other web server still serving the previous release, and rolling back means pointing the symlink at the previous directory. The template’s validate option runs nginx -t before replacing the file, so a broken configuration never reaches the live path. ansible.posix.synchronize wraps rsync, which must be installed on both ends; ansible.builtin.copy works without it but is slower for many files.
Pitfalls:
become: trueon the whole play when only some tasks need root. Grant it per task or block where practical.- Deploying to all hosts at once. A bad release takes everything down. Use
serial, and remove hosts from the load balancer while they update.
Windows deployment
Section titled “Windows deployment”Ansible manages Windows hosts with PowerShell-based modules from the ansible.windows and community.windows collections. Two connection types are supported: WinRM (ansible_connection: winrm), the traditional option, and SSH (ansible_connection: ssh with ansible_shell_type: powershell), officially supported since Ansible 2.18 using the OpenSSH server shipped with Windows; Ansible’s documentation states official SSH support effectively starts with Windows Server 2022 because it needs OpenSSH 7.9.0.0 or later.
For WinRM, configure an HTTPS listener on port 5986 with a certificate, open the firewall for it, and choose an authentication transport (ansible_winrm_transport): basic, certificate, ntlm, kerberos or credssp. Prefer Kerberos for domain-joined hosts, keep certificate validation on (ansible_winrm_server_cert_validation: validate), and use HTTP on 5985 only for isolated labs. The control node needs the pywinrm Python package.
- name: Deploy the OrdersPortal admin site to IIS hosts: windows tasks: - name: Install IIS ansible.windows.win_feature: name: Web-Server state: present include_management_tools: true register: iis
- name: Reboot if the feature install requires it ansible.windows.win_reboot: when: iis.reboot_required
- name: Copy the site files ansible.windows.win_copy: src: "{{ playbook_dir }}/dist/" dest: C:\inetpub\ordersportal\
- name: Make sure the W3SVC service is running ansible.windows.win_service: name: W3SVC state: started start_mode: autoPrivilege escalation on Windows uses become_method: runas when a task must run as a different user, for example to access network resources that WinRM’s network logon cannot reach.
Pitfalls:
- Disabling certificate validation to “make it work”. It opens the connection to interception. Fix the certificate chain instead.
- Linux modules on Windows hosts.
ansible.builtin.copyandtemplatedo not work on Windows; use thewin_equivalents (win_copy,win_template).
Secrets with Ansible Vault
Section titled “Secrets with Ansible Vault”Ansible Vault encrypts data with AES256 so secrets can live in the repository next to the code that uses them. Encrypt whole files (ansible-vault encrypt group_vars/production/vault.yml) or single values with encrypt_string:
ansible-vault encrypt_string --vault-password-file .vault_pass 'S3cret-Example' --name ordersportal_db_passwordordersportal_db_password: !vault | $ANSIBLE_VAULT;1.1;AES256 33393431653234366237346666666331373432326535623930306265353664633763633537363363 ...Playbooks decrypt values in memory at run time when given the vault password with --vault-password-file, --ask-vault-pass, or a vault ID for several passwords. Without it, the run stops with “Attempting to decrypt but no vault secrets found”, which is what happened when the test playbook was run without the password file. Mark tasks that handle secrets with no_log: true so values do not appear in output.
Vault protects secrets at rest in Git, but the vault password becomes the key to everything. In CI, provide it as a protected, masked file variable. Many teams instead read secrets at run time from a secret manager (HashiCorp Vault, Azure Key Vault, AWS Secrets Manager) through lookup plugins, which avoids a shared password and supports rotation.
Pitfalls:
- Committing the vault password file. Add it to
.gitignore; it decrypts every secret in the repository. - Printing secrets with
debug. Even an accidental debug task leaks them to CI logs.
GitLab CI integration
Section titled “GitLab CI integration”Running Ansible from a pipeline gives every change review, a dry run and an audit trail. A typical OrdersPortal setup lints and runs check mode on merge requests, and deploys from the default branch with a manual approval for production. The job images, keys and vault password come from CI/CD variables of type File, marked protected and masked. This configuration was checked for YAML syntax only and not run on GitLab:
# .gitlab-ci.yml (deployment project)default: image: python:3.13-slim before_script: - pip install --no-cache-dir ansible==15.0.0 ansible-lint - apt-get update && apt-get install -y --no-install-recommends openssh-client rsync - install -m 600 "$DEPLOY_SSH_KEY" ~/deploy_key
stages: [lint, plan, deploy]
ansible_lint: stage: lint before_script: - pip install --no-cache-dir ansible==15.0.0 ansible-lint script: - ansible-lint deploy-web.yml deploy-windows.yml roles/
check_staging: stage: plan script: - ansible-playbook -i inventories/staging deploy-web.yml --check --diff --private-key ~/deploy_key --vault-password-file "$VAULT_PASSWORD_FILE" rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event"
deploy_staging: stage: deploy environment: staging script: - ansible-playbook -i inventories/staging deploy-web.yml --private-key ~/deploy_key --vault-password-file "$VAULT_PASSWORD_FILE" rules: - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
deploy_production: stage: deploy environment: production script: - ansible-playbook -i inventories/production deploy-web.yml --private-key ~/deploy_key --vault-password-file "$VAULT_PASSWORD_FILE" rules: - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH when: manualPin the Ansible version (and collection versions in requirements.yml) so a new release cannot change behavior between the check and the deploy. For host key checking, add the known hosts from a variable rather than disabling StrictHostKeyChecking. Keep the job log as the record of what changed, and protect the production environment so only approved roles can run its job. See GitLab CI/CD pipelines for rules, protected variables and environments.
Pitfalls:
- Unpinned
pip install ansible. A major release lands mid-week and deployments change behavior. Pin it. - Running production deployments from laptops. It bypasses review and leaves no audit trail. Deploy from the pipeline.
Choosing between them
Section titled “Choosing between them”| You need | Use |
|---|---|
| Predict changes before applying them | --check --diff |
| Restart only when configuration changed | Handlers |
| Reuse automation across playbooks and repositories | Roles, shared as versioned collections |
| Roll out safely across a group | serial with load balancer drain and health checks |
| Manage Windows Server 2022 or later | SSH with PowerShell, or WinRM over HTTPS with Kerberos |
| Store secrets beside the code | Ansible Vault, with the password in CI as a protected file variable |
| Create cloud infrastructure | Terraform, then Ansible for configuration |
Interview questions
Section titled “Interview questions”What does “agentless” mean for Ansible, and what does a managed node still need? No long-running agent is installed. Ansible connects over SSH or WinRM, copies modules, runs them and removes them. Linux hosts need Python and SSH; Windows hosts need PowerShell and WinRM or the OpenSSH server.
What makes a task idempotent, and why do command and shell break it?
An idempotent task checks current state and changes only what differs, so repeated runs report ok. command and shell cannot know the state, so they run every time and report changed, unless you add creates, removes or changed_when.
When do handlers run?
At the end of the play (or at a meta: flush_handlers task), once, and only if at least one task that notified them reported changed.
How do you keep secrets in an Ansible repository?
Encrypt them with Ansible Vault (files or single values) and supply the vault password at run time, or look them up from an external secret manager. Use no_log on tasks that handle them.
Senior scenario: OrdersPortal’s Ansible deployments occasionally take down both web servers and nobody knows what each run changed. How do you redesign the process?
Run deployments only from the pipeline, with --check --diff output attached to merge requests and full logs kept per run. Deploy with serial: 1 (or a percentage) and max_fail_percentage: 0, drain each host from the load balancer before updating it and verify a health endpoint before re-adding it. Use versioned release directories with a symlink switch so rollback is instant, pin Ansible and collection versions, and add ansible-lint and Molecule tests for the roles.
Related pages
Section titled “Related pages”- DevOps overview
- GitLab CI/CD pipelines: rules, protected variables and environments used by the deployment jobs.
- Terraform basics and the core workflow: provisioning the hosts Ansible configures.
- Docker images, containers and registries: an alternative packaging model for the same application.