如何使用Ansible在AWS创建Network Load Balancer?能否借助Boto3实现?
Creating an AWS Network Load Balancer with Ansible via Boto3
Absolutely! Even though Ansible doesn’t have a dedicated Network Load Balancer (NLB) module at the moment, you can fully implement NLB creation in AWS using Boto3—AWS’s official Python SDK—right within your Ansible playbooks. Below are two straightforward approaches to get this done:
Approach 1: Use the script Module to Run an External Boto3 Script
This method involves writing a standalone Python script that uses Boto3 to create the NLB, then calling that script from your playbook.
Step 1: Write the Boto3 Script (create_nlb.py)
import boto3 def create_network_load_balancer(): # Initialize the ELBv2 client (NLBs use the ELBv2 API) elbv2_client = boto3.client('elbv2', region_name='us-east-1') # Update your region here # Create the NLB nlb_response = elbv2_client.create_load_balancer( Name='my-production-nlb', Subnets=['subnet-0123456789abcdef0', 'subnet-0abcdef1234567890'], # Replace with your subnets Scheme='internet-facing', # Use 'internal' for private NLBs Type='network', IpAddressType='ipv4' ) # Create a target group for the NLB target_group_response = elbv2_client.create_target_group( Name='my-nlb-target-group', Protocol='TCP', Port=80, VpcId='vpc-0123456789abcdef0', # Replace with your VPC ID TargetType='instance' # Can also be 'ip' or 'lambda' ) # Attach a listener to forward traffic to the target group elbv2_client.create_listener( LoadBalancerArn=nlb_response['LoadBalancers'][0]['LoadBalancerArn'], Protocol='TCP', Port=80, DefaultActions=[ { 'Type': 'forward', 'TargetGroupArn': target_group_response['TargetGroups'][0]['TargetGroupArn'] } ] ) print(f"NLB created successfully! ARN: {nlb_response['LoadBalancers'][0]['LoadBalancerArn']}") if __name__ == "__main__": create_network_load_balancer()
Step 2: Call the Script from Your Ansible Playbook
- name: Deploy AWS NLB using Boto3 script hosts: localhost gather_facts: false vars: aws_access_key: "{{ your_aws_access_key }}" aws_secret_key: "{{ your_aws_secret_key }}" aws_region: us-east-1 tasks: - name: Execute NLB creation script ansible.builtin.script: create_nlb.py environment: AWS_ACCESS_KEY_ID: "{{ aws_access_key }}" AWS_SECRET_ACCESS_KEY: "{{ aws_secret_key }}" AWS_DEFAULT_REGION: "{{ aws_region }}"
Approach 2: Use the python Module for Inline Boto3 Code
If you prefer to keep everything within the playbook without external files, you can run Boto3 code directly using Ansible’s python module:
- name: Create AWS NLB with inline Boto3 code hosts: localhost gather_facts: false vars: aws_region: us-east-1 nlb_name: my-inline-nlb subnet_ids: ['subnet-0123456789abcdef0', 'subnet-0abcdef1234567890'] vpc_id: vpc-0123456789abcdef0 tasks: - name: Run inline Boto3 logic to create NLB ansible.builtin.python: code: | import boto3 import json # Initialize ELBv2 client elbv2 = boto3.client('elbv2', region_name='{{ aws_region }}') # Create NLB nlb = elbv2.create_load_balancer( Name='{{ nlb_name }}', Subnets={{ subnet_ids }}, Scheme='internet-facing', Type='network', IpAddressType='ipv4' ) # Create target group target_group = elbv2.create_target_group( Name='{{ nlb_name }}-tg', Protocol='TCP', Port=80, VpcId='{{ vpc_id }}', TargetType='instance' ) # Attach listener elbv2.create_listener( LoadBalancerArn=nlb['LoadBalancers'][0]['LoadBalancerArn'], Protocol='TCP', Port=80, DefaultActions=[{'Type': 'forward', 'TargetGroupArn': target_group['TargetGroups'][0]['TargetGroupArn']}] ) # Return structured result output = { 'changed': True, 'nlb_arn': nlb['LoadBalancers'][0]['LoadBalancerArn'], 'target_group_arn': target_group['TargetGroups'][0]['TargetGroupArn'] } print(json.dumps(output)) register: nlb_output - name: Print created NLB details ansible.builtin.debug: msg: | NLB ARN: {{ (nlb_output.stdout | from_json).nlb_arn }} Target Group ARN: {{ (nlb_output.stdout | from_json).target_group_arn }}
Key Notes
- Prerequisites: Ensure the machine running Ansible has Boto3 installed (
pip install boto3). You’ll also need valid AWS credentials configured (either via environment variables,~/.aws/credentials, or IAM roles if running on EC2). - Permissions: The AWS credentials used need permissions like
elasticloadbalancing:CreateLoadBalancer,elasticloadbalancing:CreateTargetGroup, andelasticloadbalancing:CreateListener. - Customization: Adjust parameters like subnet IDs, VPC ID, ports, protocols, and NLB scheme (public/private) to match your infrastructure needs.
内容的提问来源于stack exchange,提问作者Elieyal
相关产品推荐
相关产品推荐

