Created
April 13, 2024 21:16
-
-
Save apotitech/776082e2022c3bff1e2af3b7b3a28140 to your computer and use it in GitHub Desktop.
haproxy.yml file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
- hosts: localhost | |
become: yes | |
vars_files: | |
- aws_credentials.yml # Contains AWS access keys and secret keys | |
- aws_ec2_configs.yml # Contains configuration such as AWS region | |
# Handlers are tasks that respond to a notify directive and are typically used to restart services | |
handlers: | |
- name: Restart HAProxy service | |
ansible.builtin.service: | |
name: haproxy | |
state: restarted | |
listen: "restart haproxy" | |
tasks: | |
- name: Install HAProxy | |
ansible.builtin.package: | |
name: haproxy | |
state: present | |
notify: "restart haproxy" # Notify handler if the package is installed or updated | |
- name: Ensure HAProxy service is started and enabled on boot | |
ansible.builtin.service: | |
name: haproxy | |
state: started | |
enabled: yes | |
- name: Gather EC2 instance information | |
amazon.aws.ec2_instance_info: | |
aws_access_key: "{{ aws_access_key }}" | |
aws_secret_key: "{{ aws_secret_access_key }}" | |
region: "{{ region_name }}" | |
filters: | |
"tag:Name": "ansible-managed-servers" | |
instance-state-name: ["running"] | |
register: ec2_info | |
failed_when: ec2_info.instances | length == 0 # Fail if no instances are found | |
- name: Set private IP addresses of EC2 instances | |
set_fact: | |
private_ip: "{{ ec2_info.instances | map(attribute='private_ip_address') | list }}" | |
- name: Display the private IP addresses of EC2 instances | |
ansible.builtin.debug: | |
var: private_ip | |
- name: Update HAProxy configuration with EC2 instance IPs | |
ansible.builtin.template: | |
src: haproxy.j2 | |
dest: /etc/haproxy/haproxy.cfg | |
notify: "restart haproxy" # Notify handler if the template changes | |
# Flush handlers to ensure any configuration changes take effect | |
post_tasks: | |
- name: Ensure HAProxy service is restarted if needed | |
meta: flush_handlers |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment