Skip to content

Instantly share code, notes, and snippets.

@avoidik
Last active October 7, 2022 08:03
Show Gist options
  • Save avoidik/9537ea6893719a1cb49b51f16dd23f57 to your computer and use it in GitHub Desktop.
Save avoidik/9537ea6893719a1cb49b51f16dd23f57 to your computer and use it in GitHub Desktop.
Run AWS metadata service locally

Run AWS metadata service locally

The idea is to run AWS metadata service on a local machine and redirect all link-local level requests to a mock server, which will provide real IAM credentials.

Install amazon-ec2-metadata-mock

curl -fsSL ec2-metadata-mock https://github.com/aws/amazon-ec2-metadata-mock/releases/download/v1.11.2/ec2-metadata-mock-`uname | tr '[:upper:]' '[:lower:]'`-`dpkg --print-architecture` -o /usr/local/bin/ec2-metadata-mock
chmod +x /usr/local/bin/ec2-metadata-mock

Install helper script

curl -fsSLO https://raw.githubusercontent.com/slimm609/mock-instance-profile/main/generate_mock_config.py

Configure network

Direct traffic to proxy using either of options

sudo ifconfig lo:0 169.254.169.254 netmask 255.255.255.255
sudo ip addr add 169.254.169.254/32 dev lo label lo:0
sudo iptables \
  --append PREROUTING \
  --destination 169.254.169.254 \
  --protocol tcp \
  --dport 80 \
  --in-interface <interface> \ # enp0s3, docker0, br-+
  --jump DNAT \
  --table nat \
  --to-destination <ip>:<port> \ # 127.0.0.1:8080
  --wait

Run

Make sure that corresponding AWS named profile has been configured, in this case we're using default

AWS_PROFILE="default" python3 generate_mock_config.py --roleArn arn:aws:iam::123456789012:role/example_role
ec2-metadata-mock -n 169.254.169.254 -p 80 -c ~/.aws/mock_config.json

Optional: Systemd service

sudo mkdir -p /opt/ec2-metadata-mock
sudo cp generate_mock_config.py /opt/ec2-metadata-mock/
sudo cp ~/.aws/mock_config.json /opt/ec2-metadata-mock/
sudo nano /etc/systemd/system/ec2-metadata-mock.service

Note: Keep in mind that IAM credentials will be limited in time, hence you would need to periodically refresh the mock_config.json file.

[Unit]
Description=amazon-ec2-metadata-mock
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/ec2-metadata-mock -n 169.254.169.254 -p 80 -c /opt/ec2-metadata-mock/mock_config.json
WorkingDirectory=/opt/ec2-metadata-mock
PrivateTmp=true
ProtectSystem=true
ProtectHome=true
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable ec2-metadata-mock.service
sudo systemctl start ec2-metadata-mock.service
sudo systemctl status ec2-metadata-mock.service

References

https://github.com/aws/amazon-ec2-metadata-mock

https://github.com/jippi/go-metadataproxy

https://github.com/slimm609/mock-instance-profile

https://medium.com/@slimm609/aws-instance-profile-for-local-development-f144b0a7b8b9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment