How to update my IP for security groups with AWS API Gateway + Lambda(node.js)

How to update my IP for security groups with AWS API Gateway + Lambda(node.js)

If I want to connect to AWS services from my home PC environment as I work remotely more and more, I would set My IP in the inbound rule.

If you reboot your router at home, the global IP may change, so you have to set My IP in the inbound security group each time. This is a hassle, so I created an API Gateway + Lambda that updates My IP via API.

My IP is http://checkip.amazonaws.comにGETメソッドでアクセスすれば取得できます. But when you hit it on Lambda with superagent or something, it returns the address of the EC2 where Lambda is running. (You can find out by logging in to the EC2 and doing curl -X GET http://checkip.amazonaws.com to try it out)

Once you have done this, it is assumed that you have created a security group from the management console. (We know the security group ID)

Delete inbound rules with the revokeSecurityGroupIngress method.

Delete the inbound rules of the security group once in the revokeSecurityGroupIngress method.

Here is an example Lambda to delete.

const AWS = require('aws-sdk')
AWS.config.update({ region: 'ap-northeast-1' })
const ec2 = new AWS.EC2({ apiVersion: '2016-11-15' })

exports.handler = async (event) => {
  const params = {
    GroupId: "sg-0a4bgh87c26a497654", // security group ID
    IpPermissions: [
      {
        FromPort: 22,
        IpProtocol: "tcp",
        IpRanges: [
          {
            CidrIp: "50.55.111.82/32" // my IP
          }
        ],
        ToPort: 22
      }
    ]
  }
  await ec2.revokeSecurityGroupIngress(params).promise()

  const response = {
    statusCode: 200,
    body: JSON.stringify('OK'),
  }
  return response
}

Get My Current IP

Since Lambda(node.js) is running on EC2, it is impossible to get the current My IP from Lambda(node.js). (Maybe)

Therefore, we will use a query parameter from API Gateway.

https://example.com/xxx/?deleteip=66.66.66.xx&currentip=66.66.66.yy *Image of REST API like this

Create inbound rules with the authorizeSecurityGroupIngress method

The authorizeSecurityGroupIngress method creates the inbound rules for the security group once.

Here is an example Lambda to create.

const AWS = require('aws-sdk')
AWS.config.update({ region: 'ap-northeast-1' })
const ec2 = new AWS.EC2({ apiVersion: '2016-11-15' })

exports.handler = async (event) => {
  const params = {
    GroupId: "sg-0a4bgh87c26a497654", // security group ID
    IpPermissions: [
      {
        FromPort: 22,
        IpProtocol: "tcp",
        IpRanges: [
          {
            CidrIp: "50.55.111.82/32",// my IP
            Description: "setumei desu"
          }
        ],
        ToPort: 22
      }
    ]
  }
  await ec2.authorizeSecurityGroupIngress(params).promise()

  const response = {
    statusCode: 200,
    body: JSON.stringify('OK'),
  };
  return response;
};

Create an API to update My IP

For API Gateway, specify currentip and deleteip in the query string and check “Use Lambda proxy integration”. Finally, create the Lambda, not taking into account things like wrong IP.

AWS API Gateway + Lambda(node.js)でセキュリティグループのマイIPを更新する方法

Lambda Example.

const AWS = require('aws-sdk')
AWS.config.update({ region: 'ap-northeast-1' })
const ec2 = new AWS.EC2({ apiVersion: '2016-11-15' })

exports.handler = async (event) => {
  const securityGroup = "sg-0a4bgh87c26a497654" // security group ID
  const deleteip = event.queryStringParameters.deleteip
  const currentip = event.queryStringParameters.currentip
  const params = (securityGroup, ip) => {
    return {
      GroupId: securityGroup,
      IpPermissions: [
        {
          FromPort: 22,
          IpProtocol: "tcp",
          IpRanges: [
            {
              CidrIp: ip + "/32",
              Description: "setumei desu"
            }
          ],
          ToPort: 22
        }
      ]
    }
  }
  const p1 = ec2.revokeSecurityGroupIngress(params(securityGroup, deleteip)).promise().catch(()=>console.log('削除失敗'))
  const p2 = ec2.authorizeSecurityGroupIngress(params(securityGroup, currentip)).promise().catch(()=>console.log('作成失敗'))
  await Promise.all([p1, p2])

  const response = {
  statusCode: 200,
  body: JSON.stringify(currentip),
  };
  return response
}

curl command.

curl -X GET https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/v1/?deleteip=60.66.193.82\&currentip=60.66.193.10

You are not authorized to perform this operation.

If “You are not authorized to perform this operation.” appears during Lambda execution, you do not have sufficient access rights to EC2.

Reference Site

Class: AWS.EC2 — AWS SDK for JavaScript

コメント

Discover more from 株式会社CONFRAGE ITソリューション事業部

Subscribe now to keep reading and get access to the full archive.

Continue reading

Copied title and URL