Mark Locklear
Mark Locklear

Reputation: 5325

Update a single vhost file using Ansible

I have the following file: roles/homepage/templates/vhost_443.conf.j2

<VirtualHost *:443>
    ServerName {{ vhost_name }}
    {% if vhost_aliases is defined %}
    {% for vhost_alias in vhost_aliases %}
    ServerAlias {{ vhost_alias }}
    {% endfor %}
    {% endif %}
    ServerAdmin [email protected]
    DocumentRoot {{ vhost_document_root }}
    ErrorLog {{ vhost_log_dir }}/error.log
    CustomLog  {{ vhost_log_dir }}/access.log combined
    LogLevel info ssl:warn
    # LogLevel alert rewrite:t
    ...

This file is referenced in roles/homepage/tasks/main.yml

...
- name: create ssl vhost
  template:
    src: vhost_443.conf.j2
    dest: "/etc/apache2/sites-available/{{ vhost_name }}_443.conf"
  notify: restart apache
  tags:
    - vhostconfig
  ...

Is there a way to run just this portion (task?) in roles/homepage/tasks/main.yml so I am only updating the vhost_443.conf file on the server without running all the other tasks in main.yml, or should I create a task just to update this file?

I was considering running: ansible-playbook roles/homepage/tasks/main.yml but this would run all the other commands in main.yml.

Upvotes: 0

Views: 748

Answers (2)

Mark Locklear
Mark Locklear

Reputation: 5325

The solution I ended up going with was to add a tag update_vhost to the specific task I wanted to run in roles/homepage/tasks/main.yml. So in the

...
- name: create ssl vhost
  template:
    src: vhost_443.conf.j2
    dest: "/etc/apache2/sites-available/{{ vhost_name }}_443.conf"
  notify: restart apache
  tags: ['vhostconfig', 'update_vhost']
  ...

Now when I want to run that specific task I run ansible-playbook playbooks/webapps/homepage.yml --tags "update_vhost" to run that task only.

Upvotes: 1

Mike A
Mike A

Reputation: 510

If you want to keep roles/homepage/tasks/main.yml as one file, then you may want to separate the logic into blocks. Create a variable homepage-run

If you want to run the whole role, set homepage-run: full

If you want to run the vhost update, set homepage-run: vhost

- block:
  - name: Run homepage setup part 1
    - task1
    - task2
    - task3
  when: homepage-run == "full"

- block:
  - name: Run vhost setup
    - name: create ssl vhost
      template:
        src: vhost_443.conf.j2
        dest: "/etc/apache2/sites-available/{{ vhost_name }}_443.conf"
      notify: restart apache
      tags:
        - vhostconfig
  when: ( homepage-run == "full" ) or ( homepage-run == "vhost" )

- block:
  - name: Run homepage setup part 2
    - task1
    - task2
    - task3
  when: homepage-run == "full"

Upvotes: 1

Related Questions